repo_name
stringlengths
6
91
path
stringlengths
6
999
copies
stringclasses
283 values
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
rdgonzalez85/BTHorizontalPageableView
BTHorizontalPageableView/BTHorizontalPageableView/BTHorizontalPageableView.swift
1
5738
// // BTHorizontalPageableView.swift // // Created by Rodrigo Gonzalez on 1/21/16. // Copyright © 2016 Rodrigo Gonzalez. All rights reserved. // import UIKit /** The BTHorizontalPageableView class defines a rectangular area on the screen and the interfaces for managing the content in that area. It provides support for displaying multiple contents as it were only one. It allow users to scroll within that content by making swiping gestures. To create a BTHorizontalPageableView you can use code like the following: let btScrollView = BTHorizontalPageableView(frame: frame) */ public class BTHorizontalPageableView: UIView, YSSegmentedControlDelegate, UIScrollViewDelegate { //// The Segmented control, used for display the 'titles' bar. var segmentedControl : YSSegmentedControl? { didSet { oldValue?.removeFromSuperview() self.addSubview(segmentedControl!) segmentedControl!.delegate = self segmentedControl?.appearance.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.4) segmentedControl?.appearance.selectorColor = UIColor.whiteColor() segmentedControl?.appearance.textColor = UIColor.whiteColor() segmentedControl?.appearance.selectedTextColor = UIColor.whiteColor() } } //// Indicates if the 'views' should be placed under the 'titles' bar. var viewsUnderSegmentedControl = true { didSet { if (viewsUnderSegmentedControl != oldValue) { var frame = scrollView.frame if (viewsUnderSegmentedControl) { frame.origin.y -= segmentedHeight } else { frame.origin.y += segmentedHeight } scrollView.frame = frame } } } //// Height of the segmented view. var segmentedHeight : CGFloat = 44.0 //// Y origin point of the segmented view. var segmentedYOrigin : CGFloat = 0.0 //// X origin point of the segmented view. var segmentedXOrigin : CGFloat = 0.0 //// The titles of the segments. var titles : Array<String>? { didSet { self.segmentedControl = YSSegmentedControl( frame: CGRect( x: self.bounds.origin.x + segmentedXOrigin, y: self.bounds.origin.y + segmentedYOrigin, width: self.frame.width, height: segmentedHeight), titles: titles!) } } //// The duration of the animation for scrolling to a new page. var scrollViewPageChangeAnimationDuration : NSTimeInterval = 0.5 //// The container for the views. var scrollView = UIScrollView() /// The containing views. var views : Array<UIView>? { didSet { addViews() } } public override var frame:CGRect { didSet { scrollView.frame = frame } } override init (frame : CGRect) { super.init(frame : frame) addSubview(self.scrollView) setupScrollView() } convenience init () { self.init(frame: CGRect.zero) } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.addSubview(self.scrollView) } /** Add all the views in 'views' to 'scrollView' */ private func addViews() { var x : CGFloat = 0.0 guard let safeViews = views else { return } for view in safeViews { var frame = view.frame frame.origin.x = x view.frame = frame scrollView.addSubview(view) x += view.frame.width } scrollView.contentSize = CGSize(width: x, height: scrollView.frame.height) } /** Setups 'scrollView'. Assigns scrollView delegate and set the pagingEnabled property to true. */ private func setupScrollView() { scrollView.frame = self.bounds scrollView.pagingEnabled = true scrollView.delegate = self scrollView.showsHorizontalScrollIndicator = false scrollView.showsVerticalScrollIndicator = false } /** Scrolls the 'scrollView' to 'page' page. - Parameter page: The number of page to scroll to. */ private func scrollToPage(page : Int) { guard let safeViews = views where page < safeViews.count else { return } var frame = scrollView.frame frame.origin.x = frame.width * CGFloat(page) UIView.animateWithDuration(scrollViewPageChangeAnimationDuration, animations: { () -> Void in self.scrollView.scrollRectToVisible(frame, animated: false) }) } //MARK: YSSegmentedControlDelegate internal func segmentedControlDidPressedItemAtIndex (segmentedControl: YSSegmentedControl, index: Int) { scrollToPage(index) } //MARK: UIScrollViewDelegate public func scrollViewWillEndDragging(scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) { let fractionalPage = targetContentOffset.memory.x / scrollView.frame.size.width; let page = ceil(fractionalPage) guard let safeControl = segmentedControl else { return } guard let safeTitles = titles where Int(page) < safeTitles.count && Int(page) >= 0 else { return } safeControl.selectItemAtIndex(Int(page)) } }
mit
blockchain/My-Wallet-V3-iOS
Modules/FeatureKYC/Sources/FeatureKYCUI/NavigationCTA.swift
1
1162
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import BlockchainComponentLibrary import Localization import PlatformUIKit import UIKit private typealias L10n = LocalizationConstants.NewKYC.Steps.AccountUsage enum NavigationCTA { case dismiss case help case skip case none } extension NavigationCTA { var image: UIImage? { switch self { case .dismiss: return UIImage( named: "Close Circle v2", in: .componentLibrary, compatibleWith: nil )?.withRenderingMode(.alwaysOriginal) case .help: return UIImage(named: "ios_icon_more", in: .featureKYCUI, compatibleWith: nil) case .none, .skip: return nil } } var title: String { switch self { case .dismiss, .help, .none: return "" case .skip: return L10n.skipButtonTitle } } var visibility: PlatformUIKit.Visibility { switch self { case .dismiss, .help, .skip: return .visible case .none: return .hidden } } }
lgpl-3.0
LimCrazy/SwiftProject3.0-Master
SwiftPreject-Master/SwiftPreject-Master/Class/CustomTabBarVC.swift
1
3414
// // CustomTabBarVC.swift // SwiftPreject-Master // // Created by lim on 2016/12/11. // Copyright © 2016年 Lim. All rights reserved. // import UIKit class CustomTabBarVC: UITabBarController { override func viewDidLoad() { super.viewDidLoad() setupUI() } func setupUI() -> () { UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName:UIColor.lightGray,NSFontAttributeName:UIFont.systemFont(ofSize: 11)], for: .normal) UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName:UIColor.blue,NSFontAttributeName:UIFont.systemFont(ofSize: 11)], for: .highlighted) UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName:UIColor.red,NSFontAttributeName:UIFont.systemFont(ofSize: 11)], for: .selected) tabBar.isTranslucent = false; // let lineView = UIView(frame: CGRect(x: 0, y: 0, width:KScreenWidth, height: 0.5)) // lineView.backgroundColor = UIColor.lightGray // lineView.alpha = 0.8 // tabBar.addSubview(lineView) let homeNavigaiton = YM_Tools.stroyboard(sbName: "Main", identfier: "NavHomeVC") self.configTabbarItem(title: "今日特卖", imgName:"home_tab_home_btn" , nav: homeNavigaiton) let iMessageNavigation = YM_Tools.stroyboard(sbName: "Main", identfier: "NaviMessageVC") self.configTabbarItem(title: "淘宝特价", imgName:"home_tab_cpc_btn" , nav: iMessageNavigation) let personCenterNavigation = YM_Tools.stroyboard(sbName: "Main", identfier: "NavPersonCenter") self.configTabbarItem(title: "拼团", imgName:"home_tab_pina_btn" , nav: personCenterNavigation) let breakNewsNavigation = YM_Tools.stroyboard(sbName: "Main", identfier: "NavBreakNewsVC") self.configTabbarItem(title: "购物车", imgName:"home_tab_point_btn" , nav: breakNewsNavigation) let mineNavigation = YM_Tools.stroyboard(sbName: "Main", identfier: "NavMineVC") self.configTabbarItem(title: "我的", imgName:"home_tab_personal_btn" , nav: mineNavigation) self.viewControllers = [homeNavigaiton, iMessageNavigation, personCenterNavigation, breakNewsNavigation, mineNavigation] } func configTabbarItem(title:String,imgName:String,nav:UINavigationController) -> () { let img = UIImage(named: imgName)?.withRenderingMode(.alwaysOriginal) let selectImg = UIImage(named: String.init(format: "%@_c",imgName))?.withRenderingMode(.alwaysOriginal) nav.tabBarItem = UITabBarItem.init(title: title, image: img, selectedImage: selectImg) nav.tabBarItem.titlePositionAdjustment = UIOffset(horizontal: 0, vertical: -3) nav.tabBarItem.imageInsets = UIEdgeInsetsMake(7, 0, -7, 0) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
apache-2.0
adamyanalunas/GrowlerFills-iOS
CaliforniaGrowlerFillTests/CaliforniaGrowlerFillTests.swift
1
946
// // CaliforniaGrowlerFillTests.swift // CaliforniaGrowlerFillTests // // Created by Adam Yanalunas on 7/13/14. // Copyright (c) 2014 Subtracktion. All rights reserved. // import UIKit import XCTest class CaliforniaGrowlerFillTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. XCTAssert(true, "Pass") } func testPerformanceExample() { // This is an example of a performance test case. self.measureBlock() { // Put the code you want to measure the time of here. } } }
mit
fs/ios-base-swift
Swift-Base/Tools/Views/TextView.swift
1
1651
// // TextView.swift // Tools // // Created by Oleg Gorelov on 30/05/2018. // Copyright © 2018 Flatstack. All rights reserved. // import UIKit @IBDesignable public class TextView: UITextView { // MARK: - Instance Properties @IBInspectable public var bottomOutset: CGFloat { get { return self.touchEdgeOutset.bottom } set { self.touchEdgeOutset.bottom = newValue } } @IBInspectable public var leftOutset: CGFloat { get { return self.touchEdgeOutset.left } set { self.touchEdgeOutset.left = newValue } } @IBInspectable public var rightOutset: CGFloat { get { return self.touchEdgeOutset.right } set { self.touchEdgeOutset.right = newValue } } @IBInspectable public var topOutset: CGFloat { get { return self.touchEdgeOutset.top } set { self.touchEdgeOutset.top = newValue } } public var touchEdgeOutset: UIEdgeInsets = UIEdgeInsets.zero // MARK: - UIControl public override func point(inside point: CGPoint, with event: UIEvent?) -> Bool { let rect = CGRect(x: self.bounds.origin.x - self.touchEdgeOutset.left, y: self.bounds.origin.y - self.touchEdgeOutset.top, width: self.bounds.width + self.touchEdgeOutset.left + self.touchEdgeOutset.right, height: self.bounds.height + self.touchEdgeOutset.top + self.touchEdgeOutset.bottom) return rect.contains(point) } }
mit
wrutkowski/Lucid-Weather-Clock
Pods/Charts/Charts/Classes/Renderers/ChartYAxisRendererHorizontalBarChart.swift
6
11759
// // ChartYAxisRendererHorizontalBarChart.swift // Charts // // Created by Daniel Cohen Gindi on 3/3/15. // // 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 #if !os(OSX) import UIKit #endif open class ChartYAxisRendererHorizontalBarChart: ChartYAxisRenderer { public override init(viewPortHandler: ChartViewPortHandler, yAxis: ChartYAxis, transformer: ChartTransformer!) { super.init(viewPortHandler: viewPortHandler, yAxis: yAxis, transformer: transformer) } /// Computes the axis values. open override func computeAxis(yMin: Double, yMax: Double) { guard let yAxis = yAxis else { return } var yMin = yMin, yMax = yMax // calculate the starting and entry point of the y-labels (depending on zoom / contentrect bounds) if (viewPortHandler.contentHeight > 10.0 && !viewPortHandler.isFullyZoomedOutX) { let p1 = transformer.getValueByTouchPoint(CGPoint(x: viewPortHandler.contentLeft, y: viewPortHandler.contentTop)) let p2 = transformer.getValueByTouchPoint(CGPoint(x: viewPortHandler.contentRight, y: viewPortHandler.contentTop)) if (!yAxis.inverted) { yMin = Double(p1.x) yMax = Double(p2.x) } else { yMin = Double(p2.x) yMax = Double(p1.x) } } computeAxisValues(min: yMin, max: yMax) } /// draws the y-axis labels to the screen open override func renderAxisLabels(context: CGContext) { guard let yAxis = yAxis else { return } if (!yAxis.enabled || !yAxis.drawLabelsEnabled) { return } var positions = [CGPoint]() positions.reserveCapacity(yAxis.entries.count) for i in 0 ..< yAxis.entries.count { positions.append(CGPoint(x: CGFloat(yAxis.entries[i]), y: 0.0)) } transformer.pointValuesToPixel(&positions) let lineHeight = yAxis.labelFont.lineHeight let baseYOffset: CGFloat = 2.5 let dependency = yAxis.axisDependency let labelPosition = yAxis.labelPosition var yPos: CGFloat = 0.0 if (dependency == .left) { if (labelPosition == .outsideChart) { yPos = viewPortHandler.contentTop - baseYOffset } else { yPos = viewPortHandler.contentTop - baseYOffset } } else { if (labelPosition == .outsideChart) { yPos = viewPortHandler.contentBottom + lineHeight + baseYOffset } else { yPos = viewPortHandler.contentBottom + lineHeight + baseYOffset } } // For compatibility with Android code, we keep above calculation the same, // And here we pull the line back up yPos -= lineHeight drawYLabels(context: context, fixedPosition: yPos, positions: positions, offset: yAxis.yOffset) } private var _axisLineSegmentsBuffer = [CGPoint](repeating: CGPoint(), count: 2) open override func renderAxisLine(context: CGContext) { guard let yAxis = yAxis else { return } if (!yAxis.enabled || !yAxis.drawAxisLineEnabled) { return } context.saveGState() context.setStrokeColor(yAxis.axisLineColor.cgColor) context.setLineWidth(yAxis.axisLineWidth) if (yAxis.axisLineDashLengths != nil) { context.setLineDash(phase: yAxis.axisLineDashPhase, lengths: yAxis.axisLineDashLengths) } else { context.setLineDash(phase: 0.0, lengths: []) } if (yAxis.axisDependency == .left) { _axisLineSegmentsBuffer[0].x = viewPortHandler.contentLeft _axisLineSegmentsBuffer[0].y = viewPortHandler.contentTop _axisLineSegmentsBuffer[1].x = viewPortHandler.contentRight _axisLineSegmentsBuffer[1].y = viewPortHandler.contentTop context.strokeLineSegments(between: _axisLineSegmentsBuffer) } else { _axisLineSegmentsBuffer[0].x = viewPortHandler.contentLeft _axisLineSegmentsBuffer[0].y = viewPortHandler.contentBottom _axisLineSegmentsBuffer[1].x = viewPortHandler.contentRight _axisLineSegmentsBuffer[1].y = viewPortHandler.contentBottom context.strokeLineSegments(between: _axisLineSegmentsBuffer) } context.restoreGState() } /// draws the y-labels on the specified x-position open func drawYLabels(context: CGContext, fixedPosition: CGFloat, positions: [CGPoint], offset: CGFloat) { guard let yAxis = yAxis else { return } let labelFont = yAxis.labelFont let labelTextColor = yAxis.labelTextColor for i in 0 ..< yAxis.entryCount { let text = yAxis.getFormattedLabel(i) if (!yAxis.drawTopYLabelEntryEnabled && i >= yAxis.entryCount - 1) { return } ChartUtils.drawText(context: context, text: text, point: CGPoint(x: positions[i].x, y: fixedPosition - offset), align: .center, attributes: [NSFontAttributeName: labelFont, NSForegroundColorAttributeName: labelTextColor]) } } open override func renderGridLines(context: CGContext) { guard let yAxis = yAxis else { return } if !yAxis.enabled { return } if yAxis.drawGridLinesEnabled { context.saveGState() // pre alloc var position = CGPoint() context.setShouldAntialias(yAxis.gridAntialiasEnabled) context.setStrokeColor(yAxis.gridColor.cgColor) context.setLineWidth(yAxis.gridLineWidth) context.setLineCap(yAxis.gridLineCap) if (yAxis.gridLineDashLengths != nil) { context.setLineDash(phase: yAxis.gridLineDashPhase, lengths: yAxis.gridLineDashLengths) } else { context.setLineDash(phase: 0.0, lengths: []) } // draw the horizontal grid for i in 0 ..< yAxis.entryCount { position.x = CGFloat(yAxis.entries[i]) position.y = 0.0 transformer.pointValueToPixel(&position) context.beginPath() context.move(to: CGPoint(x: position.x, y: viewPortHandler.contentTop)) context.addLine(to: CGPoint(x: position.x, y: viewPortHandler.contentBottom)) context.strokePath() } context.restoreGState() } if yAxis.drawZeroLineEnabled { // draw zero line var position = CGPoint(x: 0.0, y: 0.0) transformer.pointValueToPixel(&position) drawZeroLine(context: context, x1: position.x, x2: position.x, y1: viewPortHandler.contentTop, y2: viewPortHandler.contentBottom); } } private var _limitLineSegmentsBuffer = [CGPoint](repeating: CGPoint(), count: 2) open override func renderLimitLines(context: CGContext) { guard let yAxis = yAxis else { return } var limitLines = yAxis.limitLines if (limitLines.count <= 0) { return } context.saveGState() let trans = transformer.valueToPixelMatrix var position = CGPoint(x: 0.0, y: 0.0) for i in 0 ..< limitLines.count { let l = limitLines[i] if !l.enabled { continue } position.x = CGFloat(l.limit) position.y = 0.0 position = position.applying(trans) _limitLineSegmentsBuffer[0].x = position.x _limitLineSegmentsBuffer[0].y = viewPortHandler.contentTop _limitLineSegmentsBuffer[1].x = position.x _limitLineSegmentsBuffer[1].y = viewPortHandler.contentBottom context.setStrokeColor(l.lineColor.cgColor) context.setLineWidth(l.lineWidth) if (l.lineDashLengths != nil) { context.setLineDash(phase: l.lineDashPhase, lengths: l.lineDashLengths!) } else { context.setLineDash(phase: 0.0, lengths: []) } context.strokeLineSegments(between: _limitLineSegmentsBuffer) let label = l.label // if drawing the limit-value label is enabled if (l.drawLabelEnabled && label.characters.count > 0) { let labelLineHeight = l.valueFont.lineHeight let xOffset: CGFloat = l.lineWidth + l.xOffset let yOffset: CGFloat = 2.0 + l.yOffset if (l.labelPosition == .rightTop) { ChartUtils.drawText(context: context, text: label, point: CGPoint( x: position.x + xOffset, y: viewPortHandler.contentTop + yOffset), align: .left, attributes: [NSFontAttributeName: l.valueFont, NSForegroundColorAttributeName: l.valueTextColor]) } else if (l.labelPosition == .rightBottom) { ChartUtils.drawText(context: context, text: label, point: CGPoint( x: position.x + xOffset, y: viewPortHandler.contentBottom - labelLineHeight - yOffset), align: .left, attributes: [NSFontAttributeName: l.valueFont, NSForegroundColorAttributeName: l.valueTextColor]) } else if (l.labelPosition == .leftTop) { ChartUtils.drawText(context: context, text: label, point: CGPoint( x: position.x - xOffset, y: viewPortHandler.contentTop + yOffset), align: .right, attributes: [NSFontAttributeName: l.valueFont, NSForegroundColorAttributeName: l.valueTextColor]) } else { ChartUtils.drawText(context: context, text: label, point: CGPoint( x: position.x - xOffset, y: viewPortHandler.contentBottom - labelLineHeight - yOffset), align: .right, attributes: [NSFontAttributeName: l.valueFont, NSForegroundColorAttributeName: l.valueTextColor]) } } } context.restoreGState() } }
mit
mmllr/CleanTweeter
CleanTweeter/UseCases/NewPost/UI/Presenter/TagAndMentionHighlightingTransformer.swift
1
1306
import Foundation class TagAndMentionHighlightingTransformer : ValueTransformer { let resourceFactory: ResourceFactory init(factory: ResourceFactory) { self.resourceFactory = factory super.init() } override class func transformedValueClass() -> AnyClass { return NSAttributedString.self } override class func allowsReverseTransformation() -> Bool { return false } override func transformedValue(_ value: Any?) -> Any? { guard let transformedValue = value as! String? else { return nil } return transformedValue.findRangesWithPattern("((@|#)([A-Z0-9a-z(é|ë|ê|è|à|â|ä|á|ù|ü|û|ú|ì|ï|î|í)_]+))|(http(s)?://([A-Z0-9a-z._-]*(/)?)*)").reduce(NSMutableAttributedString(string: transformedValue)) { let string = $0 let length = transformedValue.distance(from: $1.lowerBound, to: $1.upperBound) let range = NSMakeRange(transformedValue.distance(from: transformedValue.startIndex, to: $1.lowerBound), length) string.addAttribute(resourceFactory.highlightingAttribute.0, value: self.resourceFactory.highlightingAttribute.1, range: range) return string } } } // Helper function inserted by Swift 4.2 migrator. fileprivate func convertToNSAttributedStringKey(_ input: String) -> NSAttributedString.Key { return NSAttributedString.Key(rawValue: input) }
mit
hooman/swift
test/Distributed/Runtime/distributed_actor_local.swift
1
2913
// RUN: %target-run-simple-swift(-Xfrontend -enable-experimental-distributed -parse-as-library) | %FileCheck %s // REQUIRES: executable_test // REQUIRES: concurrency // REQUIRES: distributed // rdar://76038845 // UNSUPPORTED: use_os_stdlib // UNSUPPORTED: back_deployment_runtime // REQUIRES: rdar78290608 import _Distributed @available(SwiftStdlib 5.5, *) distributed actor SomeSpecificDistributedActor { distributed func hello() async throws { print("hello from \(self.id)") } distributed func echo(int: Int) async throws -> Int { int } } // ==== Execute ---------------------------------------------------------------- @_silgen_name("swift_distributed_actor_is_remote") func __isRemoteActor(_ actor: AnyObject) -> Bool func __isLocalActor(_ actor: AnyObject) -> Bool { return !__isRemoteActor(actor) } // ==== Fake Transport --------------------------------------------------------- @available(SwiftStdlib 5.5, *) struct ActorAddress: ActorIdentity { let address: String init(parse address : String) { self.address = address } } @available(SwiftStdlib 5.5, *) struct FakeTransport: ActorTransport { func decodeIdentity(from decoder: Decoder) throws -> AnyActorIdentity { fatalError("not implemented \(#function)") } func resolve<Act>(_ identity: Act.ID, as actorType: Act.Type) throws -> Act? where Act: DistributedActor { return nil } func assignIdentity<Act>(_ actorType: Act.Type) -> AnyActorIdentity where Act: DistributedActor { .init(ActorAddress(parse: "")) } public func actorReady<Act>(_ actor: Act) where Act: DistributedActor { print("\(#function):\(actor)") } func resignIdentity(_ id: AnyActorIdentity) {} } // ==== Execute ---------------------------------------------------------------- @available(SwiftStdlib 5.5, *) func test_initializers() { let address = ActorAddress(parse: "") let transport = FakeTransport() _ = SomeSpecificDistributedActor(transport: transport) _ = try! SomeSpecificDistributedActor(resolve: .init(address), using: transport) } @available(SwiftStdlib 5.5, *) func test_address() { let transport = FakeTransport() let actor = SomeSpecificDistributedActor(transport: transport) _ = actor.id } @available(SwiftStdlib 5.5, *) func test_run(transport: FakeTransport) async { let actor = SomeSpecificDistributedActor(transport: transport) print("before") // CHECK: before try! await actor.hello() print("after") // CHECK: after } @available(SwiftStdlib 5.5, *) func test_echo(transport: FakeTransport) async { let actor = SomeSpecificDistributedActor(transport: transport) let echo = try! await actor.echo(int: 42) print("echo: \(echo)") // CHECK: echo: 42 } @available(SwiftStdlib 5.5, *) @main struct Main { static func main() async { await test_run(transport: FakeTransport()) await test_echo(transport: FakeTransport()) } }
apache-2.0
lamb/trials
Weather/WeatherUITests/WeatherUITests.swift
1
1234
// // WeatherUITests.swift // WeatherUITests // // Created by Lamb on 15/10/21. // Copyright © 2015年 Lamb. All rights reserved. // import XCTest class WeatherUITests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method. XCUIApplication().launch() // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. } }
apache-2.0
lorentey/swift
validation-test/stdlib/Slice/Slice_Of_DefaultedMutableRangeReplaceableCollection_FullWidth.swift
16
3863
// -*- swift -*- //===----------------------------------------------------------------------===// // Automatically Generated From validation-test/stdlib/Slice/Inputs/Template.swift.gyb // Do Not Edit Directly! //===----------------------------------------------------------------------===// // RUN: %target-run-simple-swift // REQUIRES: executable_test // FIXME: the test is too slow when the standard library is not optimized. // REQUIRES: optimized_stdlib import StdlibUnittest import StdlibCollectionUnittest var SliceTests = TestSuite("Collection") let prefix: [Int] = [] let suffix: [Int] = [] func makeCollection(elements: [OpaqueValue<Int>]) -> Slice<DefaultedMutableRangeReplaceableCollection<OpaqueValue<Int>>> { var baseElements = prefix.map(OpaqueValue.init) baseElements.append(contentsOf: elements) baseElements.append(contentsOf: suffix.map(OpaqueValue.init)) let base = DefaultedMutableRangeReplaceableCollection(elements: baseElements) let startIndex = base.index( base.startIndex, offsetBy: numericCast(prefix.count)) let endIndex = base.index( base.startIndex, offsetBy: numericCast(prefix.count + elements.count)) return Slice(base: base, bounds: startIndex..<endIndex) } func makeCollectionOfEquatable(elements: [MinimalEquatableValue]) -> Slice<DefaultedMutableRangeReplaceableCollection<MinimalEquatableValue>> { var baseElements = prefix.map(MinimalEquatableValue.init) baseElements.append(contentsOf: elements) baseElements.append(contentsOf: suffix.map(MinimalEquatableValue.init)) let base = DefaultedMutableRangeReplaceableCollection(elements: baseElements) let startIndex = base.index( base.startIndex, offsetBy: numericCast(prefix.count)) let endIndex = base.index( base.startIndex, offsetBy: numericCast(prefix.count + elements.count)) return Slice(base: base, bounds: startIndex..<endIndex) } func makeCollectionOfComparable(elements: [MinimalComparableValue]) -> Slice<DefaultedMutableRangeReplaceableCollection<MinimalComparableValue>> { var baseElements = prefix.map(MinimalComparableValue.init) baseElements.append(contentsOf: elements) baseElements.append(contentsOf: suffix.map(MinimalComparableValue.init)) let base = DefaultedMutableRangeReplaceableCollection(elements: baseElements) let startIndex = base.index( base.startIndex, offsetBy: numericCast(prefix.count)) let endIndex = base.index( base.startIndex, offsetBy: numericCast(prefix.count + elements.count)) return Slice(base: base, bounds: startIndex..<endIndex) } var resiliencyChecks = CollectionMisuseResiliencyChecks.all resiliencyChecks.creatingOutOfBoundsIndicesBehavior = .trap resiliencyChecks.subscriptOnOutOfBoundsIndicesBehavior = .trap resiliencyChecks.subscriptRangeOnOutOfBoundsRangesBehavior = .trap SliceTests.addRangeReplaceableSliceTests( "Slice_Of_DefaultedMutableRangeReplaceableCollection_FullWidth.swift.", makeCollection: makeCollection, wrapValue: identity, extractValue: identity, makeCollectionOfEquatable: makeCollectionOfEquatable, wrapValueIntoEquatable: identityEq, extractValueFromEquatable: identityEq, resiliencyChecks: resiliencyChecks, outOfBoundsIndexOffset: 6 ) SliceTests.addMutableCollectionTests( "Slice_Of_DefaultedMutableRangeReplaceableCollection_FullWidth.swift.", makeCollection: makeCollection, wrapValue: identity, extractValue: identity, makeCollectionOfEquatable: makeCollectionOfEquatable, wrapValueIntoEquatable: identityEq, extractValueFromEquatable: identityEq, makeCollectionOfComparable: makeCollectionOfComparable, wrapValueIntoComparable: identityComp, extractValueFromComparable: identityComp, resiliencyChecks: resiliencyChecks, outOfBoundsIndexOffset: 6 , withUnsafeMutableBufferPointerIsSupported: false, isFixedLengthCollection: true ) runAllTests()
apache-2.0
lorentey/swift
validation-test/compiler_crashers_fixed/00986-swift-unboundgenerictype-get.swift
65
597
// 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 // RUN: not %target-swift-frontend %s -typecheck n class l<g> { let enum e<q> : r { func k<q>() -> q -> q { return { h o h 1 { } } class k { m func p() -> String { let m: String = { }() struct g<b where f.h == e.h> { } } } protocol h : e { func e
apache-2.0
NilStack/NilColorKit
NilColorKitTests/NilColorKitTests.swift
1
898
// // NilColorKitTests.swift // NilColorKitTests // // Created by Peng on 10/2/14. // Copyright (c) 2014 peng. All rights reserved. // import UIKit import XCTest class NilColorKitTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. XCTAssert(true, "Pass") } func testPerformanceExample() { // This is an example of a performance test case. self.measureBlock() { // Put the code you want to measure the time of here. } } }
mit
pixelmaid/piper
Palette-Knife/SocketManager.swift
2
5085
// // SocketManager.swift // PaletteKnife // // Created by JENNIFER MARY JACOBS on 6/27/16. // Copyright © 2016 pixelmaid. All rights reserved. // import Foundation import Starscream //central manager for all requests to web socket class SocketManager: WebSocketDelegate{ var socket = WebSocket(url: NSURL(string: "ws://pure-beach-75578.herokuapp.com/")!, protocols: ["drawing"]) //var socket = WebSocket(url: NSURL(string: "ws://localhost:5000")!, protocols: ["ipad_client"]) var socketEvent = Event<(String,JSON?)>(); var firstConnection = true; var targets = [WebTransmitter](); //objects which can send or recieve data var startTime:NSDate? var dataQueue = [String](); var transmitComplete = true; let dataKey = NSUUID().UUIDString; init(){ socket.delegate = self; } func connect(){ socket.connect() } // MARK: Websocket Delegate Methods. func websocketDidConnect(ws: WebSocket) { print("websocket is connected") //send name of client socket.writeString("{\"name\":\"drawing\"}") if(firstConnection){ socketEvent.raise(("first_connection",nil)); } else{ socketEvent.raise(("connected",nil)); } } func websocketDidDisconnect(ws: WebSocket, error: NSError?) { if let e = error { print("websocket is disconnected: \(e.localizedDescription)") } else { print("websocket disconnected") } socketEvent.raise(("disconnected",nil)); } func websocketDidReceiveMessage(ws: WebSocket, text: String) { if(text == "init_data_recieved" || text == "message recieved"){ if(dataQueue.count>0){ socket.writeString(dataQueue.removeAtIndex(0)); } else{ transmitComplete = true; } } else if(text == "fabricator connected"){ // self.sendFabricationConfigData(); } else{ if let dataFromString = text.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) { let json = JSON(data: dataFromString) socketEvent.raise(("fabricator_data",json)) } } } func websocketDidReceiveData(ws: WebSocket, data: NSData) { } // MARK: Disconnect Action func disconnect() { if socket.isConnected { socket.disconnect() } else { socket.connect() } } func sendFabricationConfigData(){ var source_string = "[\"VR, .2, .1, .4, 10, .1, .4, .4, 10, 1, .200, 100, .150, 65, 0, 0, .200, .250 \","; source_string += "\"SW, 2, , \"," source_string += "\"FS, C:/Users/ShopBot/Desktop/Debug/\"" source_string+="]" var data = "{\"type\":\"gcode\"," data += "\"data\":"+source_string+"}" socket.writeString(data) } func sendStylusData() { var string = "{\"type\":\"stylus_data\",\"canvas_id\":\""+stylus.id; string += "\",\"stylusData\":{" string+="\"time\":"+String(stylus.getTimeElapsed())+"," string+="\"pressure\":"+String(stylus.force)+"," string+="\"angle\":"+String(stylus.angle)+"," string+="\"penDown\":"+String(stylus.penDown)+"," string+="\"speed\":"+String(stylus.speed)+"," string+="\"position\":{\"x\":"+String(stylus.position.x)+",\"y\":"+String(stylus.position.y)+"}" // string+="\"delta\":{\"x\":"+String(delta.x)+",\"y\":"+String(delta.y)+"}" string+="}}" dataGenerated(string,key:"_") } func initAction(target:WebTransmitter, type:String){ let data = "{\"type\":\""+type+"\",\"id\":\""+target.id+"\",\"name\":\""+target.name+"\"}"; targets.append(target); target.transmitEvent.addHandler(self,handler: SocketManager.dataGenerated, key:dataKey); target.initEvent.addHandler(self,handler: SocketManager.initEvent, key:dataKey); self.dataGenerated(data,key:"_"); if(type == "brush_init"){ let b = target as! Brush b.setupTransition(); } } func initEvent(data:(WebTransmitter,String), key:String){ self.initAction(data.0, type: data.1) } func dataGenerated(data:(String), key:String){ if(transmitComplete){ transmitComplete = false; socket.writeString(data) } else{ dataQueue.append(data) } } func sendBehaviorData(data:(String)){ let string = "{\"type\":\"behavior_data\",\"data\":"+data+"}" if(transmitComplete){ transmitComplete = false; socket.writeString(string) } else{ dataQueue.append(string) } } }
mit
jjochen/photostickers
MessagesExtension/Scenes/Messages App/Application.swift
1
1303
// // MessageApp.swift // PhotoStickers // // Created by Jochen on 29.03.19. // Copyright © 2019 Jochen Pfeiffer. All rights reserved. // import Foundation final class Application { private let stickerService: StickerService private let imageStoreService: ImageStoreService private let stickerRenderService: StickerRenderService init() { #if PREFILL_STICKERS let dataFolderType = DataFolderType.documentsPrefilled(subfolder: "UITests") #else let dataFolderType = DataFolderType.appGroup #endif let dataFolder = DataFolderService(type: dataFolderType) imageStoreService = ImageStoreService(url: dataFolder.imagesURL) stickerService = StickerService(realmType: .onDisk(url: dataFolder.realmURL), imageStoreService: imageStoreService) stickerRenderService = StickerRenderService() } lazy var appServices = { AppServices(stickerService: self.stickerService, imageStoreService: self.imageStoreService, stickerRenderService: self.stickerRenderService) }() } struct AppServices: HasStickerService, HasImageStoreService, HasStickerRenderService { let stickerService: StickerService let imageStoreService: ImageStoreService let stickerRenderService: StickerRenderService }
mit
abertelrud/swift-package-manager
Sources/SPMTestSupport/SwiftPMProduct.swift
2
1298
//===----------------------------------------------------------------------===// // // This source file is part of the Swift open source project // // Copyright (c) 2019 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 // //===----------------------------------------------------------------------===// import TSCBasic @_exported import TSCTestSupport public enum SwiftPMProduct: Product { case SwiftBuild case SwiftPackage case SwiftPackageRegistry case SwiftTest case SwiftRun case XCTestHelper /// Executable name. public var exec: RelativePath { switch self { case .SwiftBuild: return RelativePath("swift-build") case .SwiftPackage: return RelativePath("swift-package") case .SwiftPackageRegistry: return RelativePath("swift-package-registry") case .SwiftTest: return RelativePath("swift-test") case .SwiftRun: return RelativePath("swift-run") case .XCTestHelper: return RelativePath("swiftpm-xctest-helper") } } }
apache-2.0
LeeShiYoung/LSYWeibo
LSYWeiBoTests/LSYWeiBoTests.swift
1
977
// // LSYWeiBoTests.swift // LSYWeiBoTests // // Created by 李世洋 on 16/4/30. // Copyright © 2016年 李世洋. All rights reserved. // import XCTest @testable import LSYWeiBo class LSYWeiBoTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() { // This is an example of a performance test case. self.measureBlock { // Put the code you want to measure the time of here. } } }
artistic-2.0
toineheuvelmans/Metron
Playground.playground/Pages/2. CoordinateSystem.xcplaygroundpage/Contents.swift
1
899
import CoreGraphics import Metron /*: CoordinateSystem, CornerPosition and Side # CoordinateSystem A `CoordinateSystem` is a simple description of a two-dimensional space defined by its origin (the visual corner in which the origin `{0, 0}` is found. On iOS this defaults to top / left, while on macOS this is bottom / left. The `CoordinateSystem` is used to translate from visual positions (e.g. top, right, bottom, left) to coordinate positions (minY, maxX, maxY, minX). */ let cs1 = CoordinateSystem.default let cs2 = CoordinateSystem(origin: .bottomRight) let cs = cs1 cs.edges cs.side(for: .minYEdge) cs.edge(for: .left) cs.corners cs.corner(for: .bottomRight) cs.position(for: .maxXminY) cs.corners(startingAt: .minXminY, rotating: .clockwise) cs.edges(startingAt: .minXEdge, rotating: .counterClockwise) //: --- //: [BACK: Angle](@previous) | [NEXT: Extensions](@next)
mit
SwiftStudies/OysterKit
Sources/STLR/Generated/Extensions/STLR+CustomStringConvertable.swift
1
4474
// Copyright (c) 2016, RED When Excited // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import Foundation extension STLR : CustomStringConvertible { public var description: Swift.String { let result = TextFile(grammar.scopeName+".STLR") result.print("grammar \(grammar.scopeName)","") for module in grammar.modules ?? [] { result.print("import \(module.moduleName)") } result.print("") for rule in grammar.rules { result.print(rule.description) } return result.content } } extension STLR.Rule : CustomStringConvertible{ public var description : String { return "\(identifier)\(tokenType == nil ? "" : "\(tokenType!)") \(assignmentOperators.rawValue) \(expression)" } } extension STLR.Expression : CustomStringConvertible { public var description : String { switch self { case .element(let element): return element.description case .sequence(let sequence): return sequence.map({$0.description}).joined(separator: " ") case .choice(let choices): return choices.map({$0.description}).joined(separator: " | ") } } } extension STLR.Element : CustomStringConvertible { public var description : String { let quantity = quantifier?.rawValue ?? "" let allAttribs = annotations?.map({"\($0)"}).joined(separator: " ") ?? "" let prefix = allAttribs+(allAttribs.isEmpty ? "" : " ")+[lookahead,negated,transient,void].compactMap({$0}).joined(separator: "") var core : String if let group = group { core = "\(prefix)(\(group.expression))\(quantity)" } else if let identifier = identifier { core = "\(prefix)\(identifier)\(quantity)" } else if let terminal = terminal { core = "\(prefix)\(terminal.description)\(quantity)" } else { core = "!!UNKNOWN ELEMENT TYPE!!" } return core } } extension STLR.Annotation : CustomStringConvertible { public var description : String { return "@\(label)"+(literal == nil ? "" : "(\(literal!))") } } extension STLR.Literal : CustomStringConvertible { public var description : String { switch self { case .boolean(let value): return "\(value)" case .number(let value): return "\(value)" case .string(let value): return value.stringBody.debugDescription } } } extension STLR.Terminal : CustomStringConvertible { public var description : String { switch self { case .endOfFile(_): return ".endOfFile" case .characterSet(let characterSet): return ".\(characterSet.characterSetName)" case .regex(let regex): return "/\(regex)/" case .terminalString(let terminalString): return terminalString.terminalBody.debugDescription case .characterRange(let characterRange): return "\(characterRange[0].terminalBody)...\(characterRange[0].terminalBody)" } } }
bsd-2-clause
Takanu/Pelican
Sources/Pelican/API/Types/Inline/ChosenInlineResult.swift
1
942
// // ChosenInlineResult.swift // Pelican // // Created by Takanu Kyriako on 19/12/2017. // import Foundation /** Represents a result of an inline query that was chosen by the user and sent to the chat. */ public struct ChosenInlineResult: UpdateModel, Codable { /// The unique identifier for the result that was chosen. var resultID: String /// The user that chose the result. var from: User /// The query that was used to obtain the result var query: String /// Sender location, only for bots that require user location. var location: Location? /// Identifier of the sent inline message. Available only if there is an inline keyboard attached to the message. var inlineMessageID: String? /// Coding keys to map values when Encoding and Decoding. enum CodingKeys: String, CodingKey { case resultID = "inline_query_id" case from case query case location case inlineMessageID = "inline_message_id" } }
mit
lanjing99/RxSwiftDemo
13-intermediate-rxcocoa/starter/Wundercast/Controllers/Extensions/MKMapView+Rx.swift
1
1185
/* * Copyright (c) 2014-2016 Razeware LLC * * 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 MapKit import RxSwift import RxCocoa
mit
iosprogrammingwithswift/iosprogrammingwithswift
15_SwiftNetworking/SwiftNetworkingTests/SwiftNetworkingTests.swift
1
930
// // SwiftNetworkingTests.swift // SwiftNetworkingTests // // Created by Andreas Wittmann on 11/01/15. // Copyright (c) 2015 🐨 + 🙉. All rights reserved. // import UIKit import XCTest class SwiftNetworkingTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. XCTAssert(true, "Pass") } func testPerformanceExample() { // This is an example of a performance test case. self.measureBlock() { // Put the code you want to measure the time of here. } } }
mit
manticarodrigo/FieldTextView
FieldTextView.swift
1
1576
// // FieldTextView.swift // Edumate // // Created by Rodrigo Mantica on 12/9/16. // Copyright © 2016 Rodrigo Mantica. All rights reserved. // import UIKit class FieldTextView : UITextView, UITextViewDelegate { override var contentSize: CGSize { didSet { var topCorrection = (self.bounds.size.height - self.contentSize.height * self.zoomScale) / 2.0 topCorrection = max(0, topCorrection) self.contentInset = UIEdgeInsets(top: topCorrection, left: 0, bottom: 0, right: 0) } } let placeholderLabel = UILabel() var placeholder: String? required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.setupView() } override func layoutSubviews() { super.layoutSubviews() self.setupView() } private func setupView() { self.placeholderLabel.text = self.placeholder ?? "Tap to start typing..." self.placeholderLabel.textAlignment = self.textAlignment self.placeholderLabel.font = self.font self.placeholderLabel.sizeToFit() var topCorrection = (self.bounds.size.height - self.contentSize.height * self.zoomScale) / 2.0 topCorrection = max(0, topCorrection) self.placeholderLabel.frame = CGRect(x: 0, y: -topCorrection, width: self.frame.width, height: self.frame.height) self.placeholderLabel.textColor = UIColor(white: 0, alpha: 0.25) self.placeholderLabel.isHidden = !self.text.isEmpty self.addSubview(self.placeholderLabel) } }
apache-2.0
sf-arte/Spica
Spica/Flickr.swift
1
8409
// // Flickr.swift // Spica // // Created by Suita Fujino on 2016/09/28. // Copyright © 2016年 ARTE Co., Ltd. All rights reserved. // import OAuthSwift import SwiftyJSON /** FlickrのAPIを呼ぶクラス */ class Flickr { // MARK: 定数 /// Flickr APIのURL private let apiURL = "https://api.flickr.com/services/rest" /// データ保存用のキー private enum KeyForUserDefaults : String { case oauthToken = "OAuthToken" case oauthTokenSecret = "OAuthTokenSecret" } // MARK: - 構造体 /// Flickrから返ってきたトークン private struct OAuthToken { let token : String let secret : String } /// OAuth認証に必要なパラメータ struct OAuthParams { let consumerKey : String let consumerSecret: String let requestTokenURL = "https://www.flickr.com/services/oauth/request_token" let authorizeURL = "https://www.flickr.com/services/oauth/authorize" let accessTokenURL = "https://www.flickr.com/services/oauth/access_token" init(key: String, secret: String) { consumerKey = key consumerSecret = secret } init?(path: String) { do { let text = try String(contentsOfFile: path, encoding: String.Encoding.utf8) let lines = text.components(separatedBy: CharacterSet.newlines) consumerKey = lines[0] consumerSecret = lines[1] } catch (let error) { log?.error(error) return nil } } } // MARK: - プロパティ private let params : OAuthParams private var oauthSwift : OAuth1Swift private var oauthToken : OAuthToken? { didSet { guard let oauthToken = oauthToken else { return } let defaults = UserDefaults.standard defaults.set(oauthToken.token, forKey: KeyForUserDefaults.oauthToken.rawValue) defaults.set(oauthToken.secret, forKey: KeyForUserDefaults.oauthTokenSecret.rawValue) } } // MARK: - Lifecycle init(params: OAuthParams, loadsToken : Bool = true) { self.params = params oauthSwift = OAuth1Swift( consumerKey: params.consumerKey, consumerSecret: params.consumerSecret, requestTokenUrl: params.requestTokenURL, authorizeUrl: params.authorizeURL, accessTokenUrl: params.accessTokenURL ) oauthToken = nil let defaults = UserDefaults.standard // OAuth Tokenのデータがすでにあればそれを読み込み if let token = defaults.object(forKey: KeyForUserDefaults.oauthToken.rawValue) as? String, let secret = defaults.object(forKey: KeyForUserDefaults.oauthTokenSecret.rawValue) as? String, loadsToken { oauthSwift.client = OAuthSwiftClient( consumerKey: params.consumerKey, consumerSecret: params.consumerSecret, oauthToken: token, oauthTokenSecret: secret, version: .oauth1 ) oauthToken = OAuthToken(token: token, secret: secret) } } // MARK: - メソッド /// flickrのユーザーアカウントを表示して、アプリの認証をする。認証を既にしていた場合は処理を行わない。 /// 成功した場合、consumer keyとconsumer secretを利用してOAuth tokenを取得する。 func authorize() { if oauthToken != nil { return } oauthSwift.authorize( withCallbackURL: URL(string: "Spica://oauth-callback/flickr")!, success: { [weak self] credential, response, parameters in self?.oauthToken = OAuthToken(token: credential.oauthToken, secret: credential.oauthTokenSecret) }, failure: { [weak self] error in self?.onAuthorizationFailed(error: error) } ) } /// 認証失敗時の処理 /// /// - parameter error: エラー内容 func onAuthorizationFailed(error: OAuthSwiftError) { log?.error(error.localizedDescription) } /// 指定された座標周辺の写真をJSON形式で取得し、パースする。パースしたデータはPhotoクラスの配列に格納される。 /// /// TODO: 失敗時の処理。未認証時認証。 /// /// - parameter leftBottom: 写真を検索する範囲の左下の座標 /// - parameter rightTop: 写真を検索する範囲の右上の座標 /// - parameter count: 1回に取得する件数。500件まで /// - parameter handler: パースしたデータに対して実行する処理 /// - parameter text: 検索する文字列 func getPhotos(leftBottom: Coordinates, rightTop: Coordinates, count: Int, text: String?, handler: @escaping ([Photo]) -> ()) { // 東経180度線を跨ぐ時の処理。180度線で2つに分割する if leftBottom.longitude > rightTop.longitude { let leftLongitudeDifference = 180.0 - leftBottom.longitude let rightLongitudeDifference = rightTop.longitude + 180.0 let leftCount = Int(Double(count) * leftLongitudeDifference / (leftLongitudeDifference + rightLongitudeDifference)) let rightCount = count - leftCount getPhotos( leftBottom: leftBottom, rightTop: Coordinates(latitude: rightTop.latitude, longitude: 180.0), count: leftCount, text: text ) { [weak self] leftPhotos in self?.getPhotos( leftBottom: Coordinates(latitude: leftBottom.latitude, longitude: -180.0), rightTop: rightTop, count: rightCount, text: text ) { rightPhotos in handler(leftPhotos + rightPhotos) } } return } var parameters : OAuthSwift.Parameters = [ "api_key" : params.consumerKey, "format" : "json", "bbox" : "\(leftBottom.longitude),\(leftBottom.latitude),\(rightTop.longitude),\(rightTop.latitude)", "method" : "flickr.photos.search", "sort" : "interestingness-desc", // not working "extras" : "geo,owner_name,url_o,url_sq,url_l", "per_page" : count, "nojsoncallback" : 1 ] if let text = text, text != "" { parameters["text"] = text } // UIテスト時はモックサーバーを使う let url = ProcessInfo().arguments.index(of: "--mockserver") == nil ? apiURL : "http://127.0.0.1:4567/rest/" oauthSwift.client.get(url, parameters: parameters, headers: nil, success: { response in let json = JSON(data: response.data) let status = json["stat"].stringValue if status != "ok" { log?.error(json["message"].stringValue) } handler(json["photos"]["photo"].arrayValue.map{ Flickr.decode(from: $0) }) }, failure: { error in log?.error(error) } ) } } extension Flickr { static func decode(from json: JSON) -> Photo { let id = json["id"].intValue let owner = json["owner"].stringValue let ownerName = json["ownername"].stringValue let title = json["title"].stringValue let iconURL = json["url_sq"].stringValue let largeURL = json["url_l"].stringValue let originalURL = json["url_o"].stringValue let coordinates = Coordinates(latitude: json["latitude"].doubleValue, longitude: json["longitude"].doubleValue) return Photo( id: id, owner: owner, ownerName: ownerName, iconURL: iconURL, largeURL: largeURL, originalURL: originalURL, photoTitle: title, coordinate: coordinates ) } }
mit
Legoless/iOS-Course
2015-1/Lesson13/Gamebox/Gamebox/GameManager.swift
3
1607
// // GameManager.swift // Gamebox // // Created by Dal Rupnik on 21/10/15. // Copyright © 2015 Unified Sense. All rights reserved. // import Foundation class GameManager : NSObject { static let shared = GameManager() var games : [Game]? var allGames : [Game] { if games == nil { loadAllGames() } return games! } func addGame (game : Game) { if games == nil { loadAllGames() } games!.append(game) NSNotificationCenter.defaultCenter().postNotificationName("NewGame", object: game) } func save () { guard let games = games else { return } var serializedGames = [AnyObject]() for game in games { serializedGames.append(game.toDictionary()) } NSUserDefaults.standardUserDefaults().setObject(serializedGames, forKey: "AllGames") NSUserDefaults.standardUserDefaults().synchronize() } func loadAllGames () { self.games = loadGames() } private func loadGames () -> [Game] { let serializedGames = NSUserDefaults.standardUserDefaults().objectForKey("AllGames") var games = [Game]() if let serializedGames = serializedGames as? [[String : AnyObject]] { for game in serializedGames { let newGame = Game(dictionary: game) games.append(newGame) } } return games } }
mit
Dynamit/DTCalendarView-iOS
Example/DTCalendarView/ViewController.swift
1
5543
// // ViewController.swift // DTCalendarView // // Created by timle8n1-dynamit on 06/14/2017. // Copyright (c) 2017 timle8n1-dynamit. All rights reserved. // import UIKit import DTCalendarView class ViewController: UIViewController { fileprivate let now = Date() fileprivate let calendar = Calendar.current @IBOutlet private var calendarView: DTCalendarView! { didSet { calendarView.delegate = self calendarView.displayEndDate = Date(timeIntervalSinceNow: 60 * 60 * 24 * 30 * 12 * 2) calendarView.previewDaysInPreviousAndMonth = true calendarView.paginateMonths = true } } fileprivate let monthYearFormatter: DateFormatter = { let formatter = DateFormatter() formatter.timeStyle = .none formatter.dateFormat = "MMMM YYYY" return formatter }() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func viewWillAppear(_ animated: Bool) { let now = Date() calendarView.selectionStartDate = now calendarView.selectionEndDate = now.addingTimeInterval(60 * 60 * 24 * 5) calendarView.scrollTo(month: calendarView.displayEndDate, animated: false) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } fileprivate func currentDate(matchesMonthAndYearOf date: Date) -> Bool { let nowMonth = calendar.component(.month, from: now) let nowYear = calendar.component(.year, from: now) let askMonth = calendar.component(.month, from: date) let askYear = calendar.component(.year, from: date) if nowMonth == askMonth && nowYear == askYear { return true } return false } } extension ViewController: DTCalendarViewDelegate { func calendarView(_ calendarView: DTCalendarView, dragFromDate fromDate: Date, toDate: Date) { if let nowDayOfYear = calendar.ordinality(of: .day, in: .year, for: now), let selectDayOfYear = calendar.ordinality(of :.day, in: .year, for: toDate), selectDayOfYear <= nowDayOfYear { return } if let startDate = calendarView.selectionStartDate, fromDate == startDate { if let endDate = calendarView.selectionEndDate { if toDate < endDate { calendarView.selectionStartDate = toDate } } else { calendarView.selectionStartDate = toDate } } else if let endDate = calendarView.selectionEndDate, fromDate == endDate { if let startDate = calendarView.selectionStartDate { if toDate > startDate { calendarView.selectionEndDate = toDate } } else { calendarView.selectionEndDate = toDate } } } func calendarView(_ calendarView: DTCalendarView, viewForMonth month: Date) -> UIView { let label = UILabel() label.text = monthYearFormatter.string(from: month) label.textColor = UIColor.black label.textAlignment = .center label.backgroundColor = UIColor.white return label } func calendarView(_ calendarView: DTCalendarView, disabledDaysInMonth month: Date) -> [Int]? { if currentDate(matchesMonthAndYearOf: month) { var disabledDays = [Int]() let nowDay = calendar.component(.day, from: now) for day in 1 ... nowDay { disabledDays.append(day) } return disabledDays } return nil } func calendarView(_ calendarView: DTCalendarView, didSelectDate date: Date) { if let nowDayOfYear = calendar.ordinality(of: .day, in: .year, for: now), let selectDayOfYear = calendar.ordinality(of :.day, in: .year, for: date), calendar.component(.year, from: now) == calendar.component(.year, from: date), selectDayOfYear <= nowDayOfYear { return } if calendarView.selectionStartDate == nil { calendarView.selectionStartDate = date } else if calendarView.selectionEndDate == nil { if let startDateValue = calendarView.selectionStartDate { if date <= startDateValue { calendarView.selectionStartDate = date } else { calendarView.selectionEndDate = date } } } else { calendarView.selectionStartDate = date calendarView.selectionEndDate = nil } } func calendarViewHeightForWeekRows(_ calendarView: DTCalendarView) -> CGFloat { return 60 } func calendarViewHeightForWeekdayLabelRow(_ calendarView: DTCalendarView) -> CGFloat { return 50 } func calendarViewHeightForMonthView(_ calendarView: DTCalendarView) -> CGFloat { return 60 } }
mit
herveperoteau/TracktionProto2
TracktionProto2/RealmStack/RealmLayer.swift
1
4570
// // DataModel.swift // TracktionProto2 // // Created by Hervé PEROTEAU on 14/02/2016. // Copyright © 2016 Hervé PEROTEAU. All rights reserved. // import Foundation import RealmSwift let SessionStateInit = 0 let SessionStateKeepData = 1 let SessionStateDataComplete = 2 class RMSession: Object { dynamic var sessionId:Int = 0 dynamic var dateStart: Double = 0 // dateunix dynamic var dateEnd: Double = 0 // dateunix dynamic var countEvents = 0; dynamic var state: Int = SessionStateInit let events = List<RMEvent>() override static func primaryKey() -> String? { return "sessionId" } func stateStr()->String { switch(state) { case SessionStateInit: return "INIT" case SessionStateKeepData: return "KEEPDATA" case SessionStateDataComplete: return "DATACOMPLETE" default : return "???" } } } class RMEvent: Object { dynamic var sessionId: Int = 0 dynamic var x: Double = 0 dynamic var y: Double = 0 dynamic var z: Double = 0 dynamic var dateEvent: Double = 0 // dateunix } class RealmLayer { // MARK: - Mocks func createMockDatas() { // Get the default Realm let realm = try! Realm() let sessions = realm.objects(RMSession) if (sessions.count == 0) { var dateStart = NSDate(timeIntervalSinceNow: -86400).timeIntervalSince1970 var dateEnd = dateStart + 60.0 for (var sessionId=1; sessionId<20; sessionId++) { // Create fake session let trackSession = TrackSession() trackSession.trackSessionId = sessionId trackSession.dateStart = dateStart trackSession.dateEnd = dateEnd saveTrackSession(trackSession) // Create fake events for (var eventId=0; eventId<1000; eventId++) { let item = TrackDataItem() item.trackSessionId = sessionId item.timeStamp = dateStart + (Double)(eventId)/50.0 item.accelerationX = 0.1 + (Double)(eventId)/500.0 item.accelerationY = 0.2 + (Double)(eventId)/300.0 item.accelerationZ = 0.3 + (Double)(eventId)/200.0 saveTrackDataItem(item) } // Update END session trackSession.info = infoEndSession saveTrackSession(trackSession) // Prepare next fake session dateStart = dateEnd + 600 dateEnd = dateStart + 60 } } } // MARK: - Save func saveTrackSession(trackSession: TrackSession) -> RMSession { // Get the default Realm let realm = try! Realm() if (trackSession.info == infoEndSession) { // Query if session exist let session = realm.objects(RMSession).filter("sessionId == \(trackSession.trackSessionId)").first assert(session != nil, "Session \(trackSession.trackSessionId) not exist in Realm !") // Update an object with a transaction try! realm.write { session!.state = SessionStateDataComplete } return session! } // New session let newSession = RMSession() newSession.sessionId = trackSession.trackSessionId newSession.dateStart = trackSession.dateStart newSession.dateEnd = trackSession.dateEnd newSession.state = SessionStateInit // Add to the Realm inside a transaction try! realm.write { realm.add(newSession) } return newSession } func saveTrackDataItem(item: TrackDataItem) { // Get the default Realm let realm = try! Realm() // Query if session exist let session = realm.objects(RMSession).filter("sessionId == \(item.trackSessionId)").first assert(session != nil, "Session \(item.trackSessionId) not exist in Realm !") let eventTrack = RMEvent() eventTrack.sessionId = item.trackSessionId eventTrack.dateEvent = item.timeStamp eventTrack.x = item.accelerationX eventTrack.y = item.accelerationY eventTrack.z = item.accelerationZ // Add to the Realm inside a transaction try! realm.write { // add event realm.add(eventTrack) // Update session event count session!.countEvents++ if (session!.state == SessionStateInit) { session!.state = SessionStateKeepData } } } // MARK: - Query func getListSessions() -> Results<RMSession> { return try! Realm().objects(RMSession) } func getEventsForSession(sessionId: Int) -> Results<RMEvent> { return try! Realm().objects(RMEvent).filter("sessionId == \(sessionId)") } }
mit
EnderTan/ETNavBarTransparent
ETNavBarTransparentDemo/ETNavBarTransparentDemo/MainViewController.swift
1
601
// // MainViewController.swift // ETNavBarTransparentDemo // // Created by Bing on 2017/3/1. // Copyright © 2017年 tanyunbing. All rights reserved. // import UIKit class MainViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Testing for Color NavigationBar // self.navigationController?.navigationBar.barTintColor = .red if #available(iOS 11.0, *) { // Testing for LargeTitlesMode on iOS11 // self.navigationController?.navigationBar.prefersLargeTitles = true } } }
mit
codefellows/sea-c24-iOS-F2
Day 5-8 AutoLayout:Camera:plist:Archiver/AutoLayout/Person.swift
1
1086
// // Person.swift // AutoLayout // // Created by Bradley Johnson on 11/10/14. // Copyright (c) 2014 Code Fellows. All rights reserved. // import Foundation import UIKit class Person : NSObject, NSCoding { var firstName : String var lastName : String var image : UIImage? init (first : String) { self.firstName = first self.lastName = "Doe" } required init(coder aDecoder: NSCoder) { self.firstName = aDecoder.decodeObjectForKey("firstName") as String self.lastName = aDecoder.decodeObjectForKey("lastName") as String if let decodedImage = aDecoder.decodeObjectForKey("image") as? UIImage { self.image = decodedImage } } func encodeWithCoder(aCoder: NSCoder) { aCoder.encodeObject(self.firstName, forKey: "firstName") aCoder.encodeObject(self.lastName, forKey: "lastName") if self.image != nil { aCoder.encodeObject(self.image!, forKey: "image") } else { aCoder.encodeObject(nil, forKey: "image") } } }
mit
crazypoo/PTools
PooToolsSource/SignView/PTEasySignatureView.swift
1
9904
// // PTEasySignatureView.swift // PooTools_Example // // Created by jax on 2022/10/5. // Copyright © 2022 crazypoo. All rights reserved. // import UIKit import SnapKit import SwifterSwift import SJAttributesStringMaker public class PTSignatureConfig:NSObject { public var lineWidth:CGFloat = 1 public var signNavTitleFont:UIFont = UIFont.appfont(size: 12,bold: true) public var signNavTitleColor:UIColor = UIColor.randomColor public var signNavDescFont:UIFont = UIFont.appfont(size: 10) public var signNavDescColor:UIColor = UIColor.randomColor public var signContentTitleFont:UIFont = UIFont.appfont(size: 15,bold: true) public var signContentTitleColor:UIColor = UIColor.randomColor public var signContentDescFont:UIFont = UIFont.appfont(size: 13) public var signContentDescColor:UIColor = UIColor.randomColor public var infoTitle:String = "请在白色区域手写签名" public var infoDesc:String = "正楷,工整书写" public var clearName:String = "清除" public var clearFont:UIFont = .appfont(size: 14) public var clearTextColor:UIColor = .randomColor public var saveName:String = "保存" public var saveFont:UIFont = .appfont(size: 14) public var saveTextColor:UIColor = .randomColor public var navBarColor:UIColor = .randomColor public var signViewBackground:UIColor = .randomColor public var waterMarkMessage:String = "" } public typealias OnSignatureWriteAction = (_ have:Bool) -> Void class PTEasySignatureView: UIView { var viewConfig:PTSignatureConfig! var minFloat:CGFloat = 0 var maxFloat:CGFloat = 0 var previousPoint:CGPoint = .zero var currentPointArr:NSMutableArray = NSMutableArray() var hasSignatureImg:Bool = false var isHaveDraw:Bool = false var onSignatureWriteAction:OnSignatureWriteAction? var touchForce:CGFloat = 0 var isSure:Bool = false var showMessage:String = "" var SignatureImg:UIImage! var path:UIBezierPath! func createPath()->UIBezierPath { let paths = UIBezierPath() paths.lineWidth = self.viewConfig.lineWidth paths.lineCapStyle = .round paths.lineJoinStyle = .round return paths } lazy var infoLabel:UILabel = { let view = UILabel() view.numberOfLines = 0 view.attributedText = NSMutableAttributedString.sj.makeText({ make in if !self.viewConfig.infoTitle.stringIsEmpty() { make.append(self.viewConfig.infoTitle).font(self.viewConfig.signContentTitleFont).textColor(self.viewConfig.signContentTitleColor).lineSpacing(CGFloat.ScaleW(w: 4.5)).alignment(.center) } if !self.viewConfig.infoDesc.stringIsEmpty() { make.append("\n\(self.viewConfig.infoDesc)").font(self.viewConfig.signContentDescFont).textColor(self.viewConfig.signContentDescColor).alignment(.center) } }) view.textAlignment = .center return view }() init(viewConfig:PTSignatureConfig) { self.viewConfig = viewConfig super.init(frame: .zero) self.commonInit() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } func midPoint(p0:CGPoint,p1:CGPoint)->CGPoint { return CGPoint(x: (p0.x + p1.x) / 2, y: (p0.y + p1.y) / 2) } func check3DTouch()->Bool { return self.traitCollection.forceTouchCapability == .available } func commonInit() { self.backgroundColor = self.viewConfig.signViewBackground self.path = self.createPath() let pan = UIPanGestureRecognizer.init { sender in let senderPan = (sender as! UIPanGestureRecognizer) let currentPoint = senderPan.location(in: self) let midPoint = self.midPoint(p0: self.previousPoint, p1: currentPoint) self.currentPointArr.add(NSValue.init(cgPoint: currentPoint)) self.hasSignatureImg = true let viewHeight = self.frame.size.height let currentY = currentPoint.y switch senderPan.state { case .began: self.path.move(to: currentPoint) case .changed: self.path.addQuadCurve(to: midPoint, controlPoint: self.previousPoint) default:break } if currentY >= 0 && viewHeight >= currentY { if self.maxFloat == 0 && self.minFloat == 0 { self.maxFloat = currentPoint.x self.minFloat = currentPoint.x } else { if currentPoint.x >= self.maxFloat { self.maxFloat = currentPoint.x } if self.minFloat >= currentPoint.x { self.minFloat = currentPoint.x } } } self.previousPoint = currentPoint self.setNeedsDisplay() self.isHaveDraw = true if self.onSignatureWriteAction != nil { self.onSignatureWriteAction!(true) } } pan.minimumNumberOfTouches = 1 pan.maximumNumberOfTouches = 1 self.addGestureRecognizer(pan) self.addSubview(self.infoLabel) self.infoLabel.snp.makeConstraints { make in make.centerY.centerX.equalToSuperview() } } override func draw(_ rect: CGRect) { if self.check3DTouch() { UIColor(white: 0, alpha: self.viewConfig.lineWidth * (1 - self.touchForce)).setStroke() } else { UIColor.black.setStroke() } self.path.stroke() if !self.isSure && !self.isHaveDraw { self.infoLabel.isHidden = false } else { self.infoLabel.isHidden = true self.isSure = false } } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { let touche = touches.first if self.check3DTouch() { self.touchForce = touche!.force } } override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { let touche = touches.first if self.check3DTouch() { self.touchForce = touche!.force } } func clearSign() { if self.currentPointArr.count > 0 { self.currentPointArr.removeAllObjects() } self.hasSignatureImg = false self.maxFloat = 0 self.minFloat = 0 self.isHaveDraw = false self.path = self.createPath() self.setNeedsDisplay() if self.onSignatureWriteAction != nil { self.onSignatureWriteAction!(false) } } func saveSign() { if self.minFloat == 0 && self.maxFloat == 0 { self.minFloat = 0 self.maxFloat = 0 } self.isSure = true self.setNeedsDisplay() self.imageRepresentation() } func scaleToSize(image:UIImage)->UIImage { let rect:CGRect = CGRect(x: 0, y: 0, width: image.size.width, height: self.frame.size.height) UIGraphicsBeginImageContext(rect.size) image.draw(in: rect) let scaledImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() self.setNeedsDisplay() return scaledImage! } func cutImage(image:UIImage)->UIImage { var rect:CGRect! if self.minFloat == 0 && self.maxFloat == 0 { rect = .zero } else { rect = CGRect(x: self.minFloat - 3, y: 0, width: self.maxFloat - self.minFloat + 6, height: self.frame.size.height) } let imageRef = image.cgImage!.cropping(to: rect) let img = UIImage(cgImage: imageRef!) let lastImage = self.addText(image: img, text: self.showMessage) self.setNeedsDisplay() return lastImage } func addText(image:UIImage,text:String)->UIImage { let imageW = image.size.width let imageH = image.size.height let textFont = self.viewConfig.signContentTitleFont let sizeToFit = text.nsString.boundingRect(with: CGSize(width: 128, height: 30),options: NSStringDrawingOptions.usesLineFragmentOrigin,attributes: [NSAttributedString.Key.font:textFont], context: nil).size UIGraphicsBeginImageContext(image.size) UIColor.red.set() image.draw(in: CGRect(x: 0, y: 0, width: imageW, height: imageH)) text.nsString.draw(in: CGRect(x: (imageW - sizeToFit.width) / 2, y: (imageH - sizeToFit.height) / 2, width: sizeToFit.width, height: sizeToFit.height),withAttributes: [NSAttributedString.Key.font:textFont]) let aimage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return aimage! } func imageRepresentation() { UIGraphicsBeginImageContextWithOptions(self.bounds.size, false, UIScreen.main.scale) self.layer.render(in: UIGraphicsGetCurrentContext()!) var images:UIImage = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() images = PTImageBlackToTransparent.imageBlack(toTransparent: images) if self.showMessage.stringIsEmpty() { self.SignatureImg = self.scaleToSize(image: images) } else { let img = self.cutImage(image: images) self.SignatureImg = self.scaleToSize(image: img) } } }
mit
thehorbach/instagram-clone
Pods/SwiftKeychainWrapper/SwiftKeychainWrapper/KeychainItemAccessibility.swift
1
6158
// // KeychainOptions.swift // SwiftKeychainWrapper // // Created by James Blair on 4/24/16. // Copyright © 2016 Jason Rendel. All rights reserved. // // The MIT License (MIT) // // 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 protocol KeychainAttrRepresentable { var keychainAttrValue: CFString { get } } // MARK: - KeychainItemAccessibility public enum KeychainItemAccessibility { /** The data in the keychain item cannot be accessed after a restart until the device has been unlocked once by the user. After the first unlock, the data remains accessible until the next restart. This is recommended for items that need to be accessed by background applications. Items with this attribute migrate to a new device when using encrypted backups. */ @available(iOS 4, *) case afterFirstUnlock /** The data in the keychain item cannot be accessed after a restart until the device has been unlocked once by the user. After the first unlock, the data remains accessible until the next restart. This is recommended for items that need to be accessed by background applications. Items with this attribute do not migrate to a new device. Thus, after restoring from a backup of a different device, these items will not be present. */ @available(iOS 4, *) case afterFirstUnlockThisDeviceOnly /** The data in the keychain item can always be accessed regardless of whether the device is locked. This is not recommended for application use. Items with this attribute migrate to a new device when using encrypted backups. */ @available(iOS 4, *) case always /** The data in the keychain can only be accessed when the device is unlocked. Only available if a passcode is set on the device. This is recommended for items that only need to be accessible while the application is in the foreground. Items with this attribute never migrate to a new device. After a backup is restored to a new device, these items are missing. No items can be stored in this class on devices without a passcode. Disabling the device passcode causes all items in this class to be deleted. */ @available(iOS 8, *) case whenPasscodeSetThisDeviceOnly /** The data in the keychain item can always be accessed regardless of whether the device is locked. This is not recommended for application use. Items with this attribute do not migrate to a new device. Thus, after restoring from a backup of a different device, these items will not be present. */ @available(iOS 4, *) case alwaysThisDeviceOnly /** The data in the keychain item can be accessed only while the device is unlocked by the user. This is recommended for items that need to be accessible only while the application is in the foreground. Items with this attribute migrate to a new device when using encrypted backups. This is the default value for keychain items added without explicitly setting an accessibility constant. */ @available(iOS 4, *) case whenUnlocked /** The data in the keychain item can be accessed only while the device is unlocked by the user. This is recommended for items that need to be accessible only while the application is in the foreground. Items with this attribute do not migrate to a new device. Thus, after restoring from a backup of a different device, these items will not be present. */ @available(iOS 4, *) case whenUnlockedThisDeviceOnly static func accessibilityForAttributeValue(_ keychainAttrValue: CFString) -> KeychainItemAccessibility? { for (key, value) in keychainItemAccessibilityLookup { if value == keychainAttrValue { return key } } return nil } } private let keychainItemAccessibilityLookup: [KeychainItemAccessibility:CFString] = { var lookup: [KeychainItemAccessibility:CFString] = [ .afterFirstUnlock: kSecAttrAccessibleAfterFirstUnlock, .afterFirstUnlockThisDeviceOnly: kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly, .always: kSecAttrAccessibleAlways, .alwaysThisDeviceOnly : kSecAttrAccessibleAlwaysThisDeviceOnly, .whenUnlocked: kSecAttrAccessibleWhenUnlocked, .whenUnlockedThisDeviceOnly: kSecAttrAccessibleWhenUnlockedThisDeviceOnly ] // INFO: While this framework only supports iOS 8 and up, the files themselves can be pulled directly into an iOS 7 project and work fine as long as this #available check is in place. Unfortunately, this also generates a warning in the framework project for now. if #available(iOSApplicationExtension 8, *) { lookup[.whenPasscodeSetThisDeviceOnly] = kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly } return lookup }() extension KeychainItemAccessibility : KeychainAttrRepresentable { internal var keychainAttrValue: CFString { return keychainItemAccessibilityLookup[self]! } }
mit
soapyigu/LeetCode_Swift
DFS/CombinationSum.swift
1
953
/** * Question Link: https://leetcode.com/problems/combination-sum/ * Primary idea: Classic Depth-first Search * * Time Complexity: O(n^n), Space Complexity: O(2^n - 1) * */ class CombinationSum { func combinationSum(candidates: [Int], _ target: Int) -> [[Int]] { var res = [[Int]]() var path = [Int]() _dfs(candidates.sorted(by: <), target, &res, &path, 0) return res } private func _dfs(candidates: [Int], _ target: Int, inout _ res: [[Int]], inout _ path: [Int], _ index: Int) { if target == 0 { res.append(Array(path)) return } for i in index..<candidates.count { guard candidates[i] <= target else { break } path.append(candidates[i]) _dfs(candidates, target - candidates[i], &res, &path, i) path.removeLast() } } }
mit
coolmacmaniac/swift-ios
rw/BullsEye/BullsEye/ViewController.swift
1
3219
// // ViewController.swift // BullsEye // // Created by Sourabh on 11/03/18. // Copyright © 2018 Home. All rights reserved. // import UIKit class ViewController: UIViewController { var targetValue = 0 var currentValue = 0 var score = 0 var round = 0 @IBOutlet weak var slider: UISlider! @IBOutlet weak var targetLabel: UILabel! @IBOutlet weak var scoreLabel: UILabel! @IBOutlet weak var roundLabel: UILabel! //Drongo@123 override func viewDidLoad() { super.viewDidLoad() customizeSlider() startNewGame() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func sliderMoved(_ slider: UISlider) { currentValue = lroundf(slider.value) //print("Val: \(slider.value), Int: \(Int(slider.value)), lroundf: \(lroundf(slider.value))") } @IBAction func showAlert(_ sender: UIButton) { let difference = abs(targetValue - currentValue) var points = 100 - difference // bonus points if difference == 0 { points += 100 // 100 extra bonus } else if difference == 1 { points += 50 // 50 extra bonus } // compute overall score score += points let title: String if difference == 0 { title = "Perfect!!" } else if difference < 5 { title = "You almost had it!" } else if difference < 10 { title = "Pretty good!" } else { title = "Oh! that wasn't close..." } let alert = UIAlertController( title: title, message: "You scored \(points) points", preferredStyle: .alert) let action = UIAlertAction( title: "Close", style: .default, handler: popupHandler) alert.addAction(action) self.present(alert, animated: true, completion: nil) } @IBAction func startNewGame() { currentValue = 0 score = 0 round = 0 startNewRound() } // MARK: - func customizeSlider() { let thumbImageNormal = #imageLiteral(resourceName: "SliderThumb-Normal") // UIImage(named: "SliderThumb-Normal") slider.setThumbImage(thumbImageNormal, for: .normal) let thumbImageHighlighted = #imageLiteral(resourceName: "SliderThumb-Highlighted") // UIImage(named: "SliderThumb-Highlighted") slider.setThumbImage(thumbImageHighlighted, for: .highlighted) let insets = UIEdgeInsets(top: 0, left: 14, bottom: 0, right: 14) let trackLeftImage = #imageLiteral(resourceName: "SliderTrackLeft") // UIImage(named: "SliderTrackLeft") let trackLeftResizable = trackLeftImage.resizableImage(withCapInsets: insets) slider.setMinimumTrackImage(trackLeftResizable, for: .normal) let trackRightImage = #imageLiteral(resourceName: "SliderTrackRight") // UIImage(named: "SliderTrackRight") let trackRightResizable = trackRightImage.resizableImage(withCapInsets: insets) slider.setMaximumTrackImage(trackRightResizable, for: .normal) } func popupHandler(_ action: UIAlertAction) { startNewRound() } func updateLabels() { targetLabel.text = String(targetValue) scoreLabel.text = String(score) roundLabel.text = String(round) } func startNewRound() { round += 1 targetValue = 1 + Int(arc4random_uniform(100)) currentValue = 50 slider.value = Float(currentValue) updateLabels() } }
gpl-3.0
ostatnicky/kancional-ios
Cancional/UI/Song Detail/AppereanceThemeButton.swift
1
1524
// // AppereanceColorButton.swift // Cancional // // Created by Jiri Ostatnicky on 11/06/2017. // Copyright © 2017 Jiri Ostatnicky. All rights reserved. // import UIKit class AppearanceThemeButton: UIButton { @objc var theme: AppearanceTheme? override var isSelected: Bool { didSet { if isSelected { setSelectedBorder() } else { setNormalBorder() } } } override var isHighlighted: Bool { didSet { isSelected = !isHighlighted } } // MARK: - Life cycle override func awakeFromNib() { super.awakeFromNib() setupUI() } func configure(theme: AppearanceTheme) { self.theme = theme updateUI() } } private extension AppearanceThemeButton { func setupUI() { clipsToBounds = true layer.cornerRadius = 44/2 setNormalBorder() } func updateUI() { guard let theme = theme else { return } let color = UIColor(hexString: theme.backgroundColor) backgroundColor = color setBackgroundImage(UIImage.init(color: color), for: .normal) } func setNormalBorder() { layer.borderColor = UIColor.black.withAlphaComponent(0.3).cgColor layer.borderWidth = 0.5 } func setSelectedBorder() { layer.borderColor = UIColor.Cancional.tintColor().cgColor layer.borderWidth = 6 } }
mit
safx/MioDashboard-swift
MioDashboard-swift WatchKit Extension/InterfaceController.swift
1
5741
// // InterfaceController.swift // MioDashboard-swift WatchKit Extension // // Created by Safx Developer on 2015/05/17. // Copyright (c) 2015年 Safx Developers. All rights reserved. // import WatchKit import Foundation import IIJMioKit class TableRow : NSObject { @IBOutlet weak var hddServiceCode: WKInterfaceLabel! @IBOutlet weak var couponTotal: WKInterfaceLabel! @IBOutlet weak var couponUsedToday: WKInterfaceLabel! var model: MIOCouponInfo_s! { didSet { let f = createByteCountFormatter() hddServiceCode.setText(model!.hddServiceCode) couponTotal.setText(f.stringFromByteCount(Int64(model!.totalCouponVolume) * 1000 * 1000)) couponUsedToday.setText(f.stringFromByteCount(Int64(model!.couponUsedToday) * 1000 * 1000)) } } } class InterfaceController: WKInterfaceController { @IBOutlet weak var table: WKInterfaceTable! @IBOutlet weak var additionalInfo: WKInterfaceLabel! private var model: [MIOCouponInfo_s] = [] private var lastUpdated: NSDate? override func awakeWithContext(context: AnyObject?) { MIORestClient.sharedClient.setUp() super.awakeWithContext(context) restoreSavedInfo { m, date in self.model = m self.lastUpdated = date self.setTableData(model) } } override func willActivate() { // This method is called when watch view controller is about to be visible to user super.willActivate() if let d = lastUpdated where NSDate().timeIntervalSinceDate(d) < 300 { return } loadTableData() } override func didDeactivate() { // This method is called when watch view controller is no longer visible super.didDeactivate() } override func contextForSegueWithIdentifier(segueIdentifier: String, inTable table: WKInterfaceTable, rowIndex: Int) -> AnyObject? { precondition(segueIdentifier == "detail") return rowIndex < model.count ? self.model[rowIndex] : nil } private func loadTableData() { let client = MIORestClient.sharedClient if !client.authorized { let status = client.loadAccessToken() if status != .Success { additionalInfo.setText(status.rawValue) return } } client.getMergedInfo { [weak self] (response, error) -> Void in if let e = error { self?.additionalInfo.setText("Error: \(e.code) \(e.description)") } else if let r = response { if r.returnCode != "OK" { self?.additionalInfo.setText(r.returnCode) } else { if let s = self { let m = r.couponInfo!.map{ MIOCouponInfo_s(info: $0) } s.setTableData(m) s.additionalInfo.setText("") s.lastUpdated = NSDate() saveInfo(m, lastUpdated: s.lastUpdated!) } } } else { self?.additionalInfo.setText("No response") } } } private func setTableData(cs: [MIOCouponInfo_s]) { if cs.isEmpty { self.additionalInfo.setText("No data") return } table.setNumberOfRows(cs.count, withRowType: "default") for (i, c) in cs.enumerate() { if let row = table.rowControllerAtIndex(i) as? TableRow { row.model = c } } model = cs } // TODO: use other RowType private func setErrorData(reason: String) { table.setNumberOfRows(1, withRowType: "default") if let row = table.rowControllerAtIndex(0) as? TableRow { row.hddServiceCode.setText(reason) row.couponTotal.setText("Error") row.couponUsedToday.setText("") } } // TODO: use other RowType private func setErrorData(reason: NSError) { table.setNumberOfRows(1, withRowType: "default") if let row = table.rowControllerAtIndex(0) as? TableRow { row.hddServiceCode.setText("\(reason.domain)") row.couponTotal.setText("\(reason.code)") row.couponUsedToday.setText("\(reason.description)") } } } class DetailTableRow : NSObject { @IBOutlet weak var number: WKInterfaceLabel! @IBOutlet weak var couponUsedToday: WKInterfaceLabel! var model: MIOCouponHdoInfo_s! { didSet { let f = createByteCountFormatter() number.setText(model!.phoneNumber) couponUsedToday.setText(f.stringFromByteCount(Int64(model!.couponUsedToday) * 1000 * 1000)) } } } class DetailInterfaceController: WKInterfaceController { @IBOutlet weak var table: WKInterfaceTable! override func awakeWithContext(context: AnyObject?) { super.awakeWithContext(context) if let m = context as? MIOCouponInfo_s { setTableData(m) } } override func willActivate() { // This method is called when watch view controller is about to be visible to user super.willActivate() } override func didDeactivate() { // This method is called when watch view controller is no longer visible super.didDeactivate() } private func setTableData(model: MIOCouponInfo_s) { let cs = model.hdoInfo table.setNumberOfRows(cs.count, withRowType: "default") for (i, c) in cs.enumerate() { if let row = table.rowControllerAtIndex(i) as? DetailTableRow { row.model = c } } } }
mit
ps2/rileylink_ios
MinimedKitTests/GlucoseEvents/GlucoseSensorDataGlucoseEventTests.swift
1
529
// // GlucoseSensorDataGlucoseEventTests.swift // RileyLink // // Created by Timothy Mecklem on 10/18/16. // Copyright © 2016 Pete Schwamb. All rights reserved. // import XCTest @testable import MinimedKit class GlucoseSensorDataGlucoseEventTests: XCTestCase { func testDecoding() { let rawData = Data(hexadecimalString: "35")! let subject = GlucoseSensorDataGlucoseEvent(availableData: rawData, relativeTimestamp: DateComponents())! XCTAssertEqual(subject.sgv, 106) } }
mit
seeRead/roundware-ios-framework-v2
Pod/Classes/RWFrameworkHTTP.swift
1
26066
// // RWFrameworkHTTP.swift // RWFramework // // Created by Joe Zobkiw on 2/6/15. // Copyright (c) 2015 Roundware. All rights reserved. // import Foundation import MobileCoreServices extension RWFramework: URLSessionDelegate, URLSessionTaskDelegate, URLSessionDataDelegate /*, NSURLSessionDownloadDelegate */ { func httpPostUsers(device_id: String, client_type: String, completion:@escaping (_ data: NSData?, _ error: NSError?) -> Void) { if let url = NSURL(string: RWFrameworkURLFactory.postUsersURL()) { let postData = ["device_id": device_id, "client_type": client_type] postDataToURL(url: url, postData: postData, completion: completion) } else { let error = NSError(domain:self.reverse_domain, code:NSURLErrorBadURL, userInfo:[NSLocalizedDescriptionKey : "postUsersURL unable to be created."]) completion(nil, error) } } func httpPostSessions(project_id: String, timezone: String, client_system: String, language: String, completion:@escaping (_ data: NSData?, _ error: NSError?) -> Void) { if let url = NSURL(string: RWFrameworkURLFactory.postSessionsURL()) { let postData = ["project_id": project_id, "timezone": timezone, "client_system": client_system, "language": language] postDataToURL(url: url, postData: postData, completion: completion) } else { let error = NSError(domain:self.reverse_domain, code:NSURLErrorBadURL, userInfo:[NSLocalizedDescriptionKey : "postSessionsURL unable to be created."]) completion(nil, error) } } func httpGetProjectsId(project_id: String, session_id: String, completion:@escaping (_ data: NSData?, _ error: NSError?) -> Void) { if let url = NSURL(string: RWFrameworkURLFactory.getProjectsIdURL(project_id: project_id, session_id: session_id)) { getDataFromURL(url: url, completion: completion) } else { let error = NSError(domain:self.reverse_domain, code:NSURLErrorBadURL, userInfo:[NSLocalizedDescriptionKey : "getProjectsIdURL unable to be created."]) completion(nil, error) } } func httpGetProjectsIdTags(project_id: String, session_id: String, completion:@escaping (_ data: NSData?, _ error: NSError?) -> Void) { if let url = NSURL(string: RWFrameworkURLFactory.getProjectsIdTagsURL(project_id: project_id, session_id: session_id)) { getDataFromURL(url: url, completion: completion) } else { let error = NSError(domain:self.reverse_domain, code:NSURLErrorBadURL, userInfo:[NSLocalizedDescriptionKey : "getProjectsIdTagsURL unable to be created."]) completion(nil, error) } } func httpGetProjectsIdUIGroups(project_id: String, session_id: String, completion:@escaping (_ data: NSData?, _ error: NSError?) -> Void) { if let url = NSURL(string: RWFrameworkURLFactory.getProjectsIdUIGroupsURL(project_id: project_id, session_id: session_id)) { getDataFromURL(url: url, completion: completion) } else { let error = NSError(domain:self.reverse_domain, code:NSURLErrorBadURL, userInfo:[NSLocalizedDescriptionKey : "getProjectsIdUIGroupsURL unable to be created."]) completion(nil, error) } } func httpPostStreams(session_id: String, latitude: String?, longitude: String?, completion:@escaping (_ data: NSData?, _ error: NSError?) -> Void) { if let url = NSURL(string: RWFrameworkURLFactory.postStreamsURL()) { var postData = ["session_id": session_id] if let ourLatitude = latitude, let ourLongitude = longitude { postData["latitude"] = ourLatitude postData["longitude"] = ourLongitude } postDataToURL(url: url, postData: postData, completion: completion) } else { let error = NSError(domain:self.reverse_domain, code:NSURLErrorBadURL, userInfo:[NSLocalizedDescriptionKey : "postStreamsURL unable to be created."]) completion(nil, error) } } func httpPatchStreamsId(stream_id: String, latitude: String, longitude: String, completion:@escaping (_ data: NSData?, _ error: NSError?) -> Void) { if let url = NSURL(string: RWFrameworkURLFactory.patchStreamsIdURL(stream_id: stream_id)) { let postData = ["latitude": latitude, "longitude": longitude] patchDataToURL(url: url, postData: postData, completion: completion) } else { let error = NSError(domain:self.reverse_domain, code:NSURLErrorBadURL, userInfo:[NSLocalizedDescriptionKey : "patchStreamsIdURL unable to be created."]) completion(nil, error) } } func httpPatchStreamsId(stream_id: String, tag_ids: String, completion:@escaping (_ data: NSData?, _ error: NSError?) -> Void) { if let url = NSURL(string: RWFrameworkURLFactory.patchStreamsIdURL(stream_id: stream_id)) { let postData = ["tag_ids": tag_ids] patchDataToURL(url: url, postData: postData, completion: completion) } else { let error = NSError(domain:self.reverse_domain, code:NSURLErrorBadURL, userInfo:[NSLocalizedDescriptionKey : "patchStreamsIdURL unable to be created."]) completion(nil, error) } } func httpPostStreamsIdHeartbeat(stream_id: String, completion:@escaping (_ data: NSData?, _ error: NSError?) -> Void) { if let url = NSURL(string: RWFrameworkURLFactory.postStreamsIdHeartbeatURL(stream_id: stream_id)) { let postData = [:] as Dictionary<String, String> postDataToURL(url: url, postData: postData, completion: completion) } else { let error = NSError(domain:self.reverse_domain, code:NSURLErrorBadURL, userInfo:[NSLocalizedDescriptionKey : "postStreamsIdHeartbeatURL unable to be created."]) completion(nil, error) } } func httpPostStreamsIdSkip(stream_id: String, completion:@escaping (_ data: NSData?, _ error: NSError?) -> Void) { if let url = NSURL(string: RWFrameworkURLFactory.postStreamsIdSkipURL(stream_id: stream_id)) { let postData = [:] as Dictionary<String, String> postDataToURL(url: url, postData: postData, completion: completion) } else { let error = NSError(domain:self.reverse_domain, code:NSURLErrorBadURL, userInfo:[NSLocalizedDescriptionKey : "postStreamsIdSkipURL unable to be created."]) completion(nil, error) } } func httpPostStreamsIdPlayAsset(stream_id: String, asset_id: String, completion:@escaping (_ data: NSData?, _ error: NSError?) -> Void) { if let url = NSURL(string: RWFrameworkURLFactory.postStreamsIdPlayAssetURL(stream_id: stream_id)) { let postData = ["asset_id": asset_id] as Dictionary<String, String> postDataToURL(url: url, postData: postData, completion: completion) } else { let error = NSError(domain:self.reverse_domain, code:NSURLErrorBadURL, userInfo:[NSLocalizedDescriptionKey : "postStreamsIdPlayAssetURL unable to be created."]) completion(nil, error) } } func httpPostStreamsIdReplayAsset(stream_id: String, completion:@escaping (_ data: NSData?, _ error: NSError?) -> Void) { if let url = NSURL(string: RWFrameworkURLFactory.postStreamsIdReplayAssetURL(stream_id: stream_id)) { let postData = [:] as Dictionary<String, String> postDataToURL(url: url, postData: postData, completion: completion) } else { let error = NSError(domain:self.reverse_domain, code:NSURLErrorBadURL, userInfo:[NSLocalizedDescriptionKey : "postStreamsIdReplayAssetURL unable to be created."]) completion(nil, error) } } func httpPostStreamsIdPause(stream_id: String, completion:@escaping (_ data: NSData?, _ error: NSError?) -> Void) { if let url = NSURL(string: RWFrameworkURLFactory.postStreamsIdPauseURL(stream_id: stream_id)) { let postData = [:] as Dictionary<String, String> postDataToURL(url: url, postData: postData, completion: completion) } else { let error = NSError(domain:self.reverse_domain, code:NSURLErrorBadURL, userInfo:[NSLocalizedDescriptionKey : "postStreamsIdPauseURL unable to be created."]) completion(nil, error) } } func httpPostStreamsIdResume(stream_id: String, completion:@escaping (_ data: NSData?, _ error: NSError?) -> Void) { if let url = NSURL(string: RWFrameworkURLFactory.postStreamsIdResumeURL(stream_id: stream_id)) { let postData = [:] as Dictionary<String, String> postDataToURL(url: url, postData: postData, completion: completion) } else { let error = NSError(domain:self.reverse_domain, code:NSURLErrorBadURL, userInfo:[NSLocalizedDescriptionKey : "postStreamsIdResumeURL unable to be created."]) completion(nil, error) } } func httpGetStreamsIdCurrent(stream_id: String, completion:@escaping (_ data: NSData?, _ error: NSError?) -> Void) { if let url = NSURL(string: RWFrameworkURLFactory.getStreamsIdCurrentURL(stream_id: stream_id)) { getDataFromURL(url: url, completion: completion) } else { let error = NSError(domain:self.reverse_domain, code:NSURLErrorBadURL, userInfo:[NSLocalizedDescriptionKey : "getStreamsIdCurrentURL unable to be created."]) completion(nil, error) } } func httpPostEnvelopes(session_id: String, completion:@escaping (_ data: NSData?, _ error: NSError?) -> Void) { if let url = NSURL(string: RWFrameworkURLFactory.postEnvelopesURL()) { let postData = ["session_id": session_id] postDataToURL(url: url, postData: postData, completion: completion) } else { let error = NSError(domain:self.reverse_domain, code:NSURLErrorBadURL, userInfo:[NSLocalizedDescriptionKey : "postEnvelopesURL unable to be created."]) completion(nil, error) } } func httpPatchEnvelopesId(media: Media, session_id: String, completion:@escaping (_ data: NSData?, _ error: NSError?) -> Void) { if let url = NSURL(string: RWFrameworkURLFactory.patchEnvelopesIdURL(envelope_id: media.envelopeID.stringValue)) { let serverMediaType = mapMediaTypeToServerMediaType(mediaType: media.mediaType) let postData = ["session_id": session_id, "media_type": serverMediaType.rawValue, "latitude": media.latitude.stringValue, "longitude": media.longitude.stringValue, "tag_ids": media.tagIDs, "description": media.desc] patchFileAndDataToURL(url: url, filePath: media.string, postData: postData, completion: completion) } else { let error = NSError(domain:self.reverse_domain, code:NSURLErrorBadURL, userInfo:[NSLocalizedDescriptionKey : "httpPatchEnvelopesId unable to be created."]) completion(nil, error) } } func httpGetAssets(dict: [String:String], completion:@escaping (_ data: NSData?, _ error: NSError?) -> Void) { if let url = NSURL(string: RWFrameworkURLFactory.getAssetsURL(dict: dict)) { getDataFromURL(url: url, completion: completion) } else { let error = NSError(domain:self.reverse_domain, code:NSURLErrorBadURL, userInfo:[NSLocalizedDescriptionKey : "httpGetAssets unable to be created."]) completion(nil, error) } } func httpGetAssetsId(asset_id: String, completion:@escaping (_ data: NSData?, _ error: NSError?) -> Void) { if let url = NSURL(string: RWFrameworkURLFactory.getAssetsIdURL(asset_id: asset_id)) { getDataFromURL(url: url, completion: completion) } else { let error = NSError(domain:self.reverse_domain, code:NSURLErrorBadURL, userInfo:[NSLocalizedDescriptionKey : "httpGetAssetsId unable to be created."]) completion(nil, error) } } func httpPostAssetsIdVotes(asset_id: String, session_id: String, vote_type: String, value: NSNumber = 0, completion:@escaping (_ data: NSData?, _ error: NSError?) -> Void) { if let url = NSURL(string: RWFrameworkURLFactory.postAssetsIdVotesURL(asset_id: asset_id)) { let postData = ["session_id": session_id, "vote_type": vote_type, "value": value.stringValue] postDataToURL(url: url, postData: postData, completion: completion) } else { let error = NSError(domain:self.reverse_domain, code:NSURLErrorBadURL, userInfo:[NSLocalizedDescriptionKey : "postAssetsIdVotesURL unable to be created."]) completion(nil, error) } } func httpGetAssetsIdVotes(asset_id: String, completion:@escaping (_ data: NSData?, _ error: NSError?) -> Void) { if let url = NSURL(string: RWFrameworkURLFactory.getAssetsIdVotesURL(asset_id: asset_id)) { getDataFromURL(url: url, completion: completion) } else { let error = NSError(domain:self.reverse_domain, code:NSURLErrorBadURL, userInfo:[NSLocalizedDescriptionKey : "getAssetsIdVotesURL unable to be created."]) completion(nil, error) } } func httpPostEvents(session_id: String, event_type: String, data: String?, latitude: String, longitude: String, client_time: String, tag_ids: String, completion:@escaping (_ data: NSData?, _ error: NSError?) -> Void) { if let url = NSURL(string: RWFrameworkURLFactory.postEventsURL()) { let postData = ["session_id": session_id, "event_type": event_type, "data": data ?? "", "latitude": latitude, "longitude": longitude, "client_time": client_time, "tag_ids": tag_ids] postDataToURL(url: url, postData: postData, completion: completion) } else { let error = NSError(domain:self.reverse_domain, code:NSURLErrorBadURL, userInfo:[NSLocalizedDescriptionKey : "postEventsURL unable to be created."]) completion(nil, error) } } // MARK: - Generic functions // Upload file and load data via PATCH and return in completion with or without error func patchFileAndDataToURL(url: NSURL, filePath: String, postData: Dictionary<String,String>, completion:@escaping (_ data: NSData?, _ error: NSError?) -> Void) { // println(object: "patchFileAndDataToURL: " + url.absoluteString + " filePath = " + filePath + " postData = " + postData.description) // Multipart/form-data boundary func makeBoundary() -> String { let uuid = NSUUID().uuidString return "Boundary-\(uuid)" } let boundary = makeBoundary() // Mime type var mimeType: String { get { let pathExtension = (filePath as NSString).pathExtension let UTI = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, pathExtension as CFString, nil) let str = UTTypeCopyPreferredTagWithClass(UTI!.takeRetainedValue(), kUTTagClassMIMEType) if (str == nil) { return "application/octet-stream" } else { return str!.takeUnretainedValue() as String } } } let session = URLSession.shared let request = NSMutableURLRequest(url: url as URL) request.httpMethod = "PATCH" // Token let token = RWFrameworkConfig.getConfigValueAsString(key: "token", group: RWFrameworkConfig.ConfigGroup.Client) if token.lengthOfBytes(using: String.Encoding.utf8) > 0 { request.addValue("token \(token)", forHTTPHeaderField: "Authorization") } // Multipart/form-data request.addValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type") var error: NSError? let fileData: NSData? do { fileData = try NSData(contentsOfFile: filePath, options: NSData.ReadingOptions.alwaysMapped) } catch let error1 as NSError { error = error1 fileData = nil } if (fileData == nil || error != nil) { completion(nil, error) return } // The actual Multipart/form-data content let data = NSMutableData() data.append("--\(boundary)\r\n".data(using: String.Encoding.utf8, allowLossyConversion: false)!) let fileName = (filePath as NSString).lastPathComponent data.append("Content-Disposition: form-data; name=\"file\"; filename=\"\(fileName)\"\r\n".data(using: String.Encoding.utf8, allowLossyConversion: false)!) data.append("Content-Type: \(mimeType)\r\n".data(using: String.Encoding.utf8, allowLossyConversion: false)!) println(object: "mimeType = \(mimeType)") data.append("\r\n".data(using: String.Encoding.utf8, allowLossyConversion: false)!) data.append(fileData! as Data) data.append("\r\n".data(using: String.Encoding.utf8, allowLossyConversion: false)!) for (key, value) in postData { if (value.lengthOfBytes(using: String.Encoding.utf8) > 0) { data.append("--\(boundary)\r\n".data(using: String.Encoding.utf8, allowLossyConversion: false)!) data.append("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n\(value)\r\n".data(using: String.Encoding.utf8, allowLossyConversion: false)!) } } data.append("--\(boundary)--\r\n".data(using: String.Encoding.utf8, allowLossyConversion: false)!) let uploadTask = session.uploadTask(with: request as URLRequest, from: data as Data, completionHandler: { (data: Data?, response: URLResponse?, error: Error?) -> Void in if let errorResponse = error { completion(nil, errorResponse as NSError?) } else if let httpResponse = response as? HTTPURLResponse { if httpResponse.statusCode == 200 { completion(data as NSData?, nil) } else { let error = NSError(domain:self.reverse_domain, code:httpResponse.statusCode, userInfo:[NSLocalizedDescriptionKey : "HTTP status code \(httpResponse.statusCode)."]) completion(data as NSData?, error) } } else { let error = NSError(domain:self.reverse_domain, code:NSURLErrorUnknown, userInfo:[NSLocalizedDescriptionKey : "HTTP request returned no data and no error."]) completion(nil, error) } }) uploadTask.resume() } // Load data via PATCH and return in completion with or without error func patchDataToURL(url: NSURL, postData: Dictionary<String,String>, completion:@escaping (_ data: NSData?, _ error: NSError?) -> Void) { println(object: "patchDataToURL: " + url.absoluteString! + " postData = " + postData.description) let session = URLSession.shared let request = NSMutableURLRequest(url: url as URL) request.httpMethod = "PATCH" request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "content-type") let token = RWFrameworkConfig.getConfigValueAsString(key: "token", group: RWFrameworkConfig.ConfigGroup.Client) if token.lengthOfBytes(using: String.Encoding.utf8) > 0 { request.addValue("token \(token)", forHTTPHeaderField: "Authorization") } var body = "" for (key, value) in postData { body += "\(key)=\(value)&" } request.httpBody = body.data( using: String.Encoding.utf8, allowLossyConversion: false) let loadDataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data: Data?, response: URLResponse?, error: Error?) -> Void in if let errorResponse = error { completion(nil, errorResponse as NSError?) } else if let httpResponse = response as? HTTPURLResponse { if httpResponse.statusCode == 200 { completion(data as NSData?, nil) } else { let error = NSError(domain:self.reverse_domain, code:httpResponse.statusCode, userInfo:[NSLocalizedDescriptionKey : "HTTP status code \(httpResponse.statusCode)."]) completion(data as NSData?, error) } } else { let error = NSError(domain:self.reverse_domain, code:NSURLErrorUnknown, userInfo:[NSLocalizedDescriptionKey : "HTTP request returned no data and no error."]) completion(nil, error) } }) loadDataTask.resume() } // Load data via POST and return in completion with or without error func postDataToURL(url: NSURL, postData: Dictionary<String,String>, completion:@escaping (_ data: NSData?, _ error: NSError?) -> Void) { println(object: "postDataToURL: " + url.absoluteString! + " postData = " + postData.description) let session = URLSession.shared let request = NSMutableURLRequest(url: url as URL) request.httpMethod = "POST" let token = RWFrameworkConfig.getConfigValueAsString(key: "token", group: RWFrameworkConfig.ConfigGroup.Client) if token.lengthOfBytes(using: String.Encoding.utf8) > 0 { request.addValue("token \(token)", forHTTPHeaderField: "Authorization") //could set for whole session //session.configuration.HTTPAdditionalHeaders = ["Authorization" : "token \(token)"] } var body = "" for (key, value) in postData { body += "\(key)=\(value)&" } request.httpBody = body.data( using: String.Encoding.utf8, allowLossyConversion: false) let loadDataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data: Data?, response: URLResponse?, error: Error?) -> Void in if let errorResponse = error { completion(nil, errorResponse as NSError?) } else if let httpResponse = response as? HTTPURLResponse { if httpResponse.statusCode == 200 { completion(data as NSData?, nil) } else { let error = NSError(domain:self.reverse_domain, code:httpResponse.statusCode, userInfo:[NSLocalizedDescriptionKey : "HTTP status code \(httpResponse.statusCode)."]) //let's see those error messages //let dict = JSON(data: data!) //self.println(dict) completion(data as NSData?, error) } } else { let error = NSError(domain:self.reverse_domain, code:NSURLErrorUnknown, userInfo:[NSLocalizedDescriptionKey : "HTTP request returned no data and no error."]) completion(nil, error) } }) loadDataTask.resume() } /// Load data via GET and return in completion with or without error func getDataFromURL(url: NSURL, completion:@escaping (_ data: NSData?, _ error: NSError?) -> Void) { println(object: "getDataFromURL: " + url.absoluteString!) let session = URLSession.shared let request = NSMutableURLRequest(url: url as URL) request.httpMethod = "GET" let token = RWFrameworkConfig.getConfigValueAsString(key: "token", group: RWFrameworkConfig.ConfigGroup.Client) if token.lengthOfBytes(using: String.Encoding.utf8) > 0 { request.addValue("token \(token)", forHTTPHeaderField: "Authorization") } let loadDataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data: Data?, response: URLResponse?, error: Error?) -> Void in if let errorResponse = error { completion(nil, errorResponse as NSError?) } else if let httpResponse = response as? HTTPURLResponse { if httpResponse.statusCode == 200 { completion(data as NSData?, nil) } else { let error = NSError(domain:self.reverse_domain, code:httpResponse.statusCode, userInfo:[NSLocalizedDescriptionKey : "HTTP status code \(httpResponse.statusCode)."]) completion(data as NSData?, error) } } else { let error = NSError(domain:self.reverse_domain, code:NSURLErrorUnknown, userInfo:[NSLocalizedDescriptionKey : "HTTP request returned no data and no error."]) completion(nil, error) } }) loadDataTask.resume() } /// Load data via GET and return in completion with or without error /// This call does NOT add any token that may exist func loadDataFromURL(url: NSURL, completion:@escaping (_ data: NSData?, _ error: NSError?) -> Void) { println(object: "loadDataFromURL: " + url.absoluteString!) let session = URLSession.shared let loadDataTask = session.dataTask(with: url as URL, completionHandler: { (data: Data?, response: URLResponse?, error: Error?) -> Void in if let errorResponse = error { completion(nil, errorResponse as NSError?) } else if let httpResponse = response as? HTTPURLResponse { if httpResponse.statusCode == 200 { completion(data as NSData?, nil) } else { let error = NSError(domain:self.reverse_domain, code:httpResponse.statusCode, userInfo:[NSLocalizedDescriptionKey : "HTTP status code \(httpResponse.statusCode)."]) completion(nil, error) } } else { let error = NSError(domain:self.reverse_domain, code:NSURLErrorUnknown, userInfo:[NSLocalizedDescriptionKey : "HTTP request returned no data and no error."]) completion(nil, error) } }) loadDataTask.resume() } // MARK: - NSURLSessionDelegate // MARK: - NSURLSessionTaskDelegate // MARK: - NSURLSessionDataDelegate }
mit
JakeLin/IBAnimatable
Sources/Views/AnimatableView.swift
2
6072
// // Created by Jake Lin on 11/18/15. // Copyright © 2015 IBAnimatable. All rights reserved. // import UIKit @IBDesignable open class AnimatableView: UIView, CornerDesignable, FillDesignable, BorderDesignable, RotationDesignable, ShadowDesignable, BlurDesignable, TintDesignable, GradientDesignable, MaskDesignable, Animatable { // MARK: - CornerDesignable @IBInspectable open var cornerRadius: CGFloat = CGFloat.nan { didSet { configureCornerRadius() } } open var cornerSides: CornerSides = .allSides { didSet { configureCornerRadius() } } @IBInspectable var _cornerSides: String? { didSet { cornerSides = CornerSides(rawValue: _cornerSides) } } // MARK: - FillDesignable @IBInspectable open var fillColor: UIColor? { didSet { configureFillColor() } } open var predefinedColor: ColorType? { didSet { configureFillColor() } } @IBInspectable var _predefinedColor: String? { didSet { predefinedColor = ColorType(string: _predefinedColor) } } @IBInspectable open var opacity: CGFloat = CGFloat.nan { didSet { configureOpacity() } } // MARK: - BorderDesignable open var borderType: BorderType = .solid { didSet { configureBorder() } } @IBInspectable var _borderType: String? { didSet { borderType = BorderType(string: _borderType) } } @IBInspectable open var borderColor: UIColor? { didSet { configureBorder() } } @IBInspectable open var borderWidth: CGFloat = CGFloat.nan { didSet { configureBorder() } } open var borderSides: BorderSides = .AllSides { didSet { configureBorder() } } @IBInspectable var _borderSides: String? { didSet { borderSides = BorderSides(rawValue: _borderSides) } } // MARK: - RotationDesignable @IBInspectable open var rotate: CGFloat = CGFloat.nan { didSet { configureRotate() } } // MARK: - ShadowDesignable @IBInspectable open var shadowColor: UIColor? { didSet { configureShadowColor() } } @IBInspectable open var shadowRadius: CGFloat = CGFloat.nan { didSet { configureShadowRadius() } } @IBInspectable open var shadowOpacity: CGFloat = CGFloat.nan { didSet { configureShadowOpacity() } } @IBInspectable open var shadowOffset: CGPoint = CGPoint(x: CGFloat.nan, y: CGFloat.nan) { didSet { configureShadowOffset() } } // MARK: - BlurDesignable open var blurEffectStyle: UIBlurEffect.Style? { didSet { configureBlurEffectStyle() } } @IBInspectable var _blurEffectStyle: String? { didSet { blurEffectStyle = UIBlurEffect.Style(string: _blurEffectStyle) } } open var vibrancyEffectStyle: UIBlurEffect.Style? { didSet { configureBlurEffectStyle() } } @IBInspectable var _vibrancyEffectStyle: String? { didSet { vibrancyEffectStyle = UIBlurEffect.Style(string: _vibrancyEffectStyle) } } @IBInspectable open var blurOpacity: CGFloat = CGFloat.nan { didSet { configureBlurEffectStyle() } } // MARK: - TintDesignable @IBInspectable open var tintOpacity: CGFloat = CGFloat.nan @IBInspectable open var shadeOpacity: CGFloat = CGFloat.nan @IBInspectable open var toneColor: UIColor? @IBInspectable open var toneOpacity: CGFloat = CGFloat.nan // MARK: - GradientDesignable open var gradientMode: GradientMode = .linear @IBInspectable var _gradientMode: String? { didSet { gradientMode = GradientMode(string: _gradientMode) ?? .linear } } @IBInspectable open var startColor: UIColor? @IBInspectable open var endColor: UIColor? open var predefinedGradient: GradientType? @IBInspectable var _predefinedGradient: String? { didSet { predefinedGradient = GradientType(string: _predefinedGradient) } } open var startPoint: GradientStartPoint = .top @IBInspectable var _startPoint: String? { didSet { startPoint = GradientStartPoint(string: _startPoint, default: .top) } } // MARK: - MaskDesignable open var maskType: MaskType = .none { didSet { configureMask(previousMaskType: oldValue) configureBorder() configureMaskShadow() } } /// The mask type used in Interface Builder. **Should not** use this property in code. @IBInspectable var _maskType: String? { didSet { maskType = MaskType(string: _maskType) } } // MARK: - Animatable open var animationType: AnimationType = .none @IBInspectable var _animationType: String? { didSet { animationType = AnimationType(string: _animationType) } } @IBInspectable open var autoRun: Bool = true @IBInspectable open var duration: Double = Double.nan @IBInspectable open var delay: Double = Double.nan @IBInspectable open var damping: CGFloat = CGFloat.nan @IBInspectable open var velocity: CGFloat = CGFloat.nan @IBInspectable open var force: CGFloat = CGFloat.nan @IBInspectable var _timingFunction: String = "" { didSet { timingFunction = TimingFunctionType(string: _timingFunction) } } open var timingFunction: TimingFunctionType = .none // MARK: - Lifecycle open override func prepareForInterfaceBuilder() { super.prepareForInterfaceBuilder() configureInspectableProperties() } open override func awakeFromNib() { super.awakeFromNib() configureInspectableProperties() } open override func layoutSubviews() { super.layoutSubviews() configureAfterLayoutSubviews() autoRunAnimation() } // MARK: - Private fileprivate func configureInspectableProperties() { configureAnimatableProperties() configureTintedColor() } fileprivate func configureAfterLayoutSubviews() { configureMask(previousMaskType: maskType) configureCornerRadius() configureBorder() configureMaskShadow() configureGradient() } }
mit
AgaKhanFoundation/WCF-iOS
Steps4Impact/OnboardingV2/OnboardingPageViewController.swift
1
3394
/** * Copyright © 2019 Aga Khan Foundation * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. **/ import SnapKit import UIKit class OnboardingPageViewController: ViewController { struct PageContext: Context { let title: String let asset: Assets let tagLine: String? init(title: String, asset: Assets, tagLine: String? = nil) { self.title = title self.asset = asset self.tagLine = tagLine } } private let titleLabel = UILabel(typography: .headerTitle, color: Style.Colors.FoundationGreen) private let imageView = UIImageView() private let taglineLabel = UILabel(typography: .bodyRegular, color: Style.Colors.FoundationGreen) convenience init(context: PageContext) { self.init() configure(context: context) } override func configureView() { super.configureView() titleLabel.numberOfLines = 2 titleLabel.adjustsFontSizeToFitWidth = true imageView.contentMode = .scaleAspectFit imageView.setContentCompressionResistancePriority(.defaultLow, for: .vertical) imageView.setContentHuggingPriority(.defaultLow, for: .vertical) taglineLabel.textAlignment = .center view.addSubview(titleLabel) { $0.leading.trailing.top.equalToSuperview().inset(Style.Padding.p32) } view.addSubview(taglineLabel) { $0.leading.trailing.bottom.equalToSuperview().inset(Style.Padding.p32) } let layoutGuide = UILayoutGuide() view.addLayoutGuide(layoutGuide) { $0.leading.trailing.equalToSuperview().inset(Style.Padding.p32) $0.top.equalTo(titleLabel.snp.bottom) $0.bottom.equalTo(taglineLabel.snp.top) } view.insertSubview(imageView, belowSubview: titleLabel) imageView.snp.makeConstraints { $0.leading.trailing.equalToSuperview().inset(Style.Padding.p32) $0.centerY.equalTo(layoutGuide) } } func configure(context: PageContext) { titleLabel.text = context.title imageView.image = context.asset.image taglineLabel.text = context.tagLine } }
bsd-3-clause
jtbandes/swift
validation-test/compiler_crashers/28738-impl-genericparams-empty-key-depth-impl-genericparams-back-getdepth-key-index-im.swift
5
489
// 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 // REQUIRES: asserts // RUN: not --crash %target-swift-frontend %s -emit-ir protocol P}extension P{{}typealias a:P}extension P.a{protocol P
apache-2.0
aucl/YandexDiskKit
YandexDiskKit/YandexDiskKit/String+YDisk.swift
1
2020
// // String+YDisk.swift // // Copyright (c) 2014-2015, Clemens Auer // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND // ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // import Foundation extension String { func urlEncoded() -> String { let charactersToEscape = "!*'();:@&=+$,/?%#[]\" " let allowedCharacters = NSCharacterSet(charactersInString: charactersToEscape).invertedSet return self.stringByAddingPercentEncodingWithAllowedCharacters(allowedCharacters) ?? self } mutating func appendOptionalURLParameter<T>(name: String, value: T?) { if let value = value { let seperator = self.rangeOfString("?") == nil ? "?" : "&" self.splice("\(seperator)\(name)=\(value)", atIndex: self.endIndex) } } }
bsd-2-clause
asp2insp/CodePathFinalProject
Pretto/AddEventDateCell.swift
1
1506
// // AddEventDateCell.swift // Pretto // // Created by Francisco de la Pena on 6/14/15. // Copyright (c) 2015 Pretto. All rights reserved. // import UIKit class AddEventDateCell: UITableViewCell { @IBOutlet var startOrEndLabel: UILabel! @IBOutlet var dateLabel: UILabel! var isStartDate: Bool! { didSet { startOrEndLabel.text = isStartDate! ? "Starts" : "Ends" } } var date: NSDate! { didSet { dateFormatter.dateFormat = "MMM, d - hh:mm a" if isStartDate! { var interval = abs(NSDate().timeIntervalSinceDate(date)) if interval < (60 * 1) { println("Time Interval Since Now = \(interval)") dateLabel.text = "Now!" } else { dateLabel.text = dateFormatter.stringFromDate(date) } } else { dateLabel.text = dateFormatter.stringFromDate(date) } } } override func awakeFromNib() { super.awakeFromNib() self.selectionStyle = UITableViewCellSelectionStyle.None self.dateLabel.textColor = UIColor.lightGrayColor() self.startOrEndLabel.textColor = UIColor.prettoOrange() self.tintColor = UIColor.whiteColor() } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
mit
MTR2D2/TIY-Assignments
Forecaster/Forecaster/APIController.swift
1
2899
// // APIController.swift // Forecaster // // Created by Michael Reynolds on 10/29/15. // Copyright © 2015 The Iron Yard. All rights reserved. // import Foundation class APIController { var delegate: APIControllerProtocol init(delegate: APIControllerProtocol) { self.delegate = delegate } func searchMapsFor(searchTerm: String) { let urlPath = "https://maps.googleapis.com/maps/api/geocode/json?address=santa+cruz&components=postal_code:\(searchTerm)&sensor=false" let url = NSURL(string: urlPath) let session = NSURLSession.sharedSession() // not NSURLConnection, use NSURLSession! let task = session.dataTaskWithURL(url!, completionHandler: {data, response, error -> Void in print("Task completed") if error != nil { print(error!.localizedDescription) } else { if let dictionary = self.parseJSON(data!) { if let results: NSArray = dictionary["results"] as? NSArray { self.delegate.didReceiveAPIResults(results) } } } }) task.resume() } func searchWeatherFor(city: City) { let latitude = city.latitude let longitude = city.longitude let urlPath = "https://api.forecast.io/forecast/1b3f124941abc3fc2e9ab22e93ba68b4/\(latitude),\(longitude)" print(city.latitude) ; print(city.longitude) let url = NSURL(string: urlPath) let session = NSURLSession.sharedSession() // not NSURLConnection, use NSURLSession! let task = session.dataTaskWithURL(url!, completionHandler: {data, response, error -> Void in print("Task completed") if error != nil { print(error!.localizedDescription) } else { if let dictionary = self.parseJSON(data!) { if let currently: NSDictionary = dictionary["currently"] as? NSDictionary { self.delegate.didReceiveAPIWeatherResults(currently, city: city) } } } }) task.resume() } func parseJSON(data: NSData) -> NSDictionary? { do { let dictionary: NSDictionary! = try NSJSONSerialization.JSONObjectWithData(data, options: []) as! NSDictionary return dictionary } catch let error as NSError { print(error) return nil } } } //https://api.forecast.io/forecast/APIKEY/LATITUDE,LONGITUDE
cc0-1.0
Donny8028/Swift-Animation
Emoji Slot Machine/Emoji Slot Machine/ViewController.swift
1
3159
// // ViewController.swift // Emoji Slot Machine // // Created by 賢瑭 何 on 2016/5/19. // Copyright © 2016年 Donny. All rights reserved. // import UIKit class ViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource { let emojis = ["😂","😎","😡","😱","💩","👽","👀","🐷","🐨","🐣","🙉","🐶","🐯"] var leftRow = [Int]() var midRow = [Int]() var rightRow = [Int]() @IBOutlet weak var buttonView: UIButton! @IBOutlet weak var mid: UIPickerView! @IBAction func start() { var fixedRow: Int? for i in 0...2 { let row = arc4random_uniform(99) mid.selectRow(Int(row), inComponent: i, animated: true) fixedRow = Int(row) } if let row = fixedRow where leftRow[row] == midRow[row] && midRow[row] == rightRow[row] { let alert = UIAlertController(title: "Bingo!", message: "Congrats!", preferredStyle: .Alert) alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil)) } } override func viewDidLoad() { super.viewDidLoad() mid.dataSource = self mid.delegate = self buttonView.layer.cornerRadius = 6 for _ in 0...100 { let left = arc4random_uniform(13) let mid = arc4random_uniform(13) let right = arc4random_uniform(13) leftRow.append(Int(left)) midRow.append(Int(mid)) rightRow.append(Int(right)) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int { return 3 } func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return 100 } func pickerView(pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusingView view: UIView?) -> UIView { switch component { case 0 : var left = [String]() let view = UILabel() view.font = UIFont.systemFontOfSize(50) for i in leftRow { left.append(emojis[i]) } view.text = left[row] return view case 1 : var mid = [String]() let view = UILabel() view.font = UIFont.systemFontOfSize(50) for i in midRow { mid.append(emojis[i]) } view.text = mid[row] return view case 2 : var right = [String]() let view = UILabel() view.font = UIFont.systemFontOfSize(50) for i in rightRow { right.append(emojis[i]) } view.text = right[row] return view default: let view = UILabel() return view } } func pickerView(pickerView: UIPickerView, rowHeightForComponent component: Int) -> CGFloat { return 100 } }
mit
ntaku/SwiftEssential
SwiftEssential/ExtImage.swift
1
4239
import Foundation import UIKit public extension UIImage { /** 中心を正方形にクロップする (Exifの画像の向きは考慮されない) */ @objc func crop() -> UIImage { let w = self.size.width let h = self.size.height let size = (w < h) ? w : h let sx = self.size.width/2 - size/2 let sy = self.size.height/2 - size/2 let rect = CGRect(x: sx, y: sy, width: size, height: size) return crop(bounds: rect) } /** 指定した位置をクロップする (Exifの画像の向きは考慮されない) */ @objc func crop(bounds: CGRect) -> UIImage { let cgImage = self.cgImage?.cropping(to: bounds) return UIImage(cgImage: cgImage!) } /** 長辺が指定したサイズになるように自動リサイズする */ @objc func autoResize(_ maxsize: CGFloat) -> UIImage { if(maxsize > 0){ let ratio = maxsize / max(self.size.width, self.size.height) let size = CGSize(width: self.size.width * ratio, height: self.size.height * ratio) // オリジナルが指定サイズより小さい場合 //(resizeを実行しておかないとExifの向きが上向きに修正されないので実行される場合と挙動が異なってしまう。) if self.size.width <= size.width && self.size.height <= size.height { return resize(self.size) } return resize(size) } return resize(self.size) } /** 指定サイズでリサイズする (Exifの画像の向きが上に修正される) */ @objc func resize(_ size: CGSize) -> UIImage { return UIGraphicsImageRenderer(size: size, format: imageRendererFormat).image { (context) in draw(in: CGRect(x: 0, y: 0, width: size.width, height: size.height)) } } @objc func orientationString() -> String { switch self.imageOrientation { case .up: return "Up" case .down: return "Down" case .left: return "Left" case .right: return "Right" case .upMirrored: return "UpMirrored" case .downMirrored: return "DownMirrored" case .leftMirrored: return "LeftMirrored" case .rightMirrored: return "RightMirrored" @unknown default: return "Unknown" } } /** JPGに変換する */ @objc func toJpeg(_ quality: CGFloat) -> Data? { return self.jpegData(compressionQuality: quality) } /** PNGに変換する */ @objc func toPng() -> Data? { return self.pngData() } /** 指定色の画像を生成する */ @objc class func image(from color: UIColor) -> UIImage { return image(from: color, size: CGSize(width: 1, height: 1)) } //TODO UIGraphicsImageRendererにリプレイス /** 指定色/サイズの画像を生成する */ @objc class func image(from color: UIColor, size: CGSize) -> UIImage { let rect: CGRect = CGRect(x: 0, y: 0, width: size.width, height: size.height) UIGraphicsBeginImageContextWithOptions(CGSize(width: size.width, height: size.height), false, 0) color.setFill() UIRectFill(rect) let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() return image } //TODO UIGraphicsImageRendererにリプレイス /** 指定色の画像に変換する */ @objc func maskWith(color: UIColor) -> UIImage { UIGraphicsBeginImageContextWithOptions(size, false, scale) let context = UIGraphicsGetCurrentContext()! context.translateBy(x: 0, y: size.height) context.scaleBy(x: 1.0, y: -1.0) context.setBlendMode(.normal) let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height) context.clip(to: rect, mask: cgImage!) color.setFill() context.fill(rect) let newImage = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() return newImage } }
mit
ethanneff/iOS-Swift-Modular-Design-With-Multiple-Storyboards
ModularDesignUITests/ModularDesignUITests.swift
1
1260
// // ModularDesignUITests.swift // ModularDesignUITests // // Created by Ethan Neff on 1/29/16. // Copyright © 2016 Ethan Neff. All rights reserved. // import XCTest class ModularDesignUITests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method. XCUIApplication().launch() // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. } }
mit
rad182/CellSignal
Watch Extension/InterfaceController.swift
1
2088
// // InterfaceController.swift // Watch Extension // // Created by Royce Albert Dy on 14/11/2015. // Copyright © 2015 rad182. All rights reserved. // import WatchKit import Foundation class InterfaceController: WKInterfaceController { @IBOutlet weak var radioTechnologyLabel: WKInterfaceLabel! private var isFetchingData = false override func awakeWithContext(context: AnyObject?) { super.awakeWithContext(context) // Configure interface objects here. } override func didAppear() { super.didAppear() print("didAppear") self.reloadData() } override func willActivate() { // This method is called when watch view controller is about to be visible to user super.willActivate() print("willActivate") self.reloadData() } override func didDeactivate() { // This method is called when watch view controller is no longer visible super.didDeactivate() } // MARK: - Methods func reloadData() { if self.isFetchingData { return } if let currentSession = SessionUtility.currentSession where currentSession.reachable { self.isFetchingData = true SessionUtility.updateCurrentRadioAccessTechnologyAndCurrentSignalStrengthPercentage { (currentRadioAccessTechnology, currentSignalStrengthPercentage) -> Void in self.isFetchingData = false if let currentRadioAccessTechnology = currentRadioAccessTechnology where currentRadioAccessTechnology.isEmpty == false { self.radioTechnologyLabel.setText(currentRadioAccessTechnology) SessionUtility.refreshComplications() print(currentRadioAccessTechnology) } else { self.radioTechnologyLabel.setText("No Signal") } } } else { self.radioTechnologyLabel.setText("Not Reachable") print("not reachable") } } }
mit
Turistforeningen/SjekkUT
ios/SjekkUt/views/style/DntTextView.swift
1
677
// // DntTextView.swift // SjekkUt // // Created by Henrik Hartz on 14.02.2017. // Copyright © 2017 Den Norske Turistforening. All rights reserved. // import Foundation @IBDesignable class DntTextView: UITextView { required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setupDntTextView() } func setupDntTextView() { self.layer.cornerRadius = 5 self.layer.borderColor = UIColor.lightGray.cgColor self.layer.borderWidth = 1 self.layer.shadowColor = UIColor.black.cgColor self.layer.shadowOpacity = 0.25 self.layer.shadowOffset = CGSize(width: 1, height: 1) } }
mit
ArtSabintsev/Apple-Watch-WatchKit-CocoaHeads-DC-Talk-
Cocoaheads Sample WatchKit App/Cocoaheads/ViewController.swift
1
506
// // ViewController.swift // Cocoaheads // // Created by Arthur Sabintsev on 4/2/15. // Copyright (c) 2015 ID.me. All rights reserved. // import UIKit 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. } }
mit
gregomni/swift
validation-test/compiler_crashers_fixed/00237-swift-declrefexpr-setspecialized.swift
3
3053
// 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 // RUN: not %target-swift-frontend %s -typecheck -requirement-machine-inferred-signatures=on func b(c) -> <d>(() -> d) { } struct d<f : e, g: e where g.h == f.h> { } protocol e { typealias h } struct c<d : Sequence> { var b: d } func a<d>() -> [c<d>] { return [] } func i(c: () -> ()) { } class a { var _ = i() { } } protocol A { typealias E } struct B<T : A> { let h: T let i: T.E } protocol C { typealias F func g<T where T.E == F>(f: B<T>) } struct D : C { typealias F = Int func g<T where T.E == F>(f: B<T>) { } } protocol A { func c() -> String } class B { func d() -> String { return "" B) { } } func ^(a: Boolean, Bool) -> Bool { return !(a) } func f<T : Boolean>(b: T) { } f(true as Boolean) var f = 1 var e: Int -> Int = { return $0 } let d: Int = { c, b in }(f, e) func d<b: Sequence, e where Optional<e> == b.Iterator.Element>(c : b) -> e? { for (mx : e?) in c { } } protocol a { } protocol b : a { } protocol c : a { } protocol d { typealias f = a } struct e : d { typealias f = b } func i<j : b, k : d where k.f == j> (n: k) { } func i<l : d where l.f == c> (n: l) { } i(e(ass func c() } class b: a { class func c() { } } (b() as a).dynamicType.c() class a<f : b, g : b where f.d == g> { } protocol b { typealias d typealias e } struct c<h : b> : b { typealias d = h typealias e = a<c<h>, d> } class a { typealias b = b } func a(b: Int = 0) { } let c = a c() enum S<T> { case C(T, () -> ()) } func f() { ({}) } enum S<T> : P { func f<T>() -> T -> T { return { x in x } } } protocol P { func f<T>()(T) -> T } protocol A { typealias B func b(B) } struct X<Y> : A { func b(b: X.Type) { } } class A<T : A> { } protocol a { typealias d typealias e = d typealias f = d } class b<h : c, i : c where h.g == i> : a { } class b<h, i> { } protocol c { typealias g } struct A<T> { let a: [(T, () -> ())] = [] } struct c<d, e: b where d.c == e> { } func a(x: Any, y: Any) -> (((Any, Any) -> Any) -> Any) { return { (m: (Any, Any) -> Any) -> Any in return m(x, y) } } func b(z: (((Any, Any) -> Any) -> Any)) -> Any { return z({ (p: Any, q:Any) -> Any in return p }) } b(a(1, a(2, 3))) func a<T>() -> (T, T -> T) -> T { var b: ((T, T -> T) -> T)! return b } protocol b { class func e() } struct c { var d: b.Type func e() { d.e() } } import Foundation class d<c>: NSObject { var b: c init(b: c) { self.b = b } } func a<T>() { enum b { case c } } protocol a : a { } class A : A { } class B : C { } typealias C = B
apache-2.0
heitara/swift-3
playgrounds/Lecture4.playground/Contents.swift
1
8796
//: Playground - noun: a place where people can play import UIKit /* Какво е playground? Това вид проект, който се изпозлва от xCode. Интерактивно показва какво е състоянието на паметта на компютъра във всеки един ред на изпълнение на код-а. Позволява лесно онагледяване на примерния код. Много по лесно може да се анализира кода. Можем да скицираме проблеми и техните решения, които да използваме за напред. */ // Лекция 4 // курс: Увод в прогрмаирането със Swift /* N-торки */ let person = (name: "Иван", familyName: "Петров", age: 25) //тип : (name: String, familyName: String, age: Int) //(String, String, Int) let p:(String, String, age: Int)? = person print("Здравей, \(person.name)!") print("Здравей, г-н \(person.familyName)!") print("Здравей, г-н \(person.1)!") if let pp = p, pp.age > 20 { print("Г-н \(pp.1), Вие сте на \(pp.age) години.") } print("Г-н \(p?.1), Вие сте на \(p?.age) години.") var x:Int? = 7 print("\(x)") /* Интересен пример, който демонстира силата на switch */ let point = (1, 1) switch point { case let (x, y) where x == y: print("X is \(x). Y is \(y). They have the same value."); case (1, let y): print("X is 1. Y is \(y). They could be different."); case (let x, 1): print("X is \(x). Y is 1. They could be different."); case let (x, y) where x > y: print("X is \(x). Y is \(y). X is greater than Y."); default: print("Are you sure?") } //Нека да напишем първата функция, която агрегира няколко действия. //без параметри и без резултат func severalActions() { print("Action 1") print("Action 2") print("Action 3") } //сума на две числа func printSum() { let a = 3 let b = 4 print("Sum \(a) + \(b) = \(a + b)") } //с параметри без резултат //сума на две числа func printSum(a:Int, b:Int) { return; print("Sum \(a) + \(b) = \(a + b)") } //извикване на функцията printSum() //printSum(3, 5) printSum(a:3, b:5) //променливите са let func sum(a:Int, b:Int,in sum: inout Int) { // a = a + b sum = a + b } var sumAB:Int = 0 sum(a:3, b:4, in:&sumAB) //тук ще активираме нашата функция. Може да мислим че я извикваме (call) severalActions() //severalActions() func functionName(labelName constantName:String) -> String { let reurnedValue = constantName + " was passed" return reurnedValue } func functionName(_ a: Int, _ variableName:Double = 5) -> String { let reurnedValue = String(variableName) + " was passed" return reurnedValue } //functionName(1); functionName(17); func f(_ a:Int, _ b:String = "dsadsa", s:String = "dsadsa" ) { let _ = String(a) + " was passed" print("F1001") } func f(_ a:Int,_ b:String = "dsadsa" ) { let _ = String(a) + " was passed" print("F1000") } //func f(_ a:Int) { // let _ = String(a) + " was passed" // print("F1") //} f(4) func functionName(_ variableName:String) -> String { let reurnedValue = variableName + " was passed" return reurnedValue } //ако променим името на аргумента swift счита това за нова различна функция. Т.е. имената на аргумента func functionName(labelNameNew variableName:String) -> String { let reurnedValue = variableName + " NEW was passed" return reurnedValue } //ето и извикването на функцията let resultOfFunctionCall = functionName(labelName: "Nothing") let resultOfFunctionCall2 = functionName("Nothing") functionName(labelNameNew: "Nothing") //когато изпуснем името на аргумента, името на променливата се изпозлва за негово име. т.е. двете съвпадат func functionName(variableName:String) -> String { let reurnedValue = variableName + " was passed. v2" return reurnedValue } //за да извикаме 2рата версия трябва да направим следното обръщение functionName(variableName: "Nothing") // func functionName3(variableName:String) -> String { return variableName + " was passed" } //Пример: на български език //как би изглеждал код-а функцията, ако използваме utf и кирилица func смениСтойността(на вход:inout Int,с новаСтойност: Int) { вход = новаСтойност } func смениСтойността(_ вход:inout Int,_ новаСтойност: Int) { вход = новаСтойност } var променлива = 5 смениСтойността(на: &променлива, с: 15) print("Стойността на променливата е \(променлива)") //класическото програмиране, с което сме свикнали от C, C++, Java смениСтойността(&променлива, 25) print("Стойността на променливата е \(променлива)") //функция, която връша резултат func seven() -> Int { return 7 } let s = seven() print("Това е числото \(s).") /* // невалидна функция, поради дублиране на имената func functionName(argumentName variableName:String, argumentName variableName2:Int) -> String { let reurnedValue = variableName + " was passed" return reurnedValue } */ //как да не позлваме името (label) на аргумент func concatenateStrings(_ s1:String, _ s2:String) -> String { return s1 + s2 } let helloWorld = concatenateStrings("Hello ", "world!") //define a function which finds min and max value in a array of integers func minMax(numbers:[Int]) -> (Int, Int) { var min = Int.max var max = Int.min for val in numbers { if min > val { min = val } if max < val { max = val } } return (min, max) } print(minMax(numbers: [12, 2, 6, 3, 4, 5, 2, 10])) func maxItemIndex(numbers:[Int]) -> (item:Int, index:Int) { var index = -1 var max = Int.min for (i, val) in numbers.enumerated() { if max < val { max = val index = i } } return (max, index) } let maxItemTuple = maxItemIndex(numbers: [12, 2, 6, 3, 4, 5, 2, 10]) if maxItemTuple.index >= 0 { print("Max item is \(maxItemTuple.item).") } func generateGreeting(greet:String, thing:String = "world") -> String { return greet + thing + "!" } print(generateGreeting(greet: "Hello ")) print(generateGreeting(greet: "Hello ", thing: " Swift 4")) func maxValue(params numbers:Int...) -> Int { var max = Int.min for v in numbers { if max < v { max = v } } return max } func maxValue(params numbers:Int) -> Int { return numbers } print(maxValue(params: 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 50, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5)) print(maxValue(params: 1)) func updateVar(_ x: inout Int, newValue: Int = 5) { x = newValue } var ten = 10 print(ten) updateVar(&ten, newValue: 15) print(ten) //the same example as above, but the paramter has a label func updateVar(oldVariable x: inout Int, newValue: Int = 5) { x = newValue } ten = 10 print(ten) updateVar(oldVariable:&ten, newValue: 15) print(ten) func generateGreeting(_ greeting: String?) -> String { guard let greeting = greeting else { //there is no greeting, we return something and finish return "No greeting :(" } //there is a greeting and we generate a greeting message return greeting + " Swift 4!" } print(generateGreeting(nil)) print(generateGreeting("Hey")) let number = 5 let divisor = 3 let remainder = number % divisor //remainder is again integer let quotient = number / divisor // quotient is again integer let hey = "Hi" let greeting = hey + " Swift 4!" //operator + concatenates strings
mit
richardpiazza/MiseEnPlace
Sources/MiseEnPlace/Double+MiseEnPlace.swift
1
1151
import Foundation public extension Double { /// Rounds to the number of decimal-places specified func rounded(to places: Int) -> Double { let divisor = pow(10.0, Double(places)) return (self * divisor).rounded() / divisor } /// An interpreted representation of the value, composed of the /// integral and fraction as needed. var fractionedString: String { guard self.isNaN == false && self.isInfinite == false else { return "0" } let decomposedAmount = modf(self) guard decomposedAmount.1 > 0.0 else { return "\(Int(decomposedAmount.0))" } let integral = Int(decomposedAmount.0) let fraction = Fraction(proximateValue: decomposedAmount.1) switch fraction { case .zero: return "\(integral)" case .one: return "\(Int(integral + 1))" default: if integral == 0 { return "\(fraction.description)" } else { return "\(integral)\(fraction.description)" } } } }
mit
weby/Stencil
Sources/Filters.swift
1
601
func toString(value: Any?) -> String? { if let value = value as? String { return value } else if let value = value as? CustomStringConvertible { return value.description } return nil } func capitalise(value: Any?) -> Any? { if let value = toString(value: value) { return value.capitalized } return value } func uppercase(value: Any?) -> Any? { if let value = toString(value: value) { return value.uppercased() } return value } func lowercase(value: Any?) -> Any? { if let value = toString(value: value) { return value.lowercased() } return value }
bsd-2-clause
ksco/swift-algorithm-club-cn
Segment Tree/SegmentTree.swift
1
2429
/* Segment tree Performance: building the tree is O(n) query is O(log n) replace item is O(log n) */ public class SegmentTree<T> { private var value: T private var function: (T, T) -> T private var leftBound: Int private var rightBound: Int private var leftChild: SegmentTree<T>? private var rightChild: SegmentTree<T>? public init(array: [T], leftBound: Int, rightBound: Int, function: (T, T) -> T) { self.leftBound = leftBound self.rightBound = rightBound self.function = function if leftBound == rightBound { value = array[leftBound] } else { let middle = (leftBound + rightBound) / 2 leftChild = SegmentTree<T>(array: array, leftBound: leftBound, rightBound: middle, function: function) rightChild = SegmentTree<T>(array: array, leftBound: middle+1, rightBound: rightBound, function: function) value = function(leftChild!.value, rightChild!.value) } } public convenience init(array: [T], function: (T, T) -> T) { self.init(array: array, leftBound: 0, rightBound: array.count-1, function: function) } public func queryWithLeftBound(leftBound: Int, rightBound: Int) -> T { if self.leftBound == leftBound && self.rightBound == rightBound { return self.value } guard let leftChild = leftChild else { fatalError("leftChild should not be nil") } guard let rightChild = rightChild else { fatalError("rightChild should not be nil") } if leftChild.rightBound < leftBound { return rightChild.queryWithLeftBound(leftBound, rightBound: rightBound) } else if rightChild.leftBound > rightBound { return leftChild.queryWithLeftBound(leftBound, rightBound: rightBound) } else { let leftResult = leftChild.queryWithLeftBound(leftBound, rightBound: leftChild.rightBound) let rightResult = rightChild.queryWithLeftBound(rightChild.leftBound, rightBound: rightBound) return function(leftResult, rightResult) } } public func replaceItemAtIndex(index: Int, withItem item: T) { if leftBound == rightBound { value = item } else if let leftChild = leftChild, rightChild = rightChild { if leftChild.rightBound >= index { leftChild.replaceItemAtIndex(index, withItem: item) } else { rightChild.replaceItemAtIndex(index, withItem: item) } value = function(leftChild.value, rightChild.value) } } }
mit
aleph7/PlotKit
PlotKit/Model/PointSet.swift
1
2141
// Copyright © 2015 Venture Media Labs. All rights reserved. // // This file is part of PlotKit. The full PlotKit copyright notice, including // terms governing use, modification, and redistribution, is contained in the // file LICENSE at the root of the source code distribution tree. import Foundation public enum PointType { case none case ring(radius: Double) case disk(radius: Double) case square(side: Double) case filledSquare(side: Double) } public struct Point { public var x: Double public var y: Double public init(x: Double, y: Double) { self.x = x self.y = y } } public class PointSet { public var points: [Point] { didSet { updateIntervals() } } public var lineWidth = CGFloat(1.0) public var lineColor: NSColor? = NSColor.red public var fillColor: NSColor? = nil public var pointColor: NSColor? = NSColor.red public var pointType = PointType.none public var xInterval: ClosedRange<Double> = (0 ... 0) public var yInterval: ClosedRange<Double> = (0 ... 0) public init() { self.points = [] } public init<T: Sequence>(points: T) where T.Iterator.Element == Point { self.points = [Point](points) updateIntervals() } public init<T: Sequence>(values: T) where T.Iterator.Element == Double { self.points = values.enumerated().map{ Point(x: Double($0.0), y: $0.1) } updateIntervals() } func updateIntervals() { guard let first = points.first else { xInterval = 0...0 yInterval = 0...0 return } var minX = first.x var maxX = first.x var minY = first.y var maxY = first.y for p in points { if p.x < minX { minX = p.x } if p.x > maxX { maxX = p.x } if p.y < minY { minY = p.y } if p.y > maxY { maxY = p.y } } xInterval = minX...maxX yInterval = minY...maxY } }
mit
crescentflare/SmartMockServer
MockLibIOS/Example/SmartMockLib/AppDelegate.swift
1
809
// // AppDelegate.swift // SmartMockLib Example // // The application delegate, handling global events while the app is running // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { return true } func applicationWillResignActive(_ application: UIApplication) { } func applicationDidEnterBackground(_ application: UIApplication) { } func applicationWillEnterForeground(_ application: UIApplication) { } func applicationDidBecomeActive(_ application: UIApplication) { } func applicationWillTerminate(_ application: UIApplication) { } }
mit
OscarSwanros/swift
test/SourceKit/CodeComplete/complete_filter.swift
31
3678
struct Foo { func aaa() {} func aab() {} func abc() {} func b() {} func c() {} } func foo() { let x = Foo() x.#^FOO,,a,aa,ab,abc,abcd^# } // XFAIL: broken_std_regex // RUN: %sourcekitd-test -req=complete.open -pos=11:5 %s -- %s > %t.all // RUN: %FileCheck -check-prefix=CHECK-ALL %s < %t.all // CHECK-ALL: key.name: "aaa // CHECK-ALL: key.name: "aab // CHECK-ALL: key.name: "abc // CHECK-ALL: key.name: "b // CHECK-ALL: key.name: "c // RUN: %sourcekitd-test -req=complete.open -pos=11:5 \ // RUN: -req-opts=filtertext=a %s -- %s > %t.a // RUN: %FileCheck -check-prefix=CHECKA %s < %t.a // CHECKA-NOT: key.name // CHECKA: key.name: "aaa // CHECKA: key.name: "aab // CHECKA: key.name: "abc // CHECKA-NOT: key.name: "b // CHECKA-NOT: key.name: "c // RUN: %sourcekitd-test -req=complete.open -pos=11:5 %s -- %s \ // RUN: == -req=complete.update -pos=11:5 -req-opts=filtertext=a %s -- %s > %t.both // RUN: cat %t.all %t.a > %t.both.check // RUN: diff -u %t.both %t.both.check // RUN: %sourcekitd-test -req=complete.open -pos=11:5 \ // RUN: -req-opts=filtertext=b %s -- %s > %t.b // RUN: %FileCheck -check-prefix=CHECKB %s < %t.b // CHECKB-NOT: key.name // CHECKB: key.name: "b // CHECKB-NOT: key.name: "c // RUN: %sourcekitd-test -req=complete.open -pos=11:5 \ // RUN: -req-opts=filtertext=c %s -- %s > %t.c // RUN: %FileCheck -check-prefix=CHECKC %s < %t.c // CHECKC-NOT: key.name // CHECKC: key.name: "c // RUN: %sourcekitd-test -req=complete.open -pos=11:5 \ // RUN: -req-opts=filtertext=d %s -- %s > %t.d // RUN: %FileCheck -check-prefix=CHECKD %s < %t.d // CHECKD-NOT: key.name // CHECKD: ], // CHECKD-NEXT: key.kind: source.lang.swift.codecomplete.group // CHECKD-NEXT: key.name: "" // CHECKD-NEXT: key.nextrequeststart: 0 // CHECKD-NEXT: } // RUN: %complete-test -tok=FOO %s | %FileCheck %s // CHECK-LABEL: Results for filterText: [ // CHECK-NEXT: aaa() // CHECK-NEXT: aab() // CHECK-NEXT: abc() // CHECK-NEXT: b() // CHECK-NEXT: c() // CHECK-NEXT: ] // CHECK-LABEL: Results for filterText: a [ // CHECK-NEXT: aaa() // CHECK-NEXT: aab() // CHECK-NEXT: abc() // CHECK-NEXT: ] // CHECK-LABEL: Results for filterText: aa [ // CHECK-NEXT: aaa() // CHECK-NEXT: aab() // CHECK-NEXT: ] // CHECK-LABEL: Results for filterText: abc [ // CHECK-NEXT: abc() // CHECK-NEXT: ] // CHECK-LABEL: Results for filterText: abcd [ // CHECK-NEXT: ] struct A {} func over() {} func overload() {} func overload(_ x: A) {} func test() { #^OVER,over,overload,overloadp^# } // Don't create empty groups, or groups with one element // RUN: %complete-test -group=overloads -tok=OVER %s | %FileCheck -check-prefix=GROUP %s // GROUP-LABEL: Results for filterText: over [ // GROUP: overload: // GROUP-NEXT: overload() // GROUP-NEXT: overload(x: A) // GROUP: ] // GROUP-LABEL: Results for filterText: overload [ // GROUP-NEXT: overload() // GROUP-NEXT: overload(x: A) // GROUP-NEXT: ] // GROUP-LABEL: Results for filterText: overloadp [ // GROUP-NEXT: ] struct UnnamedArgs { func dontMatchAgainst(_ unnamed: Int, arguments: Int, _ unnamed2:Int) {} func test() { self.#^UNNAMED_ARGS_0,dont,arguments,unnamed^# } } // RUN: %complete-test -tok=UNNAMED_ARGS_0 %s | %FileCheck %s -check-prefix=UNNAMED_ARGS_0 // UNNAMED_ARGS_0: Results for filterText: dont [ // UNNAMED_ARGS_0-NEXT: dontMatchAgainst(unnamed: Int, arguments: Int, unnamed2: Int) // UNNAMED_ARGS_0-NEXT: ] // UNNAMED_ARGS_0-NEXT: Results for filterText: arguments [ // UNNAMED_ARGS_0-NEXT: dontMatchAgainst(unnamed: Int, arguments: Int, unnamed2: Int) // UNNAMED_ARGS_0-NEXT: ] // UNNAMED_ARGS_0-NEXT: Results for filterText: unnamed [ // UNNAMED_ARGS_0-NEXT: ]
apache-2.0
nguyenantinhbk77/practice-swift
Calendar/Accessing the contents of Calendars/Accessing the contents of Calendars/ViewController.swift
2
187
// // ViewController.swift // Accessing the contents of Calendars // // Created by Domenico on 25/05/15. // License MIT // import UIKit class ViewController: UIViewController { }
mit
LoopKit/LoopKit
LoopKitUI/View Controllers/GlucoseEntryTableViewController.swift
1
2171
// // GlucoseEntryTableViewController.swift // LoopKitUI // // Created by Michael Pangburn on 11/24/18. // Copyright © 2018 LoopKit Authors. All rights reserved. // import UIKit import HealthKit import LoopKit public protocol GlucoseEntryTableViewControllerDelegate: AnyObject { func glucoseEntryTableViewControllerDidChangeGlucose(_ controller: GlucoseEntryTableViewController) } public class GlucoseEntryTableViewController: TextFieldTableViewController { let glucoseUnit: HKUnit private lazy var glucoseFormatter: NumberFormatter = { let quantityFormatter = QuantityFormatter() quantityFormatter.setPreferredNumberFormatter(for: glucoseUnit) return quantityFormatter.numberFormatter }() public var glucose: HKQuantity? { get { guard let value = value, let doubleValue = Double(value) else { return nil } return HKQuantity(unit: glucoseUnit, doubleValue: doubleValue) } set { if let newValue = newValue { value = glucoseFormatter.string(from: newValue.doubleValue(for: glucoseUnit)) } else { value = nil } } } public weak var glucoseEntryDelegate: GlucoseEntryTableViewControllerDelegate? public init(glucoseUnit: HKUnit) { self.glucoseUnit = glucoseUnit super.init(style: .grouped) unit = glucoseUnit.shortLocalizedUnitString() keyboardType = .decimalPad placeholder = "Enter glucose value" delegate = self } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension GlucoseEntryTableViewController: TextFieldTableViewControllerDelegate { public func textFieldTableViewControllerDidEndEditing(_ controller: TextFieldTableViewController) { glucoseEntryDelegate?.glucoseEntryTableViewControllerDidChangeGlucose(self) } public func textFieldTableViewControllerDidReturn(_ controller: TextFieldTableViewController) { glucoseEntryDelegate?.glucoseEntryTableViewControllerDidChangeGlucose(self) } }
mit
chenl326/stwitter
stwitter/stwitter/Classes/Tools/Extensions/Bundle+Extension.swift
2
350
// // Bundle+Extension.swift // WeiBo // // Created by yao wei on 16/9/9. // Copyright © 2016年 yao wei. All rights reserved. // import Foundation extension Bundle { //计算性属性 类似于函数 没有参数 有返回值 var nameSpace : String { return infoDictionary?["CFBundleName"] as? String ?? "" } }
apache-2.0
zeroc-ice/ice
swift/test/Ice/timeout/AllTests.swift
3
11514
// // Copyright (c) ZeroC, Inc. All rights reserved. // import Foundation import Ice import TestCommon func connect(_ prx: Ice.ObjectPrx) throws -> Ice.Connection { for _ in 0 ..< 10 { do { _ = try prx.ice_getConnection() break } catch is Ice.ConnectTimeoutException { // Can sporadically occur with slow machines } } return try prx.ice_getConnection()! } public func allTests(helper: TestHelper) throws { let controller = try checkedCast( prx: helper.communicator().stringToProxy("controller:\(helper.getTestEndpoint(num: 1))")!, type: ControllerPrx.self)! do { try allTestsWithController(helper: helper, controller: controller) } catch { // Ensure the adapter is not in the holding state when an unexpected exception occurs to prevent // the test from hanging on exit in case a connection which disables timeouts is still opened. try controller.resumeAdapter() throw error } } public func allTestsWithController(helper: TestHelper, controller: ControllerPrx) throws { func test(_ value: Bool, file: String = #file, line: Int = #line) throws { try helper.test(value, file: file, line: line) } let communicator = helper.communicator() let sref = "timeout:\(helper.getTestEndpoint(num: 0))" let obj = try communicator.stringToProxy(sref)! let timeout = try checkedCast(prx: obj, type: TimeoutPrx.self)! let output = helper.getWriter() output.write("testing connect timeout... ") do { // // Expect ConnectTimeoutException. // let to = timeout.ice_timeout(100) try controller.holdAdapter(-1) do { try to.op() try test(false) } catch is Ice.ConnectTimeoutException { // Expected. } try controller.resumeAdapter() try timeout.op() // Ensure adapter is active. } do { // // Expect success. // let to = timeout.ice_timeout(-1) try controller.holdAdapter(100) do { try to.op() } catch is Ice.ConnectTimeoutException { try test(false) } } output.writeLine("ok") // The sequence needs to be large enough to fill the write/recv buffers let seq = ByteSeq(repeating: 0, count: 2_000_000) output.write("testing connection timeout... ") do { // // Expect TimeoutException. // let to = timeout.ice_timeout(250) _ = try connect(to) try controller.holdAdapter(-1) do { try to.sendData(seq) try test(false) } catch is Ice.TimeoutException { // Expected. } try controller.resumeAdapter() try timeout.op() // Ensure adapter is active. } do { // // Expect success. // let to = timeout.ice_timeout(2000) try controller.holdAdapter(100) do { try to.sendData(ByteSeq(repeating: 0, count: 1_000_000)) } catch is Ice.TimeoutException { try test(false) } } output.writeLine("ok") output.write("testing invocation timeout... ") do { let connection = try obj.ice_getConnection() var to = timeout.ice_invocationTimeout(100) try test(connection === to.ice_getConnection()) do { try to.sleep(1000) try test(false) } catch is Ice.InvocationTimeoutException {} try obj.ice_ping() to = timeout.ice_invocationTimeout(1000) try test(connection === to.ice_getConnection()) do { try to.sleep(100) } catch is Ice.InvocationTimeoutException { try test(false) } try test(connection === to.ice_getConnection()) } do { // // Expect InvocationTimeoutException. // let to = timeout.ice_invocationTimeout(100) do { try to.sleepAsync(500).wait() try test(false) } catch is Ice.InvocationTimeoutException {} try timeout.ice_ping() } do { // // Expect success. // let to = timeout.ice_invocationTimeout(1000) do { try to.sleepAsync(100).wait() } catch { try test(false) } } do { // // Backward compatible connection timeouts // let to = timeout.ice_invocationTimeout(-2).ice_timeout(250) var con = try connect(to) do { try to.sleep(750) try test(false) } catch is Ice.TimeoutException { do { _ = try con.getInfo() try test(false) } catch is Ice.TimeoutException { // Connection got closed as well. } } try timeout.ice_ping() do { con = try connect(to) try to.sleepAsync(750).wait() try test(false) } catch is Ice.TimeoutException { do { _ = try con.getInfo() try test(false) } catch is Ice.TimeoutException { // Connection got closed as well. } } try obj.ice_ping() } output.writeLine("ok") output.write("testing close timeout... ") do { let to = timeout.ice_timeout(250) let connection = try connect(to) try controller.holdAdapter(-1) try connection.close(.GracefullyWithWait) do { _ = try connection.getInfo() // getInfo() doesn't throw in the closing state. } catch is Ice.LocalException { try test(false) } while true { do { _ = try connection.getInfo() Thread.sleep(forTimeInterval: 0.01) } catch let ex as Ice.ConnectionManuallyClosedException { // Expected. try test(ex.graceful) // swiftlint:disable unneeded_break_in_switch break } } try controller.resumeAdapter() try timeout.op() // Ensure adapter is active. } output.writeLine("ok") output.write("testing timeout overrides... ") do { // // Test Ice.Override.Timeout. This property overrides all // endpoint timeouts. // let properties = communicator.getProperties().clone() properties.setProperty(key: "Ice.Override.ConnectTimeout", value: "250") properties.setProperty(key: "Ice.Override.Timeout", value: "100") var initData = Ice.InitializationData() initData.properties = properties let comm = try helper.initialize(initData) var to = try uncheckedCast(prx: comm.stringToProxy(sref)!, type: TimeoutPrx.self) _ = try connect(to) try controller.holdAdapter(-1) do { try to.sendData(seq) try test(false) } catch is Ice.TimeoutException { // Expected. } try controller.resumeAdapter() try timeout.op() // Ensure adapter is active. // // Calling ice_timeout() should have no effect. // to = to.ice_timeout(1000) _ = try connect(to) try controller.holdAdapter(-1) do { try to.sendData(seq) try test(false) } catch is Ice.TimeoutException { // Expected. } try controller.resumeAdapter() try timeout.op() // Ensure adapter is active. comm.destroy() } do { // // Test Ice.Override.ConnectTimeout. // let properties = communicator.getProperties().clone() properties.setProperty(key: "Ice.Override.ConnectTimeout", value: "250") var initData = Ice.InitializationData() initData.properties = properties let comm = try helper.initialize(initData) try controller.holdAdapter(-1) var to = try uncheckedCast(prx: comm.stringToProxy(sref)!, type: TimeoutPrx.self) do { try to.op() try test(false) } catch is Ice.ConnectTimeoutException { // Expected. } try controller.resumeAdapter() try timeout.op() // Ensure adapter is active. // // Calling ice_timeout() should have no effect on the connect timeout. // try controller.holdAdapter(-1) to = to.ice_timeout(1000) do { try to.op() try test(false) } catch is Ice.ConnectTimeoutException { // Expected. } try controller.resumeAdapter() try timeout.op() // Ensure adapter is active. // // Verify that timeout set via ice_timeout() is still used for requests. // to = to.ice_timeout(250) _ = try connect(to) try controller.holdAdapter(-1) do { try to.sendData(seq) try test(false) } catch is Ice.TimeoutException { // Expected. } try controller.resumeAdapter() try timeout.op() // Ensure adapter is active. comm.destroy() } do { // // Test Ice.Override.CloseTimeout. // let properties = communicator.getProperties().clone() properties.setProperty(key: "Ice.Override.CloseTimeout", value: "100") var initData = Ice.InitializationData() initData.properties = properties let comm = try helper.initialize(initData) _ = try comm.stringToProxy(sref)!.ice_getConnection() try controller.holdAdapter(-1) let begin = DispatchTime.now() comm.destroy() let elapsed = DispatchTime.now().uptimeNanoseconds - begin.uptimeNanoseconds try test((elapsed / 1_000_000) < 1000) try controller.resumeAdapter() } output.writeLine("ok") output.write("testing invocation timeouts with collocated calls... ") do { communicator.getProperties().setProperty(key: "TimeoutCollocated.AdapterId", value: "timeoutAdapter") let adapter = try communicator.createObjectAdapter("TimeoutCollocated") try adapter.activate() let proxy = try uncheckedCast(prx: adapter.addWithUUID(TimeoutDisp(TimeoutI())), type: TimeoutPrx.self).ice_invocationTimeout(100) do { try proxy.sleep(500) try test(false) } catch is Ice.InvocationTimeoutException {} do { try proxy.sleepAsync(500).wait() try test(false) } catch is Ice.InvocationTimeoutException {} do { try proxy.ice_invocationTimeout(-2).ice_ping() try proxy.ice_invocationTimeout(-2).ice_pingAsync().wait() } catch is Ice.Exception { try test(false) } let batchTimeout = proxy.ice_batchOneway() try batchTimeout.ice_ping() try batchTimeout.ice_ping() try batchTimeout.ice_ping() _ = proxy.ice_invocationTimeout(-1).sleepAsync(500) // Keep the server thread pool busy. do { try batchTimeout.ice_flushBatchRequestsAsync().wait() try test(false) } catch is Ice.InvocationTimeoutException {} adapter.destroy() } output.writeLine("ok") try controller.shutdown() }
gpl-2.0
LoopKit/LoopKit
LoopKit/DailyValueSchedule.swift
1
9251
// // QuantitySchedule.swift // Naterade // // Created by Nathan Racklyeft on 1/18/16. // Copyright © 2016 Nathan Racklyeft. All rights reserved. // import Foundation import HealthKit public struct RepeatingScheduleValue<T> { public var startTime: TimeInterval public var value: T public init(startTime: TimeInterval, value: T) { self.startTime = startTime self.value = value } public func map<U>(_ transform: (T) -> U) -> RepeatingScheduleValue<U> { return RepeatingScheduleValue<U>(startTime: startTime, value: transform(value)) } } extension RepeatingScheduleValue: Equatable where T: Equatable { public static func == (lhs: RepeatingScheduleValue, rhs: RepeatingScheduleValue) -> Bool { return abs(lhs.startTime - rhs.startTime) < .ulpOfOne && lhs.value == rhs.value } } extension RepeatingScheduleValue: Hashable where T: Hashable {} public struct AbsoluteScheduleValue<T>: TimelineValue { public let startDate: Date public let endDate: Date public let value: T } extension AbsoluteScheduleValue: Equatable where T: Equatable {} extension RepeatingScheduleValue: RawRepresentable where T: RawRepresentable { public typealias RawValue = [String: Any] public init?(rawValue: RawValue) { guard let startTime = rawValue["startTime"] as? Double, let rawValue = rawValue["value"] as? T.RawValue, let value = T(rawValue: rawValue) else { return nil } self.init(startTime: startTime, value: value) } public var rawValue: RawValue { return [ "startTime": startTime, "value": value.rawValue ] } } extension RepeatingScheduleValue: Codable where T: Codable {} public protocol DailySchedule { associatedtype T var items: [RepeatingScheduleValue<T>] { get } var timeZone: TimeZone { get set } func between(start startDate: Date, end endDate: Date) -> [AbsoluteScheduleValue<T>] func value(at time: Date) -> T } public extension DailySchedule { func value(at time: Date) -> T { return between(start: time, end: time).first!.value } } extension DailySchedule where T: Comparable { public func valueRange() -> ClosedRange<T> { items.range(of: { $0.value })! } } public struct DailyValueSchedule<T>: DailySchedule { let referenceTimeInterval: TimeInterval let repeatInterval: TimeInterval public let items: [RepeatingScheduleValue<T>] public var timeZone: TimeZone public init?(dailyItems: [RepeatingScheduleValue<T>], timeZone: TimeZone? = nil) { self.repeatInterval = TimeInterval(hours: 24) self.items = dailyItems.sorted { $0.startTime < $1.startTime } self.timeZone = timeZone ?? TimeZone.currentFixed guard let firstItem = self.items.first else { return nil } referenceTimeInterval = firstItem.startTime } var maxTimeInterval: TimeInterval { return referenceTimeInterval + repeatInterval } /** Returns the time interval for a given date normalized to the span of the schedule items - parameter date: The date to convert */ func scheduleOffset(for date: Date) -> TimeInterval { // The time interval since a reference date in the specified time zone let interval = date.timeIntervalSinceReferenceDate + TimeInterval(timeZone.secondsFromGMT(for: date)) // The offset of the time interval since the last occurence of the reference time + n * repeatIntervals. // If the repeat interval was 1 day, this is the fractional amount of time since the most recent repeat interval starting at the reference time return ((interval - referenceTimeInterval).truncatingRemainder(dividingBy: repeatInterval)) + referenceTimeInterval } /** Returns a slice of schedule items that occur between two dates - parameter startDate: The start date of the range - parameter endDate: The end date of the range - returns: A slice of `ScheduleItem` values */ public func between(start startDate: Date, end endDate: Date) -> [AbsoluteScheduleValue<T>] { guard startDate <= endDate else { return [] } let startOffset = scheduleOffset(for: startDate) let endOffset = startOffset + endDate.timeIntervalSince(startDate) guard endOffset <= maxTimeInterval else { let boundaryDate = startDate.addingTimeInterval(maxTimeInterval - startOffset) return between(start: startDate, end: boundaryDate) + between(start: boundaryDate, end: endDate) } var startIndex = 0 var endIndex = items.count for (index, item) in items.enumerated() { if startOffset >= item.startTime { startIndex = index } if endOffset < item.startTime { endIndex = index break } } let referenceDate = startDate.addingTimeInterval(-startOffset) return (startIndex..<endIndex).map { (index) in let item = items[index] let endTime = index + 1 < items.count ? items[index + 1].startTime : maxTimeInterval return AbsoluteScheduleValue( startDate: referenceDate.addingTimeInterval(item.startTime), endDate: referenceDate.addingTimeInterval(endTime), value: item.value ) } } public func map<U>(_ transform: (T) -> U) -> DailyValueSchedule<U> { return DailyValueSchedule<U>( dailyItems: items.map { $0.map(transform) }, timeZone: timeZone )! } public static func zip<L, R>(_ lhs: DailyValueSchedule<L>, _ rhs: DailyValueSchedule<R>) -> DailyValueSchedule where T == (L, R) { precondition(lhs.timeZone == rhs.timeZone) var (leftCursor, rightCursor) = (lhs.items.startIndex, rhs.items.startIndex) var alignedItems: [RepeatingScheduleValue<(L, R)>] = [] repeat { let (leftItem, rightItem) = (lhs.items[leftCursor], rhs.items[rightCursor]) let alignedItem = RepeatingScheduleValue( startTime: max(leftItem.startTime, rightItem.startTime), value: (leftItem.value, rightItem.value) ) alignedItems.append(alignedItem) let nextLeftStartTime = leftCursor == lhs.items.endIndex - 1 ? nil : lhs.items[leftCursor + 1].startTime let nextRightStartTime = rightCursor == rhs.items.endIndex - 1 ? nil : rhs.items[rightCursor + 1].startTime switch (nextLeftStartTime, nextRightStartTime) { case (.some(let leftStart), .some(let rightStart)): if leftStart < rightStart { leftCursor += 1 } else if rightStart < leftStart { rightCursor += 1 } else { leftCursor += 1 rightCursor += 1 } case (.some, .none): leftCursor += 1 case (.none, .some): rightCursor += 1 case (.none, .none): leftCursor += 1 rightCursor += 1 } } while leftCursor < lhs.items.endIndex && rightCursor < rhs.items.endIndex return DailyValueSchedule(dailyItems: alignedItems, timeZone: lhs.timeZone)! } } extension DailyValueSchedule: RawRepresentable, CustomDebugStringConvertible where T: RawRepresentable { public typealias RawValue = [String: Any] public init?(rawValue: RawValue) { guard let rawItems = rawValue["items"] as? [RepeatingScheduleValue<T>.RawValue] else { return nil } var timeZone: TimeZone? if let offset = rawValue["timeZone"] as? Int { timeZone = TimeZone(secondsFromGMT: offset) } let validScheduleItems = rawItems.compactMap(RepeatingScheduleValue<T>.init(rawValue:)) guard validScheduleItems.count == rawItems.count else { return nil } self.init(dailyItems: validScheduleItems, timeZone: timeZone) } public var rawValue: RawValue { let rawItems = items.map { $0.rawValue } return [ "timeZone": timeZone.secondsFromGMT(), "items": rawItems ] } public var debugDescription: String { return String(reflecting: rawValue) } } extension DailyValueSchedule: Codable where T: Codable {} extension DailyValueSchedule: Equatable where T: Equatable {} extension RepeatingScheduleValue { public static func == <L: Equatable, R: Equatable> (lhs: RepeatingScheduleValue, rhs: RepeatingScheduleValue) -> Bool where T == (L, R) { return lhs.startTime == rhs.startTime && lhs.value == rhs.value } } extension DailyValueSchedule { public static func == <L: Equatable, R: Equatable> (lhs: DailyValueSchedule, rhs: DailyValueSchedule) -> Bool where T == (L, R) { return lhs.timeZone == rhs.timeZone && lhs.items.count == rhs.items.count && Swift.zip(lhs.items, rhs.items).allSatisfy(==) } }
mit
grafele/Prototyper
Prototyper/Classes/APIHandler.swift
2
8060
// // APIHandler.swift // Prototype // // Created by Stefan Kofler on 17.06.15. // Copyright (c) 2015 Stephan Rabanser. All rights reserved. // import Foundation import UIKit let sharedInstance = APIHandler() private let defaultBoundary = "------VohpleBoundary4QuqLuM1cE5lMwCy" class APIHandler { let session: URLSession var appId: String! { return Bundle.main.object(forInfoDictionaryKey: "PrototyperAppId") as? String ?? UserDefaults.standard.string(forKey: UserDefaultKeys.AppId) } var releaseId: String! { return Bundle.main.object(forInfoDictionaryKey: "PrototyperReleaseId") as? String ?? UserDefaults.standard.string(forKey: UserDefaultKeys.ReleaseId) } var isLoggedIn: Bool = false init() { let sessionConfig = URLSessionConfiguration.default session = URLSession(configuration: sessionConfig) } class var sharedAPIHandler: APIHandler { return sharedInstance } // MARK: API Methods func fetchReleaseInformation(success: @escaping (_ appId: String, _ releaseId: String) -> Void, failure: @escaping (_ error : Error?) -> Void) { let bundleId = Bundle.main.infoDictionary?[kCFBundleIdentifierKey as String] as? String ?? "" let bundleVersion = Bundle.main.infoDictionary?[kCFBundleVersionKey as String] as? String ?? "" let url = URL(string: API.EndPoints.fetchReleaseInfo(bundleId: bundleId, bundleVersion: bundleVersion), relativeTo: API.BaseURL)! let request = jsonRequestForHttpMethod(.GET, requestURL: url) executeRequest(request as URLRequest) { (data, response, error) in guard let data = data else { failure(error) return } do { let dict = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Int] if let dict = dict, let appId = dict["app_id"], let releaseId = dict["release_id"] { success("\(appId)", "\(releaseId)") } else { failure(error) } } catch { failure(error) } } } func login(_ email: String, password: String, success: @escaping (Void) -> Void, failure: @escaping (_ error : Error?) -> Void) { let params = postParamsForLogin(email: email, password: password) let articlesURL = URL(string: API.EndPoints.Login, relativeTo: API.BaseURL as URL?) guard let requestURL = articlesURL else { failure(NSError.APIURLError()) return } guard let bodyData = try? JSONSerialization.data(withJSONObject: params, options: JSONSerialization.WritingOptions.prettyPrinted) else { failure(NSError.dataEncodeError()) return } let request = jsonRequestForHttpMethod(.POST, requestURL: requestURL, bodyData: bodyData) executeRequest(request as URLRequest) { (data, response, networkError) in let httpURLResponse: HTTPURLResponse! = response as? HTTPURLResponse let error = (data == nil || httpURLResponse.statusCode != 200) ? NSError.dataParseError() : networkError error != nil ? failure(error) : success() self.isLoggedIn = error == nil } } func sendGeneralFeedback(description: String, name: String? = nil, success: @escaping (Void) -> Void, failure: @escaping (_ error : Error?) -> Void) { guard let appId = appId, let releaseId = releaseId else { print("You need to set the app and release id first") return } let url = URL(string: API.EndPoints.feedback(appId, releaseId: releaseId, text: description.escapedString, username: name?.escapedString), relativeTo: API.BaseURL)! let request = jsonRequestForHttpMethod(.POST, requestURL: url) executeRequest(request as URLRequest) { (data, response, error) in error != nil ? failure(error) : success() } } func sendScreenFeedback(screenshot: UIImage, description: String, name: String? = nil, success: @escaping (Void) -> Void, failure: @escaping (_ error : Error?) -> Void) { guard let appId = appId, let releaseId = releaseId else { print("You need to set the app and release id first") failure(nil) return } let contentType = "\(MimeType.Multipart.rawValue); boundary=\(defaultBoundary)" let bodyData = bodyDataForImage(screenshot) let url = URL(string: API.EndPoints.feedback(appId, releaseId: releaseId, text: description.escapedString, username: name?.escapedString), relativeTo: API.BaseURL)! let request = jsonRequestForHttpMethod(.POST, requestURL: url, bodyData: bodyData, contentType: contentType) executeRequest(request as URLRequest) { (data, response, error) in error != nil ? failure(error) : success() } } func sendShareRequest(for email: String, because explanation: String, name: String? = nil, success: @escaping (Void) -> Void, failure: @escaping (_ error : Error?) -> Void) { guard let appId = appId, let releaseId = releaseId else { print("You need to set the app and release id first") failure(nil) return } let url = URL(string: API.EndPoints.share(appId, releaseId: releaseId, sharedEmail: email.escapedString, explanation: explanation.escapedString, username: name?.escapedString), relativeTo: API.BaseURL)! let request = jsonRequestForHttpMethod(.POST, requestURL: url) executeRequest(request as URLRequest) { (data, response, error) in error != nil ? failure(error) : success() } } // TODO: Add method to check for new versions // MARK: Helper fileprivate func jsonRequestForHttpMethod(_ method: HTTPMethod, requestURL: URL, bodyData: Data? = nil, contentType: String = MimeType.JSON.rawValue) -> NSMutableURLRequest { let request = NSMutableURLRequest(url: requestURL) request.httpMethod = method.rawValue request.setValue(contentType, forHTTPHeaderField: HTTPHeaderField.ContentType.rawValue) request.setValue(MimeType.JSON.rawValue, forHTTPHeaderField: HTTPHeaderField.Accept.rawValue) request.httpBody = bodyData return request } fileprivate func bodyDataForImage(_ image: UIImage, boundary: String = defaultBoundary) -> Data { let bodyData = NSMutableData() let imageData = UIImageJPEGRepresentation(image, 0.4) bodyData.append("--\(boundary)\r\n".data(using: String.Encoding.utf8, allowLossyConversion: true)!) bodyData.append("Content-Disposition: form-data; name=\"[feedback]screenshot\"; filename=\"screenshot.jpg\"\r\n".data(using: String.Encoding.utf8, allowLossyConversion: true)!) bodyData.append("Content-Type: image/jpeg\r\n\r\n".data(using: String.Encoding.utf8, allowLossyConversion: true)!) bodyData.append(imageData!) bodyData.append("\r\n--\(boundary)--\r\n".data(using: String.Encoding.utf8, allowLossyConversion: true)!) return bodyData as Data } fileprivate func executeRequest(_ request: URLRequest, completionHandler: @escaping (Data?, URLResponse?, Error?) -> Void) { let dataTask = session.dataTask(with: request, completionHandler: { (data, response, error) in OperationQueue.main.addOperation { completionHandler(data, response, error) } return () }) dataTask.resume() } // MARK: Post params fileprivate func postParamsForLogin(email: String, password: String) -> [String: Any] { typealias Session = API.DataTypes.Session return [Session.Session: [Session.Email: email, Session.Password: password]] } }
mit
ikesyo/Himotoki
Package.swift
1
466
// swift-tools-version:5.0 import PackageDescription let package = Package( name: "Himotoki", platforms: [ .macOS(.v10_10), .iOS(.v8), .tvOS(.v9), .watchOS(.v2) ], products: [ .library(name: "Himotoki", targets: ["Himotoki"]), ], targets: [ .target(name: "Himotoki", dependencies: [], path: "Sources"), .testTarget(name: "HimotokiTests", dependencies: ["Himotoki"]), ], swiftLanguageVersions: [.v5] )
mit
gottesmm/swift
test/expr/expressions.swift
2
36345
// RUN: %target-typecheck-verify-swift //===----------------------------------------------------------------------===// // Tests and samples. //===----------------------------------------------------------------------===// // Comment. With unicode characters: ¡ç®åz¥! func markUsed<T>(_: T) {} // Various function types. var func1 : () -> () // No input, no output. var func2 : (Int) -> Int var func3 : () -> () -> () // Takes nothing, returns a fn. var func3a : () -> (() -> ()) // same as func3 var func6 : (_ fn : (Int,Int) -> Int) -> () // Takes a fn, returns nothing. var func7 : () -> (Int,Int,Int) // Takes nothing, returns tuple. // Top-Level expressions. These are 'main' content. func1() _ = 4+7 var bind_test1 : () -> () = func1 var bind_test2 : Int = 4; func1 // expected-error {{expression resolves to an unused l-value}} (func1, func2) // expected-error {{expression resolves to an unused l-value}} func basictest() { // Simple integer variables. var x : Int var x2 = 4 // Simple Type inference. var x3 = 4+x*(4+x2)/97 // Basic Expressions. // Declaring a variable Void, aka (), is fine too. var v : Void var x4 : Bool = true var x5 : Bool = 4 // expected-error {{cannot convert value of type 'Int' to specified type 'Bool'}} //var x6 : Float = 4+5 var x7 = 4; 5 // expected-warning {{integer literal is unused}} // Test implicit conversion of integer literal to non-Int64 type. var x8 : Int8 = 4 x8 = x8 + 1 _ = x8 + 1 _ = 0 + x8 1.0 + x8 // expected-error{{binary operator '+' cannot be applied to operands of type 'Double' and 'Int8'}} // expected-note @-1 {{overloads for '+' exist with these partially matching parameter lists:}} var x9 : Int16 = x8 + 1 // expected-error {{cannot convert value of type 'Int8' to specified type 'Int16'}} // Various tuple types. var tuple1 : () var tuple2 : (Int) var tuple3 : (Int, Int, ()) var tuple2a : (a : Int) // expected-error{{cannot create a single-element tuple with an element label}}{{18-22=}} var tuple3a : (a : Int, b : Int, c : ()) var tuple4 = (1, 2) // Tuple literal. var tuple5 = (1, 2, 3, 4) // Tuple literal. var tuple6 = (1 2) // expected-error {{expected ',' separator}} {{18-18=,}} // Brace expressions. var brace3 = { var brace2 = 42 // variable shadowing. _ = brace2+7 } // Function calls. var call1 : () = func1() var call2 = func2(1) var call3 : () = func3()() // Cannot call an integer. bind_test2() // expected-error {{cannot call value of non-function type 'Int'}}{{13-15=}} } // <https://bugs.swift.org/browse/SR-3522> func testUnusedLiterals_SR3522() { 42 // expected-warning {{integer literal is unused}} 2.71828 // expected-warning {{floating-point literal is unused}} true // expected-warning {{boolean literal is unused}} false // expected-warning {{boolean literal is unused}} "Hello" // expected-warning {{string literal is unused}} "Hello \(42)" // expected-warning {{string literal is unused}} #file // expected-warning {{#file literal is unused}} (#line) // expected-warning {{#line literal is unused}} #column // expected-warning {{#column literal is unused}} #function // expected-warning {{#function literal is unused}} #dsohandle // expected-warning {{#dsohandle literal is unused}} __FILE__ // expected-error {{__FILE__ has been replaced with #file in Swift 3}} expected-warning {{#file literal is unused}} __LINE__ // expected-error {{__LINE__ has been replaced with #line in Swift 3}} expected-warning {{#line literal is unused}} __COLUMN__ // expected-error {{__COLUMN__ has been replaced with #column in Swift 3}} expected-warning {{#column literal is unused}} __FUNCTION__ // expected-error {{__FUNCTION__ has been replaced with #function in Swift 3}} expected-warning {{#function literal is unused}} __DSO_HANDLE__ // expected-error {{__DSO_HANDLE__ has been replaced with #dsohandle in Swift 3}} expected-warning {{#dsohandle literal is unused}} nil // expected-error {{'nil' requires a contextual type}} #fileLiteral(resourceName: "what.txt") // expected-error {{could not infer type of file reference literal}} expected-note * {{}} #imageLiteral(resourceName: "hello.png") // expected-error {{could not infer type of image literal}} expected-note * {{}} #colorLiteral(red: 1, green: 0, blue: 0, alpha: 1) // expected-error {{could not infer type of color literal}} expected-note * {{}} } // Infix operators and attribute lists. infix operator %% : MinPrecedence precedencegroup MinPrecedence { associativity: left lowerThan: AssignmentPrecedence } func %%(a: Int, b: Int) -> () {} var infixtest : () = 4 % 2 + 27 %% 123 // The 'func' keyword gives a nice simplification for function definitions. func funcdecl1(_ a: Int, _ y: Int) {} func funcdecl2() { return funcdecl1(4, 2) } func funcdecl3() -> Int { return 12 } func funcdecl4(_ a: ((Int) -> Int), b: Int) {} func signal(_ sig: Int, f: (Int) -> Void) -> (Int) -> Void {} // Doing fun things with named arguments. Basic stuff first. func funcdecl6(_ a: Int, b: Int) -> Int { return a+b } // Can dive into tuples, 'b' is a reference to a whole tuple, c and d are // fields in one. Cannot dive into functions or through aliases. func funcdecl7(_ a: Int, b: (c: Int, d: Int), third: (c: Int, d: Int)) -> Int { _ = a + b.0 + b.c + third.0 + third.1 b.foo // expected-error {{value of tuple type '(c: Int, d: Int)' has no member 'foo'}} } // Error recovery. func testfunc2 (_: ((), Int) -> Int) -> Int {} func errorRecovery() { testfunc2({ $0 + 1 }) // expected-error {{contextual closure type '((), Int) -> Int' expects 2 arguments, but 1 was used in closure body}} enum union1 { case bar case baz } var a: Int = .hello // expected-error {{type 'Int' has no member 'hello'}} var b: union1 = .bar // ok var c: union1 = .xyz // expected-error {{type 'union1' has no member 'xyz'}} var d: (Int,Int,Int) = (1,2) // expected-error {{cannot convert value of type '(Int, Int)' to specified type '(Int, Int, Int)'}} var e: (Int,Int) = (1, 2, 3) // expected-error {{cannot convert value of type '(Int, Int, Int)' to specified type '(Int, Int)'}} var f: (Int,Int) = (1, 2, f : 3) // expected-error {{cannot convert value of type '(Int, Int, f: Int)' to specified type '(Int, Int)'}} // <rdar://problem/22426860> CrashTracer: [USER] swift at …mous_namespace::ConstraintGenerator::getTypeForPattern + 698 var (g1, g2, g3) = (1, 2) // expected-error {{'(Int, Int)' is not convertible to '(_, _, _)', tuples have a different number of elements}} } func acceptsInt(_ x: Int) {} acceptsInt(unknown_var) // expected-error {{use of unresolved identifier 'unknown_var'}} var test1a: (Int) -> (Int) -> Int = { { $0 } } // expected-error{{contextual type for closure argument list expects 1 argument, which cannot be implicitly ignored}} {{38-38= _ in}} var test1b = { 42 } var test1c = { { 42 } } var test1d = { { { 42 } } } func test2(_ a: Int, b: Int) -> (c: Int) { // expected-error{{cannot create a single-element tuple with an element label}} {{34-37=}} expected-note {{did you mean 'a'?}} expected-note {{did you mean 'b'?}} _ = a+b a+b+c // expected-error{{use of unresolved identifier 'c'}} return a+b } func test3(_ arg1: Int, arg2: Int) -> Int { return 4 } func test4() -> ((_ arg1: Int, _ arg2: Int) -> Int) { return test3 } func test5() { let a: (Int, Int) = (1,2) var _: ((Int) -> Int, Int) = a // expected-error {{cannot convert value of type '(Int, Int)' to specified type '((Int) -> Int, Int)'}} let c: (a: Int, b: Int) = (1,2) let _: (b: Int, a: Int) = c // Ok, reshuffle tuple. } // Functions can obviously take and return values. func w3(_ a: Int) -> Int { return a } func w4(_: Int) -> Int { return 4 } func b1() {} func foo1(_ a: Int, b: Int) -> Int {} func foo2(_ a: Int) -> (_ b: Int) -> Int {} func foo3(_ a: Int = 2, b: Int = 3) {} prefix operator ^^ prefix func ^^(a: Int) -> Int { return a + 1 } func test_unary1() { var x: Int x = ^^(^^x) x = *x // expected-error {{'*' is not a prefix unary operator}} x = x* // expected-error {{'*' is not a postfix unary operator}} x = +(-x) x = + -x // expected-error {{unary operator cannot be separated from its operand}} {{8-9=}} } func test_unary2() { var x: Int // FIXME: second diagnostic is redundant. x = &; // expected-error {{expected expression after unary operator}} expected-error {{expected expression in assignment}} } func test_unary3() { var x: Int // FIXME: second diagnostic is redundant. x = &, // expected-error {{expected expression after unary operator}} expected-error {{expected expression in assignment}} } func test_as_1() { var _: Int } func test_as_2() { let x: Int = 1 x as [] // expected-error {{expected element type}} } func test_lambda() { // A simple closure. var a = { (value: Int) -> () in markUsed(value+1) } // A recursive lambda. // FIXME: This should definitely be accepted. var fib = { (n: Int) -> Int in if (n < 2) { return n } return fib(n-1)+fib(n-2) // expected-error 2 {{variable used within its own initial value}} } } func test_lambda2() { { () -> protocol<Int> in // expected-warning @-1 {{'protocol<...>' composition syntax is deprecated and not needed here}} {{11-24=Int}} // expected-error @-2 {{non-protocol type 'Int' cannot be used within a protocol composition}} // expected-warning @-3 {{result of call is unused}} return 1 }() } func test_floating_point() { _ = 0.0 _ = 100.1 var _: Float = 0.0 var _: Double = 0.0 } func test_nonassoc(_ x: Int, y: Int) -> Bool { // FIXME: the second error and note here should arguably disappear return x == y == x // expected-error {{adjacent operators are in non-associative precedence group 'ComparisonPrecedence'}} expected-error {{binary operator '==' cannot be applied to operands of type 'Bool' and 'Int'}} expected-note {{overloads for '==' exist with these partially matching parameter lists:}} } // More realistic examples. func fib(_ n: Int) -> Int { if (n < 2) { return n } return fib(n-2) + fib(n-1) } //===----------------------------------------------------------------------===// // Integer Literals //===----------------------------------------------------------------------===// // FIXME: Should warn about integer constants being too large <rdar://problem/14070127> var il_a: Bool = 4 // expected-error {{cannot convert value of type 'Int' to specified type 'Bool'}} var il_b: Int8 = 123123 var il_c: Int8 = 4 // ok struct int_test4 : ExpressibleByIntegerLiteral { typealias IntegerLiteralType = Int init(integerLiteral value: Int) {} // user type. } var il_g: int_test4 = 4 // This just barely fits in Int64. var il_i: Int64 = 18446744073709551615 // This constant is too large to fit in an Int64, but it is fine for Int128. // FIXME: Should warn about the first. <rdar://problem/14070127> var il_j: Int64 = 18446744073709551616 // var il_k: Int128 = 18446744073709551616 var bin_literal: Int64 = 0b100101 var hex_literal: Int64 = 0x100101 var oct_literal: Int64 = 0o100101 // verify that we're not using C rules var oct_literal_test: Int64 = 0123 assert(oct_literal_test == 123) // ensure that we swallow random invalid chars after the first invalid char var invalid_num_literal: Int64 = 0QWERTY // expected-error{{expected a digit after integer literal prefix}} var invalid_bin_literal: Int64 = 0bQWERTY // expected-error{{expected a digit after integer literal prefix}} var invalid_hex_literal: Int64 = 0xQWERTY // expected-error{{expected a digit after integer literal prefix}} var invalid_oct_literal: Int64 = 0oQWERTY // expected-error{{expected a digit after integer literal prefix}} var invalid_exp_literal: Double = 1.0e+QWERTY // expected-error{{expected a digit in floating point exponent}} // rdar://11088443 var negative_int32: Int32 = -1 // <rdar://problem/11287167> var tupleelemvar = 1 markUsed((tupleelemvar, tupleelemvar).1) func int_literals() { // Fits exactly in 64-bits - rdar://11297273 _ = 1239123123123123 // Overly large integer. // FIXME: Should warn about it. <rdar://problem/14070127> _ = 123912312312312312312 } // <rdar://problem/12830375> func tuple_of_rvalues(_ a:Int, b:Int) -> Int { return (a, b).1 } extension Int { func testLexingMethodAfterIntLiteral() {} func _0() {} // Hex letters func ffa() {} // Hex letters + non hex. func describe() {} // Hex letters + 'p'. func eap() {} // Hex letters + 'p' + non hex. func fpValue() {} } 123.testLexingMethodAfterIntLiteral() 0b101.testLexingMethodAfterIntLiteral() 0o123.testLexingMethodAfterIntLiteral() 0x1FFF.testLexingMethodAfterIntLiteral() 123._0() 0b101._0() 0o123._0() 0x1FFF._0() 0x1fff.ffa() 0x1FFF.describe() 0x1FFF.eap() 0x1FFF.fpValue() var separator1: Int = 1_ var separator2: Int = 1_000 var separator4: Int = 0b1111_0000_ var separator5: Int = 0b1111_0000 var separator6: Int = 0o127_777_ var separator7: Int = 0o127_777 var separator8: Int = 0x12FF_FFFF var separator9: Int = 0x12FF_FFFF_ //===----------------------------------------------------------------------===// // Float Literals //===----------------------------------------------------------------------===// var fl_a = 0.0 var fl_b: Double = 1.0 var fl_c: Float = 2.0 // FIXME: crummy diagnostic var fl_d: Float = 2.0.0 // expected-error {{expected named member of numeric literal}} var fl_e: Float = 1.0e42 var fl_f: Float = 1.0e+ // expected-error {{expected a digit in floating point exponent}} var fl_g: Float = 1.0E+42 var fl_h: Float = 2e-42 var vl_i: Float = -.45 // expected-error {{'.45' is not a valid floating point literal; it must be written '0.45'}} {{20-20=0}} var fl_j: Float = 0x1p0 var fl_k: Float = 0x1.0p0 var fl_l: Float = 0x1.0 // expected-error {{hexadecimal floating point literal must end with an exponent}} var fl_m: Float = 0x1.FFFFFEP-2 var fl_n: Float = 0x1.fffffep+2 var fl_o: Float = 0x1.fffffep+ // expected-error {{expected a digit in floating point exponent}} var fl_p: Float = 0x1p // expected-error {{expected a digit in floating point exponent}} var fl_q: Float = 0x1p+ // expected-error {{expected a digit in floating point exponent}} var fl_r: Float = 0x1.0fp // expected-error {{expected a digit in floating point exponent}} var fl_s: Float = 0x1.0fp+ // expected-error {{expected a digit in floating point exponent}} var fl_t: Float = 0x1.p // expected-error {{value of type 'Int' has no member 'p'}} var fl_u: Float = 0x1.p2 // expected-error {{value of type 'Int' has no member 'p2'}} var fl_v: Float = 0x1.p+ // expected-error {{'+' is not a postfix unary operator}} var fl_w: Float = 0x1.p+2 // expected-error {{value of type 'Int' has no member 'p'}} var if1: Double = 1.0 + 4 // integer literal ok as double. var if2: Float = 1.0 + 4 // integer literal ok as float. var fl_separator1: Double = 1_.2_ var fl_separator2: Double = 1_000.2_ var fl_separator3: Double = 1_000.200_001 var fl_separator4: Double = 1_000.200_001e1_ var fl_separator5: Double = 1_000.200_001e1_000 var fl_separator6: Double = 1_000.200_001e1_000 var fl_separator7: Double = 0x1_.0FFF_p1_ var fl_separator8: Double = 0x1_0000.0FFF_ABCDp10_001 var fl_bad_separator1: Double = 1e_ // expected-error {{expected a digit in floating point exponent}} var fl_bad_separator2: Double = 0x1p_ // expected-error {{expected a digit in floating point exponent}} expected-error{{'_' can only appear in a pattern or on the left side of an assignment}} expected-error {{consecutive statements on a line must be separated by ';'}} {{37-37=;}} //===----------------------------------------------------------------------===// // String Literals //===----------------------------------------------------------------------===// var st_a = "" var st_b: String = "" var st_c = "asdfasd // expected-error {{unterminated string literal}} var st_d = " \t\n\r\"\'\\ " // Valid simple escapes var st_e = " \u{12}\u{0012}\u{00000078} " // Valid unicode escapes var st_u1 = " \u{1} " var st_u2 = " \u{123} " var st_u3 = " \u{1234567} " // expected-error {{invalid unicode scalar}} var st_u4 = " \q " // expected-error {{invalid escape sequence in literal}} var st_u5 = " \u{FFFFFFFF} " // expected-error {{invalid unicode scalar}} var st_u6 = " \u{D7FF} \u{E000} " // Fencepost UTF-16 surrogate pairs. var st_u7 = " \u{D800} " // expected-error {{invalid unicode scalar}} var st_u8 = " \u{DFFF} " // expected-error {{invalid unicode scalar}} var st_u10 = " \u{0010FFFD} " // Last valid codepoint, 0xFFFE and 0xFFFF are reserved in each plane var st_u11 = " \u{00110000} " // expected-error {{invalid unicode scalar}} func stringliterals(_ d: [String: Int]) { // rdar://11385385 let x = 4 "Hello \(x+1) world" // expected-warning {{string literal is unused}} "Error: \(x+1"; // expected-error {{unterminated string literal}} "Error: \(x+1 // expected-error {{unterminated string literal}} ; // expected-error {{';' statements are not allowed}} // rdar://14050788 [DF] String Interpolations can't contain quotes "test \("nested")" "test \("\("doubly nested")")" "test \(d["hi"])" "test \("quoted-paren )")" "test \("quoted-paren (")" "test \("\\")" "test \("\n")" "test \("\")" // expected-error {{unterminated string literal}} "test \ // expected-error @-1 {{unterminated string literal}} expected-error @-1 {{invalid escape sequence in literal}} "test \("\ // expected-error @-1 {{unterminated string literal}} "test newline \("something" + "something else")" // expected-error @-2 {{unterminated string literal}} expected-error @-1 {{unterminated string literal}} // expected-warning @+2 {{variable 'x2' was never used; consider replacing with '_' or removing it}} // expected-error @+1 {{unterminated string literal}} var x2 : () = ("hello" + " ; } func testSingleQuoteStringLiterals() { _ = 'abc' // expected-error{{single-quoted string literal found, use '"'}}{{7-12="abc"}} _ = 'abc' + "def" // expected-error{{single-quoted string literal found, use '"'}}{{7-12="abc"}} _ = 'ab\nc' // expected-error{{single-quoted string literal found, use '"'}}{{7-14="ab\\nc"}} _ = "abc\('def')" // expected-error{{single-quoted string literal found, use '"'}}{{13-18="def"}} _ = "abc' // expected-error{{unterminated string literal}} _ = 'abc" // expected-error{{unterminated string literal}} _ = "a'c" _ = 'ab\'c' // expected-error{{single-quoted string literal found, use '"'}}{{7-14="ab'c"}} _ = 'ab"c' // expected-error{{single-quoted string literal found, use '"'}}{{7-13="ab\\"c"}} _ = 'ab\"c' // expected-error{{single-quoted string literal found, use '"'}}{{7-14="ab\\"c"}} _ = 'ab\\"c' // expected-error{{single-quoted string literal found, use '"'}}{{7-15="ab\\\\\\"c"}} } // <rdar://problem/17128913> var s = "" s.append(contentsOf: ["x"]) //===----------------------------------------------------------------------===// // InOut arguments //===----------------------------------------------------------------------===// func takesInt(_ x: Int) {} func takesExplicitInt(_ x: inout Int) { } func testInOut(_ arg: inout Int) { var x: Int takesExplicitInt(x) // expected-error{{passing value of type 'Int' to an inout parameter requires explicit '&'}} {{20-20=&}} takesExplicitInt(&x) takesInt(&x) // expected-error{{'&' used with non-inout argument of type 'Int'}} var y = &x // expected-error{{'&' can only appear immediately in a call argument list}} \ // expected-error {{variable has type 'inout Int' which includes nested inout parameters}} var z = &arg // expected-error{{'&' can only appear immediately in a call argument list}} \ // expected-error {{variable has type 'inout Int' which includes nested inout parameters}} takesExplicitInt(5) // expected-error {{cannot pass immutable value as inout argument: literals are not mutable}} } //===----------------------------------------------------------------------===// // Conversions //===----------------------------------------------------------------------===// var pi_f: Float var pi_d: Double struct SpecialPi {} // Type with no implicit construction. var pi_s: SpecialPi func getPi() -> Float {} // expected-note 3 {{found this candidate}} func getPi() -> Double {} // expected-note 3 {{found this candidate}} func getPi() -> SpecialPi {} enum Empty { } extension Empty { init(_ f: Float) { } } func conversionTest(_ a: inout Double, b: inout Int) { var f: Float var d: Double a = Double(b) a = Double(f) a = Double(d) // no-warning b = Int(a) f = Float(b) var pi_f1 = Float(pi_f) var pi_d1 = Double(pi_d) var pi_s1 = SpecialPi(pi_s) // expected-error {{argument passed to call that takes no arguments}} var pi_f2 = Float(getPi()) // expected-error {{ambiguous use of 'getPi()'}} var pi_d2 = Double(getPi()) // expected-error {{ambiguous use of 'getPi()'}} var pi_s2: SpecialPi = getPi() // no-warning var float = Float.self var pi_f3 = float.init(getPi()) // expected-error {{ambiguous use of 'getPi()'}} var pi_f4 = float.init(pi_f) var e = Empty(f) var e2 = Empty(d) // expected-error{{cannot convert value of type 'Double' to expected argument type 'Float'}} var e3 = Empty(Float(d)) } struct Rule { // expected-note {{'init(target:dependencies:)' declared here}} var target: String var dependencies: String } var ruleVar: Rule ruleVar = Rule("a") // expected-error {{missing argument for parameter 'dependencies' in call}} class C { var x: C? init(other: C?) { x = other } func method() {} } _ = C(3) // expected-error {{missing argument label 'other:' in call}} _ = C(other: 3) // expected-error {{cannot convert value of type 'Int' to expected argument type 'C?'}} //===----------------------------------------------------------------------===// // Unary Operators //===----------------------------------------------------------------------===// func unaryOps(_ i8: inout Int8, i64: inout Int64) { i8 = ~i8 i64 += 1 i8 -= 1 Int64(5) += 1 // expected-error{{left side of mutating operator isn't mutable: function call returns immutable value}} // <rdar://problem/17691565> attempt to modify a 'let' variable with ++ results in typecheck error not being able to apply ++ to Float let a = i8 // expected-note {{change 'let' to 'var' to make it mutable}} {{3-6=var}} a += 1 // expected-error {{left side of mutating operator isn't mutable: 'a' is a 'let' constant}} var b : Int { get { }} b += 1 // expected-error {{left side of mutating operator isn't mutable: 'b' is a get-only property}} } //===----------------------------------------------------------------------===// // Iteration //===----------------------------------------------------------------------===// func..<(x: Double, y: Double) -> Double { return x + y } func iterators() { _ = 0..<42 _ = 0.0..<42.0 } //===----------------------------------------------------------------------===// // Magic literal expressions //===----------------------------------------------------------------------===// func magic_literals() { _ = __FILE__ // expected-error {{__FILE__ has been replaced with #file in Swift 3}} _ = __LINE__ // expected-error {{__LINE__ has been replaced with #line in Swift 3}} _ = __COLUMN__ // expected-error {{__COLUMN__ has been replaced with #column in Swift 3}} _ = __DSO_HANDLE__ // expected-error {{__DSO_HANDLE__ has been replaced with #dsohandle in Swift 3}} _ = #file _ = #line + #column var _: UInt8 = #line + #column } //===----------------------------------------------------------------------===// // lvalue processing //===----------------------------------------------------------------------===// infix operator +-+= @discardableResult func +-+= (x: inout Int, y: Int) -> Int { return 0} func lvalue_processing() { var i = 0 i += 1 // obviously ok var fn = (+-+=) var n = 42 fn(n, 12) // expected-error {{passing value of type 'Int' to an inout parameter requires explicit '&'}} {{6-6=&}} fn(&n, 12) // expected-warning {{result of call is unused, but produces 'Int'}} n +-+= 12 (+-+=)(&n, 12) // ok. (+-+=)(n, 12) // expected-error {{passing value of type 'Int' to an inout parameter requires explicit '&'}} {{10-10=&}} } struct Foo { func method() {} mutating func mutatingMethod() {} } func test() { var x = Foo() let y = Foo() // FIXME: Bad diagnostics // rdar://15708430 (&x).method() // expected-error {{type of expression is ambiguous without more context}} (&x).mutatingMethod() // expected-error {{cannot use mutating member on immutable value of type 'inout Foo'}} } // Unused results. func unusedExpressionResults() { // Unused l-value _ // expected-error{{'_' can only appear in a pattern or on the left side of an assignment}} // <rdar://problem/20749592> Conditional Optional binding hides compiler error let optionalc:C? = nil optionalc?.method() // ok optionalc?.method // expected-error {{expression resolves to an unused function}} } //===----------------------------------------------------------------------===// // Collection Literals //===----------------------------------------------------------------------===// func arrayLiterals() { let _ = [1,2,3] let _ : [Int] = [] let _ = [] // expected-error {{empty collection literal requires an explicit type}} } func dictionaryLiterals() { let _ = [1 : "foo",2 : "bar",3 : "baz"] let _: Dictionary<Int, String> = [:] let _ = [:] // expected-error {{empty collection literal requires an explicit type}} } func invalidDictionaryLiteral() { // FIXME: lots of unnecessary diagnostics. var a = [1: ; // expected-error {{expected value in dictionary literal}} var b = [1: ;] // expected-error {{expected value in dictionary literal}} var c = [1: "one" ;] // expected-error {{expected key expression in dictionary literal}} expected-error {{expected ',' separator}} {{20-20=,}} var d = [1: "one", ;] // expected-error {{expected key expression in dictionary literal}} var e = [1: "one", 2] // expected-error {{expected ':' in dictionary literal}} var f = [1: "one", 2 ;] // expected-error {{expected ':' in dictionary literal}} var g = [1: "one", 2: ;] // expected-error {{expected value in dictionary literal}} } // FIXME: The issue here is a type compatibility problem, there is no ambiguity. [4].joined(separator: [1]) // expected-error {{type of expression is ambiguous without more context}} [4].joined(separator: [[[1]]]) // expected-error {{type of expression is ambiguous without more context}} //===----------------------------------------------------------------------===// // nil/metatype comparisons //===----------------------------------------------------------------------===// _ = Int.self == nil // expected-warning {{comparing non-optional value of type 'Any.Type' to nil always returns false}} _ = nil == Int.self // expected-warning {{comparing non-optional value of type 'Any.Type' to nil always returns false}} _ = Int.self != nil // expected-warning {{comparing non-optional value of type 'Any.Type' to nil always returns true}} _ = nil != Int.self // expected-warning {{comparing non-optional value of type 'Any.Type' to nil always returns true}} // <rdar://problem/19032294> Disallow postfix ? when not chaining func testOptionalChaining(_ a : Int?, b : Int!, c : Int??) { _ = a? // expected-error {{optional chain has no effect, expression already produces 'Int?'}} {{8-9=}} _ = a?.customMirror _ = b? // expected-error {{'?' must be followed by a call, member lookup, or subscript}} _ = b?.customMirror var _: Int? = c? // expected-error {{'?' must be followed by a call, member lookup, or subscript}} } // <rdar://problem/19657458> Nil Coalescing operator (??) should have a higher precedence func testNilCoalescePrecedence(cond: Bool, a: Int?, r: CountableClosedRange<Int>?) { // ?? should have higher precedence than logical operators like || and comparisons. if cond || (a ?? 42 > 0) {} // Ok. if (cond || a) ?? 42 > 0 {} // expected-error {{cannot be used as a boolean}} {{15-15=(}} {{16-16= != nil)}} if (cond || a) ?? (42 > 0) {} // expected-error {{cannot be used as a boolean}} {{15-15=(}} {{16-16= != nil)}} if cond || a ?? 42 > 0 {} // Parses as the first one, not the others. // ?? should have lower precedence than range and arithmetic operators. let r1 = r ?? (0...42) // ok let r2 = (r ?? 0)...42 // not ok: expected-error {{cannot convert value of type 'Int' to expected argument type 'CountableClosedRange<Int>'}} let r3 = r ?? 0...42 // parses as the first one, not the second. // <rdar://problem/27457457> [Type checker] Diagnose unsavory optional injections // Accidental optional injection for ??. let i = 42 _ = i ?? 17 // expected-warning {{left side of nil coalescing operator '??' has non-optional type 'Int', so the right side is never used}} {{9-15=}} } // <rdar://problem/19772570> Parsing of as and ?? regressed func testOptionalTypeParsing(_ a : AnyObject) -> String { return a as? String ?? "default name string here" } func testParenExprInTheWay() { let x = 42 if x & 4.0 {} // expected-error {{binary operator '&' cannot be applied to operands of type 'Int' and 'Double'}} expected-note {{expected an argument list of type '(Int, Int)'}} if (x & 4.0) {} // expected-error {{binary operator '&' cannot be applied to operands of type 'Int' and 'Double'}} expected-note {{expected an argument list of type '(Int, Int)'}} if !(x & 4.0) {} // expected-error {{binary operator '&' cannot be applied to operands of type 'Int' and 'Double'}} //expected-note @-1 {{expected an argument list of type '(Int, Int)'}} if x & x {} // expected-error {{'Int' is not convertible to 'Bool'}} } // <rdar://problem/21352576> Mixed method/property overload groups can cause a crash during constraint optimization public struct TestPropMethodOverloadGroup { public typealias Hello = String public let apply:(Hello) -> Int public func apply(_ input:Hello) -> Int { return apply(input) } } // <rdar://problem/18496742> Passing ternary operator expression as inout crashes Swift compiler func inoutTests(_ arr: inout Int) { var x = 1, y = 2 (true ? &x : &y) // expected-error 2 {{'&' can only appear immediately in a call argument list}} // expected-warning @-1 {{expression of type 'inout Int' is unused}} let a = (true ? &x : &y) // expected-error 2 {{'&' can only appear immediately in a call argument list}} // expected-error @-1 {{variable has type 'inout Int' which includes nested inout parameters}} inoutTests(true ? &x : &y); // expected-error 2 {{'&' can only appear immediately in a call argument list}} &_ // expected-error {{expression type 'inout _' is ambiguous without more context}} inoutTests((&x)) // expected-error {{'&' can only appear immediately in a call argument list}} inoutTests(&x) // <rdar://problem/17489894> inout not rejected as operand to assignment operator &x += y // expected-error {{'&' can only appear immediately in a call argument list}} // <rdar://problem/23249098> func takeAny(_ x: Any) {} takeAny(&x) // expected-error{{'&' used with non-inout argument of type 'Any'}} func takeManyAny(_ x: Any...) {} takeManyAny(&x) // expected-error{{'&' used with non-inout argument of type 'Any'}} takeManyAny(1, &x) // expected-error{{'&' used with non-inout argument of type 'Any'}} func takeIntAndAny(_ x: Int, _ y: Any) {} takeIntAndAny(1, &x) // expected-error{{'&' used with non-inout argument of type 'Any'}} } // <rdar://problem/20802757> Compiler crash in default argument & inout expr var g20802757 = 2 func r20802757(_ z: inout Int = &g20802757) { // expected-error {{'&' can only appear immediately in a call argument list}} print(z) } _ = _.foo // expected-error {{type of expression is ambiguous without more context}} // <rdar://problem/22211854> wrong arg list crashing sourcekit func r22211854() { func f(_ x: Int, _ y: Int, _ z: String = "") {} // expected-note 2 {{'f' declared here}} func g<T>(_ x: T, _ y: T, _ z: String = "") {} // expected-note 2 {{'g' declared here}} f(1) // expected-error{{missing argument for parameter #2 in call}} g(1) // expected-error{{missing argument for parameter #2 in call}} func h() -> Int { return 1 } f(h() == 1) // expected-error{{missing argument for parameter #2 in call}} g(h() == 1) // expected-error{{missing argument for parameter #2 in call}} } // <rdar://problem/22348394> Compiler crash on invoking function with labeled defaulted param with non-labeled argument func r22348394() { func f(x: Int = 0) { } f(Int(3)) // expected-error{{missing argument label 'x:' in call}} } // <rdar://problem/23185177> Compiler crashes in Assertion failed: ((AllowOverwrite || !E->hasLValueAccessKind()) && "l-value access kind has already been set"), function visit protocol P { var y: String? { get } } func r23185177(_ x: P?) -> [String] { return x?.y // expected-error{{cannot convert return expression of type 'String?' to return type '[String]'}} } // <rdar://problem/22913570> Miscompile: wrong argument parsing when calling a function in swift2.0 func r22913570() { func f(_ from: Int = 0, to: Int) {} // expected-note {{'f(_:to:)' declared here}} f(1 + 1) // expected-error{{missing argument for parameter 'to' in call}} } // <rdar://problem/23708702> Emit deprecation warnings for ++/-- in Swift 2.2 func swift22_deprecation_increment_decrement() { var i = 0 var f = 1.0 i++ // expected-error {{'++' is unavailable}} {{4-6= += 1}} --i // expected-error {{'--' is unavailable}} {{3-5=}} {{6-6= -= 1}} _ = i++ // expected-error {{'++' is unavailable}} ++f // expected-error {{'++' is unavailable}} {{3-5=}} {{6-6= += 1}} f-- // expected-error {{'--' is unavailable}} {{4-6= -= 1}} _ = f-- // expected-error {{'--' is unavailable}} {{none}} // <rdar://problem/24530312> Swift ++fix-it produces bad code in nested expressions // This should not get a fixit hint. var j = 2 i = ++j // expected-error {{'++' is unavailable}} {{none}} } // SR-628 mixing lvalues and rvalues in tuple expression var x = 0 var y = 1 let _ = (x, x + 1).0 let _ = (x, 3).1 (x,y) = (2,3) (x,4) = (1,2) // expected-error {{cannot assign to value: literals are not mutable}} (x,y).1 = 7 // expected-error {{cannot assign to immutable expression of type 'Int'}} x = (x,(3,y)).1.1 // SE-0101 sizeof family functions are reconfigured into MemoryLayout protocol Pse0101 { associatedtype Value func getIt() -> Value } class Cse0101<U> { typealias T = U var val: U { fatalError() } } func se0101<P: Pse0101>(x: Cse0101<P>) { // Note: The first case is actually not allowed, but it is very common and can be compiled currently. _ = sizeof(P) // expected-error {{'sizeof' is unavailable: use MemoryLayout<T>.size instead.}} {{7-14=MemoryLayout<}} {{15-16=>.size}} {{none}} // expected-warning@-1 {{missing '.self' for reference to metatype of type 'P'}} _ = sizeof(P.self) // expected-error {{'sizeof' is unavailable: use MemoryLayout<T>.size instead.}} {{7-14=MemoryLayout<}} {{15-21=>.size}} {{none}} _ = sizeof(P.Value.self) // expected-error {{'sizeof' is unavailable: use MemoryLayout<T>.size instead.}} {{7-14=MemoryLayout<}} {{21-27=>.size}} {{none}} _ = sizeof(Cse0101<P>.self) // expected-error {{'sizeof' is unavailable: use MemoryLayout<T>.size instead.}} {{7-14=MemoryLayout<}} {{24-30=>.size}} {{none}} _ = alignof(Cse0101<P>.T.self) // expected-error {{'alignof' is unavailable: use MemoryLayout<T>.alignment instead.}} {{7-15=MemoryLayout<}} {{27-33=>.alignment}} {{none}} _ = strideof(P.Type.self) // expected-error {{'strideof' is unavailable: use MemoryLayout<T>.stride instead.}} {{7-16=MemoryLayout<}} {{22-28=>.stride}} {{none}} _ = sizeof(type(of: x)) // expected-error {{'sizeof' is unavailable: use MemoryLayout<T>.size instead.}} {{7-26=MemoryLayout<Cse0101<P>>.size}} {{none}} }
apache-2.0
bman4789/bpm
BPM/BPM/MainViewController.swift
1
3203
// // MainViewController.swift // BPM // // Created by Brian Mitchell and Zach Litzinger on 4/8/16. // Copyright © 2016 Brian Mitchell. All rights reserved. // import UIKit import Foundation import ChameleonFramework import FontAwesome_swift class MainViewController: UIViewController { var loadTheme: Bool = { Style.loadTheme() return true }() @IBOutlet weak var settings: UIButton! @IBOutlet weak var bpmDisplay: UILabel! @IBOutlet weak var bpmTap: BMButton! override func viewDidLoad() { super.viewDidLoad() settings.titleLabel?.font = UIFont.fontAwesomeOfSize(30) settings.setTitle(String.fontAwesomeIconWithName(.Cog), forState: .Normal) } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) updateTheme() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func updateTheme() { self.setStatusBarStyle(UIStatusBarStyleContrast) self.view.backgroundColor = Style.colorArray[2] bpmDisplay.textColor = UIColor(contrastingBlackOrWhiteColorOn:Style.colorArray[2], isFlat:Style.isFlat) bpmTap.setTitleColor(UIColor(contrastingBlackOrWhiteColorOn:Style.colorArray[2], isFlat:Style.isFlat), forState: UIControlState.Normal) bpmTap.strokeColor = Style.colorArray[1].colorWithAlphaComponent(0.25) bpmTap.rippleColor = Style.colorArray[1].colorWithAlphaComponent(0.33) self.view.tintColor = UIColor(contrastingBlackOrWhiteColorOn:Style.colorArray[2], isFlat:Style.isFlat) } // BPM logic and functionality var X: Double = 0.0 var P: Double = 0.0 var Q: Double = 0.0 var A: Double = 0.0 var H: Double = 0.0 var R: Double = 0.0 var lastTime: NSDate? = nil func initBPM() { X = 1 //Initial Duration between the taps P = 0.1 //Initial confidence in the measurements of the values of x Q = 0.00001 //Constant error: you know that you are often slow A = 1 // ------- might be important? H = 0.001 //How accurately we believe the instrument is measuring R = 0.0001 //Speed of response to variant lastTime = nil } @IBAction func bpmTap(sender: BMButton) { if lastTime?.timeIntervalSinceNow < -5.0 { initBPM() } let timeDiff = timeDifference() let calculation = correct(timeDiff) bpmDisplay.text = "\(Int(60.0 / calculation))" } func timeDifference() -> Double { let currentTime = NSDate() if lastTime == nil { lastTime = NSDate(timeIntervalSinceNow: -1) } let timeDiff = currentTime.timeIntervalSinceDate(lastTime!) lastTime = currentTime return timeDiff } func predict() { X = A * X P = A * P + Q } func correct(measurement: Double) -> Double { predict() let K = P * (1 / (P + R)) X = X + K * (measurement - X) P = (1 - K) * P return X } }
mit
airspeedswift/swift-compiler-crashes
crashes-fuzzing/02189-swift-type-walk.swift
12
221
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing protocol A { protocol A { func a<j : a } func b ( A
mit
petroladkin/SwiftyBluetooth
SwiftyBluetooth/Source/CBExtensions.swift
1
6437
// // CBExtensions.swift // // Copyright (c) 2016 Jordane Belanger // // 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 CoreBluetooth extension CBPeripheral { public func serviceWithUUID(_ uuid: CBUUID) -> CBService? { guard let services = self.services else { return nil } return services.filter { $0.uuid == uuid }.first } public func servicesWithUUIDs(_ servicesUUIDs: [CBUUID]) -> (foundServices: [CBService], missingServicesUUIDs: [CBUUID]) { assert(servicesUUIDs.count > 0) guard let currentServices = self.services , currentServices.count > 0 else { return (foundServices: [], missingServicesUUIDs: servicesUUIDs) } let currentServicesUUIDs = currentServices.map { $0.uuid } let currentServicesUUIDsSet = Set(currentServicesUUIDs) let requestedServicesUUIDsSet = Set(servicesUUIDs) let foundServicesUUIDsSet = requestedServicesUUIDsSet.intersection(currentServicesUUIDsSet) let missingServicesUUIDsSet = requestedServicesUUIDsSet.subtracting(currentServicesUUIDsSet) let foundServices = currentServices.filter { foundServicesUUIDsSet.contains($0.uuid) } return (foundServices: foundServices, missingServicesUUIDs: Array(missingServicesUUIDsSet)) } public var uuidIdentifier: UUID { #if os(OSX) if #available(OSX 10.13, *) { return self.identifier } else { let description: String = self.description //<CBPeripheral: 0x6080000c3fe0 identifier = 7E33A1DD-7E65-4162-89A4-F44A2B4F9D67, Name = "(null)", state = disconnected> guard let range = description.range(of:"identifier = .+?,", options:.regularExpression) else { return UUID(uuidString: "11111111-1111-1111-1111-111111111111")! } var uuid = description.substring(with: range) //identifier = 7E33A1DD-7E65-4162-89A4-F44A2B4F9D67, uuid = uuid.substring(from: uuid.index(uuid.startIndex, offsetBy: 13)) //7E33A1DD-7E65-4162-89A4-F44A2B4F9D67, uuid = uuid.substring(to: uuid.index(before: uuid.endIndex)) //7E33A1DD-7E65-4162-89A4-F44A2B4F9D67 return UUID(uuidString: uuid)! } #else return self.identifier #endif } } extension CBService { public func characteristicWithUUID(_ uuid: CBUUID) -> CBCharacteristic? { guard let characteristics = self.characteristics else { return nil } return characteristics.filter { $0.uuid == uuid }.first } public func characteristicsWithUUIDs(_ characteristicsUUIDs: [CBUUID]) -> (foundCharacteristics: [CBCharacteristic], missingCharacteristicsUUIDs: [CBUUID]) { assert(characteristicsUUIDs.count > 0) guard let currentCharacteristics = self.characteristics , currentCharacteristics.count > 0 else { return (foundCharacteristics: [], missingCharacteristicsUUIDs: characteristicsUUIDs) } let currentCharacteristicsUUID = currentCharacteristics.map { $0.uuid } let currentCharacteristicsUUIDSet = Set(currentCharacteristicsUUID) let requestedCharacteristicsUUIDSet = Set(characteristicsUUIDs) let foundCharacteristicsUUIDSet = requestedCharacteristicsUUIDSet.intersection(currentCharacteristicsUUIDSet) let missingCharacteristicsUUIDSet = requestedCharacteristicsUUIDSet.subtracting(currentCharacteristicsUUIDSet) let foundCharacteristics = currentCharacteristics.filter { foundCharacteristicsUUIDSet.contains($0.uuid) } return (foundCharacteristics: foundCharacteristics, missingCharacteristicsUUIDs: Array(missingCharacteristicsUUIDSet)) } } extension CBCharacteristic { public func descriptorWithUUID(_ uuid: CBUUID) -> CBDescriptor? { guard let descriptors = self.descriptors else { return nil } return descriptors.filter { $0.uuid == uuid }.first } public func descriptorsWithUUIDs(_ descriptorsUUIDs: [CBUUID]) -> (foundDescriptors: [CBDescriptor], missingDescriptorsUUIDs: [CBUUID]) { assert(descriptorsUUIDs.count > 0) guard let currentDescriptors = self.descriptors , currentDescriptors.count > 0 else { return (foundDescriptors: [], missingDescriptorsUUIDs: descriptorsUUIDs) } let currentDescriptorsUUIDs = currentDescriptors.map { $0.uuid } let currentDescriptorsUUIDsSet = Set(currentDescriptorsUUIDs) let requestedDescriptorsUUIDsSet = Set(descriptorsUUIDs) let foundDescriptorsUUIDsSet = requestedDescriptorsUUIDsSet.intersection(currentDescriptorsUUIDsSet) let missingDescriptorsUUIDsSet = requestedDescriptorsUUIDsSet.subtracting(currentDescriptorsUUIDsSet) let foundDescriptors = currentDescriptors.filter { foundDescriptorsUUIDsSet.contains($0.uuid) } return (foundDescriptors: foundDescriptors, missingDescriptorsUUIDs: Array(missingDescriptorsUUIDsSet)) } }
mit
Fenrikur/ef-app_ios
Eurofurence/Modules/Event Feedback/Presenter/EventFeedbackPresenterFactoryImpl.swift
1
2035
import EurofurenceModel struct EventFeedbackPresenterFactoryImpl: EventFeedbackPresenterFactory { private let eventService: EventsService private let dayOfWeekFormatter: DayOfWeekFormatter private let startTimeFormatter: HoursDateFormatter private let endTimeFormatter: HoursDateFormatter private let successHaptic: SuccessHaptic private let failureHaptic: FailureHaptic private let successWaitingRule: EventFeedbackSuccessWaitingRule init(eventService: EventsService, dayOfWeekFormatter: DayOfWeekFormatter, startTimeFormatter: HoursDateFormatter, endTimeFormatter: HoursDateFormatter, successHaptic: SuccessHaptic, failureHaptic: FailureHaptic, successWaitingRule: EventFeedbackSuccessWaitingRule) { self.eventService = eventService self.dayOfWeekFormatter = dayOfWeekFormatter self.startTimeFormatter = startTimeFormatter self.endTimeFormatter = endTimeFormatter self.successHaptic = successHaptic self.failureHaptic = failureHaptic self.successWaitingRule = successWaitingRule } func makeEventFeedbackPresenter(for event: EventIdentifier, scene: EventFeedbackScene, delegate: EventFeedbackModuleDelegate) { guard let event = eventService.fetchEvent(identifier: event) else { return } _ = EventFeedbackPresenter(event: event, scene: scene, delegate: delegate, dayOfWeekFormatter: dayOfWeekFormatter, startTimeFormatter: startTimeFormatter, endTimeFormatter: endTimeFormatter, successHaptic: successHaptic, failureHaptic: failureHaptic, successWaitingRule: successWaitingRule) } }
mit
mercadopago/px-ios
MercadoPagoSDK/MercadoPagoSDK/Core/PaymentMethodSelector/Extensions/PXPaymentMethodSelector+Tracking.swift
1
4972
import Foundation // MARK: Tracking extension PXPaymentMethodSelector { func startTracking(then: @escaping (() -> Void)) { viewModel?.trackingConfiguration?.updateTracker() MPXTracker.sharedInstance.startNewSession() // Track init event var properties: [String: Any] = [:] if !String.isNullOrEmpty(viewModel?.checkoutPreference.id) { properties["checkout_preference_id"] = viewModel?.checkoutPreference.id } else if let checkoutPreference = viewModel?.checkoutPreference { properties["checkout_preference"] = getCheckoutPrefForTracking(checkoutPreference: checkoutPreference) } properties["esc_enabled"] = viewModel?.getAdvancedConfiguration().isESCEnabled() properties["express_enabled"] = viewModel?.getAdvancedConfiguration().expressEnabled viewModel?.populateCheckoutStore() properties["split_enabled"] = false MPXTracker.sharedInstance.trackEvent(event: MercadoPagoCheckoutTrackingEvents.didInitFlow(properties)) then() } func trackInitFlowFriction(flowError: InitFlowError) { var properties: [String: Any] = [:] properties["path"] = TrackingPaths.Screens.PaymentVault.getPaymentVaultPath() properties["style"] = Tracking.Style.screen properties["id"] = Tracking.Error.Id.genericError properties["message"] = "Hubo un error" properties["attributable_to"] = Tracking.Error.Atrributable.user var extraDic: [String: Any] = [:] var errorDic: [String: Any] = [:] errorDic["url"] = flowError.requestOrigin?.rawValue errorDic["retry_available"] = flowError.shouldRetry errorDic["status"] = flowError.apiException?.status if let causes = flowError.apiException?.cause { var causesDic: [String: Any] = [:] for cause in causes where !String.isNullOrEmpty(cause.code) { causesDic["code"] = cause.code causesDic["description"] = cause.causeDescription } errorDic["causes"] = causesDic } extraDic["api_error"] = errorDic properties["extra_info"] = extraDic MPXTracker.sharedInstance.trackEvent(event: GeneralErrorTrackingEvents.error(properties)) } func trackInitFlowRefreshFriction(cardId: String) { var properties: [String: Any] = [:] properties["path"] = TrackingPaths.Screens.OneTap.getOneTapPath() properties["style"] = Tracking.Style.noScreen properties["id"] = Tracking.Error.Id.genericError properties["message"] = "No se pudo recuperar la tarjeta ingresada" properties["attributable_to"] = Tracking.Error.Atrributable.mercadopago var extraDic: [String: Any] = [:] extraDic["cardId"] = cardId properties["extra_info"] = extraDic MPXTracker.sharedInstance.trackEvent(event: GeneralErrorTrackingEvents.error(properties)) } private func getCheckoutPrefForTracking(checkoutPreference: PXCheckoutPreference) -> [String: Any] { var checkoutPrefDic: [String: Any] = [:] var itemsDic: [[String: Any]] = [] for item in checkoutPreference.items { itemsDic.append(item.getItemForTracking()) } checkoutPrefDic["items"] = itemsDic checkoutPrefDic["binary_mode"] = checkoutPreference.binaryModeEnabled checkoutPrefDic["marketplace"] = checkoutPreference.marketplace checkoutPrefDic["site_id"] = checkoutPreference.siteId checkoutPrefDic["expiration_date_from"] = checkoutPreference.expirationDateFrom?.stringDate() checkoutPrefDic["expiration_date_to"] = checkoutPreference.expirationDateTo?.stringDate() checkoutPrefDic["payment_methods"] = getPaymentPreferenceForTracking(paymentPreference: checkoutPreference.paymentPreference) return checkoutPrefDic } func getPaymentPreferenceForTracking(paymentPreference: PXPaymentPreference) -> [String: Any] { var paymentPrefDic: [String: Any] = [:] paymentPrefDic["installments"] = paymentPreference.maxAcceptedInstallments paymentPrefDic["default_installments"] = paymentPreference.defaultInstallments paymentPrefDic["excluded_payment_methods"] = transformTrackingArray(paymentPreference.excludedPaymentMethodIds) paymentPrefDic["excluded_payment_types"] = transformTrackingArray(paymentPreference.excludedPaymentTypeIds) paymentPrefDic["default_card_id"] = paymentPreference.cardId return paymentPrefDic } private func transformTrackingArray(_ items: [String]) -> [[String: String]] { var newArray = [[String: String]]() for item in items { let newItem = transformTrackingItem(item) newArray.append(newItem) } return newArray } private func transformTrackingItem(_ item: String) -> [String: String] { return ["id": item] } }
mit
leonchen/simpleApp
simpleApp/AppDelegate.swift
1
2141
// // AppDelegate.swift // simpleApp // // Created by leon chen on 12/19/15. // Copyright © 2015 leon chen. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> 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 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
tokyovigilante/CesiumKit
CesiumKit/Scene/GridImageryProvider.swift
1
13191
// // GridImageryProvider.swift // CesiumKit // // Created by Ryan Walklin on 29/09/14. // Copyright (c) 2014 Test Toast. All rights reserved. // /** * An {@link ImageryProvider} that draws a wireframe grid on every tile with controllable background and glow. * May be useful for custom rendering effects or debugging terrain. * * @alias GridImageryProvider * @constructor * * @param {Object} [options] Object with the following properties: * @param {TilingScheme} [options.tilingScheme=new GeographicTilingScheme()] The tiling scheme for which to draw tiles. * @param {Number} [options.cells=8] The number of grids cells. * @param {Color} [options.color=Color(1.0, 1.0, 1.0, 0.4)] The color to draw grid lines. * @param {Color} [options.glowColor=Color(0.0, 1.0, 0.0, 0.05)] The color to draw glow for grid lines. * @param {Number} [options.glowWidth=6] The width of lines used for rendering the line glow effect. * @param {Color} [backgroundColor=Color(0.0, 0.5, 0.0, 0.2)] Background fill color. * @param {Number} [options.tileWidth=256] The width of the tile for level-of-detail selection purposes. * @param {Number} [options.tileHeight=256] The height of the tile for level-of-detail selection purposes. * @param {Number} [options.canvasSize=256] The size of the canvas used for rendering. */ class GridImageryProvider/*: ImageryProvider*/ { /* /*global define*/ define([ '../Core/Color', '../Core/defaultValue', '../Core/defined', '../Core/defineProperties', '../Core/Event', '../Core/GeographicTilingScheme' ], function( Color, defaultValue, defined, defineProperties, Event, GeographicTilingScheme) { "use strict"; var defaultColor = new Color(1.0, 1.0, 1.0, 0.4); var defaultGlowColor = new Color(0.0, 1.0, 0.0, 0.05); var defaultBackgroundColor = new Color(0.0, 0.5, 0.0, 0.2); /** * An {@link ImageryProvider} that draws a wireframe grid on every tile with controllable background and glow. * May be useful for custom rendering effects or debugging terrain. * * @alias GridImageryProvider * @constructor * * @param {Object} [options] Object with the following properties: * @param {TilingScheme} [options.tilingScheme=new GeographicTilingScheme()] The tiling scheme for which to draw tiles. * @param {Ellipsoid} [options.ellipsoid] The ellipsoid. If the tilingScheme is specified, * this parameter is ignored and the tiling scheme's ellipsoid is used instead. If neither * parameter is specified, the WGS84 ellipsoid is used. * @param {Number} [options.cells=8] The number of grids cells. * @param {Color} [options.color=Color(1.0, 1.0, 1.0, 0.4)] The color to draw grid lines. * @param {Color} [options.glowColor=Color(0.0, 1.0, 0.0, 0.05)] The color to draw glow for grid lines. * @param {Number} [options.glowWidth=6] The width of lines used for rendering the line glow effect. * @param {Color} [backgroundColor=Color(0.0, 0.5, 0.0, 0.2)] Background fill color. * @param {Number} [options.tileWidth=256] The width of the tile for level-of-detail selection purposes. * @param {Number} [options.tileHeight=256] The height of the tile for level-of-detail selection purposes. * @param {Number} [options.canvasSize=256] The size of the canvas used for rendering. */ var GridImageryProvider = function GridImageryProvider(options) { options = defaultValue(options, defaultValue.EMPTY_OBJECT); this._tilingScheme = defined(options.tilingScheme) ? options.tilingScheme : new GeographicTilingScheme({ ellipsoid : options.ellipsoid }); this._cells = defaultValue(options.cells, 8); this._color = defaultValue(options.color, defaultColor); this._glowColor = defaultValue(options.glowColor, defaultGlowColor); this._glowWidth = defaultValue(options.glowWidth, 6); this._backgroundColor = defaultValue(options.backgroundColor, defaultBackgroundColor); this._errorEvent = new Event(); this._tileWidth = defaultValue(options.tileWidth, 256); this._tileHeight = defaultValue(options.tileHeight, 256); // A little larger than tile size so lines are sharper // Note: can't be too much difference otherwise texture blowout this._canvasSize = defaultValue(options.canvasSize, 256); // We only need a single canvas since all tiles will be the same this._canvas = this._createGridCanvas(); }; defineProperties(GridImageryProvider.prototype, { /** * Gets the proxy used by this provider. * @memberof GridImageryProvider.prototype * @type {Proxy} * @readonly */ proxy : { get : function() { return undefined; } }, /** * Gets the width of each tile, in pixels. This function should * not be called before {@link GridImageryProvider#ready} returns true. * @memberof GridImageryProvider.prototype * @type {Number} * @readonly */ tileWidth : { get : function() { return this._tileWidth; } }, /** * Gets the height of each tile, in pixels. This function should * not be called before {@link GridImageryProvider#ready} returns true. * @memberof GridImageryProvider.prototype * @type {Number} * @readonly */ tileHeight : { get : function() { return this._tileHeight; } }, /** * Gets the maximum level-of-detail that can be requested. This function should * not be called before {@link GridImageryProvider#ready} returns true. * @memberof GridImageryProvider.prototype * @type {Number} * @readonly */ maximumLevel : { get : function() { return undefined; } }, /** * Gets the minimum level-of-detail that can be requested. This function should * not be called before {@link GridImageryProvider#ready} returns true. * @memberof GridImageryProvider.prototype * @type {Number} * @readonly */ minimumLevel : { get : function() { return undefined; } }, /** * Gets the tiling scheme used by this provider. This function should * not be called before {@link GridImageryProvider#ready} returns true. * @memberof GridImageryProvider.prototype * @type {TilingScheme} * @readonly */ tilingScheme : { get : function() { return this._tilingScheme; } }, /** * Gets the rectangle, in radians, of the imagery provided by this instance. This function should * not be called before {@link GridImageryProvider#ready} returns true. * @memberof GridImageryProvider.prototype * @type {Rectangle} * @readonly */ rectangle : { get : function() { return this._tilingScheme.rectangle; } }, /** * Gets the tile discard policy. If not undefined, the discard policy is responsible * for filtering out "missing" tiles via its shouldDiscardImage function. If this function * returns undefined, no tiles are filtered. This function should * not be called before {@link GridImageryProvider#ready} returns true. * @memberof GridImageryProvider.prototype * @type {TileDiscardPolicy} * @readonly */ tileDiscardPolicy : { get : function() { return undefined; } }, /** * Gets an event that is raised when the imagery provider encounters an asynchronous error. By subscribing * to the event, you will be notified of the error and can potentially recover from it. Event listeners * are passed an instance of {@link TileProviderError}. * @memberof GridImageryProvider.prototype * @type {Event} * @readonly */ errorEvent : { get : function() { return this._errorEvent; } }, /** * Gets a value indicating whether or not the provider is ready for use. * @memberof GridImageryProvider.prototype * @type {Boolean} * @readonly */ ready : { get : function() { return true; } }, /** * Gets the credit to display when this imagery provider is active. Typically this is used to credit * the source of the imagery. This function should not be called before {@link GridImageryProvider#ready} returns true. * @memberof GridImageryProvider.prototype * @type {Credit} * @readonly */ credit : { get : function() { return undefined; } }, /** * Gets a value indicating whether or not the images provided by this imagery provider * include an alpha channel. If this property is false, an alpha channel, if present, will * be ignored. If this property is true, any images without an alpha channel will be treated * as if their alpha is 1.0 everywhere. When this property is false, memory usage * and texture upload time are reduced. * @memberof GridImageryProvider.prototype * @type {Boolean} * @readonly */ hasAlphaChannel : { get : function() { return true; } } }); /** * Draws a grid of lines into a canvas. */ GridImageryProvider.prototype._drawGrid = function(context) { var minPixel = 0; var maxPixel = this._canvasSize; for (var x = 0; x <= this._cells; ++x) { var nx = x / this._cells; var val = 1 + nx * (maxPixel - 1); context.moveTo(val, minPixel); context.lineTo(val, maxPixel); context.moveTo(minPixel, val); context.lineTo(maxPixel, val); } context.stroke(); }; /** * Render a grid into a canvas with background and glow */ GridImageryProvider.prototype._createGridCanvas = function() { var canvas = document.createElement('canvas'); canvas.width = this._canvasSize; canvas.height = this._canvasSize; var minPixel = 0; var maxPixel = this._canvasSize; var context = canvas.getContext('2d'); // Fill the background var cssBackgroundColor = this._backgroundColor.toCssColorString(); context.fillStyle = cssBackgroundColor; context.fillRect(minPixel, minPixel, maxPixel, maxPixel); // Glow for grid lines var cssGlowColor = this._glowColor.toCssColorString(); context.strokeStyle = cssGlowColor; // Wide context.lineWidth = this._glowWidth; context.strokeRect(minPixel, minPixel, maxPixel, maxPixel); this._drawGrid(context); // Narrow context.lineWidth = this._glowWidth * 0.5; context.strokeRect(minPixel, minPixel, maxPixel, maxPixel); this._drawGrid(context); // Grid lines var cssColor = this._color.toCssColorString(); // Border context.strokeStyle = cssColor; context.lineWidth = 2; context.strokeRect(minPixel, minPixel, maxPixel, maxPixel); // Inner context.lineWidth = 1; this._drawGrid(context); return canvas; }; /** * Gets the credits to be displayed when a given tile is displayed. * * @param {Number} x The tile X coordinate. * @param {Number} y The tile Y coordinate. * @param {Number} level The tile level; * @returns {Credit[]} The credits to be displayed when the tile is displayed. * * @exception {DeveloperError} <code>getTileCredits</code> must not be called before the imagery provider is ready. */ GridImageryProvider.prototype.getTileCredits = function(x, y, level) { return undefined; }; /** * Requests the image for a given tile. This function should * not be called before {@link GridImageryProvider#ready} returns true. * * @param {Number} x The tile X coordinate. * @param {Number} y The tile Y coordinate. * @param {Number} level The tile level. * @returns {Promise.<Image|Canvas>|undefined} A promise for the image that will resolve when the image is available, or * undefined if there are too many active requests to the server, and the request * should be retried later. The resolved image may be either an * Image or a Canvas DOM object. */ GridImageryProvider.prototype.requestImage = function(x, y, level) { return this._canvas; }; /** * Picking features is not currently supported by this imagery provider, so this function simply returns * undefined. * * @param {Number} x The tile X coordinate. * @param {Number} y The tile Y coordinate. * @param {Number} level The tile level. * @param {Number} longitude The longitude at which to pick features. * @param {Number} latitude The latitude at which to pick features. * @return {Promise.<ImageryLayerFeatureInfo[]>|undefined} A promise for the picked features that will resolve when the asynchronous * picking completes. The resolved value is an array of {@link ImageryLayerFeatureInfo} * instances. The array may be empty if no features are found at the given location. * It may also be undefined if picking is not supported. */ GridImageryProvider.prototype.pickFeatures = function() { return undefined; }; return GridImageryProvider; }); */ }
apache-2.0
GreatfeatServices/gf-mobile-app
olivin-esguerra/ios-exam/Pods/RxCocoa/RxCocoa/Foundation/Logging.swift
37
500
// // Logging.swift // RxCocoa // // Created by Krunoslav Zaher on 4/3/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import Foundation /// Simple logging settings for RxCocoa library. public struct Logging { public typealias LogURLRequest = (URLRequest) -> Bool /// Log URL requests to standard output in curl format. public static var URLRequests: LogURLRequest = { _ in #if DEBUG return true #else return false #endif } }
apache-2.0
linusnyberg/RepoList
Pods/OAuthSwift/Sources/String+OAuthSwift.swift
1
2643
// // String+OAuthSwift.swift // OAuthSwift // // Created by Dongri Jin on 6/21/14. // Copyright (c) 2014 Dongri Jin. All rights reserved. // import Foundation extension String { var urlEncodedString: String { let customAllowedSet = CharacterSet(charactersIn: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~") let escapedString = self.addingPercentEncoding(withAllowedCharacters: customAllowedSet) return escapedString! } var parametersFromQueryString: [String: String] { return dictionaryBySplitting("&", keyValueSeparator: "=") } var urlQueryEncoded: String? { return self.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed) } fileprivate func dictionaryBySplitting(_ elementSeparator: String, keyValueSeparator: String) -> [String: String] { var string = self if(hasPrefix(elementSeparator)) { string = String(characters.dropFirst(1)) } var parameters = Dictionary<String, String>() let scanner = Scanner(string: string) var key: NSString? var value: NSString? while !scanner.isAtEnd { key = nil scanner.scanUpTo(keyValueSeparator, into: &key) scanner.scanString(keyValueSeparator, into: nil) value = nil scanner.scanUpTo(elementSeparator, into: &value) scanner.scanString(elementSeparator, into: nil) if let key = key as String?, let value = value as String? { parameters.updateValue(value, forKey: key) } } return parameters } public var headerDictionary: OAuthSwift.Headers { return dictionaryBySplitting(",", keyValueSeparator: "=") } var safeStringByRemovingPercentEncoding: String { return self.removingPercentEncoding ?? self } var droppedLast: String { return self.substring(to: self.index(before: self.endIndex)) } mutating func dropLast() { self.remove(at: self.index(before: self.endIndex)) } func substring(to offset: String.IndexDistance) -> String{ return self.substring(to: self.index(self.startIndex, offsetBy: offset)) } func substring(from offset: String.IndexDistance) -> String{ return self.substring(from: self.index(self.startIndex, offsetBy: offset)) } } extension String.Encoding { var charset: String { let charset = CFStringConvertEncodingToIANACharSetName(CFStringConvertNSStringEncodingToEncoding(self.rawValue)) return charset! as String } }
mit
suifengqjn/CatLive
CatLive/CatLive/Classes/Home/CLPageView/CLPageView.swift
1
2466
// // CLPageView.swift // CatLive // // Created by qianjn on 2017/6/11. // Copyright © 2017年 SF. All rights reserved. // import UIKit class CLPageView: UIView { // MARK: 定义属性 fileprivate var titles : [String]! fileprivate var style : CLTitleStyle! fileprivate var childVcs : [UIViewController]! fileprivate weak var parentVc : UIViewController! fileprivate var titleView : CLTitleView! fileprivate var contentView : CLContentView! // MARK: 自定义构造函数 init(frame: CGRect, titles : [String], style : CLTitleStyle, childVcs : [UIViewController], parentVc : UIViewController) { super.init(frame: frame) assert(titles.count == childVcs.count, "标题&控制器个数不同,请检测!!!") self.style = style self.titles = titles self.childVcs = childVcs self.parentVc = parentVc parentVc.automaticallyAdjustsScrollViewInsets = false setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } // MARK:- 设置界面内容 extension CLPageView { fileprivate func setupUI() { let titleH : CGFloat = 44 let titleFrame = CGRect(x: 0, y: 0, width: frame.width, height: titleH) titleView = CLTitleView(frame: titleFrame, titles: titles, style : style) titleView.delegate = self addSubview(titleView) let contentFrame = CGRect(x: 0, y: titleH, width: frame.width, height: frame.height - titleH) contentView = CLContentView(frame: contentFrame, childVcs: childVcs, parentViewController: parentVc) contentView.autoresizingMask = [.flexibleHeight, .flexibleWidth] contentView.delegate = self addSubview(contentView) } } // MARK:- 设置CLContentView的代理 extension CLPageView : CLContentViewDelegate { func contentView(_ contentView: CLContentView, progress: CGFloat, sourceIndex: Int, targetIndex: Int) { titleView.setTitleWithProgress(progress, sourceIndex: sourceIndex, targetIndex: targetIndex) } func contentViewEndScroll(_ contentView: CLContentView) { titleView.contentViewDidEndScroll() } } // MARK:- 设置CLTitleView的代理 extension CLPageView : CLTitleViewDelegate { func titleView(_ titleView: CLTitleView, selectedIndex index: Int) { contentView.setCurrentIndex(index) } }
apache-2.0
rsaenzi/MyCurrencyConverterApp
MyCurrencyConverterApp/MyCurrencyConverterApp/App/DataModels/Util/StringExtension.swift
1
680
// // StringExtension.swift // MyCurrencyConverterApp // // Created by Rigoberto Sáenz Imbacuán on 8/7/16. // Copyright © 2016 Rigoberto Sáenz Imbacuán [https://www.linkedin.com/in/rsaenzi]. All rights reserved. // import Foundation extension String { func replace(string:String, replacement:String) -> String { return self.stringByReplacingOccurrencesOfString(string, withString: replacement, options: NSStringCompareOptions.LiteralSearch, range: nil) } func noSpaces() -> String { return self.replace(" ", replacement: "") } func contains(find: String) -> Bool{ return self.rangeOfString(find) != nil } }
mit
mlilback/rc2SwiftClient
MacClient/session/output/OutputTabController.swift
1
11634
// // OutputTabController.swift // // Copyright ©2016 Mark Lilback. This file is licensed under the ISC license. // import Cocoa import Rc2Common import MJLLogger import Networking import ClientCore import ReactiveSwift import SwiftyUserDefaults enum OutputTab: Int { case console = 0, preview, webKit, image, help } // to allow parent controller to potentially modify contextual menu of a child controller protocol ContextualMenuDelegate: class { func contextMenuItems(for: OutputController) -> [NSMenuItem] } protocol OutputController: Searchable { var contextualMenuDelegate: ContextualMenuDelegate? { get set } } class OutputTabController: NSTabViewController, OutputHandler, ToolbarItemHandler { // MARK: properties @IBOutlet var additionContextMenuItems: NSMenu? var currentOutputController: OutputController! weak var consoleController: ConsoleOutputController? weak var previewController: LivePreviewDisplayController? weak var imageController: ImageOutputController? weak var webController: WebKitOutputController? weak var helpController: HelpOutputController? weak var searchButton: NSSegmentedControl? var previewOutputController: LivePreviewOutputController? { return previewController } var imageCache: ImageCache? { return sessionController?.session.imageCache } weak var sessionController: SessionController? { didSet { sessionControllerUpdated() } } weak var displayedFile: AppFile? var searchBarVisible: Bool { get { return currentOutputController.searchBarVisible } set { currentOutputController.performFind(action: newValue ? .showFindInterface : .hideFindInterface) } } let selectedOutputTab = MutableProperty<OutputTab>(.console) /// temp storage for state to restore because asked to restore before session is set private var restoredState: SessionState.OutputControllerState? // MARK: methods override func viewDidLoad() { super.viewDidLoad() NotificationCenter.default.addObserver(self, selector: #selector(handleDisplayHelp(_:)), name: .displayHelpTopic, object: nil) selectedOutputTab.signal.observe(on: UIScheduler()).observeValues { [weak self] tab in self?.switchTo(tab: tab) } } override func viewWillAppear() { super.viewWillAppear() guard consoleController == nil else { return } consoleController = firstChildViewController(self) consoleController?.viewFileOrImage = { [weak self] (fw) in self?.displayAttachment(fw) } consoleController?.contextualMenuDelegate = self previewController = firstChildViewController(self) previewController?.contextualMenuDelegate = self imageController = firstChildViewController(self) imageController?.imageCache = imageCache imageController?.contextualMenuDelegate = self webController = firstChildViewController(self) webController?.onClear = { [weak self] in self?.selectedOutputTab.value = .console } webController?.contextualMenuDelegate = self helpController = firstChildViewController(self) helpController?.contextualMenuDelegate = self currentOutputController = consoleController } private func sessionControllerUpdated() { imageController?.imageCache = imageCache DispatchQueue.main.async { self.loadSavedState() } } override func viewDidAppear() { super.viewDidAppear() if let myView = tabView as? OutputTopView { myView.windowSetCall = { self.hookupToToolbarItems(self, window: myView.window!) } } } @objc func validateMenuItem(_ menuItem: NSMenuItem) -> Bool { guard let action = menuItem.action else { return false } switch action { case #selector(switchToSubView(_:)): guard let desiredTab = OutputTab(rawValue: menuItem.tag) else { return false } return desiredTab != selectedOutputTab.value default: return false } } func initialFirstResponder() -> NSResponder { return (self.consoleController?.consoleTextField)! } func handlesToolbarItem(_ item: NSToolbarItem) -> Bool { if item.itemIdentifier.rawValue == "clear" { item.target = self item.action = #selector(OutputTabController.clearConsole(_:)) if let myItem = item as? ClearConsoleToolbarItem { myItem.textView = consoleController?.resultsView myItem.tabController = self } return true } else if item.itemIdentifier.rawValue == "search" { searchButton = item.view as? NSSegmentedControl TargetActionBlock { [weak self] _ in self?.toggleSearchBar() }.installInControl(searchButton!) if let myItem = item as? ValidatingToolbarItem { myItem.validationHandler = { [weak self] item in item.isEnabled = self?.currentOutputController.supportsSearchBar ?? false } } return true } return false } func switchToPreview() { guard selectedOutputTab.value != .preview else { return } selectedOutputTab.value = .preview } func showHelp(_ topics: [HelpTopic]) { guard topics.count > 0 else { if let rstr = sessionController?.format(errorString: NSLocalizedString("No Help Found", comment: "")) { consoleController?.append(responseString: rstr) } return } if topics.count == 1 { showHelpTopic(topics[0]) return } //TODO: handle prompt for selecting a topic out of topics showHelpTopic(topics[0]) } @objc func handleDisplayHelp(_ note: Notification) { if let topic: HelpTopic = note.object as? HelpTopic { showHelpTopic(topic) } else if let topicName = note.object as? String { showHelp(HelpController.shared.topicsWithName(topicName)) } else { //told to show without a topic. switch back to console. selectedOutputTab.value = .console } } func toggleSearchBar() { let action: NSTextFinder.Action = currentOutputController.searchBarVisible ? .hideFindInterface : .showFindInterface currentOutputController.performFind(action: action) } @IBAction func clearConsole(_ sender: Any?) { consoleController?.clearConsole(sender) imageCache?.clearCache() } /// action that switches to the OutputTab specified in a NSMenuItem's tag property @IBAction func switchToSubView(_ sender: Any?) { guard let mItem = sender as? NSMenuItem, let tab = OutputTab(rawValue: mItem.tag) else { return } selectedOutputTab.value = tab } func displayAttachment(_ fileWrapper: FileWrapper) { Log.info("told to display file \(fileWrapper.filename!)", .app) guard let attachment = try? MacConsoleAttachment.from(data: fileWrapper.regularFileContents!) else { Log.warn("asked to display invalid attachment", .app) return } switch attachment.type { case .file: if let file = sessionController?.session.workspace.file(withId: attachment.fileId) { webController?.load(file: file) selectedOutputTab.value = .webKit } else { Log.warn("error getting file attachment to display: \(attachment.fileId)", .app) let err = AppError(.fileNoLongerExists) presentError(err, modalFor: view.window!, delegate: nil, didPresent: nil, contextInfo: nil) } case .image: if let image = attachment.image { imageController?.display(image: image) selectedOutputTab.value = .image // This might not be necessary tabView.window?.toolbar?.validateVisibleItems() } } } func show(file: AppFile?) { //strip optional guard let file = file else { webController?.clearContents() selectedOutputTab.value = .console displayedFile = nil return } let url = self.sessionController!.session.fileCache.cachedUrl(file: file) guard url.fileSize() > 0 else { //caching/download bug. not sure what causes it. recache the file and then call again sessionController?.session.fileCache.recache(file: file).observe(on: UIScheduler()).startWithCompleted { self.show(file: file) } return } displayedFile = file // use webkit to handle images the user selected since the imageView only works with images in the cache self.selectedOutputTab.value = .webKit self.webController?.load(file: file) } func append(responseString: ResponseString) { consoleController?.append(responseString: responseString) //switch back to console view if appropriate type switch responseString.type { case .input, .output, .error: if selectedOutputTab.value != .console { selectedOutputTab.value = .console } default: break } } /// This is called when the current file in the editor has changed. /// It should decide if the output view should be changed to match the editor document. /// /// - Parameter editorMode: the mode of the editor func considerTabChange(editorMode: EditorMode) { switch editorMode { case .preview: selectedOutputTab.value = .preview case .source: selectedOutputTab.value = .console } } func handleSearch(action: NSTextFinder.Action) { currentOutputController.performFind(action: action) } func save(state: inout SessionState.OutputControllerState) { state.selectedTabId = selectedOutputTab.value.rawValue state.selectedImageId = imageController?.selectedImageId ?? 0 consoleController?.save(state: &state) webController?.save(state: &state.webViewState) helpController?.save(state: &state.helpViewState) } func restore(state: SessionState.OutputControllerState) { restoredState = state } /// actually loads the state from instance variable func loadSavedState() { guard let savedState = restoredState else { return } consoleController?.restore(state: savedState) if let selTab = OutputTab(rawValue: savedState.selectedTabId) { self.selectedOutputTab.value = selTab } let imgId = savedState.selectedImageId self.imageController?.display(imageId: imgId) webController?.restore(state: savedState.webViewState) helpController?.restore(state: savedState.helpViewState) restoredState = nil } } // MARK: - contextual menu delegate extension OutputTabController: ContextualMenuDelegate { func contextMenuItems(for: OutputController) -> [NSMenuItem] { // have to return copies of items guard let tmpMenu = additionContextMenuItems?.copy() as? NSMenu else { return [] } return tmpMenu.items } } // MARK: - private methods private extension OutputTabController { /// should only ever be called via the closure for selectedOutputTab.signal.observeValues set in viewDidLoad. func switchTo(tab: OutputTab) { selectedTabViewItemIndex = tab.rawValue switch selectedOutputTab.value { case .console: currentOutputController = consoleController case .preview: currentOutputController = previewController case .image: currentOutputController = imageController case .webKit: currentOutputController = webController case .help: currentOutputController = helpController } if view.window?.firstResponder == nil { view.window?.makeFirstResponder(currentOutputController as? NSResponder) } } ///actually shows the help page for the specified topic func showHelpTopic(_ topic: HelpTopic) { selectedOutputTab.value = .help helpController!.loadHelpTopic(topic) } } // MARK: - helper classes class OutputTopView: NSTabView { var windowSetCall: (() -> Void)? override func viewDidMoveToWindow() { if self.window != nil { windowSetCall?() } windowSetCall = nil } } class ClearConsoleToolbarItem: NSToolbarItem { var textView: NSTextView? weak var tabController: NSTabViewController? override func validate() { guard let textLength = textView?.textStorage?.length else { isEnabled = false; return } isEnabled = textLength > 0 && tabController?.selectedTabViewItemIndex == 0 } } class OutputConsoleToolbarItem: NSToolbarItem { weak var tabController: NSTabViewController? override func validate() { guard let tabController = tabController else { return } isEnabled = tabController.selectedTabViewItemIndex > 0 } }
isc
Swiftline/Swiftline
Source/Env.swift
3
2313
// // Env.swift // Swiftline // // Created by Omar Abdelhafith on 24/11/2015. // Copyright © 2015 Omar Abdelhafith. All rights reserved. // import Darwin public class Env { /// Return the list of all the enviromenment keys passed to the script public static var keys: [String] { let keyValues = run("env").stdout.components(separatedBy: "\n") let keys = keyValues.map { $0.components(separatedBy: "=").first! }.filter { !$0.isEmpty } return keys } /// Return the list of all the enviromenment values passed to the script public static var values: [String] { return self.keys.map { self.get($0)! } } /** Return the enviromenment for the provided key - parameter key: The enviromenment variable key - returns: The enviromenment variable value */ public static func get(_ key: String) -> String? { guard let value = getenv(key) else { return nil } return String(cString: value) } /** Set a new value for the enviromenment variable - parameter key: The enviromenment variable key - parameter value: The enviromenment variable value */ public static func set(_ key: String, _ value: String?) { if let newValue = value { setenv(key, newValue, 1) } else { unsetenv(key) } } /** Clear all the enviromenment variables */ public static func clear() { self.keys .map { String($0) } .filter { $0 != nil } .forEach{ self.set($0!, nil) } } /** Check if the enviromenment variable key exists - parameter key: The enviromenment variable key - returns: true if exists false otherwise */ public static func hasKey(_ key: String) -> Bool { return self.keys.contains(key) } /** Check if the enviromenment variable value exists - parameter key: The enviromenment variable value - returns: true if exists false otherwise */ public static func hasValue(_ value: String) -> Bool { return self.values.contains(value) } /** Iterate through the list of enviromenment variables - parameter callback: callback to call on each key/value pair */ public static func eachPair(_ callback: (_ key: String, _ value: String) -> ()) { zip(self.keys, self.values).forEach(callback) } }
mit
kylebshr/Linchi
Linchi/String-Manipulation/Character-Extension.swift
4
244
// // Character-Extension // Linchi // extension Character { /** Returns the ASCII value of `self` __precondition__: self is an ASCII character */ internal func toASCII() -> UInt8 { return String(self).utf8.first! } }
mit
banxi1988/Staff
Pods/BXiOSUtils/Pod/Classes/CGRectExtentions.swift
1
1611
// // CGRectExtentions.swift // Pods // // Created by Haizhen Lee on 15/12/18. // // import Foundation import UIKit public extension CGSize{ public func sizeByScaleToWidth(width:CGFloat) -> CGSize{ let factor = width / self.width let h = self.height * factor return CGSize(width: width, height: h) } public init(size:CGFloat){ self.init(width:size,height:size) } } public extension CGRect{ public func rectBySliceLeft(left:CGFloat) -> CGRect{ return CGRect(x: origin.x + left, y: origin.y, width: width - left, height: height) } public func rectBySliceRight(right:CGFloat) -> CGRect{ return CGRect(x: origin.x, y: origin.y, width: width - right, height: height) } public func rectBySliceTop(top:CGFloat) -> CGRect{ return insetBy(dx: 0, dy: top) } } extension CGRect{ public var center:CGPoint{ get{ return CGPoint(x: midX, y: midY) } set(newCenter){ origin.x = newCenter.x - (width / 2) origin.y = newCenter.y - (height / 2 ) } } public init(center:CGPoint,radius:CGFloat){ origin = CGPoint(x: center.x - radius, y: center.y - radius) size = CGSize(width: radius, height: radius) } public init(center:CGPoint,width:CGFloat, height:CGFloat){ origin = CGPoint(x: center.x - width * 0.5, y: center.y - height * 0.5) size = CGSize(width: width, height: height) } public init(center:CGPoint,size:CGSize){ origin = CGPoint(x: center.x - size.width * 0.5, y: center.y - size.height * 0.5) self.size = size } public var area:CGFloat{ return width * height } }
mit
RocketChat/Rocket.Chat.iOS
Pods/MobilePlayer/MobilePlayer/MobilePlayerViewController.swift
1
25438
// // MobilePlayerViewController.swift // MobilePlayer // // Created by Baris Sencan on 12/02/15. // Copyright (c) 2015 MovieLaLa. All rights reserved. // import UIKit import MediaPlayer /// A view controller for playing media content. open class MobilePlayerViewController: MPMoviePlayerViewController { // MARK: Playback State /// Playback state. public enum State { /// Either playback has not started or playback was stopped due to a `stop()` call or an error. When an error /// occurs, a corresponding `MobilePlayerDidEncounterErrorNotification` notification is posted. case idle /// The video will start playing, but sufficient data to start playback has to be loaded first. case buffering /// The video is currently playing. case playing /// The video is currently paused. case paused } /// The previous value of `state`. Default is `.Idle`. public private(set) var previousState: State = .idle /// Current `State` of the player. Default is `.Idle`. public private(set) var state: State = .idle { didSet { previousState = oldValue } } // MARK: Player Configuration // TODO: Move inside MobilePlayerConfig private static let playbackInterfaceUpdateInterval = 0.25 /// The global player configuration object that is loaded by a player if none is passed for its /// initialization. public static let globalConfig = MobilePlayerConfig() /// The configuration object that was used to initialize the player, may point to the global player configuration /// object. public let config: MobilePlayerConfig // MARK: Mapped Properties /// A localized string that represents the video this controller manages. Setting a value will update the title label /// in the user interface if one exists. open override var title: String? { didSet { guard let titleLabel = getViewForElementWithIdentifier("title") as? Label else { return} titleLabel.text = title titleLabel.superview?.setNeedsLayout() } } // MARK: Private Properties private let controlsView: MobilePlayerControlsView private var previousStatusBarHiddenValue: Bool? private var previousStatusBarStyle: UIStatusBarStyle! private var isFirstPlay = true fileprivate var seeking = false fileprivate var wasPlayingBeforeSeek = false private var playbackInterfaceUpdateTimer: Timer? private var hideControlsTimer: Timer? // MARK: Initialization /// Initializes a player with content given by `contentURL`. If provided, the overlay view controllers used to /// initialize the player should be different instances from each other. /// /// - parameters: /// - contentURL: URL of the content that will be used for playback. /// - config: Player configuration. Defaults to `globalConfig`. /// - prerollViewController: Pre-roll view controller. Defaults to `nil`. /// - pauseOverlayViewController: Pause overlay view controller. Defaults to `nil`. /// - postrollViewController: Post-roll view controller. Defaults to `nil`. public init(contentURL: URL, config: MobilePlayerConfig = MobilePlayerViewController.globalConfig, prerollViewController: MobilePlayerOverlayViewController? = nil, pauseOverlayViewController: MobilePlayerOverlayViewController? = nil, postrollViewController: MobilePlayerOverlayViewController? = nil) { self.config = config controlsView = MobilePlayerControlsView(config: config) self.prerollViewController = prerollViewController self.pauseOverlayViewController = pauseOverlayViewController self.postrollViewController = postrollViewController super.init(contentURL: contentURL) initializeMobilePlayerViewController() } /// Returns a player initialized from data in a given unarchiver. `globalConfig` is used for configuration in this /// case. In most cases the other intializer should be used. /// /// - parameters: /// - coder: An unarchiver object. public required init?(coder aDecoder: NSCoder) { config = MobilePlayerViewController.globalConfig controlsView = MobilePlayerControlsView(config: config) self.prerollViewController = nil self.pauseOverlayViewController = nil self.postrollViewController = nil super.init(coder: aDecoder) initializeMobilePlayerViewController() } private func initializeMobilePlayerViewController() { view.clipsToBounds = true edgesForExtendedLayout = [] moviePlayer.scalingMode = .aspectFit moviePlayer.controlStyle = .none initializeNotificationObservers() initializeControlsView() parseContentURLIfNeeded() if let watermarkConfig = config.watermarkConfig { showOverlayViewController(WatermarkViewController(config: watermarkConfig)) } } private func initializeNotificationObservers() { let notificationCenter = NotificationCenter.default notificationCenter.addObserver( forName: NSNotification.Name.MPMoviePlayerPlaybackStateDidChange, object: moviePlayer, queue: OperationQueue.main) { [weak self] notification in guard let slf = self else { return } slf.handleMoviePlayerPlaybackStateDidChangeNotification() NotificationCenter.default.post(name: NSNotification.Name(rawValue: MobilePlayerStateDidChangeNotification), object: slf) } notificationCenter.removeObserver( self, name: NSNotification.Name.MPMoviePlayerPlaybackDidFinish, object: moviePlayer) notificationCenter.addObserver( forName: NSNotification.Name.MPMoviePlayerPlaybackDidFinish, object: moviePlayer, queue: OperationQueue.main) { [weak self] notification in guard let slf = self else { return } if let userInfo = notification.userInfo as? [String: AnyObject], let error = userInfo["error"] as? NSError { NotificationCenter.default.post(name: NSNotification.Name(rawValue: MobilePlayerDidEncounterErrorNotification), object: self, userInfo: [MobilePlayerErrorUserInfoKey: error]) } if let postrollVC = slf.postrollViewController { slf.prerollViewController?.dismiss() slf.pauseOverlayViewController?.dismiss() slf.showOverlayViewController(postrollVC) } } } private func initializeControlsView() { (getViewForElementWithIdentifier("playback") as? Slider)?.delegate = self (getViewForElementWithIdentifier("close") as? Button)?.addCallback( callback: { [weak self] in guard let slf = self else { return } if let navigationController = slf.navigationController { navigationController.popViewController(animated: true) } else if let presentingController = slf.presentingViewController { presentingController.dismissMoviePlayerViewControllerAnimated() } }, forControlEvents: .touchUpInside) if let actionButton = getViewForElementWithIdentifier("action") as? Button { actionButton.isHidden = true // Initially hidden until 1 or more `activityItems` are set. actionButton.addCallback( callback: { [weak self] in guard let slf = self else { return } slf.showContentActions(sourceView: actionButton) }, forControlEvents: .touchUpInside) } (getViewForElementWithIdentifier("play") as? ToggleButton)?.addCallback( callback: { [weak self] in guard let slf = self else { return } slf.resetHideControlsTimer() slf.state == .playing ? slf.pause() : slf.play() }, forControlEvents: .touchUpInside) initializeControlsViewTapRecognizers() } private func initializeControlsViewTapRecognizers() { let singleTapRecognizer = UITapGestureRecognizer { [weak self] in self?.handleContentTap() } singleTapRecognizer.numberOfTapsRequired = 1 controlsView.addGestureRecognizer(singleTapRecognizer) let doubleTapRecognizer = UITapGestureRecognizer { [weak self] in self?.handleContentDoubleTap() } doubleTapRecognizer.numberOfTapsRequired = 2 controlsView.addGestureRecognizer(doubleTapRecognizer) singleTapRecognizer.require(toFail: doubleTapRecognizer) } // MARK: View Controller Lifecycle /// Called after the controller'€™s view is loaded into memory. /// /// This method is called after the view controller has loaded its view hierarchy into memory. This method is /// called regardless of whether the view hierarchy was loaded from a nib file or created programmatically in the /// `loadView` method. You usually override this method to perform additional initialization on views that were /// loaded from nib files. /// /// If you override this method make sure you call super's implementation. open override func viewDidLoad() { super.viewDidLoad() view.addSubview(controlsView) playbackInterfaceUpdateTimer = Timer.scheduledTimerWithTimeInterval( ti: MobilePlayerViewController.playbackInterfaceUpdateInterval, callback: { [weak self] in self?.updatePlaybackInterface() }, repeats: true) if let prerollViewController = prerollViewController { shouldAutoplay = false showOverlayViewController(prerollViewController) } } /// Called to notify the view controller that its view is about to layout its subviews. /// /// When a view'€™s bounds change, the view adjusts the position of its subviews. Your view controller can override /// this method to make changes before the view lays out its subviews. /// /// The default implementation of this method sets the frame of the controls view. open override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() controlsView.frame = view.bounds } /// Notifies the view controller that its view is about to be added to a view hierarchy. /// /// If `true`, the view is being added to the window using an animation. /// /// The default implementation of this method hides the status bar. /// /// - parameters: /// - animated: If `true`, the view is being added to the window using an animation. open override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // Force hide status bar. previousStatusBarHiddenValue = UIApplication.shared.isStatusBarHidden UIApplication.shared.isStatusBarHidden = true setNeedsStatusBarAppearanceUpdate() } /// Notifies the view controller that its view is about to be removed from a view hierarchy. /// /// If `true`, the disappearance of the view is being animated. /// /// The default implementation of this method stops playback and restores status bar appearance to how it was before /// the view appeared. /// /// - parameters: /// - animated: If `true`, the disappearance of the view is being animated. open override func viewWillDisappear(_ animated: Bool) { // Restore status bar appearance. if let previousStatusBarHidden = previousStatusBarHiddenValue { UIApplication.shared.isStatusBarHidden = previousStatusBarHidden setNeedsStatusBarAppearanceUpdate() } super.viewWillDisappear(animated) stop() } // MARK: Deinitialization deinit { playbackInterfaceUpdateTimer?.invalidate() hideControlsTimer?.invalidate() NotificationCenter.default.removeObserver(self) } // MARK: Playback /// Indicates whether content should begin playback automatically. /// /// The default value of this property is true. This property determines whether the playback of network-based /// content begins automatically when there is enough buffered data to ensure uninterrupted playback. public var shouldAutoplay: Bool { get { return moviePlayer.shouldAutoplay } set { moviePlayer.shouldAutoplay = newValue } } /// Initiates playback of current content. /// /// Starting playback causes dismiss to be called on prerollViewController, pauseOverlayViewController /// and postrollViewController. public func play() { moviePlayer.play() } /// Pauses playback of current content. /// /// Pausing playback causes pauseOverlayViewController to be shown. public func pause() { moviePlayer.pause() } /// Ends playback of current content. public func stop() { moviePlayer.stop() } // MARK: Video Rendering /// Makes playback content fit into player's view. public func fitVideo() { moviePlayer.scalingMode = .aspectFit } /// Makes playback content fill player's view. public func fillVideo() { moviePlayer.scalingMode = .aspectFill } /// Makes playback content switch between fill/fit modes when content area is double tapped. Overriding this method /// is recommended if you want to change this behavior. public func handleContentDoubleTap() { // TODO: videoScalingMode property and enum. moviePlayer.scalingMode != .aspectFill ? fillVideo() : fitVideo() } // MARK: Social /// An array of activity items that will be used for presenting a `UIActivityViewController` when the action /// button is pressed (if it exists). If content is playing, it is paused automatically at presentation and will /// continue after the controller is dismissed. Override `showContentActions()` if you want to change the button's /// behavior. public var activityItems: [Any]? { didSet { let isEmpty = activityItems?.isEmpty ?? true getViewForElementWithIdentifier("action")?.isHidden = isEmpty } } /// An array of activity types that will be excluded when presenting a `UIActivityViewController` public var excludedActivityTypes: [UIActivity.ActivityType]? = [ .assignToContact, .saveToCameraRoll, .postToVimeo, .airDrop ] /// Method that is called when a control interface button with identifier "action" is tapped. Presents a /// `UIActivityViewController` with `activityItems` set as its activity items. If content is playing, it is paused /// automatically at presentation and will continue after the controller is dismissed. Overriding this method is /// recommended if you want to change this behavior. /// /// parameters: /// - sourceView: On iPads the activity view controller is presented as a popover and a source view needs to /// provided or a crash will occur. open func showContentActions(sourceView: UIView? = nil) { guard let activityItems = activityItems, !activityItems.isEmpty else { return } let wasPlaying = (state == .playing) moviePlayer.pause() let activityVC = UIActivityViewController(activityItems: activityItems, applicationActivities: nil) activityVC.excludedActivityTypes = excludedActivityTypes activityVC.completionWithItemsHandler = { activityType, completed, returnedItems, activityError in if wasPlaying { self.moviePlayer.play() } } if let sourceView = sourceView { activityVC.popoverPresentationController?.sourceView = controlsView activityVC.popoverPresentationController?.sourceRect = sourceView.convert( sourceView.bounds, to: controlsView) } present(activityVC, animated: true, completion: nil) } // MARK: Controls /// Indicates if player controls are hidden. Setting its value will animate controls in or out. public var controlsHidden: Bool { get { return controlsView.controlsHidden } set { newValue ? hideControlsTimer?.invalidate() : resetHideControlsTimer() controlsView.controlsHidden = newValue } } /// Returns the view associated with given player control element identifier. /// /// - parameters: /// - identifier: Element identifier. /// - returns: View or nil if element is not found. public func getViewForElementWithIdentifier(_ identifier: String) -> UIView? { if let view = controlsView.topBar.getViewForElementWithIdentifier(identifier: identifier) { return view } return controlsView.bottomBar.getViewForElementWithIdentifier(identifier: identifier) } /// Hides/shows controls when content area is tapped once. Overriding this method is recommended if you want to change /// this behavior. public func handleContentTap() { controlsHidden = !controlsHidden } // MARK: Overlays private var timedOverlays = [TimedOverlayInfo]() /// The `MobilePlayerOverlayViewController` that will be presented on top of the player content at start. If a /// controller is set then content will not start playing automatically even if `shouldAutoplay` is `true`. The /// controller will dismiss if user presses the play button or `play()` is called. public let prerollViewController: MobilePlayerOverlayViewController? /// The `MobilePlayerOverlayViewController` that will be presented on top of the player content whenever playback is /// paused. Does not include pauses in playback due to buffering. public let pauseOverlayViewController: MobilePlayerOverlayViewController? /// The `MobilePlayerOverlayViewController` that will be presented on top of the player content when playback /// finishes. public let postrollViewController: MobilePlayerOverlayViewController? /// Presents given overlay view controller on top of the player content immediately, or at a given content time for /// a given duration. Both starting time and duration parameters should be provided to show a timed overlay. /// /// - parameters: /// - overlayViewController: The `MobilePlayerOverlayViewController` to be presented. /// - startingAtTime: Content time the overlay will be presented at. /// - forDuration: Added on top of `startingAtTime` to calculate the content time when overlay will be dismissed. public func showOverlayViewController(_ overlayViewController: MobilePlayerOverlayViewController, startingAtTime presentationTime: TimeInterval? = nil, forDuration showDuration: TimeInterval? = nil) { if let presentationTime = presentationTime, let showDuration = showDuration { timedOverlays.append(TimedOverlayInfo( startTime: presentationTime, duration: showDuration, overlay: overlayViewController)) } else if overlayViewController.parent == nil { overlayViewController.delegate = self addChild(overlayViewController) overlayViewController.view.clipsToBounds = true overlayViewController.view.frame = controlsView.overlayContainerView.bounds controlsView.overlayContainerView.addSubview(overlayViewController.view) overlayViewController.didMove(toParent: self) } } /// Dismisses all currently presented overlay view controllers and clears any timed overlays. public func clearOverlays() { for timedOverlayInfo in timedOverlays { timedOverlayInfo.overlay.dismiss() } timedOverlays.removeAll() for childViewController in children { if childViewController is WatermarkViewController { continue } (childViewController as? MobilePlayerOverlayViewController)?.dismiss() } } // MARK: Private Methods private func parseContentURLIfNeeded() { guard let youtubeID = YoutubeParser.youtubeIDFromURL(url: moviePlayer.contentURL) else { return } YoutubeParser.h264videosWithYoutubeID(youtubeID) { videoInfo, error in if let error = error { NotificationCenter.default.post(name: NSNotification.Name(rawValue: MobilePlayerDidEncounterErrorNotification), object: self, userInfo: [MobilePlayerErrorUserInfoKey: error]) } guard let videoInfo = videoInfo else { return } self.title = self.title ?? videoInfo.title if let previewImageURLString = videoInfo.previewImageURL, let previewImageURL = URL(string: previewImageURLString) { URLSession.shared.dataTask(with: previewImageURL) { data, response, error in guard let data = data else { return } DispatchQueue.main.async { self.controlsView.previewImageView.image = UIImage(data: data) } } } if let videoURL = videoInfo.videoURL { self.moviePlayer.contentURL = URL(string: videoURL) } } } private func doFirstPlaySetupIfNeeded() { if isFirstPlay { isFirstPlay = false controlsView.previewImageView.isHidden = true controlsView.activityIndicatorView.stopAnimating() } } private func updatePlaybackInterface() { if let playbackSlider = getViewForElementWithIdentifier("playback") as? Slider { playbackSlider.maximumValue = Float(moviePlayer.duration.isNormal ? moviePlayer.duration : 0) if !seeking { let sliderValue = Float(moviePlayer.currentPlaybackTime.isNormal ? moviePlayer.currentPlaybackTime : 0) playbackSlider.setValue(value: sliderValue, animatedForDuration: MobilePlayerViewController.playbackInterfaceUpdateInterval) } let availableValue = Float(moviePlayer.playableDuration.isNormal ? moviePlayer.playableDuration : 0) playbackSlider.setAvailableValue( availableValue: availableValue, animatedForDuration: MobilePlayerViewController.playbackInterfaceUpdateInterval) } if let currentTimeLabel = getViewForElementWithIdentifier("currentTime") as? Label { currentTimeLabel.text = textForPlaybackTime(time: moviePlayer.currentPlaybackTime) currentTimeLabel.superview?.setNeedsLayout() } if let remainingTimeLabel = getViewForElementWithIdentifier("remainingTime") as? Label { remainingTimeLabel.text = "-\(textForPlaybackTime(time: moviePlayer.duration - moviePlayer.currentPlaybackTime))" remainingTimeLabel.superview?.setNeedsLayout() } if let durationLabel = getViewForElementWithIdentifier("duration") as? Label { durationLabel.text = textForPlaybackTime(time: moviePlayer.duration) durationLabel.superview?.setNeedsLayout() } updateShownTimedOverlays() } private func textForPlaybackTime(time: TimeInterval) -> String { if !time.isNormal { return "00:00" } let hours = Int(floor(time / 3600)) let minutes = Int(floor((time / 60).truncatingRemainder(dividingBy: 60))) let seconds = Int(floor(time.truncatingRemainder(dividingBy: 60))) let minutesAndSeconds = NSString(format: "%02d:%02d", minutes, seconds) as String if hours > 0 { return NSString(format: "%02d:%@", hours, minutesAndSeconds) as String } else { return minutesAndSeconds } } private func resetHideControlsTimer() { hideControlsTimer?.invalidate() hideControlsTimer = Timer.scheduledTimerWithTimeInterval( ti: 3, callback: { self.controlsView.controlsHidden = (self.state == .playing) }, repeats: false) } private func handleMoviePlayerPlaybackStateDidChangeNotification() { state = StateHelper.calculateStateUsing(previousState: previousState, andPlaybackState: moviePlayer.playbackState) let playButton = getViewForElementWithIdentifier("play") as? ToggleButton if state == .playing { doFirstPlaySetupIfNeeded() playButton?.toggled = true if !controlsView.controlsHidden { resetHideControlsTimer() } prerollViewController?.dismiss() pauseOverlayViewController?.dismiss() postrollViewController?.dismiss() } else { playButton?.toggled = false hideControlsTimer?.invalidate() controlsView.controlsHidden = false if let pauseOverlayViewController = pauseOverlayViewController, (state == .paused && !seeking) { showOverlayViewController(pauseOverlayViewController) } } } private func updateShownTimedOverlays() { let currentTime = self.moviePlayer.currentPlaybackTime if !currentTime.isNormal { return } DispatchQueue.global().async { for timedOverlayInfo in self.timedOverlays { if timedOverlayInfo.startTime <= currentTime && currentTime <= timedOverlayInfo.startTime + timedOverlayInfo.duration { if timedOverlayInfo.overlay.parent == nil { DispatchQueue.main.async { self.showOverlayViewController(timedOverlayInfo.overlay) } } } else if timedOverlayInfo.overlay.parent != nil { DispatchQueue.main.async { timedOverlayInfo.overlay.dismiss() } } } } } } // MARK: - MobilePlayerOverlayViewControllerDelegate extension MobilePlayerViewController: MobilePlayerOverlayViewControllerDelegate { func dismiss(mobilePlayerOverlayViewController overlayViewController: MobilePlayerOverlayViewController) { overlayViewController.willMove(toParent: nil) overlayViewController.view.removeFromSuperview() overlayViewController.removeFromParent() if overlayViewController == prerollViewController { play() } } } // MARK: - TimeSliderDelegate extension MobilePlayerViewController: SliderDelegate { func sliderThumbPanDidBegin(slider: Slider) { seeking = true wasPlayingBeforeSeek = (state == .playing) pause() } func sliderThumbDidPan(slider: Slider) {} func sliderThumbPanDidEnd(slider: Slider) { seeking = false moviePlayer.currentPlaybackTime = TimeInterval(slider.value) if wasPlayingBeforeSeek { play() } } }
mit
xayolink/grwuye
grwuye/grwuye/AppDelegate.swift
1
620
// // AppDelegate.swift // grwuye // // Created by jiarenchao on 17/6/8. // Copyright © 2017年 xayolink. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. //全局修改UITabBar的颜色 UITabBar.appearance().tintColor = UIColor.green return true } }
apache-2.0
ben-ng/swift
validation-test/compiler_crashers_fixed/00664-swift-pattern-operator.swift
1
539
// 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 https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck func q<k:q ss f<o : h, o : h c o.o> : p { } class f<o, o> { } protocol h { } protocol p { f q: h -> h = { o }(k, q) protocol h : f { func f
apache-2.0
ben-ng/swift
test/type/self.swift
10
866
// RUN: %target-typecheck-verify-swift struct S0<T> { func foo(_ other: Self) { } // expected-error{{'Self' is only available in a protocol or as the result of a method in a class; did you mean 'S0'?}}{{21-25=S0}} } class C0<T> { func foo(_ other: Self) { } // expected-error{{'Self' is only available in a protocol or as the result of a method in a class; did you mean 'C0'?}}{{21-25=C0}} } enum E0<T> { func foo(_ other: Self) { } // expected-error{{'Self' is only available in a protocol or as the result of a method in a class; did you mean 'E0'?}}{{21-25=E0}} } // rdar://problem/21745221 struct X { typealias T = Int } extension X { struct Inner { } } extension X.Inner { func foo(_ other: Self) { } // expected-error{{'Self' is only available in a protocol or as the result of a method in a class; did you mean 'Inner'?}}{{21-25=Inner}} }
apache-2.0
CaiJingLong/ios-toast
Toast/Toast/source/ToastView.swift
1
488
// // ToastView.swift // Toast // // Created by Caijinglong on 2017/7/7. // import UIKit class ToastView:UIView{ @IBOutlet weak var content: UILabel! override init(frame: CGRect) { super.init(frame: frame) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } class func newToastView()->ToastView{ return UIView.loadViewFromXib("ToastView", ToastView.classForCoder()) as! ToastView } }
apache-2.0
adrfer/swift
stdlib/public/core/StringCharacterView.swift
1
10908
//===--- StringCharacterView.swift - String's Collection of Characters ----===// // // 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 // //===----------------------------------------------------------------------===// // // String is-not-a SequenceType or CollectionType, but it exposes a // collection of characters. // //===----------------------------------------------------------------------===// extension String { /// A `String`'s collection of `Character`s ([extended grapheme /// clusters](http://www.unicode.org/glossary/#extended_grapheme_cluster)) /// elements. public struct CharacterView { internal var _core: _StringCore /// Create a view of the `Character`s in `text`. public init(_ text: String) { self._core = text._core } public // @testable init(_ _core: _StringCore) { self._core = _core } } /// A collection of `Characters` representing the `String`'s /// [extended grapheme /// clusters](http://www.unicode.org/glossary/#extended_grapheme_cluster). public var characters: CharacterView { return CharacterView(self) } /// Efficiently mutate `self` by applying `body` to its `characters`. /// /// - Warning: Do not rely on anything about `self` (the `String` /// that is the target of this method) during the execution of /// `body`: it may not appear to have its correct value. Instead, /// use only the `String.CharacterView` argument to `body`. public mutating func withMutableCharacters<R>(body: (inout CharacterView) -> R) -> R { // Naively mutating self.characters forces multiple references to // exist at the point of mutation. Instead, temporarily move the // core of this string into a CharacterView. var tmp = CharacterView("") swap(&_core, &tmp._core) let r = body(&tmp) swap(&_core, &tmp._core) return r } /// Construct the `String` corresponding to the given sequence of /// Unicode scalars. public init(_ characters: CharacterView) { self.init(characters._core) } } /// `String.CharacterView` is a collection of `Character`. extension String.CharacterView : CollectionType { internal typealias UnicodeScalarView = String.UnicodeScalarView internal var unicodeScalars: UnicodeScalarView { return UnicodeScalarView(_core) } /// A character position. public struct Index : BidirectionalIndexType, Comparable, _Reflectable { public // SPI(Foundation) init(_base: String.UnicodeScalarView.Index) { self._base = _base self._lengthUTF16 = Index._measureExtendedGraphemeClusterForward(_base) } internal init(_base: UnicodeScalarView.Index, _lengthUTF16: Int) { self._base = _base self._lengthUTF16 = _lengthUTF16 } /// Returns the next consecutive value after `self`. /// /// - Requires: The next value is representable. public func successor() -> Index { _precondition(_base != _base._viewEndIndex, "cannot increment endIndex") return Index(_base: _endBase) } /// Returns the previous consecutive value before `self`. /// /// - Requires: The previous value is representable. public func predecessor() -> Index { _precondition(_base != _base._viewStartIndex, "cannot decrement startIndex") let predecessorLengthUTF16 = Index._measureExtendedGraphemeClusterBackward(_base) return Index( _base: UnicodeScalarView.Index( _utf16Index - predecessorLengthUTF16, _base._core)) } internal let _base: UnicodeScalarView.Index /// The length of this extended grapheme cluster in UTF-16 code units. internal let _lengthUTF16: Int /// The integer offset of this index in UTF-16 code units. public // SPI(Foundation) var _utf16Index: Int { return _base._position } /// The one past end index for this extended grapheme cluster in Unicode /// scalars. internal var _endBase: UnicodeScalarView.Index { return UnicodeScalarView.Index( _utf16Index + _lengthUTF16, _base._core) } /// Returns the length of the first extended grapheme cluster in UTF-16 /// code units. @warn_unused_result internal static func _measureExtendedGraphemeClusterForward( start: UnicodeScalarView.Index ) -> Int { var start = start let end = start._viewEndIndex if start == end { return 0 } let startIndexUTF16 = start._position let unicodeScalars = UnicodeScalarView(start._core) let graphemeClusterBreakProperty = _UnicodeGraphemeClusterBreakPropertyTrie() let segmenter = _UnicodeExtendedGraphemeClusterSegmenter() var gcb0 = graphemeClusterBreakProperty.getPropertyRawValue( unicodeScalars[start].value) start._successorInPlace() while start != end { // FIXME(performance): consider removing this "fast path". A branch // that is hard to predict could be worse for performance than a few // loads from cache to fetch the property 'gcb1'. if segmenter.isBoundaryAfter(gcb0) { break } let gcb1 = graphemeClusterBreakProperty.getPropertyRawValue( unicodeScalars[start].value) if segmenter.isBoundary(gcb0, gcb1) { break } gcb0 = gcb1 start._successorInPlace() } return start._position - startIndexUTF16 } /// Returns the length of the previous extended grapheme cluster in UTF-16 /// code units. @warn_unused_result internal static func _measureExtendedGraphemeClusterBackward( end: UnicodeScalarView.Index ) -> Int { let start = end._viewStartIndex if start == end { return 0 } let endIndexUTF16 = end._position let unicodeScalars = UnicodeScalarView(start._core) let graphemeClusterBreakProperty = _UnicodeGraphemeClusterBreakPropertyTrie() let segmenter = _UnicodeExtendedGraphemeClusterSegmenter() var graphemeClusterStart = end graphemeClusterStart._predecessorInPlace() var gcb0 = graphemeClusterBreakProperty.getPropertyRawValue( unicodeScalars[graphemeClusterStart].value) var graphemeClusterStartUTF16 = graphemeClusterStart._position while graphemeClusterStart != start { graphemeClusterStart._predecessorInPlace() let gcb1 = graphemeClusterBreakProperty.getPropertyRawValue( unicodeScalars[graphemeClusterStart].value) if segmenter.isBoundary(gcb1, gcb0) { break } gcb0 = gcb1 graphemeClusterStartUTF16 = graphemeClusterStart._position } return endIndexUTF16 - graphemeClusterStartUTF16 } /// Returns a mirror that reflects `self`. public func _getMirror() -> _MirrorType { return _IndexMirror(self) } } /// The position of the first `Character` if `self` is /// non-empty; identical to `endIndex` otherwise. public var startIndex: Index { return Index(_base: unicodeScalars.startIndex) } /// The "past the end" position. /// /// `endIndex` is not a valid argument to `subscript`, and is always /// reachable from `startIndex` by zero or more applications of /// `successor()`. public var endIndex: Index { return Index(_base: unicodeScalars.endIndex) } /// Access the `Character` at `position`. /// /// - Requires: `position` is a valid position in `self` and /// `position != endIndex`. public subscript(i: Index) -> Character { return Character(String(unicodeScalars[i._base..<i._endBase])) } internal struct _IndexMirror : _MirrorType { var _value: Index init(_ x: Index) { _value = x } var value: Any { return _value } var valueType: Any.Type { return (_value as Any).dynamicType } var objectIdentifier: ObjectIdentifier? { return nil } var disposition: _MirrorDisposition { return .Aggregate } var count: Int { return 0 } subscript(i: Int) -> (String, _MirrorType) { _preconditionFailure("_MirrorType access out of bounds") } var summary: String { return "\(_value._utf16Index)" } var quickLookObject: PlaygroundQuickLook? { return .Int(Int64(_value._utf16Index)) } } } extension String.CharacterView : RangeReplaceableCollectionType { /// Create an empty instance. public init() { self.init("") } /// Replace the given `subRange` of elements with `newElements`. /// /// Invalidates all indices with respect to `self`. /// /// - Complexity: O(`subRange.count`) if `subRange.endIndex /// == self.endIndex` and `newElements.isEmpty`, O(N) otherwise. public mutating func replaceRange< C: CollectionType where C.Generator.Element == Character >( subRange: Range<Index>, with newElements: C ) { let rawSubRange = subRange.startIndex._base._position ..< subRange.endIndex._base._position let lazyUTF16 = newElements.lazy.flatMap { $0.utf16 } _core.replaceRange(rawSubRange, with: lazyUTF16) } /// Reserve enough space to store `n` ASCII characters. /// /// - Complexity: O(`n`). public mutating func reserveCapacity(n: Int) { _core.reserveCapacity(n) } /// Append `c` to `self`. /// /// - Complexity: Amortized O(1). public mutating func append(c: Character) { switch c._representation { case .Small(let _63bits): let bytes = Character._smallValue(_63bits) _core.appendContentsOf(Character._SmallUTF16(bytes)) case .Large(_): _core.append(String(c)._core) } } /// Append the elements of `newElements` to `self`. public mutating func appendContentsOf< S : SequenceType where S.Generator.Element == Character >(newElements: S) { reserveCapacity(_core.count + newElements.underestimateCount()) for c in newElements { self.append(c) } } /// Create an instance containing `characters`. public init< S : SequenceType where S.Generator.Element == Character >(_ characters: S) { self = String.CharacterView() self.appendContentsOf(characters) } } // Algorithms extension String.CharacterView { /// Access the characters in the given `subRange`. /// /// - Complexity: O(1) unless bridging from Objective-C requires an /// O(N) conversion. public subscript(subRange: Range<Index>) -> String.CharacterView { let unicodeScalarRange = subRange.startIndex._base..<subRange.endIndex._base return String.CharacterView( String(_core).unicodeScalars[unicodeScalarRange]._core) } }
apache-2.0
fschneider1509/RuleBasedXMLParserDelegate
RuleBasedXMLParserDelegateKit/XMLRuleBasedParserDelegate.swift
1
3710
// // XMLRuleBasedParserDelegate.swift // RuleBasedXMLParserDelegate // // Created by Fabian Schneider // fabian(at)fabianschneider.org // MIT License // import Foundation class XMLRuleBasedParserDelegate<T: XMLParserNodeProtocol> : NSObject, XMLParserDelegate, XMLRuleBasedParserDelegateProtocol { private let _xmlDocument: XMLParserDocument private let _rootNode: T init(rootNode: inout T) { _rootNode = rootNode _xmlDocument = XMLParserDocument() } func addRule(rule: XMLParserRuleProtocol) { _xmlDocument.addRule(rule: rule) } func parserDidStartDocument(_ parser: XMLParser) { // Stub } func parserDidEndDocument(_ parser: XMLParser) { // Stub } func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) { let parent: String? = _xmlDocument.getParentElement() if let parent = parent { let rule: XMLParserEndEventRuleProtocol? = _xmlDocument.getRuleForElement(elementName: elementName, parentName: parent, ruleType: XMLParserEndEventRuleProtocol.self) as! XMLParserEndEventRuleProtocol? if let rule = rule { rule.doOnElementEnd(rootNode: _rootNode) } _xmlDocument.popElement() } else { do { try throwParsingError(error: XMLParserDelegateError.elementParsingError(message: "Error on parsing end tag of an element!", element: elementName)) } catch {} } } func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String] = [:]) { _xmlDocument.pushElement(elementName: elementName) let parent: String? = _xmlDocument.getParentElement() if let parent = parent { let rule: XMLParserStartEventRuleProtocol? = _xmlDocument.getRuleForElement(elementName: elementName, parentName: parent, ruleType: XMLParserStartEventRuleProtocol.self) as! XMLParserStartEventRuleProtocol? if let rule = rule { rule.doOnElementStart(rootNode: _rootNode) } } else { do { try throwParsingError(error: XMLParserDelegateError.elementParsingError(message: "Error on parsing start tag of an element!", element: elementName)) } catch {} } } func parser(_ parser: XMLParser, foundCharacters string: String) { let parent: String? = _xmlDocument.getParentElement() let currentElement: String? = _xmlDocument.getCurrentElement() if let parent = parent { if let currentElement = currentElement { let rule: XMLParserReadRuleProtocol? = _xmlDocument.getRuleForElement(elementName: currentElement, parentName: parent, ruleType: XMLParserReadRuleProtocol.self) as! XMLParserReadRuleProtocol? if let rule = rule { rule.doOnElementRead(elementValue: string, rootNode: _rootNode) } } else { do { try throwParsingError(error: XMLParserDelegateError.elementParsingError(message: "Error on parsing start tag of an element - parent!", element: parent)) } catch {} } } else { do { try throwParsingError(error: XMLParserDelegateError.elementParsingError(message: "Error on parsing value of an element!", element: "")) } catch {} } } func throwParsingError(error: XMLParserDelegateError) throws { throw error } }
mit
avito-tech/Paparazzo
Paparazzo/Core/VIPER/MaskCropper/Interactor/MaskCropperInteractor.swift
1
363
import ImageSource protocol MaskCropperInteractor: class { func canvasSize(completion: @escaping (CGSize) -> ()) func imageWithParameters(completion: @escaping (ImageCroppingData) -> ()) func croppedImage(previewImage: CGImage, completion: @escaping (CroppedImageSource) -> ()) func setCroppingParameters(_ parameters: ImageCroppingParameters) }
mit
paymentez/paymentez-ios
Demo/SceneDelegate.swift
1
2524
// // SceneDelegate.swift // Demo // // Created by Ernesto Gonzalez Nochebuena on 17/12/20. // Copyright © 2020 Paymentez. All rights reserved. // import UIKit class SceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? @available(iOS 13.0, *) func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`. // If using a storyboard, the `window` property will automatically be initialized and attached to the scene. // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead). guard let _ = (scene as? UIWindowScene) else { return } } @available(iOS 13.0, *) func sceneDidDisconnect(_ scene: UIScene) { // Called as the scene is being released by the system. // This occurs shortly after the scene enters the background, or when its session is discarded. // Release any resources associated with this scene that can be re-created the next time the scene connects. // The scene may re-connect later, as its session was not necessarily discarded (see `application:didDiscardSceneSessions` instead). } @available(iOS 13.0, *) func sceneDidBecomeActive(_ scene: UIScene) { // Called when the scene has moved from an inactive state to an active state. // Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive. } @available(iOS 13.0, *) func sceneWillResignActive(_ scene: UIScene) { // Called when the scene will move from an active state to an inactive state. // This may occur due to temporary interruptions (ex. an incoming phone call). } @available(iOS 13.0, *) func sceneWillEnterForeground(_ scene: UIScene) { // Called as the scene transitions from the background to the foreground. // Use this method to undo the changes made on entering the background. } @available(iOS 13.0, *) func sceneDidEnterBackground(_ scene: UIScene) { // Called as the scene transitions from the foreground to the background. // Use this method to save data, release shared resources, and store enough scene-specific state information // to restore the scene back to its current state. } }
mit
mcomisso/hellokiwi
kiwi/BWWalkthroughViewController.swift
1
10144
// // BWWalkthroughViewController.swift // // Created by Yari D'areglia on 15/09/14 (wait... why do I wrote code the Day of my Birthday?! C'Mon Yari... ) // Copyright (c) 2014 Yari D'areglia. All rights reserved. // import UIKit // MARK: - Protocols - /** Walkthrough Delegate: This delegate performs basic operations such as dismissing the Walkthrough or call whatever action on page change. Probably the Walkthrough is presented by this delegate. **/ @objc protocol BWWalkthroughViewControllerDelegate{ @objc optional func walkthroughCloseButtonPressed() // If the skipRequest(sender:) action is connected to a button, this function is called when that button is pressed. @objc optional func walkthroughNextButtonPressed() // @objc optional func walkthroughPrevButtonPressed() // @objc optional func walkthroughPageDidChange(pageNumber:Int) // Called when current page changes } /** Walkthrough Page: The walkthrough page represents any page added to the Walkthrough. At the moment it's only used to perform custom animations on didScroll. **/ @objc protocol BWWalkthroughPage{ // While sliding to the "next" slide (from right to left), the "current" slide changes its offset from 1.0 to 2.0 while the "next" slide changes it from 0.0 to 1.0 // While sliding to the "previous" slide (left to right), the current slide changes its offset from 1.0 to 0.0 while the "previous" slide changes it from 2.0 to 1.0 // The other pages update their offsets whith values like 2.0, 3.0, -2.0... depending on their positions and on the status of the walkthrough // This value can be used on the previous, current and next page to perform custom animations on page's subviews. @objc func walkthroughDidScroll(position:CGFloat, offset:CGFloat) // Called when the main Scrollview...scroll } @objc(BWWalkthroughViewController) class BWWalkthroughViewController: UIViewController, UIScrollViewDelegate{ // MARK: - Public properties - var delegate:BWWalkthroughViewControllerDelegate? // TODO: If you need a page control, next or prev buttons add them via IB and connect them with these Outlets @IBOutlet var pageControl:UIPageControl? @IBOutlet var nextButton:UIButton? @IBOutlet var prevButton:UIButton? @IBOutlet var closeButton:UIButton? var currentPage:Int{ // The index of the current page (readonly) get{ let page = Int((scrollview.contentOffset.x / view.bounds.size.width)) return page } } // MARK: - Private properties - private let scrollview:UIScrollView! private var controllers:[UIViewController]! private var lastViewConstraint:NSArray? // MARK: - Overrides - required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) // Setup the scrollview scrollview = UIScrollView() scrollview.showsHorizontalScrollIndicator = false scrollview.showsVerticalScrollIndicator = false scrollview.pagingEnabled = true // Controllers as empty array controllers = Array() } override init() { super.init() scrollview = UIScrollView() controllers = Array() } override func viewDidLoad() { super.viewDidLoad() // Initialize UIScrollView scrollview.delegate = self scrollview.setTranslatesAutoresizingMaskIntoConstraints(false) view.insertSubview(scrollview, atIndex: 0) //scrollview is inserted as first view of the hierarchy // Set scrollview related constraints view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[scrollview]-0-|", options:nil, metrics: nil, views: ["scrollview":scrollview])) view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[scrollview]-0-|", options:nil, metrics: nil, views: ["scrollview":scrollview])) } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated); pageControl?.numberOfPages = controllers.count pageControl?.currentPage = 0 } // MARK: - Internal methods - @IBAction func nextPage(){ if (currentPage + 1) < controllers.count { delegate?.walkthroughNextButtonPressed?() var frame = scrollview.frame frame.origin.x = CGFloat(currentPage + 1) * frame.size.width scrollview.scrollRectToVisible(frame, animated: true) } } @IBAction func prevPage(){ if currentPage > 0 { delegate?.walkthroughNextButtonPressed?() var frame = scrollview.frame frame.origin.x = CGFloat(currentPage - 1) * frame.size.width scrollview.scrollRectToVisible(frame, animated: true) } } // TODO: If you want to implement a "skip" option // connect a button to this IBAction and implement the delegate with the skipWalkthrough @IBAction func close(sender: AnyObject){ delegate?.walkthroughCloseButtonPressed?() } /** addViewController Add a new page to the walkthrough. To have information about the current position of the page in the walkthrough add a UIVIewController which implements BWWalkthroughPage */ func addViewController(vc:UIViewController)->Void{ controllers.append(vc) // Setup the viewController view vc.view.setTranslatesAutoresizingMaskIntoConstraints(false) scrollview.addSubview(vc.view) // Constraints let metricDict = ["w":vc.view.bounds.size.width,"h":vc.view.bounds.size.height] // - Generic cnst vc.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[view(h)]", options:nil, metrics: metricDict, views: ["view":vc.view])) vc.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:[view(w)]", options:nil, metrics: metricDict, views: ["view":vc.view])) scrollview.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[view]|", options:nil, metrics: nil, views: ["view":vc.view,])) // cnst for position: 1st element if controllers.count == 1{ scrollview.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[view]", options:nil, metrics: nil, views: ["view":vc.view,])) // cnst for position: other elements }else{ let previousVC = controllers[controllers.count-2] let previousView = previousVC.view; scrollview.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:[previousView]-0-[view]", options:nil, metrics: nil, views: ["previousView":previousView,"view":vc.view])) if let cst = lastViewConstraint{ scrollview.removeConstraints(cst) } lastViewConstraint = NSLayoutConstraint.constraintsWithVisualFormat("H:[view]-|", options:nil, metrics: nil, views: ["view":vc.view]) scrollview.addConstraints(lastViewConstraint!) } } /** Update the UI to reflect the current walkthrough situation **/ private func updateUI(){ // Get the current page pageControl?.currentPage = currentPage // Notify delegate about the new page delegate?.walkthroughPageDidChange?(currentPage) // Hide/Show navigation buttons if currentPage == controllers.count - 1{ nextButton?.hidden = true }else{ nextButton?.hidden = false } if currentPage == 0{ prevButton?.hidden = true }else{ prevButton?.hidden = false } } // MARK: - Scrollview Delegate - func scrollViewDidScroll(sv: UIScrollView) { for var i=0; i < controllers.count; i++ { if let vc = controllers[i] as? BWWalkthroughPage{ let mx = ((scrollview.contentOffset.x + view.bounds.size.width) - (view.bounds.size.width * CGFloat(i))) / view.bounds.size.width // While sliding to the "next" slide (from right to left), the "current" slide changes its offset from 1.0 to 2.0 while the "next" slide changes it from 0.0 to 1.0 // While sliding to the "previous" slide (left to right), the current slide changes its offset from 1.0 to 0.0 while the "previous" slide changes it from 2.0 to 1.0 // The other pages update their offsets whith values like 2.0, 3.0, -2.0... depending on their positions and on the status of the walkthrough // This value can be used on the previous, current and next page to perform custom animations on page's subviews. // print the mx value to get more info. // println("\(i):\(mx)") // We animate only the previous, current and next page if(mx < 2 && mx > -2.0){ vc.walkthroughDidScroll(scrollview.contentOffset.x, offset: mx) } } } } func scrollViewDidEndDecelerating(scrollView: UIScrollView) { updateUI() } func scrollViewDidEndScrollingAnimation(scrollView: UIScrollView) { updateUI() } /* WIP */ override func willTransitionToTraitCollection(newCollection: UITraitCollection, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) { println("CHANGE") } override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) { println("SIZE") } }
apache-2.0
actilot/ACMaterialDesignIcons
ACMaterialDesignIcons.swift
1
45525
// // ACMaterialDesignIcons.swift // ACMaterialDesignIcons // // Created by Axel Ros Campaña on 9/5/17. // Copyright © 2017 Axel Ros Campaña. All rights reserved. // import Foundation import UIKit public class ACMaterialDesignIcons { public var iconAttributedString: NSMutableAttributedString? public var fontSize: CGFloat = 0.0 public static func loadFont() { let bundle = Bundle(for: ACMaterialDesignIcons.self) let identifier = bundle.bundleIdentifier let name = "Material-Design-Iconic-Font" var fontURL: URL if identifier?.hasPrefix("org.cocoapods") == true { // If this framework is added using CocoaPods, resources is placed under a subdirectory fontURL = bundle.url(forResource: name, withExtension: "ttf", subdirectory: "ACMaterialDesignIcons.bundle")! } else { fontURL = bundle.url(forResource: name, withExtension: "ttf")! } let fontDataProvider = CGDataProvider(url: fontURL as CFURL) let newFont = CGFont(fontDataProvider!) CTFontManagerRegisterGraphicsFont(newFont, nil) } public static func icon(withCode code: String!, fontSize: CGFloat) -> ACMaterialDesignIcons { loadFont() let icon = ACMaterialDesignIcons() icon.fontSize = fontSize icon.iconAttributedString = NSMutableAttributedString(string: code, attributes: [NSFontAttributeName: iconFont(withSize: fontSize)!]) return icon } public static func iconFont(withSize size: CGFloat) -> UIFont? { let font = UIFont(name: "Material-Design-Iconic-Font", size: size) return font } public func image(_ imageSize: CGSize? = nil) -> UIImage { var imageSize = imageSize if imageSize == nil { imageSize = CGSize(width: fontSize, height: fontSize) } UIGraphicsBeginImageContextWithOptions(imageSize!, false, UIScreen.main.scale) let iconSize = iconAttributedString?.size() let xOffset = (imageSize!.width - iconSize!.width) / 2.0 let yOffset = (imageSize!.height - iconSize!.height) / 2.0 let rect = CGRect(x: xOffset, y: yOffset, width: iconSize!.width, height: iconSize!.height) iconAttributedString?.draw(in: rect) let iconImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return iconImage! } public func rangeForAttributedText() -> NSRange { return NSRange(location: 0, length: iconAttributedString!.length) } public func addAttributes(_ attributes: Dictionary<String, Any>) { iconAttributedString?.addAttributes(attributes, range: rangeForAttributedText()) } public func addAttribute(withName name: String, value: Any) { iconAttributedString?.addAttribute(name, value: value, range: rangeForAttributedText()) } public func removeAttribute(withName name: String) { iconAttributedString?.removeAttribute(name, range: rangeForAttributedText()) } public func allIcons() -> Array<String> { return [ACMaterialDesignIconCode.md_3d_rotation, ACMaterialDesignIconCode.md_airplane_off, ACMaterialDesignIconCode.md_airplane, ACMaterialDesignIconCode.md_album, ACMaterialDesignIconCode.md_archive, ACMaterialDesignIconCode.md_assignment_account, ACMaterialDesignIconCode.md_assignment_alert, ACMaterialDesignIconCode.md_assignment_check, ACMaterialDesignIconCode.md_assignment_o, ACMaterialDesignIconCode.md_assignment_return, ACMaterialDesignIconCode.md_assignment_returned, ACMaterialDesignIconCode.md_assignment, ACMaterialDesignIconCode.md_attachment_alt, ACMaterialDesignIconCode.md_attachment, ACMaterialDesignIconCode.md_audio, ACMaterialDesignIconCode.md_badge_check, ACMaterialDesignIconCode.md_balance_wallet, ACMaterialDesignIconCode.md_balance, ACMaterialDesignIconCode.md_battery_alert, ACMaterialDesignIconCode.md_battery_flash, ACMaterialDesignIconCode.md_battery_unknown, ACMaterialDesignIconCode.md_battery, ACMaterialDesignIconCode.md_bike, ACMaterialDesignIconCode.md_block_alt, ACMaterialDesignIconCode.md_block, ACMaterialDesignIconCode.md_boat, ACMaterialDesignIconCode.md_book_image, ACMaterialDesignIconCode.md_book, ACMaterialDesignIconCode.md_bookmark_outline, ACMaterialDesignIconCode.md_bookmark, ACMaterialDesignIconCode.md_brush, ACMaterialDesignIconCode.md_bug, ACMaterialDesignIconCode.md_bus, ACMaterialDesignIconCode.md_cake, ACMaterialDesignIconCode.md_car_taxi, ACMaterialDesignIconCode.md_car_wash, ACMaterialDesignIconCode.md_car, ACMaterialDesignIconCode.md_card_giftcard, ACMaterialDesignIconCode.md_card_membership, ACMaterialDesignIconCode.md_card_travel, ACMaterialDesignIconCode.md_card, ACMaterialDesignIconCode.md_case_check, ACMaterialDesignIconCode.md_case_download, ACMaterialDesignIconCode.md_case_play, ACMaterialDesignIconCode.md_case, ACMaterialDesignIconCode.md_cast_connected, ACMaterialDesignIconCode.md_cast, ACMaterialDesignIconCode.md_chart_donut, ACMaterialDesignIconCode.md_chart, ACMaterialDesignIconCode.md_city_alt, ACMaterialDesignIconCode.md_city, ACMaterialDesignIconCode.md_close_circle_o, ACMaterialDesignIconCode.md_close_circle, ACMaterialDesignIconCode.md_close, ACMaterialDesignIconCode.md_cocktail, ACMaterialDesignIconCode.md_code_setting, ACMaterialDesignIconCode.md_code_smartphone, ACMaterialDesignIconCode.md_code, ACMaterialDesignIconCode.md_coffee, ACMaterialDesignIconCode.md_collection_bookmark, ACMaterialDesignIconCode.md_collection_case_play, ACMaterialDesignIconCode.md_collection_folder_image, ACMaterialDesignIconCode.md_collection_image_o, ACMaterialDesignIconCode.md_collection_image, ACMaterialDesignIconCode.md_collection_item_1, ACMaterialDesignIconCode.md_collection_item_2, ACMaterialDesignIconCode.md_collection_item_3, ACMaterialDesignIconCode.md_collection_item_4, ACMaterialDesignIconCode.md_collection_item_5, ACMaterialDesignIconCode.md_collection_item_6, ACMaterialDesignIconCode.md_collection_item_7, ACMaterialDesignIconCode.md_collection_item_8, ACMaterialDesignIconCode.md_collection_item_9_plus, ACMaterialDesignIconCode.md_collection_item_9, ACMaterialDesignIconCode.md_collection_item, ACMaterialDesignIconCode.md_collection_music, ACMaterialDesignIconCode.md_collection_pdf, ACMaterialDesignIconCode.md_collection_plus, ACMaterialDesignIconCode.md_collection_speaker, ACMaterialDesignIconCode.md_collection_text, ACMaterialDesignIconCode.md_collection_video, ACMaterialDesignIconCode.md_compass, ACMaterialDesignIconCode.md_cutlery, ACMaterialDesignIconCode.md_delete, ACMaterialDesignIconCode.md_dialpad, ACMaterialDesignIconCode.md_dns, ACMaterialDesignIconCode.md_drink, ACMaterialDesignIconCode.md_edit, ACMaterialDesignIconCode.md_email_open, ACMaterialDesignIconCode.md_email, ACMaterialDesignIconCode.md_eye_off, ACMaterialDesignIconCode.md_eye, ACMaterialDesignIconCode.md_eyedropper, ACMaterialDesignIconCode.md_favorite_outline, ACMaterialDesignIconCode.md_favorite, ACMaterialDesignIconCode.md_filter_list, ACMaterialDesignIconCode.md_fire, ACMaterialDesignIconCode.md_flag, ACMaterialDesignIconCode.md_flare, ACMaterialDesignIconCode.md_flash_auto, ACMaterialDesignIconCode.md_flash_off, ACMaterialDesignIconCode.md_flash, ACMaterialDesignIconCode.md_flip, ACMaterialDesignIconCode.md_flower_alt, ACMaterialDesignIconCode.md_flower, ACMaterialDesignIconCode.md_font, ACMaterialDesignIconCode.md_fullscreen_alt, ACMaterialDesignIconCode.md_fullscreen_exit, ACMaterialDesignIconCode.md_fullscreen, ACMaterialDesignIconCode.md_functions, ACMaterialDesignIconCode.md_gas_station, ACMaterialDesignIconCode.md_gesture, ACMaterialDesignIconCode.md_globe_alt, ACMaterialDesignIconCode.md_globe_lock, ACMaterialDesignIconCode.md_globe, ACMaterialDesignIconCode.md_graduation_cap, ACMaterialDesignIconCode.md_home, ACMaterialDesignIconCode.md_hospital_alt, ACMaterialDesignIconCode.md_hospital, ACMaterialDesignIconCode.md_hotel, ACMaterialDesignIconCode.md_hourglass_alt, ACMaterialDesignIconCode.md_hourglass_outline, ACMaterialDesignIconCode.md_hourglass, ACMaterialDesignIconCode.md_http, ACMaterialDesignIconCode.md_image_alt, ACMaterialDesignIconCode.md_image_o, ACMaterialDesignIconCode.md_image, ACMaterialDesignIconCode.md_inbox, ACMaterialDesignIconCode.md_invert_colors_off, ACMaterialDesignIconCode.md_invert_colors, ACMaterialDesignIconCode.md_key, ACMaterialDesignIconCode.md_label_alt_outline, ACMaterialDesignIconCode.md_label_alt, ACMaterialDesignIconCode.md_label_heart, ACMaterialDesignIconCode.md_label, ACMaterialDesignIconCode.md_labels, ACMaterialDesignIconCode.md_lamp, ACMaterialDesignIconCode.md_landscape, ACMaterialDesignIconCode.md_layers_off, ACMaterialDesignIconCode.md_layers, ACMaterialDesignIconCode.md_library, ACMaterialDesignIconCode.md_link, ACMaterialDesignIconCode.md_lock_open, ACMaterialDesignIconCode.md_lock_outline, ACMaterialDesignIconCode.md_lock, ACMaterialDesignIconCode.md_mail_reply_all, ACMaterialDesignIconCode.md_mail_reply, ACMaterialDesignIconCode.md_mail_send, ACMaterialDesignIconCode.md_mall, ACMaterialDesignIconCode.md_map, ACMaterialDesignIconCode.md_menu, ACMaterialDesignIconCode.md_money_box, ACMaterialDesignIconCode.md_money_off, ACMaterialDesignIconCode.md_money, ACMaterialDesignIconCode.md_more_vert, ACMaterialDesignIconCode.md_more, ACMaterialDesignIconCode.md_movie_alt, ACMaterialDesignIconCode.md_movie, ACMaterialDesignIconCode.md_nature_people, ACMaterialDesignIconCode.md_nature, ACMaterialDesignIconCode.md_navigation, ACMaterialDesignIconCode.md_open_in_browser, ACMaterialDesignIconCode.md_open_in_new, ACMaterialDesignIconCode.md_palette, ACMaterialDesignIconCode.md_parking, ACMaterialDesignIconCode.md_pin_account, ACMaterialDesignIconCode.md_pin_assistant, ACMaterialDesignIconCode.md_pin_drop, ACMaterialDesignIconCode.md_pin_help, ACMaterialDesignIconCode.md_pin_off, ACMaterialDesignIconCode.md_pin, ACMaterialDesignIconCode.md_pizza, ACMaterialDesignIconCode.md_plaster, ACMaterialDesignIconCode.md_power_setting, ACMaterialDesignIconCode.md_power, ACMaterialDesignIconCode.md_print, ACMaterialDesignIconCode.md_puzzle_piece, ACMaterialDesignIconCode.md_quote, ACMaterialDesignIconCode.md_railway, ACMaterialDesignIconCode.md_receipt, ACMaterialDesignIconCode.md_refresh_alt, ACMaterialDesignIconCode.md_refresh_sync_alert, ACMaterialDesignIconCode.md_refresh_sync_off, ACMaterialDesignIconCode.md_refresh_sync, ACMaterialDesignIconCode.md_refresh, ACMaterialDesignIconCode.md_roller, ACMaterialDesignIconCode.md_ruler, ACMaterialDesignIconCode.md_scissors, ACMaterialDesignIconCode.md_screen_rotation_lock, ACMaterialDesignIconCode.md_screen_rotation, ACMaterialDesignIconCode.md_search_for, ACMaterialDesignIconCode.md_search_in_file, ACMaterialDesignIconCode.md_search_in_page, ACMaterialDesignIconCode.md_search_replace, ACMaterialDesignIconCode.md_search, ACMaterialDesignIconCode.md_seat, ACMaterialDesignIconCode.md_settings_square, ACMaterialDesignIconCode.md_settings, ACMaterialDesignIconCode.md_shield_check, ACMaterialDesignIconCode.md_shield_security, ACMaterialDesignIconCode.md_shopping_basket, ACMaterialDesignIconCode.md_shopping_cart_plus, ACMaterialDesignIconCode.md_shopping_cart, ACMaterialDesignIconCode.md_sign_in, ACMaterialDesignIconCode.md_sort_amount_asc, ACMaterialDesignIconCode.md_sort_amount_desc, ACMaterialDesignIconCode.md_sort_asc, ACMaterialDesignIconCode.md_sort_desc, ACMaterialDesignIconCode.md_spellcheck, ACMaterialDesignIconCode.md_storage, ACMaterialDesignIconCode.md_store_24, ACMaterialDesignIconCode.md_store, ACMaterialDesignIconCode.md_subway, ACMaterialDesignIconCode.md_sun, ACMaterialDesignIconCode.md_tab_unselected, ACMaterialDesignIconCode.md_tab, ACMaterialDesignIconCode.md_tag_close, ACMaterialDesignIconCode.md_tag_more, ACMaterialDesignIconCode.md_tag, ACMaterialDesignIconCode.md_thumb_down, ACMaterialDesignIconCode.md_thumb_up_down, ACMaterialDesignIconCode.md_thumb_up, ACMaterialDesignIconCode.md_ticket_star, ACMaterialDesignIconCode.md_toll, ACMaterialDesignIconCode.md_toys, ACMaterialDesignIconCode.md_traffic, ACMaterialDesignIconCode.md_translate, ACMaterialDesignIconCode.md_triangle_down, ACMaterialDesignIconCode.md_triangle_up, ACMaterialDesignIconCode.md_truck, ACMaterialDesignIconCode.md_turning_sign, ACMaterialDesignIconCode.md_wallpaper, ACMaterialDesignIconCode.md_washing_machine, ACMaterialDesignIconCode.md_window_maximize, ACMaterialDesignIconCode.md_window_minimize, ACMaterialDesignIconCode.md_window_restore, ACMaterialDesignIconCode.md_wrench, ACMaterialDesignIconCode.md_zoom_in, ACMaterialDesignIconCode.md_zoom_out, ACMaterialDesignIconCode.md_alert_circle_o, ACMaterialDesignIconCode.md_alert_circle, ACMaterialDesignIconCode.md_alert_octagon, ACMaterialDesignIconCode.md_alert_polygon, ACMaterialDesignIconCode.md_alert_triangle, ACMaterialDesignIconCode.md_help_outline, ACMaterialDesignIconCode.md_help, ACMaterialDesignIconCode.md_info_outline, ACMaterialDesignIconCode.md_info, ACMaterialDesignIconCode.md_notifications_active, ACMaterialDesignIconCode.md_notifications_add, ACMaterialDesignIconCode.md_notifications_none, ACMaterialDesignIconCode.md_notifications_off, ACMaterialDesignIconCode.md_notifications_paused, ACMaterialDesignIconCode.md_notifications, ACMaterialDesignIconCode.md_account_add, ACMaterialDesignIconCode.md_account_box_mail, ACMaterialDesignIconCode.md_account_box_o, ACMaterialDesignIconCode.md_account_box_phone, ACMaterialDesignIconCode.md_account_box, ACMaterialDesignIconCode.md_account_calendar, ACMaterialDesignIconCode.md_account_circle, ACMaterialDesignIconCode.md_account_o, ACMaterialDesignIconCode.md_account, ACMaterialDesignIconCode.md_accounts_add, ACMaterialDesignIconCode.md_accounts_alt, ACMaterialDesignIconCode.md_accounts_list_alt, ACMaterialDesignIconCode.md_accounts_list, ACMaterialDesignIconCode.md_accounts_outline, ACMaterialDesignIconCode.md_accounts, ACMaterialDesignIconCode.md_face, ACMaterialDesignIconCode.md_female, ACMaterialDesignIconCode.md_male_alt, ACMaterialDesignIconCode.md_male_female, ACMaterialDesignIconCode.md_male, ACMaterialDesignIconCode.md_mood_bad, ACMaterialDesignIconCode.md_mood, ACMaterialDesignIconCode.md_run, ACMaterialDesignIconCode.md_walk, ACMaterialDesignIconCode.md_cloud_box, ACMaterialDesignIconCode.md_cloud_circle, ACMaterialDesignIconCode.md_cloud_done, ACMaterialDesignIconCode.md_cloud_download, ACMaterialDesignIconCode.md_cloud_off, ACMaterialDesignIconCode.md_cloud_outline_alt, ACMaterialDesignIconCode.md_cloud_outline, ACMaterialDesignIconCode.md_cloud_upload, ACMaterialDesignIconCode.md_cloud, ACMaterialDesignIconCode.md_download, ACMaterialDesignIconCode.md_file_plus, ACMaterialDesignIconCode.md_file_text, ACMaterialDesignIconCode.md_file, ACMaterialDesignIconCode.md_folder_outline, ACMaterialDesignIconCode.md_folder_person, ACMaterialDesignIconCode.md_folder_star_alt, ACMaterialDesignIconCode.md_folder_star, ACMaterialDesignIconCode.md_folder, ACMaterialDesignIconCode.md_gif, ACMaterialDesignIconCode.md_upload, ACMaterialDesignIconCode.md_border_all, ACMaterialDesignIconCode.md_border_bottom, ACMaterialDesignIconCode.md_border_clear, ACMaterialDesignIconCode.md_border_color, ACMaterialDesignIconCode.md_border_horizontal, ACMaterialDesignIconCode.md_border_inner, ACMaterialDesignIconCode.md_border_left, ACMaterialDesignIconCode.md_border_outer, ACMaterialDesignIconCode.md_border_right, ACMaterialDesignIconCode.md_border_style, ACMaterialDesignIconCode.md_border_top, ACMaterialDesignIconCode.md_border_vertical, ACMaterialDesignIconCode.md_copy, ACMaterialDesignIconCode.md_crop, ACMaterialDesignIconCode.md_format_align_center, ACMaterialDesignIconCode.md_format_align_justify, ACMaterialDesignIconCode.md_format_align_left, ACMaterialDesignIconCode.md_format_align_right, ACMaterialDesignIconCode.md_format_bold, ACMaterialDesignIconCode.md_format_clear_all, ACMaterialDesignIconCode.md_format_clear, ACMaterialDesignIconCode.md_format_color_fill, ACMaterialDesignIconCode.md_format_color_reset, ACMaterialDesignIconCode.md_format_color_text, ACMaterialDesignIconCode.md_format_indent_decrease, ACMaterialDesignIconCode.md_format_indent_increase, ACMaterialDesignIconCode.md_format_italic, ACMaterialDesignIconCode.md_format_line_spacing, ACMaterialDesignIconCode.md_format_list_bulleted, ACMaterialDesignIconCode.md_format_list_numbered, ACMaterialDesignIconCode.md_format_ltr, ACMaterialDesignIconCode.md_format_rtl, ACMaterialDesignIconCode.md_format_size, ACMaterialDesignIconCode.md_format_strikethrough_s, ACMaterialDesignIconCode.md_format_strikethrough, ACMaterialDesignIconCode.md_format_subject, ACMaterialDesignIconCode.md_format_underlined, ACMaterialDesignIconCode.md_format_valign_bottom, ACMaterialDesignIconCode.md_format_valign_center, ACMaterialDesignIconCode.md_format_valign_top, ACMaterialDesignIconCode.md_redo, ACMaterialDesignIconCode.md_select_all, ACMaterialDesignIconCode.md_space_bar, ACMaterialDesignIconCode.md_text_format, ACMaterialDesignIconCode.md_transform, ACMaterialDesignIconCode.md_undo, ACMaterialDesignIconCode.md_wrap_text, ACMaterialDesignIconCode.md_comment_alert, ACMaterialDesignIconCode.md_comment_alt_text, ACMaterialDesignIconCode.md_comment_alt, ACMaterialDesignIconCode.md_comment_edit, ACMaterialDesignIconCode.md_comment_image, ACMaterialDesignIconCode.md_comment_list, ACMaterialDesignIconCode.md_comment_more, ACMaterialDesignIconCode.md_comment_outline, ACMaterialDesignIconCode.md_comment_text_alt, ACMaterialDesignIconCode.md_comment_text, ACMaterialDesignIconCode.md_comment_video, ACMaterialDesignIconCode.md_comment, ACMaterialDesignIconCode.md_comments, ACMaterialDesignIconCode.md_check_all, ACMaterialDesignIconCode.md_check_circle_u, ACMaterialDesignIconCode.md_check_circle, ACMaterialDesignIconCode.md_check_square, ACMaterialDesignIconCode.md_check, ACMaterialDesignIconCode.md_circle_o, ACMaterialDesignIconCode.md_circle, ACMaterialDesignIconCode.md_dot_circle_alt, ACMaterialDesignIconCode.md_dot_circle, ACMaterialDesignIconCode.md_minus_circle_outline, ACMaterialDesignIconCode.md_minus_circle, ACMaterialDesignIconCode.md_minus_square, ACMaterialDesignIconCode.md_minus, ACMaterialDesignIconCode.md_plus_circle_o_duplicate, ACMaterialDesignIconCode.md_plus_circle_o, ACMaterialDesignIconCode.md_plus_circle, ACMaterialDesignIconCode.md_plus_square, ACMaterialDesignIconCode.md_plus, ACMaterialDesignIconCode.md_square_o, ACMaterialDesignIconCode.md_star_circle, ACMaterialDesignIconCode.md_star_half, ACMaterialDesignIconCode.md_star_outline, ACMaterialDesignIconCode.md_star, ACMaterialDesignIconCode.md_bluetooth_connected, ACMaterialDesignIconCode.md_bluetooth_off, ACMaterialDesignIconCode.md_bluetooth_search, ACMaterialDesignIconCode.md_bluetooth_setting, ACMaterialDesignIconCode.md_bluetooth, ACMaterialDesignIconCode.md_camera_add, ACMaterialDesignIconCode.md_camera_alt, ACMaterialDesignIconCode.md_camera_bw, ACMaterialDesignIconCode.md_camera_front, ACMaterialDesignIconCode.md_camera_mic, ACMaterialDesignIconCode.md_camera_party_mode, ACMaterialDesignIconCode.md_camera_rear, ACMaterialDesignIconCode.md_camera_roll, ACMaterialDesignIconCode.md_camera_switch, ACMaterialDesignIconCode.md_camera, ACMaterialDesignIconCode.md_card_alert, ACMaterialDesignIconCode.md_card_off, ACMaterialDesignIconCode.md_card_sd, ACMaterialDesignIconCode.md_card_sim, ACMaterialDesignIconCode.md_desktop_mac, ACMaterialDesignIconCode.md_desktop_windows, ACMaterialDesignIconCode.md_device_hub, ACMaterialDesignIconCode.md_devices_off, ACMaterialDesignIconCode.md_devices, ACMaterialDesignIconCode.md_dock, ACMaterialDesignIconCode.md_floppy, ACMaterialDesignIconCode.md_gamepad, ACMaterialDesignIconCode.md_gps_dot, ACMaterialDesignIconCode.md_gps_off, ACMaterialDesignIconCode.md_gps, ACMaterialDesignIconCode.md_headset_mic, ACMaterialDesignIconCode.md_headset, ACMaterialDesignIconCode.md_input_antenna, ACMaterialDesignIconCode.md_input_composite, ACMaterialDesignIconCode.md_input_hdmi, ACMaterialDesignIconCode.md_input_power, ACMaterialDesignIconCode.md_input_svideo, ACMaterialDesignIconCode.md_keyboard_hide, ACMaterialDesignIconCode.md_keyboard, ACMaterialDesignIconCode.md_laptop_chromebook, ACMaterialDesignIconCode.md_laptop_mac, ACMaterialDesignIconCode.md_laptop, ACMaterialDesignIconCode.md_mic_off, ACMaterialDesignIconCode.md_mic_outline, ACMaterialDesignIconCode.md_mic_setting, ACMaterialDesignIconCode.md_mic, ACMaterialDesignIconCode.md_mouse, ACMaterialDesignIconCode.md_network_alert, ACMaterialDesignIconCode.md_network_locked, ACMaterialDesignIconCode.md_network_off, ACMaterialDesignIconCode.md_network_outline, ACMaterialDesignIconCode.md_network_setting, ACMaterialDesignIconCode.md_network, ACMaterialDesignIconCode.md_phone_bluetooth, ACMaterialDesignIconCode.md_phone_end, ACMaterialDesignIconCode.md_phone_forwarded, ACMaterialDesignIconCode.md_phone_in_talk, ACMaterialDesignIconCode.md_phone_locked, ACMaterialDesignIconCode.md_phone_missed, ACMaterialDesignIconCode.md_phone_msg, ACMaterialDesignIconCode.md_phone_paused, ACMaterialDesignIconCode.md_phone_ring, ACMaterialDesignIconCode.md_phone_setting, ACMaterialDesignIconCode.md_phone_sip, ACMaterialDesignIconCode.md_phone, ACMaterialDesignIconCode.md_portable_wifi_changes, ACMaterialDesignIconCode.md_portable_wifi_off, ACMaterialDesignIconCode.md_portable_wifi, ACMaterialDesignIconCode.md_radio, ACMaterialDesignIconCode.md_reader, ACMaterialDesignIconCode.md_remote_control_alt, ACMaterialDesignIconCode.md_remote_control, ACMaterialDesignIconCode.md_router, ACMaterialDesignIconCode.md_scanner, ACMaterialDesignIconCode.md_smartphone_android, ACMaterialDesignIconCode.md_smartphone_download, ACMaterialDesignIconCode.md_smartphone_erase, ACMaterialDesignIconCode.md_smartphone_info, ACMaterialDesignIconCode.md_smartphone_iphone, ACMaterialDesignIconCode.md_smartphone_landscape_lock, ACMaterialDesignIconCode.md_smartphone_landscape, ACMaterialDesignIconCode.md_smartphone_lock, ACMaterialDesignIconCode.md_smartphone_portrait_lock, ACMaterialDesignIconCode.md_smartphone_ring, ACMaterialDesignIconCode.md_smartphone_setting, ACMaterialDesignIconCode.md_smartphone_setup, ACMaterialDesignIconCode.md_smartphone, ACMaterialDesignIconCode.md_speaker, ACMaterialDesignIconCode.md_tablet_android, ACMaterialDesignIconCode.md_tablet_mac, ACMaterialDesignIconCode.md_tablet, ACMaterialDesignIconCode.md_tv_alt_play, ACMaterialDesignIconCode.md_tv_list, ACMaterialDesignIconCode.md_tv_play, ACMaterialDesignIconCode.md_tv, ACMaterialDesignIconCode.md_usb, ACMaterialDesignIconCode.md_videocam_off, ACMaterialDesignIconCode.md_videocam_switch, ACMaterialDesignIconCode.md_videocam, ACMaterialDesignIconCode.md_watch, ACMaterialDesignIconCode.md_wifi_alt_2, ACMaterialDesignIconCode.md_wifi_alt, ACMaterialDesignIconCode.md_wifi_info, ACMaterialDesignIconCode.md_wifi_lock, ACMaterialDesignIconCode.md_wifi_off, ACMaterialDesignIconCode.md_wifi_outline, ACMaterialDesignIconCode.md_wifi, ACMaterialDesignIconCode.md_arrow_left_bottom, ACMaterialDesignIconCode.md_arrow_left, ACMaterialDesignIconCode.md_arrow_merge, ACMaterialDesignIconCode.md_arrow_missed, ACMaterialDesignIconCode.md_arrow_right_top, ACMaterialDesignIconCode.md_arrow_right, ACMaterialDesignIconCode.md_arrow_split, ACMaterialDesignIconCode.md_arrows, ACMaterialDesignIconCode.md_caret_down_circle, ACMaterialDesignIconCode.md_caret_down, ACMaterialDesignIconCode.md_caret_left_circle, ACMaterialDesignIconCode.md_caret_left, ACMaterialDesignIconCode.md_caret_right_circle, ACMaterialDesignIconCode.md_caret_right, ACMaterialDesignIconCode.md_caret_up_circle, ACMaterialDesignIconCode.md_caret_up, ACMaterialDesignIconCode.md_chevron_down, ACMaterialDesignIconCode.md_chevron_left, ACMaterialDesignIconCode.md_chevron_right, ACMaterialDesignIconCode.md_chevron_up, ACMaterialDesignIconCode.md_forward, ACMaterialDesignIconCode.md_long_arrow_down, ACMaterialDesignIconCode.md_long_arrow_left, ACMaterialDesignIconCode.md_long_arrow_return, ACMaterialDesignIconCode.md_long_arrow_right, ACMaterialDesignIconCode.md_long_arrow_tab, ACMaterialDesignIconCode.md_long_arrow_up, ACMaterialDesignIconCode.md_rotate_ccw, ACMaterialDesignIconCode.md_rotate_cw, ACMaterialDesignIconCode.md_rotate_left, ACMaterialDesignIconCode.md_rotate_right, ACMaterialDesignIconCode.md_square_down, ACMaterialDesignIconCode.md_square_right, ACMaterialDesignIconCode.md_swap_alt, ACMaterialDesignIconCode.md_swap_vertical_circle, ACMaterialDesignIconCode.md_swap_vertical, ACMaterialDesignIconCode.md_swap, ACMaterialDesignIconCode.md_trending_down, ACMaterialDesignIconCode.md_trending_flat, ACMaterialDesignIconCode.md_trending_up, ACMaterialDesignIconCode.md_unfold_less, ACMaterialDesignIconCode.md_unfold_more, ACMaterialDesignIconCode.md_apps, ACMaterialDesignIconCode.md_grid_off, ACMaterialDesignIconCode.md_grid, ACMaterialDesignIconCode.md_view_agenda, ACMaterialDesignIconCode.md_view_array, ACMaterialDesignIconCode.md_view_carousel, ACMaterialDesignIconCode.md_view_column, ACMaterialDesignIconCode.md_view_comfy, ACMaterialDesignIconCode.md_view_compact, ACMaterialDesignIconCode.md_view_dashboard, ACMaterialDesignIconCode.md_view_day, ACMaterialDesignIconCode.md_view_headline, ACMaterialDesignIconCode.md_view_list_alt, ACMaterialDesignIconCode.md_view_list, ACMaterialDesignIconCode.md_view_module, ACMaterialDesignIconCode.md_view_quilt, ACMaterialDesignIconCode.md_view_stream, ACMaterialDesignIconCode.md_view_subtitles, ACMaterialDesignIconCode.md_view_toc, ACMaterialDesignIconCode.md_view_web, ACMaterialDesignIconCode.md_view_week, ACMaterialDesignIconCode.md_widgets, ACMaterialDesignIconCode.md_alarm_check, ACMaterialDesignIconCode.md_alarm_off, ACMaterialDesignIconCode.md_alarm_plus, ACMaterialDesignIconCode.md_alarm_snooze, ACMaterialDesignIconCode.md_alarm, ACMaterialDesignIconCode.md_calendar_alt, ACMaterialDesignIconCode.md_calendar_check, ACMaterialDesignIconCode.md_calendar_close, ACMaterialDesignIconCode.md_calendar_note, ACMaterialDesignIconCode.md_calendar, ACMaterialDesignIconCode.md_time_countdown, ACMaterialDesignIconCode.md_time_interval, ACMaterialDesignIconCode.md_time_restore_setting, ACMaterialDesignIconCode.md_time_restore, ACMaterialDesignIconCode.md_time, ACMaterialDesignIconCode.md_timer_off, ACMaterialDesignIconCode.md_timer, ACMaterialDesignIconCode.md_android_alt, ACMaterialDesignIconCode.md_android, ACMaterialDesignIconCode.md_apple, ACMaterialDesignIconCode.md_behance, ACMaterialDesignIconCode.md_codepen, ACMaterialDesignIconCode.md_dribbble, ACMaterialDesignIconCode.md_dropbox, ACMaterialDesignIconCode.md_evernote, ACMaterialDesignIconCode.md_facebook_box, ACMaterialDesignIconCode.md_facebook, ACMaterialDesignIconCode.md_github_box, ACMaterialDesignIconCode.md_github, ACMaterialDesignIconCode.md_google_drive, ACMaterialDesignIconCode.md_google_earth, ACMaterialDesignIconCode.md_google_glass, ACMaterialDesignIconCode.md_google_maps, ACMaterialDesignIconCode.md_google_pages, ACMaterialDesignIconCode.md_google_play, ACMaterialDesignIconCode.md_google_plus_box, ACMaterialDesignIconCode.md_google_plus, ACMaterialDesignIconCode.md_google, ACMaterialDesignIconCode.md_instagram, ACMaterialDesignIconCode.md_language_css3, ACMaterialDesignIconCode.md_language_html5, ACMaterialDesignIconCode.md_language_javascript, ACMaterialDesignIconCode.md_language_python_alt, ACMaterialDesignIconCode.md_language_python, ACMaterialDesignIconCode.md_lastfm, ACMaterialDesignIconCode.md_linkedin_box, ACMaterialDesignIconCode.md_paypal, ACMaterialDesignIconCode.md_pinterest_box, ACMaterialDesignIconCode.md_pocket, ACMaterialDesignIconCode.md_polymer, ACMaterialDesignIconCode.md_share, ACMaterialDesignIconCode.md_stack_overflow, ACMaterialDesignIconCode.md_steam_square, ACMaterialDesignIconCode.md_steam, ACMaterialDesignIconCode.md_twitter_box, ACMaterialDesignIconCode.md_twitter, ACMaterialDesignIconCode.md_vk, ACMaterialDesignIconCode.md_wikipedia, ACMaterialDesignIconCode.md_windows, ACMaterialDesignIconCode.md_aspect_ratio_alt, ACMaterialDesignIconCode.md_aspect_ratio, ACMaterialDesignIconCode.md_blur_circular, ACMaterialDesignIconCode.md_blur_linear, ACMaterialDesignIconCode.md_blur_off, ACMaterialDesignIconCode.md_blur, ACMaterialDesignIconCode.md_brightness_2, ACMaterialDesignIconCode.md_brightness_3, ACMaterialDesignIconCode.md_brightness_4, ACMaterialDesignIconCode.md_brightness_5, ACMaterialDesignIconCode.md_brightness_6, ACMaterialDesignIconCode.md_brightness_7, ACMaterialDesignIconCode.md_brightness_auto, ACMaterialDesignIconCode.md_brightness_setting, ACMaterialDesignIconCode.md_broken_image, ACMaterialDesignIconCode.md_center_focus_strong, ACMaterialDesignIconCode.md_center_focus_weak, ACMaterialDesignIconCode.md_compare, ACMaterialDesignIconCode.md_crop_16_9, ACMaterialDesignIconCode.md_crop_3_2, ACMaterialDesignIconCode.md_crop_5_4, ACMaterialDesignIconCode.md_crop_7_5, ACMaterialDesignIconCode.md_crop_din, ACMaterialDesignIconCode.md_crop_free, ACMaterialDesignIconCode.md_crop_landscape, ACMaterialDesignIconCode.md_crop_portrait, ACMaterialDesignIconCode.md_crop_square, ACMaterialDesignIconCode.md_exposure_alt, ACMaterialDesignIconCode.md_exposure, ACMaterialDesignIconCode.md_filter_b_and_w, ACMaterialDesignIconCode.md_filter_center_focus, ACMaterialDesignIconCode.md_filter_frames, ACMaterialDesignIconCode.md_filter_tilt_shift, ACMaterialDesignIconCode.md_gradient, ACMaterialDesignIconCode.md_grain, ACMaterialDesignIconCode.md_graphic_eq, ACMaterialDesignIconCode.md_hdr_off, ACMaterialDesignIconCode.md_hdr_strong, ACMaterialDesignIconCode.md_hdr_weak, ACMaterialDesignIconCode.md_hdr, ACMaterialDesignIconCode.md_iridescent, ACMaterialDesignIconCode.md_leak_off, ACMaterialDesignIconCode.md_leak, ACMaterialDesignIconCode.md_looks, ACMaterialDesignIconCode.md_loupe, ACMaterialDesignIconCode.md_panorama_horizontal, ACMaterialDesignIconCode.md_panorama_vertical, ACMaterialDesignIconCode.md_panorama_wide_angle, ACMaterialDesignIconCode.md_photo_size_select_large, ACMaterialDesignIconCode.md_photo_size_select_small, ACMaterialDesignIconCode.md_picture_in_picture, ACMaterialDesignIconCode.md_slideshow, ACMaterialDesignIconCode.md_texture, ACMaterialDesignIconCode.md_tonality, ACMaterialDesignIconCode.md_vignette, ACMaterialDesignIconCode.md_wb_auto, ACMaterialDesignIconCode.md_eject_alt, ACMaterialDesignIconCode.md_eject, ACMaterialDesignIconCode.md_equalizer, ACMaterialDesignIconCode.md_fast_forward, ACMaterialDesignIconCode.md_fast_rewind, ACMaterialDesignIconCode.md_forward_10, ACMaterialDesignIconCode.md_forward_30, ACMaterialDesignIconCode.md_forward_5, ACMaterialDesignIconCode.md_hearing, ACMaterialDesignIconCode.md_pause_circle_outline, ACMaterialDesignIconCode.md_pause_circle, ACMaterialDesignIconCode.md_pause, ACMaterialDesignIconCode.md_play_circle_outline, ACMaterialDesignIconCode.md_play_circle, ACMaterialDesignIconCode.md_play, ACMaterialDesignIconCode.md_playlist_audio, ACMaterialDesignIconCode.md_playlist_plus, ACMaterialDesignIconCode.md_repeat_one, ACMaterialDesignIconCode.md_repeat, ACMaterialDesignIconCode.md_replay_10, ACMaterialDesignIconCode.md_replay_30, ACMaterialDesignIconCode.md_replay_5, ACMaterialDesignIconCode.md_replay, ACMaterialDesignIconCode.md_shuffle, ACMaterialDesignIconCode.md_skip_next, ACMaterialDesignIconCode.md_skip_previous, ACMaterialDesignIconCode.md_stop, ACMaterialDesignIconCode.md_surround_sound, ACMaterialDesignIconCode.md_tune, ACMaterialDesignIconCode.md_volume_down, ACMaterialDesignIconCode.md_volume_mute, ACMaterialDesignIconCode.md_volume_off, ACMaterialDesignIconCode.md_volume_up, ACMaterialDesignIconCode.md_n_1_square, ACMaterialDesignIconCode.md_n_2_square, ACMaterialDesignIconCode.md_n_3_square, ACMaterialDesignIconCode.md_n_4_square, ACMaterialDesignIconCode.md_n_5_square, ACMaterialDesignIconCode.md_n_6_square, ACMaterialDesignIconCode.md_neg_1, ACMaterialDesignIconCode.md_neg_2, ACMaterialDesignIconCode.md_plus_1, ACMaterialDesignIconCode.md_plus_2, ACMaterialDesignIconCode.md_sec_10, ACMaterialDesignIconCode.md_sec_3, ACMaterialDesignIconCode.md_zero, ACMaterialDesignIconCode.md_airline_seat_flat_angled, ACMaterialDesignIconCode.md_airline_seat_flat, ACMaterialDesignIconCode.md_airline_seat_individual_suite, ACMaterialDesignIconCode.md_airline_seat_legroom_extra, ACMaterialDesignIconCode.md_airline_seat_legroom_normal, ACMaterialDesignIconCode.md_airline_seat_legroom_reduced, ACMaterialDesignIconCode.md_airline_seat_recline_extra, ACMaterialDesignIconCode.md_airline_seat_recline_normal, ACMaterialDesignIconCode.md_airplay, ACMaterialDesignIconCode.md_closed_caption, ACMaterialDesignIconCode.md_confirmation_number, ACMaterialDesignIconCode.md_developer_board, ACMaterialDesignIconCode.md_disc_full, ACMaterialDesignIconCode.md_explicit, ACMaterialDesignIconCode.md_flight_land, ACMaterialDesignIconCode.md_flight_takeoff, ACMaterialDesignIconCode.md_flip_to_back, ACMaterialDesignIconCode.md_flip_to_front, ACMaterialDesignIconCode.md_group_work, ACMaterialDesignIconCode.md_hd, ACMaterialDesignIconCode.md_hq, ACMaterialDesignIconCode.md_markunread_mailbox, ACMaterialDesignIconCode.md_memory, ACMaterialDesignIconCode.md_nfc, ACMaterialDesignIconCode.md_play_for_work, ACMaterialDesignIconCode.md_power_input, ACMaterialDesignIconCode.md_present_to_all, ACMaterialDesignIconCode.md_satellite, ACMaterialDesignIconCode.md_tap_and_play, ACMaterialDesignIconCode.md_vibration, ACMaterialDesignIconCode.md_voicemail] } }
mit
naoto0822/try-reactive-swift
TryRxSwift/TryRxSwift/Item.swift
1
775
// // Item.swift // TryRxSwift // // Created by naoto yamaguchi on 2016/04/11. // Copyright © 2016年 naoto yamaguchi. All rights reserved. // import UIKit public struct Item { // MARK: - Property public let id: String public let title: String public let url: String public let user: User // MARK: - Public init(dictionary: [String: AnyObject]) { self.id = dictionary["id"] as? String ?? "" self.title = dictionary["title"] as? String ?? "" self.url = dictionary["url"] as? String ?? "" if let userDictionary = dictionary["user"] as? [String: AnyObject] { self.user = User(dictionary: userDictionary) } else { self.user = User() } } }
mit
tobias/vertx-swift-eventbus
Package.swift
1
900
/** * Copyright Red Hat, Inc 2016 * * 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 PackageDescription let package = Package( name: "VertxEventBus", dependencies: [ .Package(url: "https://github.com/IBM-Swift/BlueSocket.git", majorVersion: 0, minor: 12), .Package(url: "https://github.com/IBM-Swift/SwiftyJSON.git", majorVersion: 16) ])
apache-2.0
Wakup/Wakup-iOS-SDK
Wakup/UIImageView+Fade.swift
1
787
// // UIImageView+Fade.swift // Wuakup // // Created by Guillermo Gutiérrez on 08/01/15. // Copyright (c) 2015 Yellow Pineapple. All rights reserved. // import Foundation import SDWebImage extension UIImageView { func setImageAnimated(url: URL!, completed: SDExternalCompletionBlock? = nil) { sd_setImage(with: url) { (image, error, cacheType, url) in if (cacheType == .none) { let animation = CATransition() animation.duration = 0.3 animation.type = CATransitionType.fade self.layer.add(animation, forKey: "image-load") } if let completeBlock = completed { completeBlock(image, error, cacheType, url) } } } }
mit
qxuewei/XWSwiftWB
XWSwiftWB/XWSwiftWB/Classes/Message/MessageTableVC.swift
1
443
// // MessageTableVC.swift // XWSwiftWB // // Created by 邱学伟 on 16/10/25. // Copyright © 2016年 邱学伟. All rights reserved. // import UIKit class MessageTableVC: BaseTableVC { override func viewDidLoad() { super.viewDidLoad() visitorView.setupVisitorViewInfo(iconName: "visitordiscover_image_message", tip: "登录后,别人评论你的微博,给你发消息,都会在这里收到通知") } }
apache-2.0
Octadero/TensorFlow
Sources/CAPI/Session.swift
1
20856
/* Copyright 2017 The Octadero Authors. All Rights Reserved. Created by Volodymyr Pavliukevych on 2017. Licensed under the GPL License, Version 3.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.gnu.org/licenses/gpl-3.0.txt 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 CTensorFlow import MemoryLayoutKit import Foundation import Proto /// Representation of devices in session public struct TF_Device { let name: String? let type: String? let memorySize: Int64 } /// API for driving Graph execution. /// Return a new execution session with the associated graph, or NULL on error. // /// *graph must be a valid graph (not deleted or nullptr). This function will /// prevent the graph from being deleted until TF_DeleteSession() is called. /// Does not take ownership of opts. public func newSession(graph: TF_Graph!, sessionOptions: TF_SessionOptions!) throws -> TF_Session! { let status = TF_NewStatus() defer { delete(status: status) } let session: TF_Session = TF_NewSession(graph, sessionOptions, status) if let status = status, let error = StatusError(tfStatus: status) { throw error } return session } /// This function creates a new TF_Session (which is created on success) using /// `session_options`, and then initializes state (restoring tensors and other /// assets) using `run_options`. // /// Any NULL and non-NULL value combinations for (`run_options, `meta_graph_def`) /// are valid. // /// - `export_dir` must be set to the path of the exported SavedModel. /// - `tags` must include the set of tags used to identify one MetaGraphDef in /// the SavedModel. /// - `graph` must be a graph newly allocated with TF_NewGraph(). // /// If successful, populates `graph` with the contents of the Graph and /// `meta_graph_def` with the MetaGraphDef of the loaded model. public func loadSessionFromSavedModel(sessionOptions: TF_SessionOptions, runOptions: Tensorflow_RunOptions?, exportPath: String, tags: [String], graph: TF_Graph, metaDataGraphDefInjection: (_ bufferPointer: UnsafeMutablePointer<TF_Buffer>?) throws ->Void) throws -> TF_Session { let status = TF_NewStatus() guard let exportDir = exportPath.cString(using: .utf8) else { throw CAPIError.canNotComputPointer(functionName: "for export dir")} var runOptionsBufferPointer: UnsafeMutablePointer<TF_Buffer>? = nil if let runOptions = runOptions { let data = try runOptions.serializedData() let buffer = newBuffer(from: data) runOptionsBufferPointer = buffer } let tagsCArray = try tags.cArray() defer { delete(status: status) } let metaGraphDef = TF_NewBuffer() let nullableSession = TF_LoadSessionFromSavedModel(sessionOptions, runOptionsBufferPointer, exportDir, tagsCArray.pointerList, Int32(tagsCArray.count), graph, metaGraphDef, status) if let status = status, let error = StatusError(tfStatus: status) { throw error } try metaDataGraphDefInjection(metaGraphDef) if runOptionsBufferPointer != nil { TF_DeleteBuffer(runOptionsBufferPointer) } TF_DeleteBuffer(metaGraphDef) guard let session = nullableSession else { throw CAPIError.cancelled(message: "Returned session is nil.")} return session } /// Close a session. // /// Contacts any other processes associated with the session, if applicable. /// May not be called after TF_DeleteSession(). public func close(session: TF_Session!) throws { let status = TF_NewStatus() defer { delete(status: status) } TF_CloseSession(session, status) if let status = status, let error = StatusError(tfStatus: status) { throw error } } /// Destroy a session object. // /// Even if error information is recorded in *status, this call discards all /// local resources associated with the session. The session may not be used /// during or after this call (and the session drops its reference to the /// corresponding graph). public func delete(session: TF_Session!, status: TF_Status!) { TF_DeleteSession(session, status) } /// Run the graph associated with the session starting with the supplied inputs /// (inputs[0,ninputs-1] with corresponding values in input_values[0,ninputs-1]). // /// Any NULL and non-NULL value combinations for (`run_options`, /// `run_metadata`) are valid. // /// - `run_options` may be NULL, in which case it will be ignored; or /// non-NULL, in which case it must point to a `TF_Buffer` containing the /// serialized representation of a `RunOptions` protocol buffer. /// - `run_metadata` may be NULL, in which case it will be ignored; or /// non-NULL, in which case it must point to an empty, freshly allocated /// `TF_Buffer` that may be updated to contain the serialized representation /// of a `RunMetadata` protocol buffer. // /// The caller retains ownership of `input_values` (which can be deleted using /// TF_DeleteTensor). The caller also retains ownership of `run_options` and/or /// `run_metadata` (when not NULL) and should manually call TF_DeleteBuffer on /// them. // /// On success, the tensors corresponding to outputs[0,noutputs-1] are placed in /// output_values[]. Ownership of the elements of output_values[] is transferred /// to the caller, which must eventually call TF_DeleteTensor on them. // /// On failure, output_values[] contains NULLs. public func run(session: TF_Session, runOptions: Tensorflow_RunOptions?, inputs: [TF_Output], inputsValues: [TF_Tensor?], outputs: [TF_Output], targetOperations: [TF_Operation?], metadata: UnsafeMutablePointer<TF_Buffer>?) throws -> [TF_Tensor] { var runOptionsBufferPointer: UnsafeMutablePointer<TF_Buffer>? = nil if let runOptions = runOptions { let data = try runOptions.serializedData() let buffer = newBuffer(from: data) runOptionsBufferPointer = buffer } guard inputsValues.count == inputs.count else { throw CAPIError.cancelled(message: "Incorrect number of inputs and thirs values") } let numberOfInputs = Int32(inputs.count) let numberOfOutputs = Int32(outputs.count) let numberOfTargets = Int32(targetOperations.count) let status = TF_NewStatus() /// Inputs let inputsPointer = inputs.withUnsafeBufferPointer {$0.baseAddress} let inputsValuesPointer = inputsValues.withUnsafeBufferPointer {$0.baseAddress} /// Outputs let outputsPointer = outputs.withUnsafeBufferPointer {$0.baseAddress} /// Targets let targetOperationsPointer = targetOperations.withUnsafeBufferPointer { $0.baseAddress } var outputsValuesPointer: UnsafeMutablePointer<TF_Tensor?>? if numberOfOutputs > 0 { outputsValuesPointer = UnsafeMutablePointer<TF_Tensor?>.allocate(capacity: Int(numberOfOutputs)) } else { outputsValuesPointer = UnsafeMutablePointer<TF_Tensor?>(bitPattern: 0) } defer { delete(status: status) outputsValuesPointer?.deallocate() if runOptionsBufferPointer != nil { TF_DeleteBuffer(runOptionsBufferPointer) } } TF_SessionRun(session, runOptionsBufferPointer, inputsPointer, inputsValuesPointer, numberOfInputs, outputsPointer, outputsValuesPointer, numberOfOutputs, targetOperationsPointer, numberOfTargets, metadata, status) if let status = status, let error = StatusError(tfStatus: status) { throw error } if numberOfOutputs > 0, let pointer = outputsValuesPointer { let result = UnsafeMutableBufferPointer<TF_Tensor?>(start: pointer, count: Int(numberOfOutputs)).compactMap{ $0 } return result } else { return [TF_Tensor]() } } /// RunOptions /// Input tensors /// Output tensors /// Target operations /// RunMetadata /// Output status /// Set up the graph with the intended feeds (inputs) and fetches (outputs) for a /// sequence of partial run calls. // /// On success, returns a handle that is used for subsequent PRun calls. The /// handle should be deleted with TF_DeletePRunHandle when it is no longer /// needed. // /// On failure, out_status contains a tensorflow::Status with an error /// message. /// NOTE: This is EXPERIMENTAL and subject to change. public func sessionPartialRunSetup(session: TF_Session, inputs: [TF_Output], outputs: [TF_Output], targetOperations: [TF_Operation?]) throws -> UnsafePointer<Int8> { let numberOfInputs = Int32(inputs.count) let numberOfOutputs = Int32(outputs.count) let numberOfTargets = Int32(targetOperations.count) let inputsPointer = inputs.withUnsafeBufferPointer {$0.baseAddress} let outputsPointer = outputs.withUnsafeBufferPointer {$0.baseAddress} let targetOperationsPointer = targetOperations.withUnsafeBufferPointer { $0.baseAddress } var handle = UnsafePointer<CChar>(bitPattern: 0) let status = TF_NewStatus() defer { delete(status: status) } TF_SessionPRunSetup(session, inputsPointer, numberOfInputs, outputsPointer, numberOfOutputs, targetOperationsPointer, numberOfTargets, &handle, status) if let status = status, let error = StatusError(tfStatus: status) { throw error } guard let result = handle else { throw CAPIError.cancelled(message: "Can't produce handle pointer at TF_SessionPRunSetup call.") } return result } /// Input names /// Output names /// Target operations /// Output handle /// Output status /// Continue to run the graph with additional feeds and fetches. The /// execution state is uniquely identified by the handle. /// NOTE: This is EXPERIMENTAL and subject to change. public func sessionPartialRun(session: TF_Session, handle: UnsafePointer<Int8>, inputs: [TF_Output], inputsValues: [TF_Tensor?], outputs: [TF_Output], targetOperations: [TF_Operation?]) throws -> [TF_Tensor] { guard inputsValues.count == inputs.count else { throw CAPIError.cancelled(message: "Incorrect number of inputs and thirs values") } let numberOfInputs = Int32(inputs.count) let numberOfOutputs = Int32(outputs.count) let numberOfTargets = Int32(targetOperations.count) let status = TF_NewStatus() defer { delete(status: status) } /// Inputs let inputsPointer = inputs.withUnsafeBufferPointer {$0.baseAddress} let inputsValuesPointer = inputsValues.withUnsafeBufferPointer {$0.baseAddress} /// Outputs let outputsPointer = outputs.withUnsafeBufferPointer {$0.baseAddress} /// Targets let targetOperationsPointer = targetOperations.withUnsafeBufferPointer { $0.baseAddress } var outputsValuesPointer: UnsafeMutablePointer<TF_Tensor?>? if numberOfOutputs > 0 { outputsValuesPointer = UnsafeMutablePointer<TF_Tensor?>.allocate(capacity: Int(numberOfOutputs)) } else { outputsValuesPointer = UnsafeMutablePointer<TF_Tensor?>(bitPattern: 0) } TF_SessionPRun(session, handle, inputsPointer, inputsValuesPointer, numberOfInputs, outputsPointer, outputsValuesPointer, numberOfOutputs, targetOperationsPointer, numberOfTargets, status) if let status = status, let error = StatusError(tfStatus: status) { throw error } if numberOfOutputs > 0, let pointer = outputsValuesPointer { let result = UnsafeMutableBufferPointer<TF_Tensor?>(start: pointer, count: Int(numberOfOutputs)).compactMap{ $0 } outputsValuesPointer?.deinitialize(count: Int(numberOfOutputs)) return result } else { return [TF_Tensor]() } } /// Input tensors /// Output tensors /// Target operations /// Output status /// Deletes a handle allocated by TF_SessionPRunSetup. /// Once called, no more calls to TF_SessionPRun should be made. public func deletePartialRun(handle: UnsafePointer<Int8>!) { return TF_DeletePRunHandle(handle) } /// The deprecated session API. Please switch to the above instead of /// TF_ExtendGraph(). This deprecated API can be removed at any time without /// notice. public func newDeprecatedSession(options: TF_SessionOptions!, status: TF_Status!) -> TF_DeprecatedSession! { return TF_NewDeprecatedSession(options, status) } public func closeDeprecated(session: TF_DeprecatedSession!, status: TF_Status!) { fatalError("\(#function): Not implemented.") } public func deleteDeprecated(session: TF_DeprecatedSession!, status: TF_Status!) { fatalError("\(#function): Not implemented.") } public func reset(options: TF_SessionOptions!, containers: UnsafeMutablePointer<UnsafePointer<Int8>?>!, containersNumber: Int32, status: TF_Status!) { fatalError("\(#function): Not implemented.") } /// Treat the bytes proto[0,proto_len-1] as a serialized GraphDef and /// add the nodes in that GraphDef to the graph for the session. // /// Prefer use of TF_Session and TF_GraphImportGraphDef over this. public func extendGraph(oPointer:OpaquePointer!, _ proto: UnsafeRawPointer!, _ proto_len: Int, status: TF_Status!) { fatalError("\(#function): Not implemented.") /* TF_Reset(const TF_SessionOptions* opt, const char** containers, int ncontainers, TF_Status* status); */ } /// See TF_SessionRun() above. public func run(session: TF_Session!, runOptions: Tensorflow_RunOptions?, inputNames: [String], inputs: [TF_Tensor?], outputNames: [String], targetOperationsNames: [String], metaDataGraphDefInjection: (_ bufferPointer: UnsafeMutablePointer<TF_Buffer>?) throws ->Void) throws -> [TF_Tensor] { var runOptionsBufferPointer: UnsafeMutablePointer<TF_Buffer>? = nil if let runOptions = runOptions { let data = try runOptions.serializedData() let buffer = newBuffer(from: data) runOptionsBufferPointer = buffer } let inputNamesCArray = try inputNames.cArray() let outputNamesCArray = try outputNames.cArray() let targetOperationsNamesCArray = try targetOperationsNames.cArray() let metaGraphDef = TF_NewBuffer() let status = TF_NewStatus() var inputs = inputs let inputsPointer = inputs.withUnsafeMutableBufferPointer { (pointer) -> UnsafeMutablePointer<TF_Tensor?>? in pointer.baseAddress } let numberOfOutputs = Int32(outputNames.count) var outputsValuesPointer: UnsafeMutablePointer<TF_Tensor?>? if numberOfOutputs > 0 { outputsValuesPointer = UnsafeMutablePointer<TF_Tensor?>.allocate(capacity: Int(numberOfOutputs)) } else { outputsValuesPointer = UnsafeMutablePointer<TF_Tensor?>(bitPattern: 0) } TF_Run(session, runOptionsBufferPointer, inputNamesCArray.pointerList, inputsPointer, Int32(inputs.count), outputNamesCArray.pointerList, outputsValuesPointer, numberOfOutputs, targetOperationsNamesCArray.pointerList, Int32(targetOperationsNames.count), metaGraphDef, status) try metaDataGraphDefInjection(metaGraphDef) if let status = status, let error = StatusError(tfStatus: status) { throw error } if runOptionsBufferPointer != nil { TF_DeleteBuffer(runOptionsBufferPointer) } TF_DeleteBuffer(metaGraphDef) delete(status: status) if numberOfOutputs > 0, let pointer = outputsValuesPointer { let result = UnsafeMutableBufferPointer<TF_Tensor?>(start: pointer, count: Int(numberOfOutputs)).compactMap{ $0 } pointer.deallocate() return result } else { return [TF_Tensor]() } } /// See TF_SessionPRunSetup() above. public func partialRunSetup(session:TF_Session, inputNames: [String], inputs: [TF_Output], outputs: [TF_Output], targetOperations: [TF_Operation]? = nil) throws -> UnsafePointer<Int8> { fatalError("Not ready") } /// See TF_SessionPRun above. public func partialRun(sessiong: TF_DeprecatedSession!, handle: UnsafePointer<Int8>!, inputNames: UnsafeMutablePointer<UnsafePointer<Int8>?>!, inputs: UnsafeMutablePointer<OpaquePointer?>!, inputsNumber: Int32, outputNames: UnsafeMutablePointer<UnsafePointer<Int8>?>!, outputs: UnsafeMutablePointer<OpaquePointer?>!, outputsNumber: Int32, targetOperationsNames: UnsafeMutablePointer<UnsafePointer<Int8>?>!, targetsNumber: Int32, status: TF_Status!) { TF_PRun(sessiong, handle, inputNames, inputs, inputsNumber, outputNames, outputs, outputsNumber, targetOperationsNames, targetsNumber, status) } /// TF_SessionOptions holds options that can be passed during session creation. /// Return a new options object. public func newSessionOptions() -> TF_SessionOptions! { return TF_NewSessionOptions() } /// Set the target in TF_SessionOptions.options. /// target can be empty, a single entry, or a comma separated list of entries. /// Each entry is in one of the following formats : /// "local" /// ip:port /// host:port public func set(target: UnsafePointer<Int8>!, for options: TF_SessionOptions!) { TF_SetTarget(options, target) } /// Set the config in TF_SessionOptions.options. /// config should be a serialized tensorflow.ConfigProto proto. /// If config was not parsed successfully as a ConfigProto, record the /// error information in *status. public func setConfig(options: TF_SessionOptions!, proto: UnsafeRawPointer!, protoLength: Int) throws { let status = TF_NewStatus() defer { delete(status: status) } TF_SetConfig(options, proto, protoLength, status) if let status = status, let error = StatusError(tfStatus: status) { throw error } } /// Destroy an options object. public func delete(sessionOptions: TF_SessionOptions!) { TF_DeleteSessionOptions(sessionOptions) } /// Lists all devices in a TF_Session. /// /// Caller takes ownership of the returned TF_DeviceList* which must eventually /// be freed with a call to TF_DeleteDeviceList. public func devices(`in` session: TF_Session) throws -> [TF_Device] { let status = TF_NewStatus() defer { delete(status: status) } let list = TF_SessionListDevices(session, status) if let status = status, let error = StatusError(tfStatus: status) { throw error } var devices = [TF_Device]() let count = TF_DeviceListCount(list) for index in 0..<count { guard let deviceName = String(utf8String: TF_DeviceListName(list, index, status)) else { if let status = status, let error = StatusError(tfStatus: status) { debugPrint("Error at getting device list: \(error).") } continue } guard let deviceType = String(utf8String: TF_DeviceListType(list, index, status)) else { if let status = status, let error = StatusError(tfStatus: status) { debugPrint("Error at getting device list: \(error).") } continue } let memorySize = TF_DeviceListMemoryBytes(list, index, status) if let status = status, let error = StatusError(tfStatus: status) { debugPrint("Error at getting device list: \(error).") continue } devices.append(TF_Device(name: deviceName, type: deviceType, memorySize: memorySize)) } TF_DeleteDeviceList(list) return devices }
gpl-3.0
cuappdev/podcast-ios
Recast/Core Data/Episode+CoreDataProperties.swift
1
1304
// // Episode+CoreDataProperties.swift // // // Created by Mindy Lou on 11/3/18. // // import Foundation import CoreData extension Episode { @nonobjc public class func fetchRequest() -> NSFetchRequest<Episode> { return NSFetchRequest<Episode>(entityName: "Episode") } @NSManaged public var author: String? @NSManaged public var categories: [String]? @NSManaged public var comments: String? @NSManaged public var content: String? @NSManaged public var descriptionText: String? @NSManaged public var guid: String? @NSManaged public var id: String? @NSManaged public var link: String? @NSManaged public var pubDate: NSDate? @NSManaged public var title: String? @NSManaged public var downloadInfo: DownloadInfo? @NSManaged public var enclosure: Enclosure? @NSManaged public var podcast: Podcast? @NSManaged public var source: ItemSource? @NSManaged public var iTunes: ITunesNamespace? enum Keys: String { case entityName = "Episode" case author, categories, comments, content, descriptionText, guid, id, link, pubDate, title case downloadInfo, enclosure, iTunes, podcast, source } func setValue(_ value: Any?, for key: Keys) { self.setValue(value, forKey: key.rawValue) } }
mit
xwu/swift
test/Generics/rdar83687967.swift
1
2090
// RUN: %target-typecheck-verify-swift // RUN: %target-swift-frontend -typecheck -debug-generic-signatures %s 2>&1 | %FileCheck %s // RUN: %target-swift-frontend -emit-ir %s public protocol P1 {} public protocol P2 { associatedtype A: P1 } public protocol P3 { associatedtype B: P2 associatedtype A where B.A == A } public struct G<A: P1>: P2 {} public func callee<T: P1>(_: T.Type) {} // CHECK: rdar83687967.(file).caller11@ // CHECK: Generic signature: <Child where Child : P3, Child.B == G<Child.A>> public func caller11<Child: P3>(_: Child) where Child.B == G<Child.A> { callee(Child.A.self) } // CHECK: rdar83687967.(file).caller12@ // CHECK: Generic signature: <Child where Child : P3, Child.B == G<Child.A>> public func caller12<Child: P3>(_: Child) // expected-note@-1 {{conformance constraint 'Child.A' : 'P1' implied here}} where Child.B == G<Child.A>, Child.A : P1 { // expected-warning@-1 {{redundant conformance constraint 'Child.A' : 'P1'}} // Make sure IRGen can evaluate the conformance access path // (Child : P3)(Self.B : P2)(Self.A : P1). callee(Child.A.self) } // CHECK: rdar83687967.(file).X1@ // CHECK: Requirement signature: <Self where Self.Child : P3, Self.Child.B == G<Self.Child.A>> public protocol X1 { associatedtype Child: P3 where Child.B == G<Child.A> } // CHECK: rdar83687967.(file).X2@ // CHECK: Requirement signature: <Self where Self.Child : P3, Self.Child.B == G<Self.Child.A>> public protocol X2 { associatedtype Child: P3 // expected-note@-1 {{conformance constraint 'Self.Child.A' : 'P1' implied here}} where Child.B == G<Child.A>, Child.A : P1 // expected-warning@-1 {{redundant conformance constraint 'Self.Child.A' : 'P1'}} } public func caller21<T : X1>(_: T) { // Make sure IRGen can evaluate the conformance access path // (T : X1)(Child : P3)(Self.B : P2)(Self.A : P1). callee(T.Child.A.self) } public func caller22<T : X2>(_: T) { // Make sure IRGen can evaluate the conformance access path // (T : X2)(Child : P3)(Self.B : P2)(Self.A : P1). callee(T.Child.A.self) }
apache-2.0
suifengqjn/swiftDemo
基本语法/1基础内容/11断言.playground/Contents.swift
1
603
//: Playground - noun: a place where people can play import UIKit //你可以使用全局函数 assert(_:_:) 函数来写断言。向 assert(_:_:) 函数传入一个结果为 true 或者 false 的表达式以及一条会在结果为 false 的时候显式的信息: let age = -3 assert(age >= 0, "A person's age cannot be less than zero") //在这个栗子当中,代码执行只要在 if age >= 0 评定为 true 时才会继续,就是说,如果 age 的值非负。如果 age 的值是负数,在上文的代码当中, age >= 0 评定为 false ,断言就会被触发,终止应用。
apache-2.0
Tomikes/eidolon
KioskTests/App/RAC/RACFunctionsTests.swift
7
4576
import Quick import Nimble @testable import Kiosk import ReactiveCocoa class RACFunctionsTests: QuickSpec { override func spec() { describe("email address check") { it("requires @") { let valid = stringIsEmailAddress("ashartsymail.com") as! Bool expect(valid) == false } it("requires name") { let valid = stringIsEmailAddress("@artsymail.com") as! Bool expect(valid) == false } it("requires domain") { let valid = stringIsEmailAddress("ash@.com") as! Bool expect(valid) == false } it("requires tld") { let valid = stringIsEmailAddress("ash@artsymail") as! Bool expect(valid) == false } it("validates good emails") { let valid = stringIsEmailAddress("ash@artsymail.com") as! Bool expect(valid) == true } } describe("presenting cents as dollars") { it("works with valid input") { let input = 1_000_00 let formattedDolars = centsToPresentableDollarsString(input) as! String expect(formattedDolars) == "$1,000" } it("returns the empty string on invalid input") { let input = "something not a number" let formattedDolars = centsToPresentableDollarsString(input) as! String expect(formattedDolars) == "" } } describe("zero length string check") { it("returns true for zero-length strings") { let valid = isZeroLengthString("") as! Bool expect(valid) == true } it("returns false for non zero-length strings") { let valid = isZeroLengthString("something else") as! Bool expect(valid) == false } it("returns false for non zero-length strings of spaces") { let valid = isZeroLengthString(" ") as! Bool expect(valid) == false } } describe("string length range check") { it("returns true when the string length is within the specified range") { let valid = isStringLengthIn(1..<5)(string: "hi") as! Bool expect(valid) == true } it("returns false when the string length is not within the specified range") { let valid = isStringLengthIn(3..<5)(string: "hi") as! Bool expect(valid) == false } } describe("string length check") { it("returns true when the string length is the specified length") { let valid = isStringOfLength(2)(string: "hi") as! Bool expect(valid) == true } it("returns false when the string length is not the specified length") { let valid = isStringOfLength(3)(string: "hi") as! Bool expect(valid) == false } } describe("string length minimum check") { it("returns true when the string length is the specified length") { let valid = isStringLengthAtLeast(2)(string: "hi") as! Bool expect(valid) == true } it("returns true when the string length is more than the specified length") { let valid = isStringLengthAtLeast(1)(string: "hi") as! Bool expect(valid) == true } it("returns false when the string length is less than the specified length") { let valid = isStringLengthAtLeast(3)(string: "hi") as! Bool expect(valid) == false } } describe("string length one of check") { it("returns true when the string length is one of the specified lengths") { let valid = isStringLengthOneOf([0,2])(string: "hi") as! Bool expect(valid) == true } it("returns false when the string length is not one of the specified lengths") { let valid = isStringLengthOneOf([0,1])(string: "hi") as! Bool expect(valid) == false } it("returns false when the string length is between the specified lengths") { let valid = isStringLengthOneOf([1,3])(string: "hi") as! Bool expect(valid) == false } } } }
mit
Bouke/HAP
Sources/HAP/Base/Predefined/Characteristics/Characteristic.SupportedDiagnosticsModes.swift
1
2101
import Foundation public extension AnyCharacteristic { static func supportedDiagnosticsModes( _ value: UInt32 = 0, permissions: [CharacteristicPermission] = [.read], description: String? = "Supported Diagnostics Modes", format: CharacteristicFormat? = .uint32, unit: CharacteristicUnit? = nil, maxLength: Int? = nil, maxValue: Double? = nil, minValue: Double? = nil, minStep: Double? = nil, validValues: [Double] = [], validValuesRange: Range<Double>? = nil ) -> AnyCharacteristic { AnyCharacteristic( PredefinedCharacteristic.supportedDiagnosticsModes( value, permissions: permissions, description: description, format: format, unit: unit, maxLength: maxLength, maxValue: maxValue, minValue: minValue, minStep: minStep, validValues: validValues, validValuesRange: validValuesRange) as Characteristic) } } public extension PredefinedCharacteristic { static func supportedDiagnosticsModes( _ value: UInt32 = 0, permissions: [CharacteristicPermission] = [.read], description: String? = "Supported Diagnostics Modes", format: CharacteristicFormat? = .uint32, unit: CharacteristicUnit? = nil, maxLength: Int? = nil, maxValue: Double? = nil, minValue: Double? = nil, minStep: Double? = nil, validValues: [Double] = [], validValuesRange: Range<Double>? = nil ) -> GenericCharacteristic<UInt32> { GenericCharacteristic<UInt32>( type: .supportedDiagnosticsModes, value: value, permissions: permissions, description: description, format: format, unit: unit, maxLength: maxLength, maxValue: maxValue, minValue: minValue, minStep: minStep, validValues: validValues, validValuesRange: validValuesRange) } }
mit