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
bingoogolapple/SwiftNote-PartOne
静态单元格-Storyboard/静态单元格-StoryboardTests/______StoryboardTests.swift
1
936
// // ______StoryboardTests.swift // 静态单元格-StoryboardTests // // Created by bingoogol on 14/9/25. // Copyright (c) 2014年 bingoogol. All rights reserved. // import UIKit import XCTest class ______StoryboardTests: 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. } } }
apache-2.0
mbrandonw/naturally-swift
naturally-swift/naturally-swift/Func.swift
1
1620
import Foundation /// Identity function func identity <A> (x: A) -> A { return x } /// Constant function func const <A, B> (x: A) -> B -> A { return {y in return x } } /// Function composition func • <A,B,C> (g: B -> C, f: A -> B) -> (A -> C) { return { g(f($0)) } } /// Function exponentiation infix operator ^ {associativity left} func ^ <A> (f: A -> A, n: Int) -> A -> A { if n <= 0 { return identity } return f • (f^(n-1)) } /// Pipe argument to the right func |> <A, B> (x: A, f: A -> B) -> B { return f(x) } /// Pipe function to the right func |> <A, B, C> (f: A -> B, g: B -> C) -> A -> C { return { g(f($0)) } } /// Pipe argument to the left func <| <A, B> (f: A -> B, x: A) -> B { return f(x) } /// Pipe function to the left func <| <A, B, C> (f: B -> C, g: A -> B) -> A -> C { return { f(g($0)) } } /// Currying two-argument function func curry <A, B, C> (f: (A, B) -> C) -> A -> B -> C { return {a in return {b in return f(a, b) } } } /// Currying three-argument function func curry <A, B, C, D> (f: (A, B, C) -> D) -> A -> B -> C -> D { return {a in return {b in return {c in return f(a, b, c) } } } } /// Uncurrying two-argument function func uncurry <A, B, C> (f: A -> B -> C) -> (A, B) -> C { return {a, b in return f(a)(b) } } /// Uncurrying three-argument function func uncurry <A, B, C, D> (f: A -> B -> C -> D) -> (A, B, C) -> D { return {a, b, c in return f(a)(b)(c) } } /// Flip arguments func flip <A, B, C> (f: (A, B) -> C) -> (B, A) -> C { return {b, a in return f(a, b) } }
mit
ScoutHarris/WordPress-iOS
WordPress/Classes/ViewRelated/Aztec/Renderers/SpecialTagAttachmentRenderer.swift
1
2987
import Foundation import UIKit import Aztec // MARK: - SpecialTagAttachmentRenderer. This render aims rendering WordPress specific tags. // final class SpecialTagAttachmentRenderer { /// Text Color /// var textColor = UIColor.gray } // MARK: - TextViewCommentsDelegate Methods // extension SpecialTagAttachmentRenderer: TextViewAttachmentImageProvider { func textView(_ textView: TextView, shouldRender attachment: NSTextAttachment) -> Bool { guard let commentAttachment = attachment as? CommentAttachment else { return false } return Tags.supported.contains(commentAttachment.text) } func textView(_ textView: TextView, imageFor attachment: NSTextAttachment, with size: CGSize) -> UIImage? { guard let attachment = attachment as? CommentAttachment else { return nil } UIGraphicsBeginImageContextWithOptions(size, false, 0) let label = attachment.text.uppercased() let attributes = [NSForegroundColorAttributeName: textColor] let colorMessage = NSAttributedString(string: label, attributes: attributes) let textRect = colorMessage.boundingRect(with: size, options: [.usesLineFragmentOrigin, .usesFontLeading], context: nil) let textPosition = CGPoint(x: ((size.width - textRect.width) * 0.5), y: ((size.height - textRect.height) * 0.5)) colorMessage.draw(in: CGRect(origin: textPosition , size: CGSize(width: size.width, height: textRect.size.height))) let path = UIBezierPath() let dashes = [ Constants.defaultDashCount, Constants.defaultDashCount ] path.setLineDash(dashes, count: dashes.count, phase: 0.0) path.lineWidth = Constants.defaultDashWidth let centerY = round(size.height * 0.5) path.move(to: CGPoint(x: 0, y: centerY)) path.addLine(to: CGPoint(x: ((size.width - textRect.width) * 0.5) - Constants.defaultDashWidth, y: centerY)) path.move(to: CGPoint(x:((size.width + textRect.width) * 0.5) + Constants.defaultDashWidth, y: centerY)) path.addLine(to: CGPoint(x: size.width, y: centerY)) textColor.setStroke() path.stroke() let result = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return result } func textView(_ textView: TextView, boundsFor attachment: NSTextAttachment, with lineFragment: CGRect) -> CGRect { let padding = textView.textContainer.lineFragmentPadding let width = lineFragment.width - padding * 2 return CGRect(origin: .zero, size: CGSize(width: width, height: Constants.defaultHeight)) } } // MARK: - Constants // extension SpecialTagAttachmentRenderer { struct Constants { static let defaultDashCount = CGFloat(8.0) static let defaultDashWidth = CGFloat(2.0) static let defaultHeight = CGFloat(44.0) } struct Tags { static let supported = ["more", "nextpage"] } }
gpl-2.0
MengQuietly/MQDouYuTV
MQDouYuTV/MQDouYuTV/Classes/Home/View/MQAmuseTopMenuView.swift
1
2859
// // MQAmuseTopMenuView.swift // MQDouYuTV // // Created by mengmeng on 17/1/17. // Copyright © 2017年 mengQuietly. All rights reserved. // import UIKit /// bgCell private let kAmuseTopMenuBGCellID = "kAmuseTopMenuBGCellID" class MQAmuseTopMenuView: UIView { var groupModelList: [MQAnchorGroupModel]? { didSet { amuseTopMenuBgCollectionView.reloadData() } } @IBOutlet weak var amuseTopMenuBgCollectionView: UICollectionView! @IBOutlet weak var amuseTopMenuPageControl: UIPageControl! override func awakeFromNib() { super.awakeFromNib() autoresizingMask = UIViewAutoresizing(rawValue: 0) amuseTopMenuBgCollectionView.register(UINib(nibName: "MQAmuseTopMenuCell", bundle: nil), forCellWithReuseIdentifier: kAmuseTopMenuBGCellID) } override func layoutSubviews() { super.layoutSubviews() let layout = amuseTopMenuBgCollectionView.collectionViewLayout as! UICollectionViewFlowLayout layout.scrollDirection = .horizontal layout.itemSize = amuseTopMenuBgCollectionView.bounds.size } } // MARK:-快速实现View extension MQAmuseTopMenuView { class func amuseTopMenuView() -> MQAmuseTopMenuView { return Bundle.main.loadNibNamed("MQAmuseTopMenuView", owner: nil, options: nil)?.first as! MQAmuseTopMenuView } } // MARK:- 实现代理 extension MQAmuseTopMenuView: UICollectionViewDataSource{ func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { if groupModelList == nil { return 0 } let pageNum = (groupModelList!.count - 1) / 8 + 1 print("count = \(groupModelList!.count)") amuseTopMenuPageControl.numberOfPages = pageNum return pageNum } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kAmuseTopMenuBGCellID, for: indexPath) as! MQAmuseTopMenuCell setupCellDataWithCell(cell: cell, indexPath: indexPath) return cell } // 设置cell 数据 private func setupCellDataWithCell(cell: MQAmuseTopMenuCell, indexPath: IndexPath) { let startIndex = indexPath.item * 8 var endIndex = (indexPath.item + 1) * 8 - 1 // 判断越界 if endIndex > groupModelList!.count - 1 { endIndex = groupModelList!.count - 1 } cell.anchorGroupModelList = Array(groupModelList![startIndex ... endIndex]) } } // MARK: - UICollectionViewDelegate extension MQAmuseTopMenuView:UICollectionViewDelegate { func scrollViewDidScroll(_ scrollView: UIScrollView) { amuseTopMenuPageControl.currentPage = Int(scrollView.contentOffset.x / scrollView.bounds.width) } }
mit
Antondomashnev/ADMozaicCollectionViewLayout
Pods/Nimble/Sources/Nimble/Utils/Stringers.swift
1
6908
import Foundation internal func identityAsString(_ value: Any?) -> String { let anyObject: AnyObject? #if os(Linux) anyObject = value as? AnyObject #else anyObject = value as AnyObject? #endif if let value = anyObject { return NSString(format: "<%p>", unsafeBitCast(value, to: Int.self)).description } else { return "nil" } } internal func arrayAsString<T>(_ items: [T], joiner: String = ", ") -> String { return items.reduce("") { accum, item in let prefix = (accum.isEmpty ? "" : joiner) return accum + prefix + "\(stringify(item))" } } /// A type with a customized test output text representation. /// /// This textual representation is produced when values will be /// printed in test runs, and may be useful when producing /// error messages in custom matchers. /// /// - SeeAlso: `CustomDebugStringConvertible` public protocol TestOutputStringConvertible { var testDescription: String { get } } extension Double: TestOutputStringConvertible { public var testDescription: String { return NSNumber(value: self).testDescription } } extension Float: TestOutputStringConvertible { public var testDescription: String { return NSNumber(value: self).testDescription } } extension NSNumber: TestOutputStringConvertible { // This is using `NSString(format:)` instead of // `String(format:)` because the latter somehow breaks // the travis CI build on linux. public var testDescription: String { let description = self.description if description.contains(".") { // Travis linux swiftpm build doesn't like casting String to NSString, // which is why this annoying nested initializer thing is here. // Maybe this will change in a future snapshot. let decimalPlaces = NSString(string: NSString(string: description) .components(separatedBy: ".")[1]) // SeeAlso: https://bugs.swift.org/browse/SR-1464 switch decimalPlaces.length { case 1: return NSString(format: "%0.1f", self.doubleValue).description case 2: return NSString(format: "%0.2f", self.doubleValue).description case 3: return NSString(format: "%0.3f", self.doubleValue).description default: return NSString(format: "%0.4f", self.doubleValue).description } } return self.description } } extension Array: TestOutputStringConvertible { public var testDescription: String { let list = self.map(Nimble.stringify).joined(separator: ", ") return "[\(list)]" } } extension AnySequence: TestOutputStringConvertible { public var testDescription: String { let generator = self.makeIterator() var strings = [String]() var value: AnySequence.Iterator.Element? repeat { value = generator.next() if let value = value { strings.append(stringify(value)) } } while value != nil let list = strings.joined(separator: ", ") return "[\(list)]" } } extension NSArray: TestOutputStringConvertible { public var testDescription: String { let list = Array(self).map(Nimble.stringify).joined(separator: ", ") return "(\(list))" } } extension NSIndexSet: TestOutputStringConvertible { public var testDescription: String { let list = Array(self).map(Nimble.stringify).joined(separator: ", ") return "(\(list))" } } extension String: TestOutputStringConvertible { public var testDescription: String { return self } } extension Data: TestOutputStringConvertible { public var testDescription: String { #if os(Linux) // swiftlint:disable:next todo // FIXME: Swift on Linux triggers a segfault when calling NSData's hash() (last checked on 03-11-16) return "Data<length=\(count)>" #else return "Data<hash=\((self as NSData).hash),length=\(count)>" #endif } } /// /// Returns a string appropriate for displaying in test output /// from the provided value. /// /// - parameter value: A value that will show up in a test's output. /// /// - returns: The string that is returned can be /// customized per type by conforming a type to the `TestOutputStringConvertible` /// protocol. When stringifying a non-`TestOutputStringConvertible` type, this /// function will return the value's debug description and then its /// normal description if available and in that order. Otherwise it /// will return the result of constructing a string from the value. /// /// - SeeAlso: `TestOutputStringConvertible` public func stringify<T>(_ value: T?) -> String { guard let value = value else { return "nil" } if let value = value as? TestOutputStringConvertible { return value.testDescription } if let value = value as? CustomDebugStringConvertible { return value.debugDescription } return String(describing: value) } #if os(macOS) || os(iOS) || os(tvOS) || os(watchOS) @objc public class NMBStringer: NSObject { @objc public class func stringify(_ obj: Any?) -> String { return Nimble.stringify(obj) } } #endif // MARK: Collection Type Stringers /// Attempts to generate a pretty type string for a given value. If the value is of a Objective-C /// collection type, or a subclass thereof, (e.g. `NSArray`, `NSDictionary`, etc.). /// This function will return the type name of the root class of the class cluster for better /// readability (e.g. `NSArray` instead of `__NSArrayI`). /// /// For values that don't have a type of an Objective-C collection, this function returns the /// default type description. /// /// - parameter value: A value that will be used to determine a type name. /// /// - returns: The name of the class cluster root class for Objective-C collection types, or the /// the `dynamicType` of the value for values of any other type. public func prettyCollectionType<T>(_ value: T) -> String { switch value { case is NSArray: return String(describing: NSArray.self) case is NSDictionary: return String(describing: NSDictionary.self) case is NSSet: return String(describing: NSSet.self) case is NSIndexSet: return String(describing: NSIndexSet.self) default: return String(describing: value) } } /// Returns the type name for a given collection type. This overload is used by Swift /// collection types. /// /// - parameter collection: A Swift `CollectionType` value. /// /// - returns: A string representing the `dynamicType` of the value. public func prettyCollectionType<T: Collection>(_ collection: T) -> String { return String(describing: type(of: collection)) }
mit
cnoon/swift-compiler-crashes
crashes-duplicates/14211-swift-sourcemanager-getmessage.swift
11
244
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing let NSObject { { init( = { struct S { var b = [ { x class A { class case ,
mit
wenluma/swift
test/Constraints/closures_swift4.swift
8
699
// RUN: %target-typecheck-verify-swift -swift-version 4 // rdar://problem/32432145 - compiler should emit fixit to remove "_ in" in closures if 0 parameters is expected func r32432145(_ a: () -> ()) {} r32432145 { _ in let _ = 42 } // expected-error@-1 {{contextual closure type '() -> ()' expects 0 arguments, but 1 was used in closure body}} {{13-17=}} r32432145 { _ in // expected-error@-1 {{contextual closure type '() -> ()' expects 0 arguments, but 1 was used in closure body}} {{13-17=}} print("answer is 42") } r32432145 { _,_ in // expected-error@-1 {{contextual closure type '() -> ()' expects 0 arguments, but 2 were used in closure body}} {{13-19=}} print("answer is 42") }
mit
Esri/arcgis-runtime-samples-ios
arcgis-ios-sdk-samples/Geometry/Buffer/BufferOptionsViewController.swift
1
2221
// Copyright 2018 Esri. // // 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 UIKit protocol BufferOptionsViewControllerDelegate: AnyObject { func bufferOptionsViewController(_ bufferOptionsViewController: BufferOptionsViewController, bufferDistanceChangedTo bufferDistance: Measurement<UnitLength>) } class BufferOptionsViewController: UITableViewController { @IBOutlet private weak var distanceSlider: UISlider? @IBOutlet private weak var distanceLabel: UILabel? weak var delegate: BufferOptionsViewControllerDelegate? private let measurementFormatter: MeasurementFormatter = { // use a measurement formatter so the value is automatically localized let formatter = MeasurementFormatter() // don't show decimal places formatter.numberFormatter.maximumFractionDigits = 0 return formatter }() var bufferDistance = Measurement(value: 0, unit: UnitLength.miles) { didSet { updateUIForBufferRadius() } } override func viewDidLoad() { super.viewDidLoad() updateUIForBufferRadius() } private func updateUIForBufferRadius() { // update the slider and label to match the buffer distance distanceSlider?.value = Float(bufferDistance.value) distanceLabel?.text = measurementFormatter.string(from: bufferDistance) } @IBAction func bufferSliderAction(_ sender: UISlider) { // update the buffer distance for the slider value bufferDistance.value = Double(sender.value) // notify the delegate with the new value delegate?.bufferOptionsViewController(self, bufferDistanceChangedTo: bufferDistance) } }
apache-2.0
NilStack/NilColorKit
NilColorKit/NilThemeKit.swift
1
6979
// // NilThemeKit.swift // NilThemeKit // // Created by Peng on 9/26/14. // Copyright (c) 2014 peng. All rights reserved. // import Foundation import UIKit let kDefaultNavigationBarFontSize: CGFloat = 22.0 let kDefaultTabBarFontSize: CGFloat = 14.0 class NilThemeKit { //MARK: Master Theme class func setupTheme(#primaryColor:UIColor, secondaryColor:UIColor, fontname:String, lightStatusBar:Bool) { if(lightStatusBar) { UIApplication.sharedApplication().setStatusBarStyle(UIStatusBarStyle.LightContent, animated: false) } customizeNavigationBar(barColor: primaryColor, textColor: secondaryColor, fontName: fontname, fontSize: kDefaultNavigationBarFontSize, buttonColor: secondaryColor) customizeNavigationBar(buttonColor: secondaryColor) customizeTabBar(barColor: primaryColor, textColor: secondaryColor, fontName: fontname, fontSize: kDefaultTabBarFontSize) customizeSwitch(switchOnColor: primaryColor) customizeSearchBar(barColor: primaryColor, buttonTintColor: secondaryColor) customizeActivityIndicator(color: primaryColor) customizeButton(buttonColor: primaryColor) customizeSegmentedControl(mainColor: primaryColor, secondaryColor: secondaryColor) customizeSlider(color: primaryColor) customizePageControl(mainColor: primaryColor) customizeToolbar(tintColor: primaryColor) } //MARK: UINavigationBar class func customizeNavigationBar(#barColor:UIColor, textColor:UIColor, buttonColor:UIColor) { UINavigationBar.appearance().barTintColor = barColor UINavigationBar.appearance().tintColor = buttonColor UINavigationBar.appearance().titleTextAttributes?.updateValue(textColor, forKey: NSForegroundColorAttributeName) } class func customizeNavigationBar(#barColor:UIColor, textColor:UIColor, fontName:String,fontSize:CGFloat, buttonColor:UIColor) { UINavigationBar.appearance().barTintColor = barColor UINavigationBar.appearance().tintColor = buttonColor let font: UIFont? = UIFont(name: fontName, size: fontSize) if((font) != nil) { let textAttr = [NSForegroundColorAttributeName: textColor, NSFontAttributeName: font!] UINavigationBar.appearance().titleTextAttributes = textAttr } } //MARK: UIBarButtonItem class func customizeNavigationBar(#buttonColor:UIColor) { UIBarButtonItem.appearance().tintColor = buttonColor } //MARK: UITabBar class func customizeTabBar(#barColor:UIColor, textColor:UIColor) { UITabBar.appearance().barTintColor = barColor UITabBar.appearance().tintColor = textColor } class func customizeTabBar(#barColor:UIColor, textColor:UIColor, fontName:String, fontSize:CGFloat) { UITabBar.appearance().barTintColor = barColor UITabBar.appearance().tintColor = textColor let font: UIFont? = UIFont(name: fontName, size: fontSize) if((font) != nil) { UITabBarItem.appearance().setTitleTextAttributes([NSFontAttributeName: font!], forState: UIControlState.Normal) } } //MARK: UIButton class func customizeButton(#buttonColor:UIColor) { UIButton.appearance().setTitleColor(buttonColor, forState: UIControlState.Normal) } //MARK: UISwitch class func customizeSwitch(#switchOnColor:UIColor) { UISwitch.appearance().onTintColor = switchOnColor } //MARK: UISearchBar class func customizeSearchBar(#barColor:UIColor, buttonTintColor:UIColor) { /* [[UISearchBar appearance] setBarTintColor:barColor]; [[UISearchBar appearance] setTintColor:barColor]; [[UIBarButtonItem appearanceWhenContainedIn:[UISearchBar class], nil] setTitleTextAttributes:@{NSForegroundColorAttributeName: buttonTintColor} forState:UIControlStateNormal]; */ UISearchBar.appearance().barTintColor = barColor UISearchBar.appearance().tintColor = barColor UIBarButtonItem.appearance().setTitleTextAttributes( [NSForegroundColorAttributeName:buttonTintColor], forState: UIControlState.Normal) } //MARK: UIActivityIndicator class func customizeActivityIndicator(#color:UIColor) { UIActivityIndicatorView.appearance().color = color } //MARK: UISegmentedControl class func customizeSegmentedControl(#mainColor:UIColor, secondaryColor:UIColor) { UISegmentedControl.appearance().tintColor = mainColor } //MARK: UISlider class func customizeSlider(#color:UIColor) { UISlider.appearance().minimumTrackTintColor = color } //MARK: UIToolbar class func customizeToolbar(#tintColor:UIColor) { UIToolbar.appearance().tintColor = tintColor } //MARK: UIPageControl class func customizePageControl(#mainColor:UIColor) { UIPageControl.appearance().pageIndicatorTintColor = UIColor.lightGrayColor() UIPageControl.appearance().currentPageIndicatorTintColor = mainColor UIPageControl.appearance().backgroundColor = UIColor.clearColor() } //MARK: Color utilities class func color( #r:CGFloat, g:CGFloat, b:CGFloat ) -> UIColor { let red: CGFloat = r / 255.0 let green: CGFloat = g / 255.0 let blue: CGFloat = b / 255.0 return UIColor(red: red, green: green, blue: blue, alpha: 1.0) } class func colorWithHexString(#hex: String) -> UIColor { var cString: String = hex.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()).uppercaseString // String should be 6 or 8 characters if (countElements(cString) < 6) { return UIColor.greenColor() } // strip 0X if it appears if cString.hasPrefix("0X") { cString = cString.substringFromIndex(advance(cString.startIndex, 2)) } if (countElements(cString) != 6) { return UIColor.grayColor() } var rString = cString.substringToIndex(advance(cString.startIndex, 2)) var gString = cString.substringFromIndex(advance(cString.startIndex, 2)).substringToIndex(advance(cString.startIndex, 4)) var bString = cString.substringFromIndex(advance(cString.startIndex, 4)).substringToIndex(advance(cString.startIndex, 6)) var r:CUnsignedInt = 0, g:CUnsignedInt = 0, b:CUnsignedInt = 0; NSScanner.scannerWithString(rString).scanHexInt(&r) NSScanner.scannerWithString(gString).scanHexInt(&g) NSScanner.scannerWithString(bString).scanHexInt(&b) return NilThemeKit.color(r:CGFloat(r), g:CGFloat(g), b:CGFloat(b) ) } }
mit
testpress/ios-app
ios-app/UI/TimeAnalyticsHeaderViewCell.swift
1
3786
// // TimeAnalyticsHeaderViewCell.swift // ios-app // // Copyright © 2017 Testpress. All rights reserved. // // 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 LUExpandableTableView import UIKit class TimeAnalyticsHeaderViewCell: LUExpandableTableViewSectionHeader { @IBOutlet weak var questionIndex: UILabel! @IBOutlet weak var yourTime: UILabel! @IBOutlet weak var averageTime: UILabel! @IBOutlet weak var bestTime: UILabel! var parentViewController: TimeAnalyticsTableViewController! var attemptItem: AttemptItem! var indexPath: IndexPath! func initCell(attemptItem: AttemptItem, parentViewController: TimeAnalyticsTableViewController) { self.attemptItem = attemptItem self.parentViewController = parentViewController questionIndex.text = String(attemptItem.index) yourTime.text = getFormattedValue(attemptItem.duration) bestTime.text = getFormattedValue(attemptItem.bestDuration) averageTime.text = getFormattedValue(attemptItem.averageDuration) let color = getColor(attemptItem) yourTime.textColor = color bestTime.textColor = color averageTime.textColor = color addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(onTapCell(_:)))) } @objc func onTapCell(_ sender: UITapGestureRecognizer) { let expanded = isExpanded delegate?.expandableSectionHeader(self, shouldExpandOrCollapseAtSection: section) if !expanded { parentViewController.tableView .scrollToRow(at: IndexPath(item: 0, section: section), at: .top, animated: false) } } func getColor(_ attemptItem: AttemptItem) -> UIColor { var color: String = Colors.GRAY_LIGHT_DARK if !(attemptItem.selectedAnswers.isEmpty) { color = Colors.MATERIAL_GREEN; // If question is attempted & any of the selected option is incorrect then set red color for attemptAnswer in (attemptItem.question?.answers)! { if attemptItem.selectedAnswers.contains(attemptAnswer.id) && !(attemptAnswer.isCorrect) { color = Colors.MATERIAL_RED } } } return Colors.getRGB(color) } func getFormattedValue(_ duration: Float?) -> String { guard let duration = duration else { return "-" } if duration > 60 { return String(format:"%.0f", duration / 60) + "m" } else if duration >= 1 { return String(format:"%.0f", duration) + "s" } return String(format:"%.2f", duration) + "s" } }
mit
idappthat/UTANow-iOS
Pods/Kingfisher/Kingfisher/KingfisherManager.swift
1
12796
// // KingfisherManager.swift // Kingfisher // // Created by Wei Wang on 15/4/6. // // Copyright (c) 2015 Wei Wang <onevcat@gmail.com> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit public typealias DownloadProgressBlock = ((receivedSize: Int64, totalSize: Int64) -> ()) public typealias CompletionHandler = ((image: UIImage?, error: NSError?, cacheType: CacheType, imageURL: NSURL?) -> ()) /// RetrieveImageTask represents a task of image retrieving process. /// It contains an async task of getting image from disk and from network. public class RetrieveImageTask { // If task is canceled before the download task started (which means the `downloadTask` is nil), // the download task should not begin. var cancelled: Bool = false var diskRetrieveTask: RetrieveImageDiskTask? var downloadTask: RetrieveImageDownloadTask? /** Cancel current task. If this task does not begin or already done, do nothing. */ public func cancel() { // From Xcode 7 beta 6, the `dispatch_block_cancel` will crash at runtime. // It fixed in Xcode 7.1. // See https://github.com/onevcat/Kingfisher/issues/99 for more. if let diskRetrieveTask = diskRetrieveTask { dispatch_block_cancel(diskRetrieveTask) } if let downloadTask = downloadTask { downloadTask.cancel() } cancelled = true } } /// Error domain of Kingfisher public let KingfisherErrorDomain = "com.onevcat.Kingfisher.Error" private let instance = KingfisherManager() /// Main manager class of Kingfisher. It connects Kingfisher downloader and cache. /// You can use this class to retrieve an image via a specified URL from web or cache. public class KingfisherManager { /// Options to control some downloader and cache behaviors. public typealias Options = (forceRefresh: Bool, lowPriority: Bool, cacheMemoryOnly: Bool, shouldDecode: Bool, queue: dispatch_queue_t!, scale: CGFloat) /// A preset option tuple with all value set to `false`. public static let OptionsNone: Options = { return (forceRefresh: false, lowPriority: false, cacheMemoryOnly: false, shouldDecode: false, queue: dispatch_get_main_queue(), scale: 1.0) }() /// The default set of options to be used by the manager to control some downloader and cache behaviors. public static var DefaultOptions: Options = OptionsNone /// Shared manager used by the extensions across Kingfisher. public class var sharedManager: KingfisherManager { return instance } /// Cache used by this manager public var cache: ImageCache /// Downloader used by this manager public var downloader: ImageDownloader /** Default init method - returns: A Kingfisher manager object with default cache and default downloader. */ public init() { cache = ImageCache.defaultCache downloader = ImageDownloader.defaultDownloader } /** Get an image with resource. If KingfisherOptions.None is used as `options`, Kingfisher will seek the image in memory and disk first. If not found, it will download the image at `resource.downloadURL` and cache it with `resource.cacheKey`. These default behaviors could be adjusted by passing different options. See `KingfisherOptions` for more. - parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`. - parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more. - parameter progressBlock: Called every time downloaded data changed. This could be used as a progress UI. - parameter completionHandler: Called when the whole retrieving process finished. - returns: A `RetrieveImageTask` task object. You can use this object to cancel the task. */ public func retrieveImageWithResource(resource: Resource, optionsInfo: KingfisherOptionsInfo?, progressBlock: DownloadProgressBlock?, completionHandler: CompletionHandler?) -> RetrieveImageTask { let task = RetrieveImageTask() // There is a bug in Swift compiler which prevents to write `let (options, targetCache) = parseOptionsInfo(optionsInfo)` // It will cause a compiler error. let parsedOptions = parseOptionsInfo(optionsInfo) let (options, targetCache, downloader) = (parsedOptions.0, parsedOptions.1, parsedOptions.2) if options.forceRefresh { downloadAndCacheImageWithURL(resource.downloadURL, forKey: resource.cacheKey, retrieveImageTask: task, progressBlock: progressBlock, completionHandler: completionHandler, options: options, targetCache: targetCache, downloader: downloader) } else { let diskTaskCompletionHandler: CompletionHandler = { (image, error, cacheType, imageURL) -> () in // Break retain cycle created inside diskTask closure below task.diskRetrieveTask = nil completionHandler?(image: image, error: error, cacheType: cacheType, imageURL: imageURL) } let diskTask = targetCache.retrieveImageForKey(resource.cacheKey, options: options, completionHandler: { (image, cacheType) -> () in if image != nil { diskTaskCompletionHandler(image: image, error: nil, cacheType:cacheType, imageURL: resource.downloadURL) } else { self.downloadAndCacheImageWithURL(resource.downloadURL, forKey: resource.cacheKey, retrieveImageTask: task, progressBlock: progressBlock, completionHandler: diskTaskCompletionHandler, options: options, targetCache: targetCache, downloader: downloader) } }) task.diskRetrieveTask = diskTask } return task } /** Get an image with `URL.absoluteString` as the key. If KingfisherOptions.None is used as `options`, Kingfisher will seek the image in memory and disk first. If not found, it will download the image at URL and cache it with `URL.absoluteString` value as its key. If you need to specify the key other than `URL.absoluteString`, please use resource version of this API with `resource.cacheKey` set to what you want. These default behaviors could be adjusted by passing different options. See `KingfisherOptions` for more. - parameter URL: The image URL. - parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more. - parameter progressBlock: Called every time downloaded data changed. This could be used as a progress UI. - parameter completionHandler: Called when the whole retrieving process finished. - returns: A `RetrieveImageTask` task object. You can use this object to cancel the task. */ public func retrieveImageWithURL(URL: NSURL, optionsInfo: KingfisherOptionsInfo?, progressBlock: DownloadProgressBlock?, completionHandler: CompletionHandler?) -> RetrieveImageTask { return retrieveImageWithResource(Resource(downloadURL: URL), optionsInfo: optionsInfo, progressBlock: progressBlock, completionHandler: completionHandler) } func downloadAndCacheImageWithURL(URL: NSURL, forKey key: String, retrieveImageTask: RetrieveImageTask, progressBlock: DownloadProgressBlock?, completionHandler: CompletionHandler?, options: Options, targetCache: ImageCache, downloader: ImageDownloader) { downloader.downloadImageWithURL(URL, retrieveImageTask: retrieveImageTask, options: options, progressBlock: { (receivedSize, totalSize) -> () in progressBlock?(receivedSize: receivedSize, totalSize: totalSize) }) { (image, error, imageURL, originalData) -> () in if let error = error where error.code == KingfisherError.NotModified.rawValue { // Not modified. Try to find the image from cache. // (The image should be in cache. It should be guaranteed by the framework users.) targetCache.retrieveImageForKey(key, options: options, completionHandler: { (cacheImage, cacheType) -> () in completionHandler?(image: cacheImage, error: nil, cacheType: cacheType, imageURL: URL) }) return } if let image = image, originalData = originalData { targetCache.storeImage(image, originalData: originalData, forKey: key, toDisk: !options.cacheMemoryOnly, completionHandler: nil) } completionHandler?(image: image, error: error, cacheType: .None, imageURL: URL) } } func parseOptionsInfo(optionsInfo: KingfisherOptionsInfo?) -> (Options, ImageCache, ImageDownloader) { var options = KingfisherManager.DefaultOptions var targetCache = self.cache var targetDownloader = self.downloader guard let optionsInfo = optionsInfo else { return (options, targetCache, targetDownloader) } if let optionsItem = optionsInfo.kf_findFirstMatch(.Options(.None)), case .Options(let optionsInOptionsInfo) = optionsItem { let queue = optionsInOptionsInfo.contains(KingfisherOptions.BackgroundCallback) ? dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0) : KingfisherManager.DefaultOptions.queue let scale = optionsInOptionsInfo.contains(KingfisherOptions.ScreenScale) ? UIScreen.mainScreen().scale : KingfisherManager.DefaultOptions.scale options = (forceRefresh: optionsInOptionsInfo.contains(KingfisherOptions.ForceRefresh), lowPriority: optionsInOptionsInfo.contains(KingfisherOptions.LowPriority), cacheMemoryOnly: optionsInOptionsInfo.contains(KingfisherOptions.CacheMemoryOnly), shouldDecode: optionsInOptionsInfo.contains(KingfisherOptions.BackgroundDecode), queue: queue, scale: scale) } if let optionsItem = optionsInfo.kf_findFirstMatch(.TargetCache(self.cache)), case .TargetCache(let cache) = optionsItem { targetCache = cache } if let optionsItem = optionsInfo.kf_findFirstMatch(.Downloader(self.downloader)), case .Downloader(let downloader) = optionsItem { targetDownloader = downloader } return (options, targetCache, targetDownloader) } } // MARK: - Deprecated public extension KingfisherManager { @available(*, deprecated=1.2, message="Use -retrieveImageWithURL:optionsInfo:progressBlock:completionHandler: instead.") public func retrieveImageWithURL(URL: NSURL, options: KingfisherOptions, progressBlock: DownloadProgressBlock?, completionHandler: CompletionHandler?) -> RetrieveImageTask { return retrieveImageWithURL(URL, optionsInfo: [.Options(options)], progressBlock: progressBlock, completionHandler: completionHandler) } }
mit
Boss-XP/ChatToolBar
BXPChatToolBar/BXPChatToolBar/Classes/BXPChat/BXPChatToolBar/BXPChatMoreOptions/BXPChatMoreOptionButton.swift
1
920
// // BXPChatMoreOptionButton.swift // BXPChatToolBar // // Created by 向攀 on 17/1/23. // Copyright © 2017年 Yunyun Network Technology Co,Ltd. All rights reserved. // import UIKit class BXPChatMoreOptionButton: UIButton { override func layoutSubviews() { super.layoutSubviews() let buttonWidth:CGFloat = self.frame.size.width let buttonHeight:CGFloat = self.frame.size.height let imageViewWH:CGFloat = 50 let imageViewX: CGFloat = (buttonWidth - imageViewWH) * 0.5 let imageViewY: CGFloat = (buttonHeight - imageViewWH) * 0.30; imageView?.frame = CGRect(x: imageViewX, y: imageViewY, width: imageViewWH, height: imageViewWH) let labelY: CGFloat = imageViewWH + imageViewY + (buttonHeight - imageViewWH) * 0.1; titleLabel?.frame = CGRect(x: 0, y: labelY, width: buttonWidth, height: buttonHeight - labelY) } }
apache-2.0
u10int/Kinetic
Pod/Classes/Tween.swift
1
9816
// // Tween.swift // Kinetic // // Created by Nicholas Shipes on 12/18/15. // Copyright © 2015 Urban10 Interactive, LLC. All rights reserved. // import UIKit public enum AnchorPoint { case `default` case center case top case topLeft case topRight case bottom case bottomLeft case bottomRight case left case right public func point() -> CGPoint { switch self { case .center: return CGPoint(x: 0.5, y: 0.5) case .top: return CGPoint(x: 0.5, y: 0) case .topLeft: return CGPoint(x: 0, y: 0) case .topRight: return CGPoint(x: 1, y: 0) case .bottom: return CGPoint(x: 0.5, y: 1) case .bottomLeft: return CGPoint(x: 0, y: 1) case .bottomRight: return CGPoint(x: 1, y: 1) case .left: return CGPoint(x: 0, y: 0.5) case .right: return CGPoint(x: 1, y: 0.5) default: return CGPoint(x: 0.5, y: 0.5) } } } public enum TweenMode { case to case from case fromTo } public class Tween: Animation { private(set) public var target: Tweenable public var antialiasing: Bool { get { if let view = target as? ViewType { return view.antialiasing } return false } set(newValue) { if var view = target as? ViewType { view.antialiasing = newValue } } } override public var totalTime: TimeInterval { return (elapsed - delay) } public weak var timeline: Timeline? internal var properties: [FromToValue] { return [FromToValue](propertiesByType.values) } fileprivate var propertiesByType: Dictionary<String, FromToValue> = [String: FromToValue]() private(set) var animators = [String: Animator]() fileprivate var needsPropertyPrep = false fileprivate var anchorPoint: CGPoint = AnchorPoint.center.point() public var additive = true; // MARK: Lifecycle required public init(target: Tweenable) { self.target = target super.init() self.on(.started) { [unowned self] (animation) in guard var view = self.target as? UIView else { return } view.anchorPoint = self.anchorPoint } TweenCache.session.cache(self, target: target) } deinit { propertiesByType.removeAll() } // MARK: Tween @discardableResult public func from(_ props: Property...) -> Tween { return from(props) } @discardableResult public func to(_ props: Property...) -> Tween { return to(props) } @discardableResult public func along(_ path: InterpolatablePath) -> Tween { add(Path(path), mode: .to) return self } // internal `from` and `to` methods that support a single array of Property types since we can't forward variadic arguments @discardableResult internal func from(_ props: [Property]) -> Tween { props.forEach { (prop) in add(prop, mode: .from) } return self } @discardableResult internal func to(_ props: [Property]) -> Tween { props.forEach { (prop) in add(prop, mode: .to) } return self } @discardableResult open func perspective(_ value: CGFloat) -> Tween { if var view = target as? ViewType { view.perspective = value } return self } @discardableResult open func anchor(_ anchor: AnchorPoint) -> Tween { return anchorPoint(anchor.point()) } @discardableResult open func anchorPoint(_ point: CGPoint) -> Tween { anchorPoint = point return self } // MARK: Animation override public var timingFunction: TimingFunction { didSet { animators.forEach { (_, animator) in animator.timingFunction = timingFunction } } } override public var spring: Spring? { didSet { animators.forEach { (_, animator) in animator.spring = spring } } } @discardableResult override public func delay(_ delay: CFTimeInterval) -> Tween { super.delay(delay) if timeline == nil { startTime = delay } return self } override public func kill() { super.kill() let keys = propertiesByType.map { return $0.key } TweenCache.session.removeActiveKeys(keys: keys, ofTarget: target) TweenCache.session.removeFromCache(self, target: target) } override public func play() { guard state != .running && state != .cancelled else { return } TweenCache.session.cache(self, target: target) animators.forEach { (_, animator) in animator.reset() } super.play() } // public func updateTo(options: [Property], restart: Bool = false) { // // } // MARK: Private Methods fileprivate func add(_ prop: Property, mode: TweenMode) { var value = propertiesByType[prop.key] ?? FromToValue() if mode == .from { value.from = prop // immediately set initial state for this property if var current = target.currentProperty(for: prop) { if value.to == nil { value.to = current } current.apply(prop) target.apply(current) } } else { value.to = prop } propertiesByType[prop.key] = value } // MARK: - Subscriber override func advance(_ time: Double) { guard shouldAdvance() else { return } if propertiesByType.count == 0 { return } // parent Animation class handles updating the elapsed and runningTimes accordingly super.advance(time) } override internal func canSubscribe() -> Bool { return timeline == nil } override internal func render(time: TimeInterval, advance: TimeInterval = 0) { elapsed = time setupAnimatorsIfNeeded() animators.forEach { (_, animator) in animator.render(time, advance: advance) } updated.trigger(self) } override internal func isAnimationComplete() -> Bool { var done = true // spring-based animators must determine if their animation has completed, not the animation duration animators.forEach { (_, animator) in if !animator.finished { done = false } } return done } fileprivate func setupAnimatorsIfNeeded() { var transformFrom: Transform? var transformTo: Transform? var transformKeys: [String] = [] var tweenedProps = [String: Property]() for (key, prop) in propertiesByType { var animator = animators[key] if animator == nil { // print("--------- tween.id: \(id) - animator key: \(key) ------------") var from: Property? var to: Property? let type = prop.to ?? prop.from // let additive = (prop.from == nil && !prop.isAutoTo) var isAdditive = self.additive // if we have any currently running animations for this same property, animation needs to be additive // but animation should not be additive if we have a `from` value if isAdditive { isAdditive = (prop.from != nil) ? false : TweenCache.session.hasActiveTween(forKey: key, ofTarget: target) } // there's no real presentation value when animating along a path, so disable additive if prop.from is Path || prop.to is Path { isAdditive = false self.additive = false } if let type = type, let value = target.currentProperty(for: type) { from = value to = value if let tweenFrom = prop.from { from?.apply(tweenFrom) } else if let previousTo = tweenedProps[key] { from = previousTo } else if prop.to != nil { let activeTweens = Scheduler.shared.activeTweenPropsForKey(key, ofTarget: target, excludingTween: self) if activeTweens.count > 0 { from = activeTweens.last?.to to = activeTweens.last?.to } } if let tweenTo = prop.to { to?.apply(tweenTo) } // need to update axes which are to be animated based on destination value if type is Rotation { if var _from = from as? Rotation, var _to = to as? Rotation, let tweenTo = prop.to as? Rotation { _to.applyAxes(tweenTo) _from.applyAxes(tweenTo) from = _from to = _to } } tweenedProps[key] = to } if let from = from, let to = to { // print("ANIMATION from: \(from), to: \(to)") // update stored from/to property that other tweens may reference propertiesByType[key] = FromToValue(from, to) TweenCache.session.addActiveKeys(keys: [key], toTarget: target) if let from = from as? TransformType, let to = to as? TransformType { if transformKeys.contains(key) == false { transformKeys.append(key) } if let view = target as? ViewType { if transformFrom == nil && transformTo == nil { transformFrom = Transform(view.transform3d) transformTo = Transform(view.transform3d) } transformFrom?.apply(from) transformTo?.apply(to) } } else { let tweenAnimator = Animator(from: from, to: to, duration: duration, timingFunction: timingFunction) tweenAnimator.additive = isAdditive tweenAnimator.spring = spring tweenAnimator.setPresentation({ (prop) -> Property? in return self.target.currentProperty(for: prop) }) tweenAnimator.onChange({ [unowned self] (animator, value) in if self.additive { // update running animator's `additive` property based on existance of other running animators for the same property animator.additive = TweenCache.session.hasActiveTween(forKey: animator.key, ofTarget: self.target) } self.target.apply(value) }) animator = tweenAnimator animators[key] = tweenAnimator } } else { print("Could not create animator for property \(prop)") } } } if let transformFrom = transformFrom, let transformTo = transformTo { if animators["transform"] == nil { let animator = Animator(from: transformFrom, to: transformTo, duration: duration, timingFunction: timingFunction) animator.spring = spring animator.additive = false animator.anchorPoint = anchorPoint animator.onChange({ [weak self] (animator, value) in self?.target.apply(value) }) animators["transform"] = animator transformKeys.forEach { animators[$0] = animator } } } } }
mit
jam891/Luna
Luna/LunarHeaderView.swift
1
2039
// // LunarHeaderView.swift // Luna // // Created by Andrew Shepard on 3/1/15. // Copyright (c) 2015 Andrew Shepard. All rights reserved. // import UIKit class LunarHeaderView: UIView { @IBOutlet var phaseView: LunarPhaseView! @IBOutlet var phaseNameLabel: UILabel! @IBOutlet var ageLabel: UILabel! @IBOutlet var illuminationLabel: UILabel! @IBOutlet var riseLabel: UILabel! @IBOutlet var setLabel: UILabel! class var nibName: String { return "LunarHeaderView" } var viewModel: LunarViewModel? { didSet { self.riseLabel.text = viewModel?.rise self.setLabel.text = viewModel?.set self.ageLabel.text = viewModel?.age self.illuminationLabel.text = viewModel?.illumination if let phase = viewModel?.phase { let font = UIFont(name: "EuphemiaUCAS", size: 38.0)! let color = UIColor.whiteColor() let attributes = [NSForegroundColorAttributeName: color, NSFontAttributeName: font] self.phaseNameLabel.attributedText = NSAttributedString(string: phase, attributes: attributes) } UIView.animateWithDuration(0.5, animations: { () -> Void in self.phaseView.alpha = 1.0 }) } } override func awakeFromNib() { super.awakeFromNib() self.phaseView.alpha = 0.0 self.phaseNameLabel.text = "Loading..." self.ageLabel.text = "" self.illuminationLabel.text = "" self.riseLabel.text = "" self.setLabel.text = "" self.phaseNameLabel.textColor = UIColor.whiteColor() self.ageLabel.textColor = UIColor.whiteColor() self.illuminationLabel.textColor = UIColor.whiteColor() self.riseLabel.textColor = UIColor.whiteColor() self.setLabel.textColor = UIColor.whiteColor() self.backgroundColor = UIColor.clearColor() } }
mit
austinzheng/swift
test/IDE/complete_where_clause.swift
11
7614
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=GP1 | %FileCheck %s -check-prefix=A1 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=GP2 | %FileCheck %s -check-prefix=A1 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=GP3 | %FileCheck %s -check-prefix=A1 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=GP4 | %FileCheck %s -check-prefix=TYPE1 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=GP5 | %FileCheck %s -check-prefix=TYPE1 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=GP6 | %FileCheck %s -check-prefix=A1 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FUNC_ASSOC_NODUP_1 | %FileCheck %s -check-prefix=GEN_T_ASSOC_E // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FUNC_ASSOC_NODUP_2 | %FileCheck %s -check-prefix=GEN_T_ASSOC_E // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FUNC_1 | %FileCheck %s -check-prefix=GEN_T // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FUNC_2 | %FileCheck %s -check-prefix=GEN_T_DOT // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FUNC_2_ASSOC | %FileCheck %s -check-prefix=GEN_T_ASSOC_DOT // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FUNC_3 | %FileCheck %s -check-prefix=GEN_T // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FUNC_4 | %FileCheck %s -check-prefix=GEN_T_DOT // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FUNC_5 | %FileCheck %s -check-prefix=GEN_T // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FUNC_6 | %FileCheck %s -check-prefix=GEN_T_DOT // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=SUBSCRIPT_1 | %FileCheck %s -check-prefix=GEN_T // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=SUBSCRIPT_2 | %FileCheck %s -check-prefix=GEN_T_DOT // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=INIT_1 | %FileCheck %s -check-prefix=GEN_T // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=INIT_2 | %FileCheck %s -check-prefix=GEN_T_DOT // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ALIAS_1 | %FileCheck %s -check-prefix=GEN_T // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ALIAS_2 | %FileCheck %s -check-prefix=GEN_T_DOT // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=STRUCT_1 | %FileCheck %s -check-prefix=GEN_T_NOMINAL // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=STRUCT_2 | %FileCheck %s -check-prefix=GEN_T_DOT // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=STRUCT_3 | %FileCheck %s -check-prefix=GEN_T_NOMINAL // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=STRUCT_4 | %FileCheck %s -check-prefix=GEN_T_DOT // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=CLASS_1 | %FileCheck %s -check-prefix=GEN_T_NOMINAL // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=CLASS_2 | %FileCheck %s -check-prefix=GEN_T_DOT // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ENUM_1 | %FileCheck %s -check-prefix=GEN_T_NOMINAL // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ENUM_2 | %FileCheck %s -check-prefix=GEN_T_DOT // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ASSOC_1 | %FileCheck %s -check-prefix=P2 // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ASSOC_2 | %FileCheck %s -check-prefix=U_DOT class A1<T1, T2, T3> {} class A2<T4, T5> {} protocol P1 {} extension A1 where #^GP1^#{} extension A1 where T1 : P1, #^GP2^# {} extension A1 where T1 : P1, #^GP3^# extension A1 where T1 : #^GP4^# extension A1 where T1 : P1, T2 : #^GP5^# extension A1 where T1.#^GP6^# {} // A1: Begin completions // A1-DAG: Decl[GenericTypeParam]/Local: T1[#T1#]; name=T1 // A1-DAG: Decl[GenericTypeParam]/Local: T2[#T2#]; name=T2 // A1-DAG: Decl[GenericTypeParam]/Local: T3[#T3#]; name=T3 // A1-NOT: T4 // A1-NOT: T5 // TYPE1: Begin completions // TYPE1-DAG: Decl[Protocol]/CurrModule: P1[#P1#]; name=P1 // TYPE1-DAG: Decl[Class]/CurrModule: A1[#A1#]; name=A1 // TYPE1-DAG: Decl[Class]/CurrModule: A2[#A2#]; name=A2 // TYPE1-NOT: T1 // TYPE1-NOT: T2 // TYPE1-NOT: T3 // TYPE1-NOT: T4 // TYPE1-NOT: T5 protocol A {associatedtype E} protocol B {associatedtype E} protocol C {associatedtype E} protocol D: C {associatedtype E} func ab<T: A & B>(_ arg: T) where T.#^FUNC_ASSOC_NODUP_1^# func ab<T: D>(_ arg: T) where T.#^FUNC_ASSOC_NODUP_2^# // GEN_T_ASSOC_E: Begin completions, 2 items // GEN_T_ASSOC_E-NEXT: Decl[AssociatedType]/{{Super|CurrNominal}}: E; name=E // GEN_T_ASSOC_E-NEXT: Keyword/None: Type[#T.Type#]; // GEN_T_ASSOC_E: End completions protocol Assoc { associatedtype Q } func f1<T>(_: T) where #^FUNC_1^# {} // GEN_T: Decl[GenericTypeParam]/Local: T[#T#]; name=T func f2<T>(_: T) where T.#^FUNC_2^# {} // GEN_T_DOT: Begin completions // GEN_T_DOT-DAG: Keyword/None: Type[#T.Type#]; // GEN_T_DOT-NOT: Keyword/CurrNominal: self[#T#]; // GEN_T_DOT: End completions func f2b<T: Assoc>(_: T) where T.#^FUNC_2_ASSOC^# {} // GEN_T_ASSOC_DOT: Begin completions // GEN_T_ASSOC_DOT-DAG: Decl[AssociatedType]/{{Super|CurrNominal}}: Q; // GEN_T_ASSOC_DOT-DAG: Keyword/None: Type[#T.Type#]; // GEN_T_ASSOC_DOT-NOT: Keyword/CurrNominal: self[#T#]; // GEN_T_ASSOC_DOT: End completions func f3<T>(_: T) where T == #^FUNC_3^# {} func f3<T>(_: T) where T == T.#^FUNC_4^# {} struct S1 { func f1<T>(_: T) where #^FUNC_5^# {} func f2<T>(_: T) where T.#^FUNC_6^# {} subscript<T>(x: T) -> T where #^SUBSCRIPT_1^# { return x } subscript<T>(x: T) -> T where T.#^SUBSCRIPT_2^# { return x } init<T>(_: T) where #^INIT_1^# {} init<T>(_: T) where T.#^INIT_2^# {} typealias TA1<T> = A1<T, T, T> where #^ALIAS_1^# typealias TA2<T> = A1<T, T, T> where T.#^ALIAS_2^# } struct S2<T> where #^STRUCT_1^# {} struct S3<T> where T.#^STRUCT_2^# {} struct S4<T> where T == #^STRUCT_3^# {} struct S5<T> where T == T.#^STRUCT_4^# {} class C1<T> where #^CLASS_1^# {} class C2<T> where T.#^CLASS_2^# {} enum E1<T> where #^ENUM_1^# {} enum E2<T> where T.#^ENUM_2^# {} // GEN_T_NOMINAL: Decl[GenericTypeParam]/Local: T[#T#]; name=T protocol P2 { associatedtype T where #^ASSOC_1^# associatedtype U: Assoc where U.#^ASSOC_2^# } // P2: Begin completions // P2-DAG: Decl[GenericTypeParam]/Local: Self[#Self#]; // P2-DAG: Decl[AssociatedType]/{{Super|CurrNominal}}: T; // P2-DAG: Decl[AssociatedType]/{{Super|CurrNominal}}: U; // P2: End completions // U_DOT: Begin completions // FIXME: Should complete Q from Assoc. // U_DOT-DAG: Keyword/None: Type[#Self.U.Type#]; // U_DOT: End completions
apache-2.0
luinily/hOme
hOme/Model/FlicButton.swift
1
5635
// // FlicButton.swift // hOme // // Created by Coldefy Yoann on 2016/03/08. // Copyright © 2016年 YoannColdefy. All rights reserved. // import Foundation import CloudKit class FlicButton: NSObject, SCLFlicButtonDelegate, Nameable, Button, CloudKitObject { private var _button: SCLFlicButton? private let _actionTypes: Set<ButtonActionType> = [ButtonActionType.press, ButtonActionType.doublePress, ButtonActionType.longPress] private var _actions = [ButtonActionType: CommandProtocol]() private var _flicName: String = "flic" private var _name: String = "flic" private var _identifier: UUID? private var _onPressedForUI: (() -> Void)? private var _currentCKRecordName: String? var button: SCLFlicButton? {return _button} init(button: SCLFlicButton?) { let newButton = button != nil _button = button _identifier = button?.buttonIdentifier if let button = button { _name = button.name _flicName = button.name _identifier = button.buttonIdentifier } super.init() _button?.delegate = self _button?.triggerBehavior = SCLFlicButtonTriggerBehavior.clickAndDoubleClickAndHold _button?.connect() if newButton { updateCloudKit() } } class func getButtonType() -> ButtonType { return .flic } func printButtonState() { var connectionState = "Unkown" if let button = _button { switch button.connectionState { case .connected: connectionState = "Connected" case .connecting: connectionState = "Connecting" case .disconnected: connectionState = "Disconnected" case .disconnecting: connectionState = "Disconnected" } } print(name + " buttonConnectionState: " + connectionState) } func reconnectButton() { print("reconnect flic " + name) button?.connect() } func getAvailableActionTypes() -> Set<ButtonActionType> { return _actionTypes } func flicButton(_ button: SCLFlicButton, didReceiveButtonClick queued: Bool, age: Int) { print("button " + _name + " click") _onPressedForUI?() _actions[.press]?.execute() } func flicButton(_ button: SCLFlicButton, didReceiveButtonDoubleClick queued: Bool, age: Int) { print("button " + _name + " double click") _onPressedForUI?() _actions[.doublePress]?.execute() } func flicButton(_ button: SCLFlicButton, didReceiveButtonHold queued: Bool, age: Int) { print("button " + _name + " long click") _onPressedForUI?() _actions[.longPress]?.execute() } func flicButton(_ button: SCLFlicButton, didDisconnectWithError error: Error?) { // var errorString = "" // if let error = error?.description { // errorString = error // } // print(name + " didDisconnectWithError: " + errorString) reconnectButton() } //MARK: - Nameable var name: String { get {return _name} set { _name = newValue updateCloudKit() } } private func nameSetter(_ name: String) { _name = name } var fullName: String {return _name} var internalName: String {return _flicName} //MARK: - Button func getButtonAction(actionType: ButtonActionType) -> CommandProtocol? { return _actions[actionType] } func setButtonAction(actionType: ButtonActionType, action: CommandProtocol?) { _actions[actionType] = action updateCloudKit() } func setOnPressForUI(onPress: (() -> Void)?) { _onPressedForUI = onPress } //MARK: - CloudKitObject convenience init (ckRecord: CKRecord, getCommandOfUniqueName: (_ uniqueName: String) -> CommandProtocol?, getButtonOfIdentifier: (_ identifier: UUID) -> SCLFlicButton?) throws { guard let name = ckRecord["name"] as? String else { throw CommandClassError.noDeviceNameInCKRecord } guard let flicName = ckRecord["flicName"] as? String else { throw CommandClassError.noDeviceNameInCKRecord } self.init(button: nil) _name = name _flicName = flicName if let pressAction = ckRecord["pressAction"] as? String { _actions[ButtonActionType.press] = getCommandOfUniqueName(pressAction) } if let doublePressAction = ckRecord["doublePressAction"] as? String { _actions[ButtonActionType.doublePress] = getCommandOfUniqueName(doublePressAction) } if let longPressAction = ckRecord["longPressAction"] as? String { _actions[ButtonActionType.longPress] = getCommandOfUniqueName(longPressAction) } if let identifier = ckRecord["identifier"] as? String { _identifier = UUID(uuidString: identifier) } _currentCKRecordName = ckRecord.recordID.recordName if let identifier = _identifier { _button = getButtonOfIdentifier(identifier) _button?.delegate = self _button?.triggerBehavior = SCLFlicButtonTriggerBehavior.clickAndDoubleClickAndHold _button?.connect() if _button != nil { print("Restored button " + _name) } } } func getNewCKRecordName () -> String { return "FlicButton:" + _flicName } func getCurrentCKRecordName() -> String? { return _currentCKRecordName } func setUpCKRecord(_ record: CKRecord) { record["type"] = FlicButton.getButtonType().rawValue as CKRecordValue? record["identifier"] = _identifier?.uuidString as CKRecordValue? var data = [String]() _actions.forEach { (actionType, command) in data.append(command.internalName) } record["name"] = _name as CKRecordValue? record["flicName"] = _flicName as CKRecordValue? record["pressAction"] = data[0] as CKRecordValue? record["doublePressAction"] = data[1] as CKRecordValue? record["longPressAction"] = data[2] as CKRecordValue? } func getCKRecordType() -> String { return "FlicButton" } func updateCloudKit() { CloudKitHelper.sharedHelper.export(self) _currentCKRecordName = getNewCKRecordName() } }
mit
tardieu/swift
validation-test/compiler_crashers_fixed/00023-getcallerdefaultarg.swift
65
615
// 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 // Test case submitted to project by https://github.com/practicalswift (practicalswift) // http://www.openradar.me/18041799 // https://gist.github.com/stigi/336a9851cd80fdef22ed func a(b: Int = 0) { } let c = a c()
apache-2.0
devxoul/URLNavigator
Tests/URLMatcherTests/URLConvertibleSpec.swift
1
4395
import Foundation import Nimble import Quick import URLMatcher final class URLConvertibleSpec: QuickSpec { override func spec() { describe("urlValue") { it("returns an URL instance") { let url = URL(string: "https://xoul.kr")! expect(url.urlValue) == url expect(url.absoluteString.urlValue) == url } it("returns an URL instance from unicode string") { let urlString = "https://xoul.kr/한글" expect(urlString.urlValue) == URL(string: "https://xoul.kr/%ED%95%9C%EA%B8%80")! } } describe("urlStringValue") { it("returns a URL string value") { let url = URL(string: "https://xoul.kr")! expect(url.urlStringValue) == url.absoluteString expect(url.absoluteString.urlStringValue) == url.absoluteString } } describe("queryParameters") { context("when there is no query string") { it("returns empty dictionary") { let url = "https://xoul.kr" expect(url.urlValue?.queryParameters) == [:] expect(url.urlStringValue.queryParameters) == [:] } } context("when there is an empty query string") { it("returns empty dictionary") { let url = "https://xoul.kr?" expect(url.urlValue?.queryParameters) == [:] expect(url.urlStringValue.queryParameters) == [:] } } context("when there is a query string") { let url = "https://xoul.kr?key=this%20is%20a%20value&greeting=hello+world!&int=12&int=34&url=https://foo/bar?hello=world" it("has proper keys") { expect(Set(url.urlValue!.queryParameters.keys)) == ["key", "greeting", "int", "url"] expect(Set(url.urlStringValue.queryParameters.keys)) == ["key", "greeting", "int", "url"] } it("decodes a percent encoding") { expect(url.urlValue?.queryParameters["key"]) == "this is a value" expect(url.urlStringValue.queryParameters["key"]) == "this is a value" } it("doesn't convert + to whitespace") { expect(url.urlValue?.queryParameters["greeting"]) == "hello+world!" expect(url.urlStringValue.queryParameters["greeting"]) == "hello+world!" } it("takes last value from duplicated keys") { expect(url.urlValue?.queryParameters["int"]) == "34" expect(url.urlStringValue.queryParameters["int"]) == "34" } it("has an url") { expect(url.urlValue?.queryParameters["url"]) == "https://foo/bar?hello=world" } } } describe("queryItems") { context("when there is no query string") { it("returns nil") { let url = "https://xoul.kr" expect(url.urlValue?.queryItems).to(beNil()) expect(url.urlStringValue.queryItems).to(beNil()) } } context("when there is an empty query string") { it("returns an empty array") { let url = "https://xoul.kr?" expect(url.urlValue?.queryItems) == [] expect(url.urlStringValue.queryItems) == [] } } context("when there is a query string") { let url = "https://xoul.kr?key=this%20is%20a%20value&greeting=hello+world!&int=12&int=34" it("has exact number of items") { expect(url.urlValue?.queryItems?.count) == 4 expect(url.urlStringValue.queryItems?.count) == 4 } it("decodes a percent encoding") { expect(url.urlValue?.queryItems?[0]) == URLQueryItem(name: "key", value: "this is a value") expect(url.urlStringValue.queryItems?[0]) == URLQueryItem(name: "key", value: "this is a value") } it("doesn't convert + to whitespace") { expect(url.urlValue?.queryItems?[1]) == URLQueryItem(name: "greeting", value: "hello+world!") expect(url.urlStringValue.queryItems?[1]) == URLQueryItem(name: "greeting", value: "hello+world!") } it("takes all duplicated keys") { expect(url.urlValue?.queryItems?[2]) == URLQueryItem(name: "int", value: "12") expect(url.urlValue?.queryItems?[3]) == URLQueryItem(name: "int", value: "34") expect(url.urlStringValue.queryItems?[2]) == URLQueryItem(name: "int", value: "12") expect(url.urlStringValue.queryItems?[3]) == URLQueryItem(name: "int", value: "34") } } } } }
mit
tikidunpon/SwiftMoji
Example/SwiftMoji/AppDelegate.swift
1
2156
// // AppDelegate.swift // SwiftMoji // // Created by koichi on 04/14/2016. // Copyright (c) 2016 koichi. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? private 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
NordicSemiconductor/IOS-Pods-DFU-Library
Example/Pods/ZIPFoundation/Sources/ZIPFoundation/Archive+Writing.swift
1
22257
// // Archive+Writing.swift // ZIPFoundation // // Copyright © 2017-2020 Thomas Zoechling, https://www.peakstep.com and the ZIP Foundation project authors. // Released under the MIT License. // // See https://github.com/weichsel/ZIPFoundation/blob/master/LICENSE for license information. // import Foundation extension Archive { private enum ModifyOperation: Int { case remove = -1 case add = 1 } /// Write files, directories or symlinks to the receiver. /// /// - Parameters: /// - path: The path that is used to identify an `Entry` within the `Archive` file. /// - baseURL: The base URL of the `Entry` to add. /// The `baseURL` combined with `path` must form a fully qualified file URL. /// - compressionMethod: Indicates the `CompressionMethod` that should be applied to `Entry`. /// By default, no compression will be applied. /// - bufferSize: The maximum size of the write buffer and the compression buffer (if needed). /// - progress: A progress object that can be used to track or cancel the add operation. /// - Throws: An error if the source file cannot be read or the receiver is not writable. public func addEntry(with path: String, relativeTo baseURL: URL, compressionMethod: CompressionMethod = .none, bufferSize: UInt32 = defaultWriteChunkSize, progress: Progress? = nil) throws { let fileManager = FileManager() let entryURL = baseURL.appendingPathComponent(path) guard fileManager.itemExists(at: entryURL) else { throw CocoaError(.fileReadNoSuchFile, userInfo: [NSFilePathErrorKey: entryURL.path]) } let type = try FileManager.typeForItem(at: entryURL) // symlinks do not need to be readable guard type == .symlink || fileManager.isReadableFile(atPath: entryURL.path) else { throw CocoaError(.fileReadNoPermission, userInfo: [NSFilePathErrorKey: url.path]) } let modDate = try FileManager.fileModificationDateTimeForItem(at: entryURL) let uncompressedSize = type == .directory ? 0 : try FileManager.fileSizeForItem(at: entryURL) let permissions = try FileManager.permissionsForItem(at: entryURL) var provider: Provider switch type { case .file: let entryFileSystemRepresentation = fileManager.fileSystemRepresentation(withPath: entryURL.path) guard let entryFile: UnsafeMutablePointer<FILE> = fopen(entryFileSystemRepresentation, "rb") else { throw CocoaError(.fileNoSuchFile) } defer { fclose(entryFile) } provider = { _, _ in return try Data.readChunk(of: Int(bufferSize), from: entryFile) } try self.addEntry(with: path, type: type, uncompressedSize: uncompressedSize, modificationDate: modDate, permissions: permissions, compressionMethod: compressionMethod, bufferSize: bufferSize, progress: progress, provider: provider) case .directory: provider = { _, _ in return Data() } try self.addEntry(with: path.hasSuffix("/") ? path : path + "/", type: type, uncompressedSize: uncompressedSize, modificationDate: modDate, permissions: permissions, compressionMethod: compressionMethod, bufferSize: bufferSize, progress: progress, provider: provider) case .symlink: provider = { _, _ -> Data in let linkDestination = try fileManager.destinationOfSymbolicLink(atPath: entryURL.path) let linkFileSystemRepresentation = fileManager.fileSystemRepresentation(withPath: linkDestination) let linkLength = Int(strlen(linkFileSystemRepresentation)) let linkBuffer = UnsafeBufferPointer(start: linkFileSystemRepresentation, count: linkLength) return Data(buffer: linkBuffer) } try self.addEntry(with: path, type: type, uncompressedSize: uncompressedSize, modificationDate: modDate, permissions: permissions, compressionMethod: compressionMethod, bufferSize: bufferSize, progress: progress, provider: provider) } } /// Write files, directories or symlinks to the receiver. /// /// - Parameters: /// - path: The path that is used to identify an `Entry` within the `Archive` file. /// - type: Indicates the `Entry.EntryType` of the added content. /// - uncompressedSize: The uncompressed size of the data that is going to be added with `provider`. /// - modificationDate: A `Date` describing the file modification date of the `Entry`. /// Default is the current `Date`. /// - permissions: POSIX file permissions for the `Entry`. /// Default is `0`o`644` for files and symlinks and `0`o`755` for directories. /// - compressionMethod: Indicates the `CompressionMethod` that should be applied to `Entry`. /// By default, no compression will be applied. /// - bufferSize: The maximum size of the write buffer and the compression buffer (if needed). /// - progress: A progress object that can be used to track or cancel the add operation. /// - provider: A closure that accepts a position and a chunk size. Returns a `Data` chunk. /// - Throws: An error if the source data is invalid or the receiver is not writable. public func addEntry(with path: String, type: Entry.EntryType, uncompressedSize: UInt32, modificationDate: Date = Date(), permissions: UInt16? = nil, compressionMethod: CompressionMethod = .none, bufferSize: UInt32 = defaultWriteChunkSize, progress: Progress? = nil, provider: Provider) throws { guard self.accessMode != .read else { throw ArchiveError.unwritableArchive } progress?.totalUnitCount = type == .directory ? defaultDirectoryUnitCount : Int64(uncompressedSize) var endOfCentralDirRecord = self.endOfCentralDirectoryRecord var startOfCD = Int(endOfCentralDirRecord.offsetToStartOfCentralDirectory) var existingCentralDirData = Data() fseek(self.archiveFile, startOfCD, SEEK_SET) existingCentralDirData = try Data.readChunk(of: Int(endOfCentralDirRecord.sizeOfCentralDirectory), from: self.archiveFile) fseek(self.archiveFile, startOfCD, SEEK_SET) let localFileHeaderStart = ftell(self.archiveFile) let modDateTime = modificationDate.fileModificationDateTime defer { fflush(self.archiveFile) } do { var localFileHeader = try self.writeLocalFileHeader(path: path, compressionMethod: compressionMethod, size: (uncompressedSize, 0), checksum: 0, modificationDateTime: modDateTime) let (written, checksum) = try self.writeEntry(localFileHeader: localFileHeader, type: type, compressionMethod: compressionMethod, bufferSize: bufferSize, progress: progress, provider: provider) startOfCD = ftell(self.archiveFile) fseek(self.archiveFile, localFileHeaderStart, SEEK_SET) // Write the local file header a second time. Now with compressedSize (if applicable) and a valid checksum. localFileHeader = try self.writeLocalFileHeader(path: path, compressionMethod: compressionMethod, size: (uncompressedSize, written), checksum: checksum, modificationDateTime: modDateTime) fseek(self.archiveFile, startOfCD, SEEK_SET) _ = try Data.write(chunk: existingCentralDirData, to: self.archiveFile) let permissions = permissions ?? (type == .directory ? defaultDirectoryPermissions :defaultFilePermissions) let externalAttributes = FileManager.externalFileAttributesForEntry(of: type, permissions: permissions) let offset = UInt32(localFileHeaderStart) let centralDir = try self.writeCentralDirectoryStructure(localFileHeader: localFileHeader, relativeOffset: offset, externalFileAttributes: externalAttributes) if startOfCD > UINT32_MAX { throw ArchiveError.invalidStartOfCentralDirectoryOffset } endOfCentralDirRecord = try self.writeEndOfCentralDirectory(centralDirectoryStructure: centralDir, startOfCentralDirectory: UInt32(startOfCD), operation: .add) self.endOfCentralDirectoryRecord = endOfCentralDirRecord } catch ArchiveError.cancelledOperation { try rollback(localFileHeaderStart, existingCentralDirData, endOfCentralDirRecord) throw ArchiveError.cancelledOperation } } /// Remove a ZIP `Entry` from the receiver. /// /// - Parameters: /// - entry: The `Entry` to remove. /// - bufferSize: The maximum size for the read and write buffers used during removal. /// - progress: A progress object that can be used to track or cancel the remove operation. /// - Throws: An error if the `Entry` is malformed or the receiver is not writable. public func remove(_ entry: Entry, bufferSize: UInt32 = defaultReadChunkSize, progress: Progress? = nil) throws { let manager = FileManager() let tempDir = self.uniqueTemporaryDirectoryURL() defer { try? manager.removeItem(at: tempDir) } let uniqueString = ProcessInfo.processInfo.globallyUniqueString let tempArchiveURL = tempDir.appendingPathComponent(uniqueString) do { try manager.createParentDirectoryStructure(for: tempArchiveURL) } catch { throw ArchiveError.unwritableArchive } guard let tempArchive = Archive(url: tempArchiveURL, accessMode: .create) else { throw ArchiveError.unwritableArchive } progress?.totalUnitCount = self.totalUnitCountForRemoving(entry) var centralDirectoryData = Data() var offset = 0 for currentEntry in self { let centralDirectoryStructure = currentEntry.centralDirectoryStructure if currentEntry != entry { let entryStart = Int(currentEntry.centralDirectoryStructure.relativeOffsetOfLocalHeader) fseek(self.archiveFile, entryStart, SEEK_SET) let provider: Provider = { (_, chunkSize) -> Data in return try Data.readChunk(of: Int(chunkSize), from: self.archiveFile) } let consumer: Consumer = { if progress?.isCancelled == true { throw ArchiveError.cancelledOperation } _ = try Data.write(chunk: $0, to: tempArchive.archiveFile) progress?.completedUnitCount += Int64($0.count) } _ = try Data.consumePart(of: Int(currentEntry.localSize), chunkSize: Int(bufferSize), provider: provider, consumer: consumer) let centralDir = CentralDirectoryStructure(centralDirectoryStructure: centralDirectoryStructure, offset: UInt32(offset)) centralDirectoryData.append(centralDir.data) } else { offset = currentEntry.localSize } } let startOfCentralDirectory = ftell(tempArchive.archiveFile) _ = try Data.write(chunk: centralDirectoryData, to: tempArchive.archiveFile) tempArchive.endOfCentralDirectoryRecord = self.endOfCentralDirectoryRecord let endOfCentralDirectoryRecord = try tempArchive.writeEndOfCentralDirectory(centralDirectoryStructure: entry.centralDirectoryStructure, startOfCentralDirectory: UInt32(startOfCentralDirectory), operation: .remove) tempArchive.endOfCentralDirectoryRecord = endOfCentralDirectoryRecord self.endOfCentralDirectoryRecord = endOfCentralDirectoryRecord fflush(tempArchive.archiveFile) try self.replaceCurrentArchiveWithArchive(at: tempArchive.url) } // MARK: - Helpers func uniqueTemporaryDirectoryURL() -> URL { #if swift(>=5.0) || os(macOS) || os(iOS) || os(watchOS) || os(tvOS) if let tempDir = try? FileManager().url(for: .itemReplacementDirectory, in: .userDomainMask, appropriateFor: self.url, create: true) { return tempDir } #endif return URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent( ProcessInfo.processInfo.globallyUniqueString) } func replaceCurrentArchiveWithArchive(at URL: URL) throws { fclose(self.archiveFile) let fileManager = FileManager() #if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) do { _ = try fileManager.replaceItemAt(self.url, withItemAt: URL) } catch { _ = try fileManager.removeItem(at: self.url) _ = try fileManager.moveItem(at: URL, to: self.url) } #else _ = try fileManager.removeItem(at: self.url) _ = try fileManager.moveItem(at: URL, to: self.url) #endif let fileSystemRepresentation = fileManager.fileSystemRepresentation(withPath: self.url.path) self.archiveFile = fopen(fileSystemRepresentation, "rb+") } private func writeLocalFileHeader(path: String, compressionMethod: CompressionMethod, size: (uncompressed: UInt32, compressed: UInt32), checksum: CRC32, modificationDateTime: (UInt16, UInt16)) throws -> LocalFileHeader { // We always set Bit 11 in generalPurposeBitFlag, which indicates an UTF-8 encoded path. guard let fileNameData = path.data(using: .utf8) else { throw ArchiveError.invalidEntryPath } let localFileHeader = LocalFileHeader(versionNeededToExtract: UInt16(20), generalPurposeBitFlag: UInt16(2048), compressionMethod: compressionMethod.rawValue, lastModFileTime: modificationDateTime.1, lastModFileDate: modificationDateTime.0, crc32: checksum, compressedSize: size.compressed, uncompressedSize: size.uncompressed, fileNameLength: UInt16(fileNameData.count), extraFieldLength: UInt16(0), fileNameData: fileNameData, extraFieldData: Data()) _ = try Data.write(chunk: localFileHeader.data, to: self.archiveFile) return localFileHeader } private func writeEntry(localFileHeader: LocalFileHeader, type: Entry.EntryType, compressionMethod: CompressionMethod, bufferSize: UInt32, progress: Progress? = nil, provider: Provider) throws -> (sizeWritten: UInt32, crc32: CRC32) { var checksum = CRC32(0) var sizeWritten = UInt32(0) switch type { case .file: switch compressionMethod { case .none: (sizeWritten, checksum) = try self.writeUncompressed(size: localFileHeader.uncompressedSize, bufferSize: bufferSize, progress: progress, provider: provider) case .deflate: (sizeWritten, checksum) = try self.writeCompressed(size: localFileHeader.uncompressedSize, bufferSize: bufferSize, progress: progress, provider: provider) } case .directory: _ = try provider(0, 0) if let progress = progress { progress.completedUnitCount = progress.totalUnitCount } case .symlink: (sizeWritten, checksum) = try self.writeSymbolicLink(size: localFileHeader.uncompressedSize, provider: provider) if let progress = progress { progress.completedUnitCount = progress.totalUnitCount } } return (sizeWritten, checksum) } private func writeUncompressed(size: UInt32, bufferSize: UInt32, progress: Progress? = nil, provider: Provider) throws -> (sizeWritten: UInt32, checksum: CRC32) { var position = 0 var sizeWritten = 0 var checksum = CRC32(0) while position < size { if progress?.isCancelled == true { throw ArchiveError.cancelledOperation } let readSize = (Int(size) - position) >= bufferSize ? Int(bufferSize) : (Int(size) - position) let entryChunk = try provider(Int(position), Int(readSize)) checksum = entryChunk.crc32(checksum: checksum) sizeWritten += try Data.write(chunk: entryChunk, to: self.archiveFile) position += Int(bufferSize) progress?.completedUnitCount = Int64(sizeWritten) } return (UInt32(sizeWritten), checksum) } private func writeCompressed(size: UInt32, bufferSize: UInt32, progress: Progress? = nil, provider: Provider) throws -> (sizeWritten: UInt32, checksum: CRC32) { var sizeWritten = 0 let consumer: Consumer = { data in sizeWritten += try Data.write(chunk: data, to: self.archiveFile) } let checksum = try Data.compress(size: Int(size), bufferSize: Int(bufferSize), provider: { (position, size) -> Data in if progress?.isCancelled == true { throw ArchiveError.cancelledOperation } let data = try provider(position, size) progress?.completedUnitCount += Int64(data.count) return data }, consumer: consumer) return(UInt32(sizeWritten), checksum) } private func writeSymbolicLink(size: UInt32, provider: Provider) throws -> (sizeWritten: UInt32, checksum: CRC32) { let linkData = try provider(0, Int(size)) let checksum = linkData.crc32(checksum: 0) let sizeWritten = try Data.write(chunk: linkData, to: self.archiveFile) return (UInt32(sizeWritten), checksum) } private func writeCentralDirectoryStructure(localFileHeader: LocalFileHeader, relativeOffset: UInt32, externalFileAttributes: UInt32) throws -> CentralDirectoryStructure { let centralDirectory = CentralDirectoryStructure(localFileHeader: localFileHeader, fileAttributes: externalFileAttributes, relativeOffset: relativeOffset) _ = try Data.write(chunk: centralDirectory.data, to: self.archiveFile) return centralDirectory } private func writeEndOfCentralDirectory(centralDirectoryStructure: CentralDirectoryStructure, startOfCentralDirectory: UInt32, operation: ModifyOperation) throws -> EndOfCentralDirectoryRecord { var record = self.endOfCentralDirectoryRecord let countChange = operation.rawValue var dataLength = centralDirectoryStructure.extraFieldLength dataLength += centralDirectoryStructure.fileNameLength dataLength += centralDirectoryStructure.fileCommentLength let centralDirectoryDataLengthChange = operation.rawValue * (Int(dataLength) + CentralDirectoryStructure.size) var updatedSizeOfCentralDirectory = Int(record.sizeOfCentralDirectory) updatedSizeOfCentralDirectory += centralDirectoryDataLengthChange let numberOfEntriesOnDisk = UInt16(Int(record.totalNumberOfEntriesOnDisk) + countChange) let numberOfEntriesInCentralDirectory = UInt16(Int(record.totalNumberOfEntriesInCentralDirectory) + countChange) record = EndOfCentralDirectoryRecord(record: record, numberOfEntriesOnDisk: numberOfEntriesOnDisk, numberOfEntriesInCentralDirectory: numberOfEntriesInCentralDirectory, updatedSizeOfCentralDirectory: UInt32(updatedSizeOfCentralDirectory), startOfCentralDirectory: startOfCentralDirectory) _ = try Data.write(chunk: record.data, to: self.archiveFile) return record } private func rollback(_ localFileHeaderStart: Int, _ existingCentralDirectoryData: Data, _ endOfCentralDirRecord: EndOfCentralDirectoryRecord) throws { fflush(self.archiveFile) ftruncate(fileno(self.archiveFile), off_t(localFileHeaderStart)) fseek(self.archiveFile, localFileHeaderStart, SEEK_SET) _ = try Data.write(chunk: existingCentralDirectoryData, to: self.archiveFile) _ = try Data.write(chunk: endOfCentralDirRecord.data, to: self.archiveFile) } }
bsd-3-clause
jovito-royeca/ManaKit
Sources/Classes/MGCardType+CoreDataProperties.swift
1
1435
// // MGCardType+CoreDataProperties.swift // Pods // // Created by Vito Royeca on 12/14/19. // // import Foundation import CoreData extension MGCardType { @nonobjc public class func fetchRequest() -> NSFetchRequest<MGCardType> { return NSFetchRequest<MGCardType>(entityName: "MGCardType") } @NSManaged public var name: String? @NSManaged public var nameSection: String? @NSManaged public var children: MGCardType? @NSManaged public var parent: NSSet? @NSManaged public var subtypes: NSSet? @NSManaged public var supertypes: MGCard? } // MARK: - Generated accessors for parent extension MGCardType { @objc(addParentObject:) @NSManaged public func addToParent(_ value: MGCardType) @objc(removeParentObject:) @NSManaged public func removeFromParent(_ value: MGCardType) @objc(addParent:) @NSManaged public func addToParent(_ values: NSSet) @objc(removeParent:) @NSManaged public func removeFromParent(_ values: NSSet) } // MARK: - Generated accessors for subtypes extension MGCardType { @objc(addSubtypesObject:) @NSManaged public func addToSubtypes(_ value: MGCard) @objc(removeSubtypesObject:) @NSManaged public func removeFromSubtypes(_ value: MGCard) @objc(addSubtypes:) @NSManaged public func addToSubtypes(_ values: NSSet) @objc(removeSubtypes:) @NSManaged public func removeFromSubtypes(_ values: NSSet) }
mit
CrazyKids/ADSideMenu
ADSideMenuSample/ADSideMenuSample/ViewController.swift
1
514
// // ViewController.swift // ADSideMenuSample // // Created by duanhongjin on 16/6/17. // Copyright © 2016年 CrazyKids. 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
lzpfmh/actor-platform
actor-apps/app-ios/ActorCore/Analytics.swift
1
1176
// // Copyright (c) 2014-2015 Actor LLC. <https://actor.im> // import Foundation import Crashlytics class CocoaAnalytics { private let internalAnalytics: ACActorAnalytics init(internalAnalytics: ACActorAnalytics) { self.internalAnalytics = internalAnalytics } func trackPageVisible(page: ACPage) { // Notify Fabric stats // TODO: Pass all ids Answers.logContentViewWithName(page.getContentTypeDisplay(), contentType: page.getContentType(), contentId: page.getContentId(), customAttributes: nil) // Notify internal stats internalAnalytics.trackContentVisibleWithACPage(page) } func trackPageHidden(page: ACPage) { // Unsupported in Fabric // Notify internal stats internalAnalytics.trackContentHiddenWithACPage(page) } func track(event: ACEvent) { // Notify Fabric stats // TODO: Pass all ids Answers.logCustomEventWithName(event.getActionType(), customAttributes: ["type": event.getActionId()]) // Notify internal stats internalAnalytics.trackEventWithACEvent(event) } }
mit
allevato/SwiftCGI
Sources/SwiftCGI/FCGIBeginRequestRole.swift
1
1108
// Copyright 2015 Tony Allevato // // 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. /// The application role associated with a request. enum FCGIBeginRequestRole: Int16 { /// An application that receives an HTTP request and generates an HTTP response. case Responder = 1 /// An application that receives an HTTP request and generates an authorized/unauthorized /// decision. case Authorizer = 2 /// An application that receives an HTTP request and an additional stream of data from the web /// server and generates a filtered version of the stream as a response. case Filter = 3 }
apache-2.0
wayfindrltd/wayfindr-demo-ios
Wayfindr Demo/Classes/Extensions/UIView+Borders.swift
1
4863
// // UIView+Borders.swift // Wayfindr Demo // // Created by Wayfindr on 12/11/2015. // Copyright (c) 2016 Wayfindr (http://www.wayfindr.net) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is furnished // to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A // PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE // SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // import UIKit extension UIView { /** Creates borders and adds them as subviews to the view. - parameter edges: Edges on which to create a border. - parameter colour: Color to tint the border. Default is white. - parameter thickness: Thickness of the border. Default is 1. - seealso: Taken from http://stackoverflow.com/questions/17355280/how-to-add-a-border-just-on-the-top-side-of-a-uiview - returns: Border views that have been added as subviews. */ @discardableResult func addBorder(edges: UIRectEdge, colour: UIColor = UIColor.white, thickness: CGFloat = 1) -> [UIView] { var borders = [UIView]() func border() -> UIView { let border = UIView(frame: CGRect.zero) border.backgroundColor = colour border.translatesAutoresizingMaskIntoConstraints = false return border } if edges.contains(.top) || edges.contains(.all) { let top = border() addSubview(top) addConstraints( NSLayoutConstraint.constraints(withVisualFormat: "V:|-(0)-[top(==thickness)]", options: [], metrics: ["thickness": thickness], views: ["top": top])) addConstraints( NSLayoutConstraint.constraints(withVisualFormat: "H:|-(0)-[top]-(0)-|", options: [], metrics: nil, views: ["top": top])) borders.append(top) } if edges.contains(.left) || edges.contains(.all) { let left = border() addSubview(left) addConstraints( NSLayoutConstraint.constraints(withVisualFormat: "H:|-(0)-[left(==thickness)]", options: [], metrics: ["thickness": thickness], views: ["left": left])) addConstraints( NSLayoutConstraint.constraints(withVisualFormat: "V:|-(0)-[left]-(0)-|", options: [], metrics: nil, views: ["left": left])) borders.append(left) } if edges.contains(.right) || edges.contains(.all) { let right = border() addSubview(right) addConstraints( NSLayoutConstraint.constraints(withVisualFormat: "H:[right(==thickness)]-(0)-|", options: [], metrics: ["thickness": thickness], views: ["right": right])) addConstraints( NSLayoutConstraint.constraints(withVisualFormat: "V:|-(0)-[right]-(0)-|", options: [], metrics: nil, views: ["right": right])) borders.append(right) } if edges.contains(.bottom) || edges.contains(.all) { let bottom = border() addSubview(bottom) addConstraints( NSLayoutConstraint.constraints(withVisualFormat: "V:[bottom(==thickness)]-(0)-|", options: [], metrics: ["thickness": thickness], views: ["bottom": bottom])) addConstraints( NSLayoutConstraint.constraints(withVisualFormat: "H:|-(0)-[bottom]-(0)-|", options: [], metrics: nil, views: ["bottom": bottom])) borders.append(bottom) } return borders } }
mit
jens-maus/Frameless
Frameless/JSSAlertView.swift
2
15508
// // JSSAlertView // JSSAlertView // // Created by Jay Stakelon on 9/16/14. // Copyright (c) 2014 Jay Stakelon / https://github.com/stakes - all rights reserved. // // Inspired by and modeled after https://github.com/vikmeup/SCLAlertView-Swift // by Victor Radchenko: https://github.com/vikmeup // import Foundation import UIKit class JSSAlertView: UIViewController { var containerView:UIView! var alertBackgroundView:UIView! var dismissButton:UIButton! var cancelButton:UIButton! var buttonLabel:UILabel! var cancelButtonLabel:UILabel! var titleLabel:UILabel! var textView:UITextView! var rootViewController:UIViewController! var iconImage:UIImage! var iconImageView:UIImageView! var closeAction:(()->Void)! var isAlertOpen:Bool = false enum FontType { case Title, Text, Button } var titleFont = "HelveticaNeue-Light" var textFont = "HelveticaNeue" var buttonFont = "HelveticaNeue-Bold" var defaultColor = UIColorFromHex(0xF2F4F4, alpha: 1) enum TextColorTheme { case Dark, Light } var darkTextColor = UIColorFromHex(0x000000, alpha: 0.75) var lightTextColor = UIColorFromHex(0xffffff, alpha: 0.9) let baseHeight:CGFloat = 160.0 var alertWidth:CGFloat = 290.0 let buttonHeight:CGFloat = 70.0 let padding:CGFloat = 20.0 var viewWidth:CGFloat? var viewHeight:CGFloat? // Allow alerts to be closed/renamed in a chainable manner class JSSAlertViewResponder { let alertview: JSSAlertView init(alertview: JSSAlertView) { self.alertview = alertview } func addAction(action: ()->Void) { self.alertview.addAction(action) } func setTitleFont(fontStr: String) { self.alertview.setFont(fontStr, type: .Title) } func setTextFont(fontStr: String) { self.alertview.setFont(fontStr, type: .Text) } func setButtonFont(fontStr: String) { self.alertview.setFont(fontStr, type: .Button) } func setTextTheme(theme: TextColorTheme) { self.alertview.setTextTheme(theme) } func close() { self.alertview.closeView(false) } } func setFont(fontStr: String, type: FontType) { switch type { case .Title: self.titleFont = fontStr if let font = UIFont(name: self.titleFont, size: 24) { self.titleLabel.font = font } else { self.titleLabel.font = UIFont.systemFontOfSize(24) } case .Text: if self.textView != nil { self.textFont = fontStr if let font = UIFont(name: self.textFont, size: 16) { self.textView.font = font } else { self.textView.font = UIFont.systemFontOfSize(16) } } case .Button: self.buttonFont = fontStr if let font = UIFont(name: self.buttonFont, size: 24) { self.buttonLabel.font = font } else { self.buttonLabel.font = UIFont.systemFontOfSize(24) } } // relayout to account for size changes self.viewDidLayoutSubviews() } func setTextTheme(theme: TextColorTheme) { switch theme { case .Light: recolorText(lightTextColor) case .Dark: recolorText(darkTextColor) } } func recolorText(color: UIColor) { titleLabel.textColor = color if textView != nil { textView.textColor = color } buttonLabel.textColor = color if cancelButtonLabel != nil { cancelButtonLabel.textColor = color } } required init(coder aDecoder: NSCoder) { fatalError("NSCoding not supported") } override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { super.init(nibName:nibNameOrNil, bundle:nibBundleOrNil) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewDidLayoutSubviews() { super.viewWillLayoutSubviews() let size = UIScreen.mainScreen().bounds.size self.viewWidth = size.width self.viewHeight = size.height var yPos:CGFloat = 0.0 var contentWidth:CGFloat = self.alertWidth - (self.padding*2) // position the icon image view, if there is one if self.iconImageView != nil { yPos += iconImageView.frame.height var centerX = (self.alertWidth-self.iconImageView.frame.width)/2 self.iconImageView.frame.origin = CGPoint(x: centerX, y: self.padding) yPos += padding } // position the title let titleString = titleLabel.text! as NSString let titleAttr = [NSFontAttributeName:titleLabel.font] let titleSize = CGSize(width: contentWidth, height: 90) let titleRect = titleString.boundingRectWithSize(titleSize, options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: titleAttr, context: nil) yPos += padding self.titleLabel.frame = CGRect(x: self.padding, y: yPos, width: self.alertWidth - (self.padding*2), height: ceil(titleRect.size.height)) yPos += ceil(titleRect.size.height) // position text if self.textView != nil { let textString = textView.text! as NSString let textAttr = [NSFontAttributeName:textView.font] let textSize = CGSize(width: contentWidth, height: 90) let textRect = textString.boundingRectWithSize(textSize, options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: textAttr, context: nil) self.textView.frame = CGRect(x: self.padding, y: yPos, width: self.alertWidth - (self.padding*2), height: ceil(textRect.size.height)*2) yPos += ceil(textRect.size.height) + padding/2 } // position the buttons yPos += self.padding var buttonWidth = self.alertWidth if self.cancelButton != nil { buttonWidth = self.alertWidth/2 self.cancelButton.frame = CGRect(x: 0, y: yPos, width: buttonWidth-0.5, height: self.buttonHeight) if self.cancelButtonLabel != nil { self.cancelButtonLabel.frame = CGRect(x: self.padding, y: (self.buttonHeight/2) - 15, width: buttonWidth - (self.padding*2), height: 30) } } var buttonX = buttonWidth == self.alertWidth ? 0 : buttonWidth self.dismissButton.frame = CGRect(x: buttonX, y: yPos, width: buttonWidth, height: self.buttonHeight) if self.buttonLabel != nil { self.buttonLabel.frame = CGRect(x: self.padding, y: (self.buttonHeight/2) - 15, width: buttonWidth - (self.padding*2), height: 30) } // set button fonts if self.buttonLabel != nil { buttonLabel.font = UIFont(name: self.buttonFont, size: 20) } if self.cancelButtonLabel != nil { cancelButtonLabel.font = UIFont(name: self.buttonFont, size: 20) } yPos += self.buttonHeight // size the background view self.alertBackgroundView.frame = CGRect(x: 0, y: 0, width: self.alertWidth, height: yPos) // size the container that holds everything together self.containerView.frame = CGRect(x: (self.viewWidth!-self.alertWidth)/2, y: (self.viewHeight! - yPos)/2, width: self.alertWidth, height: yPos) } func info(viewController: UIViewController, title: String, text: String?=nil, buttonText: String?=nil, cancelButtonText: String?=nil) -> JSSAlertViewResponder { var alertview = self.show(viewController, title: title, text: text, buttonText: buttonText, cancelButtonText: cancelButtonText, color: UIColorFromHex(0x3498db, alpha: 1)) alertview.setTextTheme(.Light) return alertview } func success(viewController: UIViewController, title: String, text: String?=nil, buttonText: String?=nil, cancelButtonText: String?=nil) -> JSSAlertViewResponder { return self.show(viewController, title: title, text: text, buttonText: buttonText, cancelButtonText: cancelButtonText, color: UIColorFromHex(0x2ecc71, alpha: 1)) } func warning(viewController: UIViewController, title: String, text: String?=nil, buttonText: String?=nil, cancelButtonText: String?=nil) -> JSSAlertViewResponder { return self.show(viewController, title: title, text: text, buttonText: buttonText, cancelButtonText: cancelButtonText, color: UIColorFromHex(0xf1c40f, alpha: 1)) } func danger(viewController: UIViewController, title: String, text: String?=nil, buttonText: String?=nil, cancelButtonText: String?=nil) -> JSSAlertViewResponder { var alertview = self.show(viewController, title: title, text: text, buttonText: buttonText, cancelButtonText: cancelButtonText, color: UIColorFromHex(0xe74c3c, alpha: 1)) alertview.setTextTheme(.Light) return alertview } func show(viewController: UIViewController, title: String, text: String?=nil, buttonText: String?=nil, cancelButtonText: String?=nil, color: UIColor?=nil, iconImage: UIImage?=nil) -> JSSAlertViewResponder { self.rootViewController = viewController self.rootViewController.addChildViewController(self) self.rootViewController.view.addSubview(view) self.view.backgroundColor = UIColorFromHex(0x000000, alpha: 0.7) var baseColor:UIColor? if let customColor = color { baseColor = customColor } else { baseColor = self.defaultColor } var textColor = self.darkTextColor let sz = UIScreen.mainScreen().bounds.size self.viewWidth = sz.width self.viewHeight = sz.height // Container for the entire alert modal contents self.containerView = UIView() self.view.addSubview(self.containerView!) // Background view/main color self.alertBackgroundView = UIView() alertBackgroundView.backgroundColor = baseColor alertBackgroundView.layer.cornerRadius = 4 alertBackgroundView.layer.masksToBounds = true self.containerView.addSubview(alertBackgroundView!) // Icon self.iconImage = iconImage if self.iconImage != nil { self.iconImageView = UIImageView(image: self.iconImage) self.containerView.addSubview(iconImageView) } // Title self.titleLabel = UILabel() titleLabel.textColor = textColor titleLabel.numberOfLines = 0 titleLabel.textAlignment = .Center titleLabel.font = UIFont(name: self.titleFont, size: 24) titleLabel.text = title self.containerView.addSubview(titleLabel) // View text if let str = text { self.textView = UITextView() self.textView.userInteractionEnabled = false textView.editable = false textView.textColor = textColor textView.textAlignment = .Center textView.font = UIFont(name: self.textFont, size: 16) textView.backgroundColor = UIColor.clearColor() textView.text = str self.containerView.addSubview(textView) } // Button self.dismissButton = UIButton() let buttonColor = UIImage.withColor(adjustBrightness(baseColor!, 0.8)) let buttonHighlightColor = UIImage.withColor(adjustBrightness(baseColor!, 0.9)) dismissButton.setBackgroundImage(buttonColor, forState: .Normal) dismissButton.setBackgroundImage(buttonHighlightColor, forState: .Highlighted) dismissButton.addTarget(self, action: "buttonTap", forControlEvents: .TouchUpInside) alertBackgroundView!.addSubview(dismissButton) // Button text self.buttonLabel = UILabel() buttonLabel.textColor = textColor buttonLabel.numberOfLines = 1 buttonLabel.textAlignment = .Center if let text = buttonText { buttonLabel.text = text } else { buttonLabel.text = "OK" } dismissButton.addSubview(buttonLabel) // Second cancel button if let btnText = cancelButtonText { self.cancelButton = UIButton() let buttonColor = UIImage.withColor(adjustBrightness(baseColor!, 0.8)) let buttonHighlightColor = UIImage.withColor(adjustBrightness(baseColor!, 0.9)) cancelButton.setBackgroundImage(buttonColor, forState: .Normal) cancelButton.setBackgroundImage(buttonHighlightColor, forState: .Highlighted) cancelButton.addTarget(self, action: "cancelButtonTap", forControlEvents: .TouchUpInside) alertBackgroundView!.addSubview(cancelButton) // Button text self.cancelButtonLabel = UILabel() cancelButtonLabel.alpha = 0.7 cancelButtonLabel.textColor = textColor cancelButtonLabel.numberOfLines = 1 cancelButtonLabel.textAlignment = .Center if let text = cancelButtonText { cancelButtonLabel.text = text } cancelButton.addSubview(cancelButtonLabel) } // Animate it in self.view.alpha = 0 UIView.animateWithDuration(0.2, animations: { self.view.alpha = 1 }) self.containerView.frame.origin.x = self.rootViewController.view.center.x self.containerView.center.y = -500 UIView.animateWithDuration(0.5, delay: 0.05, usingSpringWithDamping: 0.8, initialSpringVelocity: 0.5, options: nil, animations: { self.containerView.center = self.rootViewController.view.center }, completion: { finished in }) isAlertOpen = true return JSSAlertViewResponder(alertview: self) } func addAction(action: ()->Void) { self.closeAction = action } func buttonTap() { closeView(true); } func cancelButtonTap() { closeView(false); } func closeView(withCallback:Bool) { UIView.animateWithDuration(0.3, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.5, options: nil, animations: { self.containerView.center.y = self.rootViewController.view.center.y + self.viewHeight! }, completion: { finished in UIView.animateWithDuration(0.1, animations: { self.view.alpha = 0 }, completion: { finished in if withCallback == true { if let action = self.closeAction { action() } } self.removeView() }) }) } func removeView() { isAlertOpen = false self.view.removeFromSuperview() } }
mit
mlibai/XZKit
Projects/Example/CarouselViewExample/CarouselViewExample/CarouselViewExample/Example3/Example3WebViewController.swift
1
7662
// // Example3WebViewController.swift // CarouselViewExample // // Created by 徐臻 on 2019/6/6. // Copyright © 2019 mlibai. All rights reserved. // import UIKit import WebKit class Example3WebViewController: UIViewController, WKNavigationDelegate { deinit { print("VC\(index) \(self.title!): \(#function)") webView.configuration.userContentController.removeScriptMessageHandler(forName: "native") } let index: Int init(index: Int) { self.index = index super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private var url: URL? func prepareForReusing() { self.url = nil webView.load(.init(url: URL.init(string: "about:blank")!)) } func load(url: URL) { if url == self.url { return } self.url = url view.backgroundColor = UIColor(red: CGFloat(arc4random_uniform(255)) / 255.0, green: CGFloat(arc4random_uniform(255)) / 255.0, blue: CGFloat(arc4random_uniform(255)) / 255.0, alpha: 1.0) webView.loadHTMLString(loadingHTML(with: url), baseURL: nil) } var webView: WKWebView { return (view as! WebViewWrapperView).webView } override func loadView() { self.view = WebViewWrapperView.init(frame: UIScreen.main.bounds) } private lazy var messageHandler = MessageHandler.init() override func viewDidLoad() { super.viewDidLoad(); webView.configuration.userContentController.add(messageHandler, name: "native") let userScript = WKUserScript.init(source: """ $(function() { $("html").css("backgroundColor", "#fff"); $("div.hd[role='navigation']").hide(); $("div.hd-tab").hide(); $("div.edit-tab").hide(); $("div.news-class").hide(); $("div.head:not(:has(.rank-tab))").hide(); $("a.open-app-a").remove(); $("div.open-app-banner").remove(); window.webkit.messageHandlers.native.postMessage(true); // function getElementTop(el) { // if (el.parentElement) { // return getElementTop(el.parentElement) + el.offsetTop; // } // return el.offsetTop; // } // var top = getElementTop($("div.swiper-wrapper[role='menubar']")[0]); // window.webkit.messageHandlers.native.postMessage(top); }); """, injectionTime: .atDocumentEnd, forMainFrameOnly: true) webView.configuration.userContentController.addUserScript(userScript) webView.navigationDelegate = self; self.navigationItem.backBarButtonItem = UIBarButtonItem.init(title: "返回", style: .plain, target: nil, action: nil) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) print("VC\(index) \(self.title!): \(#function) \(animated)") } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) print("VC\(index) \(self.title!): \(#function) \(animated)") } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) print("VC\(index) \(self.title!): \(#function) \(animated)") } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) print("VC\(index) \(self.title!): \(#function) \(animated)") } override func willMove(toParent parent: UIViewController?) { super.willMove(toParent: parent) if let parent = parent { print("VC\(index) \(self.title!): \(#function) \(parent)") } else { print("VC\(index) \(self.title!): \(#function) nil)") } } override func didMove(toParent parent: UIViewController?) { super.didMove(toParent: parent) if let parent = parent { print("VC\(index) \(self.title!): \(#function) \(parent)") } else { print("VC\(index) \(self.title!): \(#function) nil)") } } func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) { switch navigationAction.navigationType { case .linkActivated: decisionHandler(.cancel) let webVC = Example3WebViewController.init(index: -1) webVC.title = "新闻详情" webVC.webView.load(navigationAction.request) navigationController!.pushViewController(webVC, animated: true) default: decisionHandler(.allow) } } func webViewWebContentProcessDidTerminate(_ webView: WKWebView) { guard let url = self.url else { return } self.url = nil; self.load(url: url) } class MessageHandler: NSObject, WKScriptMessageHandler { deinit { print("MessageHandler: \(#function)") } func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) { print("MessageHandler: Document was ready.") } } class WebViewWrapperView: UIView { deinit { print("WebViewWrapperView: \(#function)") } lazy var webView: WKWebView = { let webView = WKWebView.init(frame: bounds) if #available(iOS 9.0, *) { webView.allowsLinkPreview = false } else { // Fallback on earlier versions } webView.scrollView.bounces = false webView.autoresizingMask = [.flexibleWidth, .flexibleHeight] addSubview(webView) return webView }() } } fileprivate func loadingHTML(with url: URL) -> String { return """ <!DOCTYPE html><html><head><meta charset="utf-8"><title>XZKit</title><meta name="apple-mobile-web-app-capable"content="yes"><meta name="viewport"content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no"><style type="text/css">.loadEffect{width:100px;height:100px;position:absolute;top:50%;left:50%;margin-top:-50px;margin-left:-50px}.loadEffect span{display:inline-block;width:16px;height:16px;border-radius:50%;background:#c10619;position:absolute;-webkit-animation:load 1.04s ease infinite}@-webkit-keyframes load{0%{opacity:1}100%{opacity:0.2}}.loadEffect span:nth-child(1){left:0;top:50%;margin-top:-8px;-webkit-animation-delay:0.13s}.loadEffect span:nth-child(2){left:12px;top:12px;-webkit-animation-delay:0.26s}.loadEffect span:nth-child(3){left:50%;top:0;margin-left:-8px;-webkit-animation-delay:0.39s}.loadEffect span:nth-child(4){top:12px;right:12px;-webkit-animation-delay:0.52s}.loadEffect span:nth-child(5){right:0;top:50%;margin-top:-8px;-webkit-animation-delay:0.65s}.loadEffect span:nth-child(6){right:12px;bottom:12px;-webkit-animation-delay:0.78s}.loadEffect span:nth-child(7){bottom:0;left:50%;margin-left:-8px;-webkit-animation-delay:0.91s}.loadEffect span:nth-child(8){bottom:12px;left:12px;-webkit-animation-delay:1.04s}</style></head><body><div class="loadEffect"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></div></body></html><script type="text/javascript">setTimeout(function() {window.location.href="\(url.absoluteString)";}, 500);</script> """ }
mit
Incipia/Goalie
Goalie/EditListHeaderCell.swift
1
477
// // EditListHeaderCell.swift // Goalie // // Created by Gregory Klein on 3/28/16. // Copyright © 2016 Incipia. All rights reserved. // import UIKit class EditListHeaderCell: UICollectionReusableView { @IBOutlet fileprivate weak var _titleLabel: UILabel! @IBOutlet fileprivate weak var _subtitleLabel: UILabel! func configureWithOption(_ option: EditListOption) { _titleLabel.text = option.title _subtitleLabel.text = option.subtitle } }
apache-2.0
Jakobeha/lAzR4t
lAzR4t Shared/Code/UI/ColorButtonElem.swift
1
1184
// // ColorButtonElem.swift // lAzR4t // // Created by Jakob Hain on 9/30/17. // Copyright © 2017 Jakob Hain. All rights reserved. // import Foundation ///A button which represents color final class ColorButtonElem: ButtonElem { let color: AttackColor init(color: AttackColor, isSelected: Bool, pos: CellPos) { self.color = color super.init(isSelected: isSelected, pos: pos, size: CellSize.unit) } override func set(pos newPos: CellPos) -> ColorButtonElem { return ColorButtonElem( color: self.color, isSelected: self.isSelected, pos: newPos ) } override func set(isSelected newIsSelected: Bool) -> ColorButtonElem { return ColorButtonElem( color: self.color, isSelected: newIsSelected, pos: self.pos ) } override func equals(_ other: Elem) -> Bool { guard let other = other as? ColorButtonElem else { return false } return super.equals(other) && (other.color == self.color) && (other.isSelected == self.isSelected) } }
mit
kostickm/mobileStack
MobileStack/VolumeViewController.swift
1
3088
/** * Copyright IBM Corporation 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 UIKit class VolumeViewController: UIViewController, UITextFieldDelegate { var volumes = [Volume]() var volumeId:String = "" var volume: Volume? @IBOutlet weak var volumeNameLabel: UILabel! @IBOutlet weak var volumeSizeLabel: UILabel! @IBOutlet weak var volumeNameTextField: UITextField! @IBOutlet weak var volumeSizeTextField: UITextField! @IBOutlet weak var saveVolumeButton: UIBarButtonItem! @IBAction func cancelVolumeButton(_ sender: UIBarButtonItem) { dismiss(animated: true, completion: nil) } /*override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. }*/ override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // No need for semicolon getVolumes { volumes in } // Handle the text field’s user input through delegate callbacks. volumeNameTextField.delegate = self // Enable the Save button only if the text field has a valid Volume name. checkValidVolumeName() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func textFieldDidBeginEditing(_ textField: UITextField) { // Disable the Save button while editing. saveVolumeButton.isEnabled = false } func checkValidVolumeName() { // Disable the Save button if the text field is empty. let text = volumeNameTextField.text ?? "" saveVolumeButton.isEnabled = !text.isEmpty } func textFieldDidEndEditing(_ textField: UITextField) { checkValidVolumeName() navigationItem.title = textField.text } // 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. if saveVolumeButton === sender as AnyObject? { let name = volumeNameTextField.text ?? "" let size = volumeSizeTextField.text ?? "0" // Set the volume to be passed to VolumeTableViewController after the unwind segue. createVolume(name: name, size: size) } } }
apache-2.0
alltheflow/copypasta
Carthage/Checkouts/VinceRP/vincerp/Common/Core/Node.swift
1
1623
// // Created by Viktor Belenyesi on 19/04/15. // Copyright (c) 2015 Viktor Belenyesi. All rights reserved. // public class Node: Hashable { private static var hashCounter = AtomicLong(0) private let childrenHolder = AtomicReference<WeakSet<Node>>(WeakSet()) public let hashValue = Int(Node.hashCounter.getAndIncrement()) // Hashable public var children: Set<Node> { return childrenHolder.value.filter { $0.parents.contains(self) }.set } public var descendants: Set<Node> { return children ++ children.flatMap { $0.descendants } } public var parents: Set<Node> { return Set() } public var ancestors: Set<Node> { return parents ++ parents.flatMap { $0.ancestors } } func isSuccess() -> Bool { return true } func error() -> NSError { fatalError(ABSTRACT_METHOD) } func linkChild(child: Node) { if (!childrenHolder.value.hasElementPassingTest {$0 == child}) { childrenHolder.value.insert(child) } } func unlinkChild(child: Node) { childrenHolder.value = childrenHolder.value.filter {$0 != child} } func ping(incoming: Set<Node>) -> Set<Node> { fatalError(ABSTRACT_METHOD) } private var alive = true public func kill() { alive = false parents.forEach { $0.unlinkChild(self) } } var level: long { return 0 } } public func ==(lhs: Node, rhs: Node) -> Bool { return lhs.hashValue == rhs.hashValue }
mit
apple/swift
validation-test/compiler_crashers_fixed/28555-unreachable-executed-at-swift-lib-ast-type-cpp-1318.swift
63
406
// 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 -emit-ir _&[i -{$0
apache-2.0
roosmaa/Octowire-iOS
OctowireTests/EventsBrowserStateSpec.swift
1
6208
// // EventsBrowserStateSpec.swift // Octowire // // Created by Mart Roosmaa on 26/02/2017. // Copyright © 2017 Mart Roosmaa. All rights reserved. // import Foundation import ReSwift import Quick import Nimble @testable import Octowire class EventsBrowserStateSpec: QuickSpec { override func spec() { describe("actions") { let store = Store<EventsBrowserState>( reducer: EventsBrowserReducer(unfilteredEventsCapacity: 2), state: nil) it("begins initial preloading") { store.dispatch(EventsBrowserActionBeginPreloading()) expect(store.state.isPreloadingEvents).to(equal(true)) } it("ends initial preloading") { store.dispatch(EventsBrowserActionEndPreloading(preloadedEvents: [ (PullRequestEventModel(), eta: 8), (CreateEventModel(), eta: 7), (ForkEventModel(), eta: 5), (WatchEventModel(), eta: 4)])) expect(store.state.isPreloadingEvents).to(equal(false)) expect(store.state.preloadedEvents.map({ $0.eta })).to(equal([5, 4, 2, 1])) } it("reveals first preloaded event") { store.dispatch(EventsBrowserActionRevealPreloaded()) expect(store.state.filteredEvents).to(haveCount(1)) expect(store.state.filteredEvents[0]).to(beAnInstanceOf(WatchEventModel.self)) } it("reveals next preloaded above others") { store.dispatch(EventsBrowserActionRevealPreloaded()) expect(store.state.filteredEvents).to(haveCount(2)) expect(store.state.filteredEvents[0]).to(beAnInstanceOf(ForkEventModel.self)) expect(store.state.filteredEvents[1]).to(beAnInstanceOf(WatchEventModel.self)) } it("reveals nothing due preload queue having a gap") { store.dispatch(EventsBrowserActionRevealPreloaded()) expect(store.state.filteredEvents).to(haveCount(2)) expect(store.state.filteredEvents[0]).to(beAnInstanceOf(ForkEventModel.self)) expect(store.state.filteredEvents[1]).to(beAnInstanceOf(WatchEventModel.self)) } it("reveals next hitting event capacity") { store.dispatch(EventsBrowserActionRevealPreloaded()) expect(store.state.filteredEvents).to(haveCount(2)) expect(store.state.filteredEvents[0]).to(beAnInstanceOf(CreateEventModel.self)) expect(store.state.filteredEvents[1]).to(beAnInstanceOf(ForkEventModel.self)) } it("updates scroll top distance") { store.dispatch(EventsBrowserActionUpdateScrollTopDistance(to: 100)) expect(store.state.scrollTopDistance).to(equal(100)) store.dispatch(EventsBrowserActionUpdateScrollTopDistance(to: -1)) expect(store.state.scrollTopDistance).to(equal(0)) } it("updates is visible") { store.dispatch(EventsBrowserActionUpdateIsVisible(to: true)) expect(store.state.isVisible).to(equal(true)) store.dispatch(EventsBrowserActionUpdateIsVisible(to: false)) expect(store.state.isVisible).to(equal(false)) } it("filters results") { store.dispatch(EventsBrowserActionUpdateActiveFilters(to: [.forkEvents])) expect(store.state.filteredEvents).to(haveCount(1)) expect(store.state.unfilteredEvents).to(haveCount(2)) } it("doesn't reveal filtered") { store.dispatch(EventsBrowserActionRevealPreloaded()) expect(store.state.filteredEvents).to(haveCount(0)) expect(store.state.unfilteredEvents).to(haveCount(2)) } it("begins another preloading") { store.dispatch(EventsBrowserActionBeginPreloading()) expect(store.state.isPreloadingEvents).to(equal(true)) } it("ends another preloading") { store.dispatch(EventsBrowserActionEndPreloading(preloadedEvents: [ (ForkEventModel(), eta: 5), (WatchEventModel(), eta: 4)])) expect(store.state.isPreloadingEvents).to(equal(false)) expect(store.state.preloadedEvents.map({ $0.eta })).to(equal([6, 5])) } } xdescribe("action creaters") { let store = Store<AppState>( reducer: AppReducer(), state: nil) it("doesn't load events when hidden") { store.dispatch(EventsBrowserActionUpdateIsVisible(to: false)) store.dispatch(EventsBrowserActionUpdateScrollTopDistance(to: 0)) store.dispatch(loadNextEvent()) expect(store.state.eventsBrowserState.isPreloadingEvents).to(equal(false)) } it("doesn't load events when scrolled") { store.dispatch(EventsBrowserActionUpdateIsVisible(to: true)) store.dispatch(EventsBrowserActionUpdateScrollTopDistance(to: 100)) store.dispatch(loadNextEvent()) expect(store.state.eventsBrowserState.isPreloadingEvents).to(equal(false)) } it("loads events") { store.dispatch(EventsBrowserActionUpdateIsVisible(to: true)) store.dispatch(EventsBrowserActionUpdateScrollTopDistance(to: 0)) store.dispatch(loadNextEvent()) expect(store.state.eventsBrowserState.isPreloadingEvents).to(equal(true)) expect(store.state.eventsBrowserState.isPreloadingEvents).toEventually(equal(false), timeout: 5) } } } }
mit
R3dTeam/SwiftLint
Source/SwiftLintFramework/Rules/TypeNameRule.swift
5
3192
// // TypeNameRule.swift // SwiftLint // // Created by JP Simard on 2015-05-16. // Copyright (c) 2015 Realm. All rights reserved. // import SourceKittenFramework import SwiftXPC public struct TypeNameRule: ASTRule { public init() {} public let identifier = "type_name" public func validateFile(file: File) -> [StyleViolation] { return validateFile(file, dictionary: file.structure.dictionary) } public func validateFile(file: File, dictionary: XPCDictionary) -> [StyleViolation] { return (dictionary["key.substructure"] as? XPCArray ?? []).flatMap { subItem in var violations = [StyleViolation]() if let subDict = subItem as? XPCDictionary, let kindString = subDict["key.kind"] as? String, let kind = flatMap(kindString, { SwiftDeclarationKind(rawValue: $0) }) { violations.extend(validateFile(file, dictionary: subDict)) violations.extend(validateFile(file, kind: kind, dictionary: subDict)) } return violations } } public func validateFile(file: File, kind: SwiftDeclarationKind, dictionary: XPCDictionary) -> [StyleViolation] { let typeKinds: [SwiftDeclarationKind] = [ .Class, .Struct, .Typealias, .Enum, .Enumelement ] if !contains(typeKinds, kind) { return [] } var violations = [StyleViolation]() if let name = dictionary["key.name"] as? String, let offset = flatMap(dictionary["key.offset"] as? Int64, { Int($0) }) { let location = Location(file: file, offset: offset) let nameCharacterSet = NSCharacterSet(charactersInString: name) if !NSCharacterSet.alphanumericCharacterSet().isSupersetOfSet(nameCharacterSet) { violations.append(StyleViolation(type: .NameFormat, location: location, severity: .High, reason: "Type name should only contain alphanumeric characters: '\(name)'")) } else if !name.substringToIndex(name.startIndex.successor()).isUppercase() { violations.append(StyleViolation(type: .NameFormat, location: location, severity: .High, reason: "Type name should start with an uppercase character: '\(name)'")) } else if count(name) < 3 || count(name) > 40 { violations.append(StyleViolation(type: .NameFormat, location: location, severity: .Medium, reason: "Type name should be between 3 and 40 characters in length: " + "'\(name)'")) } } return violations } public let example = RuleExample( ruleName: "Type Name Rule", ruleDescription: "Type name should only contain alphanumeric characters, " + "start with an uppercase character and between 3 and 40 characters in length.", nonTriggeringExamples: [], triggeringExamples: [], showExamples: false ) }
mit
allbto/WayThere
ios/WayThere/Pods/Nimble/Nimble/Matchers/BeGreaterThanOrEqualTo.swift
78
1700
import Foundation /// A Nimble matcher that succeeds when the actual value is greater than /// or equal to the expected value. public func beGreaterThanOrEqualTo<T: Comparable>(expectedValue: T?) -> NonNilMatcherFunc<T> { return NonNilMatcherFunc { actualExpression, failureMessage in failureMessage.postfixMessage = "be greater than or equal to <\(stringify(expectedValue))>" let actualValue = actualExpression.evaluate() return actualValue >= expectedValue } } /// A Nimble matcher that succeeds when the actual value is greater than /// or equal to the expected value. public func beGreaterThanOrEqualTo<T: NMBComparable>(expectedValue: T?) -> NonNilMatcherFunc<T> { return NonNilMatcherFunc { actualExpression, failureMessage in failureMessage.postfixMessage = "be greater than or equal to <\(stringify(expectedValue))>" let actualValue = actualExpression.evaluate() let matches = actualValue != nil && actualValue!.NMB_compare(expectedValue) != NSComparisonResult.OrderedAscending return matches } } public func >=<T: Comparable>(lhs: Expectation<T>, rhs: T) { lhs.to(beGreaterThanOrEqualTo(rhs)) } public func >=<T: NMBComparable>(lhs: Expectation<T>, rhs: T) { lhs.to(beGreaterThanOrEqualTo(rhs)) } extension NMBObjCMatcher { public class func beGreaterThanOrEqualToMatcher(expected: NMBComparable?) -> NMBObjCMatcher { return NMBObjCMatcher(canMatchNil: false) { actualExpression, failureMessage, location in let expr = actualExpression.cast { $0 as? NMBComparable } return beGreaterThanOrEqualTo(expected).matches(expr, failureMessage: failureMessage) } } }
mit
mahomealex/MASQLiteWrapper
Source/SQOperation.swift
2
3319
// // SQOperation.swift // // // Created by Alex on 25/04/2017. // Copyright © 2017 Alex. All rights reserved. // import Foundation import SQLite class SQOperation : NSObject { weak var db : Connection! func save(model:SQObject) { let schema = SQSchemaCache.objectSchema(model: model) var ary:[Setter] = [] for pt in schema.properties { ary.append(pt.generalSetter(model: model)) } do { let pt = schema.primaryKeyProperty() let filterTable = schema.table.filter(pt.filter(model: model)) if let _ = try db.pluck(filterTable) {//exist _ = try db.run(filterTable.update(ary)) } else { try db.run(schema.table.insert(ary)) } } catch { print(error) } } func saveAll(models:[SQObject]) { guard models.count > 0 else { return } for model in models { save(model: model) } } func delete(model:SQObject) { let schema = SQSchemaCache.objectSchema(model: model) do { let pt = schema.primaryKeyProperty() let filterTable = schema.table.filter(pt.filter(model: model)) try db.run(filterTable.delete()) } catch { print(error) } } func queryAll(_ m:SQObject) -> [SQObject] { let schema = SQSchemaCache.objectSchema(model: m) var items:[SQObject] = [] do { let datas = try db.prepare(schema.table) for data in datas { let item = schema.objClass.init() for pt in schema.properties { pt.convertcolumnToModel(model: item, row: data) } items.append(item) } } catch { print(error) } return items } func queryAll<T:SQObject>(_ m:T.Type) -> [T] { let schema = SQSchemaCache.objectSchema(m) var items:[T] = [] do { let datas = try db.prepare(schema.table) for data in datas { let item = schema.objClass.init() for pt in schema.properties { pt.convertcolumnToModel(model: item, row: data) } items.append(item as! T) } } catch { print(error) } return items } func createTable(model:SQObject) { let schema = SQSchemaCache.objectSchema(model: model) do { try db.run(schema.table.create(ifNotExists: true, block: { (t) in for pt in schema.properties { pt.buildColumn(builder: t) } })) } catch { print(error) } } func crateTable<T:SQObject>(_ m:T.Type) { let schema = SQSchemaCache.objectSchema(m) do { // let state = _ = try db.run(schema.table.create(ifNotExists: true, block: { (t) in for pt in schema.properties { pt.buildColumn(builder: t) } })) // print(state) } catch { print(error) } } }
mit
acegreen/Bitcoin-Sample-iOS-App
Pods/Charts/Charts/Classes/Renderers/PieChartRenderer.swift
6
32536
// // PieChartRenderer.swift // Charts // // Created by Daniel Cohen Gindi on 4/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 PieChartRenderer: ChartDataRendererBase { open weak var chart: PieChartView? public init(chart: PieChartView, animator: ChartAnimator?, viewPortHandler: ChartViewPortHandler) { super.init(animator: animator, viewPortHandler: viewPortHandler) self.chart = chart } open override func drawData(context: CGContext) { guard let chart = chart else { return } let pieData = chart.data if (pieData != nil) { for set in pieData!.dataSets as! [IPieChartDataSet] { if set.visible && set.entryCount > 0 { drawDataSet(context: context, dataSet: set) } } } } open func calculateMinimumRadiusForSpacedSlice( center: CGPoint, radius: CGFloat, angle: CGFloat, arcStartPointX: CGFloat, arcStartPointY: CGFloat, startAngle: CGFloat, sweepAngle: CGFloat) -> CGFloat { let angleMiddle = startAngle + sweepAngle / 2.0 // Other point of the arc let arcEndPointX = center.x + radius * cos((startAngle + sweepAngle) * ChartUtils.Math.FDEG2RAD) let arcEndPointY = center.y + radius * sin((startAngle + sweepAngle) * ChartUtils.Math.FDEG2RAD) // Middle point on the arc let arcMidPointX = center.x + radius * cos(angleMiddle * ChartUtils.Math.FDEG2RAD) let arcMidPointY = center.y + radius * sin(angleMiddle * ChartUtils.Math.FDEG2RAD) // This is the base of the contained triangle let basePointsDistance = sqrt( pow(arcEndPointX - arcStartPointX, 2) + pow(arcEndPointY - arcStartPointY, 2)) // After reducing space from both sides of the "slice", // the angle of the contained triangle should stay the same. // So let's find out the height of that triangle. let containedTriangleHeight = (basePointsDistance / 2.0 * tan((180.0 - angle) / 2.0 * ChartUtils.Math.FDEG2RAD)) // Now we subtract that from the radius var spacedRadius = radius - containedTriangleHeight // And now subtract the height of the arc that's between the triangle and the outer circle spacedRadius -= sqrt( pow(arcMidPointX - (arcEndPointX + arcStartPointX) / 2.0, 2) + pow(arcMidPointY - (arcEndPointY + arcStartPointY) / 2.0, 2)) return spacedRadius } open func drawDataSet(context: CGContext, dataSet: IPieChartDataSet) { guard let chart = chart, let data = chart.data, let animator = animator else {return } var angle: CGFloat = 0.0 let rotationAngle = chart.rotationAngle let phaseX = animator.phaseX let phaseY = animator.phaseY let entryCount = dataSet.entryCount var drawAngles = chart.drawAngles let center = chart.centerCircleBox let radius = chart.radius let drawInnerArc = chart.drawHoleEnabled && !chart.drawSlicesUnderHoleEnabled let userInnerRadius = drawInnerArc ? radius * chart.holeRadiusPercent : 0.0 var visibleAngleCount = 0 for j in 0 ..< entryCount { guard let e = dataSet.entryForIndex(j) else { continue } if ((abs(e.value) > 0.000001)) { visibleAngleCount += 1 } } let sliceSpace = visibleAngleCount <= 1 ? 0.0 : dataSet.sliceSpace context.saveGState() for j in 0 ..< entryCount { let sliceAngle = drawAngles[j] var innerRadius = userInnerRadius guard let e = dataSet.entryForIndex(j) else { continue } // draw only if the value is greater than zero if ((abs(e.value) > 0.000001)) { if (!chart.needsHighlight(xIndex: e.xIndex, dataSetIndex: data.indexOfDataSet(dataSet))) { let accountForSliceSpacing = sliceSpace > 0.0 && sliceAngle <= 180.0 context.setFillColor(dataSet.colorAt(j).cgColor) let sliceSpaceAngleOuter = visibleAngleCount == 1 ? 0.0 : sliceSpace / (ChartUtils.Math.FDEG2RAD * radius) let startAngleOuter = rotationAngle + (angle + sliceSpaceAngleOuter / 2.0) * phaseY var sweepAngleOuter = (sliceAngle - sliceSpaceAngleOuter) * phaseY if (sweepAngleOuter < 0.0) { sweepAngleOuter = 0.0 } let arcStartPointX = center.x + radius * cos(startAngleOuter * ChartUtils.Math.FDEG2RAD) let arcStartPointY = center.y + radius * sin(startAngleOuter * ChartUtils.Math.FDEG2RAD) let path = CGMutablePath() path.move(to: CGPoint(x: arcStartPointX, y: arcStartPointY)) path.addRelativeArc(center: CGPoint(x: center.x, y: center.y), radius: radius, startAngle: startAngleOuter * ChartUtils.Math.FDEG2RAD, delta: sweepAngleOuter * ChartUtils.Math.FDEG2RAD) if drawInnerArc && (innerRadius > 0.0 || accountForSliceSpacing) { if accountForSliceSpacing { var minSpacedRadius = calculateMinimumRadiusForSpacedSlice( center: center, radius: radius, angle: sliceAngle * phaseY, arcStartPointX: arcStartPointX, arcStartPointY: arcStartPointY, startAngle: startAngleOuter, sweepAngle: sweepAngleOuter) if minSpacedRadius < 0.0 { minSpacedRadius = -minSpacedRadius } innerRadius = min(max(innerRadius, minSpacedRadius), radius) } let sliceSpaceAngleInner = visibleAngleCount == 1 || innerRadius == 0.0 ? 0.0 : sliceSpace / (ChartUtils.Math.FDEG2RAD * innerRadius) let startAngleInner = rotationAngle + (angle + sliceSpaceAngleInner / 2.0) * phaseY var sweepAngleInner = (sliceAngle - sliceSpaceAngleInner) * phaseY if (sweepAngleInner < 0.0) { sweepAngleInner = 0.0 } let endAngleInner = startAngleInner + sweepAngleInner path.addLine(to: CGPoint(x: center.x + innerRadius * cos(endAngleInner * ChartUtils.Math.FDEG2RAD), y: center.y + innerRadius * sin(endAngleInner * ChartUtils.Math.FDEG2RAD))) path.addRelativeArc(center: CGPoint(x: center.x, y: center.y), radius: innerRadius, startAngle: endAngleInner * ChartUtils.Math.FDEG2RAD, delta: -sweepAngleInner * ChartUtils.Math.FDEG2RAD) } else { if accountForSliceSpacing { let angleMiddle = startAngleOuter + sweepAngleOuter / 2.0 let sliceSpaceOffset = calculateMinimumRadiusForSpacedSlice( center: center, radius: radius, angle: sliceAngle * phaseY, arcStartPointX: arcStartPointX, arcStartPointY: arcStartPointY, startAngle: startAngleOuter, sweepAngle: sweepAngleOuter) let arcEndPointX = center.x + sliceSpaceOffset * cos(angleMiddle * ChartUtils.Math.FDEG2RAD) let arcEndPointY = center.y + sliceSpaceOffset * sin(angleMiddle * ChartUtils.Math.FDEG2RAD) path.addLine(to: CGPoint(x: arcEndPointX, y: arcEndPointY)) } else { path.addLine(to: CGPoint(x: center.x, y: center.y)) } } path.closeSubpath() context.beginPath() context.addPath(path) context.fillPath(using: .evenOdd) } } angle += sliceAngle * phaseX } context.restoreGState() } open override func drawValues(context: CGContext) { guard let chart = chart, let data = chart.data, let animator = animator else { return } let center = chart.centerCircleBox // get whole the radius let radius = chart.radius let rotationAngle = chart.rotationAngle var drawAngles = chart.drawAngles var absoluteAngles = chart.absoluteAngles let phaseX = animator.phaseX let phaseY = animator.phaseY var labelRadiusOffset = radius / 10.0 * 3.0 if chart.drawHoleEnabled { labelRadiusOffset = (radius - (radius * chart.holeRadiusPercent)) / 2.0 } let labelRadius = radius - labelRadiusOffset var dataSets = data.dataSets let yValueSum = (data as! PieChartData).yValueSum let drawXVals = chart.drawSliceTextEnabled let usePercentValuesEnabled = chart.usePercentValuesEnabled var angle: CGFloat = 0.0 var xIndex = 0 context.saveGState() defer { context.restoreGState() } for i in 0 ..< dataSets.count { guard let dataSet = dataSets[i] as? IPieChartDataSet else { continue } let drawYVals = dataSet.drawValuesEnabled if (!drawYVals && !drawXVals) { continue } let xValuePosition = dataSet.xValuePosition let yValuePosition = dataSet.yValuePosition let valueFont = dataSet.valueFont let lineHeight = valueFont.lineHeight guard let formatter = dataSet.valueFormatter else { continue } for j in 0 ..< dataSet.entryCount { if (drawXVals && !drawYVals && (j >= data.xValCount || data.xVals[j] == nil)) { continue } guard let e = dataSet.entryForIndex(j) else { continue } if (xIndex == 0) { angle = 0.0 } else { angle = absoluteAngles[xIndex - 1] * phaseX } let sliceAngle = drawAngles[xIndex] let sliceSpace = dataSet.sliceSpace let sliceSpaceMiddleAngle = sliceSpace / (ChartUtils.Math.FDEG2RAD * labelRadius) // offset needed to center the drawn text in the slice let angleOffset = (sliceAngle - sliceSpaceMiddleAngle / 2.0) / 2.0 angle = angle + angleOffset let transformedAngle = rotationAngle + angle * phaseY let value = usePercentValuesEnabled ? e.value / yValueSum * 100.0 : e.value let valueText = formatter.string(from: value as NSNumber)! let sliceXBase = cos(transformedAngle * ChartUtils.Math.FDEG2RAD) let sliceYBase = sin(transformedAngle * ChartUtils.Math.FDEG2RAD) let drawXOutside = drawXVals && xValuePosition == .outsideSlice let drawYOutside = drawYVals && yValuePosition == .outsideSlice let drawXInside = drawXVals && xValuePosition == .insideSlice let drawYInside = drawYVals && yValuePosition == .insideSlice if drawXOutside || drawYOutside { let valueLineLength1 = dataSet.valueLinePart1Length let valueLineLength2 = dataSet.valueLinePart2Length let valueLinePart1OffsetPercentage = dataSet.valueLinePart1OffsetPercentage var pt2: CGPoint var labelPoint: CGPoint var align: NSTextAlignment var line1Radius: CGFloat if chart.drawHoleEnabled { line1Radius = (radius - (radius * chart.holeRadiusPercent)) * valueLinePart1OffsetPercentage + (radius * chart.holeRadiusPercent) } else { line1Radius = radius * valueLinePart1OffsetPercentage } let polyline2Length = dataSet.valueLineVariableLength ? labelRadius * valueLineLength2 * abs(sin(transformedAngle * ChartUtils.Math.FDEG2RAD)) : labelRadius * valueLineLength2; let pt0 = CGPoint( x: line1Radius * sliceXBase + center.x, y: line1Radius * sliceYBase + center.y) let pt1 = CGPoint( x: labelRadius * (1 + valueLineLength1) * sliceXBase + center.x, y: labelRadius * (1 + valueLineLength1) * sliceYBase + center.y) if transformedAngle.truncatingRemainder(dividingBy: 360.0) >= 90.0 && transformedAngle.truncatingRemainder(dividingBy: 360.0) <= 270.0 { pt2 = CGPoint(x: pt1.x - polyline2Length, y: pt1.y) align = .right labelPoint = CGPoint(x: pt2.x - 5, y: pt2.y - lineHeight) } else { pt2 = CGPoint(x: pt1.x + polyline2Length, y: pt1.y) align = .left labelPoint = CGPoint(x: pt2.x + 5, y: pt2.y - lineHeight) } if dataSet.valueLineColor != nil { context.setStrokeColor(dataSet.valueLineColor!.cgColor) context.setLineWidth(dataSet.valueLineWidth); context.move(to: CGPoint(x: pt0.x, y: pt0.y)) context.addLine(to: CGPoint(x: pt1.x, y: pt1.y)) context.addLine(to: CGPoint(x: pt2.x, y: pt2.y)) context.drawPath(using: CGPathDrawingMode.stroke); } if drawXOutside && drawYOutside { ChartUtils.drawText( context: context, text: valueText, point: labelPoint, align: align, attributes: [NSFontAttributeName: valueFont, NSForegroundColorAttributeName: dataSet.valueTextColorAt(j)] ) if (j < data.xValCount && data.xVals[j] != nil) { ChartUtils.drawText( context: context, text: data.xVals[j]!, point: CGPoint(x: labelPoint.x, y: labelPoint.y + lineHeight), align: align, attributes: [NSFontAttributeName: valueFont, NSForegroundColorAttributeName: dataSet.valueTextColorAt(j)] ) } } else if drawXOutside { ChartUtils.drawText( context: context, text: data.xVals[j]!, point: CGPoint(x: labelPoint.x, y: labelPoint.y + lineHeight / 2.0), align: align, attributes: [NSFontAttributeName: valueFont, NSForegroundColorAttributeName: dataSet.valueTextColorAt(j)] ) } else if drawYOutside { ChartUtils.drawText( context: context, text: valueText, point: CGPoint(x: labelPoint.x, y: labelPoint.y + lineHeight / 2.0), align: align, attributes: [NSFontAttributeName: valueFont, NSForegroundColorAttributeName: dataSet.valueTextColorAt(j)] ) } } if drawXInside || drawYInside { // calculate the text position let x = labelRadius * sliceXBase + center.x let y = labelRadius * sliceYBase + center.y - lineHeight if drawXInside && drawYInside { ChartUtils.drawText( context: context, text: valueText, point: CGPoint(x: x, y: y), align: .center, attributes: [NSFontAttributeName: valueFont, NSForegroundColorAttributeName: dataSet.valueTextColorAt(j)] ) if j < data.xValCount && data.xVals[j] != nil { ChartUtils.drawText( context: context, text: data.xVals[j]!, point: CGPoint(x: x, y: y + lineHeight), align: .center, attributes: [NSFontAttributeName: valueFont, NSForegroundColorAttributeName: dataSet.valueTextColorAt(j)] ) } } else if drawXInside { ChartUtils.drawText( context: context, text: data.xVals[j]!, point: CGPoint(x: x, y: y + lineHeight / 2.0), align: .center, attributes: [NSFontAttributeName: valueFont, NSForegroundColorAttributeName: dataSet.valueTextColorAt(j)] ) } else if drawYInside { ChartUtils.drawText( context: context, text: valueText, point: CGPoint(x: x, y: y + lineHeight / 2.0), align: .center, attributes: [NSFontAttributeName: valueFont, NSForegroundColorAttributeName: dataSet.valueTextColorAt(j)] ) } } xIndex += 1 } } } open override func drawExtras(context: CGContext) { drawHole(context: context) drawCenterText(context: context) } /// draws the hole in the center of the chart and the transparent circle / hole private func drawHole(context: CGContext) { guard let chart = chart, let animator = animator else { return } if (chart.drawHoleEnabled) { context.saveGState() let radius = chart.radius let holeRadius = radius * chart.holeRadiusPercent let center = chart.centerCircleBox if let holeColor = chart.holeColor { if holeColor != NSUIColor.clear { // draw the hole-circle context.setFillColor(chart.holeColor!.cgColor) context.fillEllipse(in: CGRect(x: center.x - holeRadius, y: center.y - holeRadius, width: holeRadius * 2.0, height: holeRadius * 2.0)) } } // only draw the circle if it can be seen (not covered by the hole) if let transparentCircleColor = chart.transparentCircleColor { if transparentCircleColor != NSUIColor.clear && chart.transparentCircleRadiusPercent > chart.holeRadiusPercent { let alpha = animator.phaseX * animator.phaseY let secondHoleRadius = radius * chart.transparentCircleRadiusPercent // make transparent context.setAlpha(alpha); context.setFillColor(transparentCircleColor.cgColor) // draw the transparent-circle context.beginPath() context.addEllipse(in: CGRect( x: center.x - secondHoleRadius, y: center.y - secondHoleRadius, width: secondHoleRadius * 2.0, height: secondHoleRadius * 2.0)) context.addEllipse(in: CGRect( x: center.x - holeRadius, y: center.y - holeRadius, width: holeRadius * 2.0, height: holeRadius * 2.0)) context.fillPath(using: .evenOdd) } } context.restoreGState() } } /// draws the description text in the center of the pie chart makes most sense when center-hole is enabled private func drawCenterText(context: CGContext) { guard let chart = chart, let centerAttributedText = chart.centerAttributedText else { return } if chart.drawCenterTextEnabled && centerAttributedText.length > 0 { let center = chart.centerCircleBox let innerRadius = chart.drawHoleEnabled && !chart.drawSlicesUnderHoleEnabled ? chart.radius * chart.holeRadiusPercent : chart.radius let holeRect = CGRect(x: center.x - innerRadius, y: center.y - innerRadius, width: innerRadius * 2.0, height: innerRadius * 2.0) var boundingRect = holeRect if (chart.centerTextRadiusPercent > 0.0) { boundingRect = boundingRect.insetBy(dx: (boundingRect.width - boundingRect.width * chart.centerTextRadiusPercent) / 2.0, dy: (boundingRect.height - boundingRect.height * chart.centerTextRadiusPercent) / 2.0) } let textBounds = centerAttributedText.boundingRect(with: boundingRect.size, options: [.usesLineFragmentOrigin, .usesFontLeading, .truncatesLastVisibleLine], context: nil) var drawingRect = boundingRect drawingRect.origin.x += (boundingRect.size.width - textBounds.size.width) / 2.0 drawingRect.origin.y += (boundingRect.size.height - textBounds.size.height) / 2.0 drawingRect.size = textBounds.size context.saveGState() let clippingPath = CGPath(ellipseIn: holeRect, transform: nil) context.beginPath() context.addPath(clippingPath) context.clip() centerAttributedText.draw(with: drawingRect, options: [.usesLineFragmentOrigin, .usesFontLeading, .truncatesLastVisibleLine], context: nil) context.restoreGState() } } open override func drawHighlighted(context: CGContext, indices: [ChartHighlight]) { guard let chart = chart, let data = chart.data, let animator = animator else { return } context.saveGState() let phaseX = animator.phaseX let phaseY = animator.phaseY var angle: CGFloat = 0.0 let rotationAngle = chart.rotationAngle var drawAngles = chart.drawAngles var absoluteAngles = chart.absoluteAngles let center = chart.centerCircleBox let radius = chart.radius let drawInnerArc = chart.drawHoleEnabled && !chart.drawSlicesUnderHoleEnabled let userInnerRadius = drawInnerArc ? radius * chart.holeRadiusPercent : 0.0 for i in 0 ..< indices.count { // get the index to highlight let xIndex = indices[i].xIndex if (xIndex >= drawAngles.count) { continue } guard let set = data.getDataSetByIndex(indices[i].dataSetIndex) as? IPieChartDataSet else { continue } if !set.highlightEnabled { continue } let entryCount = set.entryCount var visibleAngleCount = 0 for j in 0 ..< entryCount { guard let e = set.entryForIndex(j) else { continue } if ((abs(e.value) > 0.000001)) { visibleAngleCount += 1 } } if (xIndex == 0) { angle = 0.0 } else { angle = absoluteAngles[xIndex - 1] * phaseX } let sliceSpace = visibleAngleCount <= 1 ? 0.0 : set.sliceSpace let sliceAngle = drawAngles[xIndex] var innerRadius = userInnerRadius let shift = set.selectionShift let highlightedRadius = radius + shift let accountForSliceSpacing = sliceSpace > 0.0 && sliceAngle <= 180.0 context.setFillColor(set.colorAt(xIndex).cgColor) let sliceSpaceAngleOuter = visibleAngleCount == 1 ? 0.0 : sliceSpace / (ChartUtils.Math.FDEG2RAD * radius) let sliceSpaceAngleShifted = visibleAngleCount == 1 ? 0.0 : sliceSpace / (ChartUtils.Math.FDEG2RAD * highlightedRadius) let startAngleOuter = rotationAngle + (angle + sliceSpaceAngleOuter / 2.0) * phaseY var sweepAngleOuter = (sliceAngle - sliceSpaceAngleOuter) * phaseY if (sweepAngleOuter < 0.0) { sweepAngleOuter = 0.0 } let startAngleShifted = rotationAngle + (angle + sliceSpaceAngleShifted / 2.0) * phaseY var sweepAngleShifted = (sliceAngle - sliceSpaceAngleShifted) * phaseY if (sweepAngleShifted < 0.0) { sweepAngleShifted = 0.0 } let path = CGMutablePath() path.move(to: CGPoint(x: center.x + highlightedRadius * cos(startAngleShifted * ChartUtils.Math.FDEG2RAD), y: center.y + highlightedRadius * sin(startAngleShifted * ChartUtils.Math.FDEG2RAD))) path.addRelativeArc(center: CGPoint(x: center.x, y: center.y), radius: highlightedRadius, startAngle: startAngleShifted * ChartUtils.Math.FDEG2RAD, delta: sweepAngleShifted * ChartUtils.Math.FDEG2RAD) var sliceSpaceRadius: CGFloat = 0.0 if accountForSliceSpacing { sliceSpaceRadius = calculateMinimumRadiusForSpacedSlice( center: center, radius: radius, angle: sliceAngle * phaseY, arcStartPointX: center.x + radius * cos(startAngleOuter * ChartUtils.Math.FDEG2RAD), arcStartPointY: center.y + radius * sin(startAngleOuter * ChartUtils.Math.FDEG2RAD), startAngle: startAngleOuter, sweepAngle: sweepAngleOuter) } if drawInnerArc && (innerRadius > 0.0 || accountForSliceSpacing) { if accountForSliceSpacing { var minSpacedRadius = sliceSpaceRadius if minSpacedRadius < 0.0 { minSpacedRadius = -minSpacedRadius } innerRadius = min(max(innerRadius, minSpacedRadius), radius) } let sliceSpaceAngleInner = visibleAngleCount == 1 || innerRadius == 0.0 ? 0.0 : sliceSpace / (ChartUtils.Math.FDEG2RAD * innerRadius) let startAngleInner = rotationAngle + (angle + sliceSpaceAngleInner / 2.0) * phaseY var sweepAngleInner = (sliceAngle - sliceSpaceAngleInner) * phaseY if (sweepAngleInner < 0.0) { sweepAngleInner = 0.0 } let endAngleInner = startAngleInner + sweepAngleInner path.addLine(to: CGPoint(x: center.x + innerRadius * cos(endAngleInner * ChartUtils.Math.FDEG2RAD), y: center.y + innerRadius * sin(endAngleInner * ChartUtils.Math.FDEG2RAD))) path.addRelativeArc(center: CGPoint(x: center.x, y: center.y), radius: innerRadius, startAngle: endAngleInner * ChartUtils.Math.FDEG2RAD, delta: -sweepAngleInner * ChartUtils.Math.FDEG2RAD) } else { if accountForSliceSpacing { let angleMiddle = startAngleOuter + sweepAngleOuter / 2.0 let arcEndPointX = center.x + sliceSpaceRadius * cos(angleMiddle * ChartUtils.Math.FDEG2RAD) let arcEndPointY = center.y + sliceSpaceRadius * sin(angleMiddle * ChartUtils.Math.FDEG2RAD) path.addLine(to: CGPoint(x: arcEndPointX, y: arcEndPointY)) } else { path.addLine(to: CGPoint(x: center.x, y: center.y)) } } path.closeSubpath() context.beginPath() context.addPath(path) context.fillPath(using: .evenOdd) } context.restoreGState() } }
mit
rockwotj/shiloh-ranch
ios/shiloh_ranch/shiloh_ranch/Helpers.swift
1
12584
// // Helpers.swift // Shiloh Ranch // // Created by Tyler Rockwood on 6/11/15. // Copyright (c) 2015 Shiloh Ranch Cowboy Church. All rights reserved. // import UIKit func showErrorDialog(error : NSError) { let dialog = UIAlertView(title: "Error!", message: error.localizedDescription, delegate: nil, cancelButtonTitle: "OK") dialog.show() } func showErrorDialog(message : String) { let dialog = UIAlertView(title: "Error!", message: message, delegate: nil, cancelButtonTitle: "OK") dialog.show() } func getApiService() -> GTLServiceShilohranch { let app = UIApplication.sharedApplication().delegate as! AppDelegate return app.service } func getDatabase() -> Database { let app = UIApplication.sharedApplication().delegate as! AppDelegate return app.database } func convertDateToUnixTime(dateString : String) -> Int64 { var timestamp = dateString.stringByReplacingOccurrencesOfString("T", withString: " ") let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SS" if let date = dateFormatter.dateFromString(timestamp) { let lastSync = Int64(date.timeIntervalSince1970 * 1000) return lastSync } else { println("Error converting datetime to unix time: \(timestamp)") return -1 } } func parseDate(dateString : String) -> NSDate? { var timestamp = dateString.stringByReplacingOccurrencesOfString("T", withString: " ") let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SS" if let date = dateFormatter.dateFromString(timestamp) { return date } else { println("Error converting datetime to unix time: \(timestamp)") return nil } } func getTimeFromDate(dateString : String) -> String? { var timestamp = dateString.stringByReplacingOccurrencesOfString("T", withString: " ") let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SS" if let date = dateFormatter.dateFromString(timestamp) { dateFormatter.dateFormat = "hh:mm aa" return dateFormatter.stringFromDate(date) } else { println("Error converting datetime to NSDate: \(timestamp)") return nil } } func prettyFormatDate(dateString : String) -> String? { var timestamp = dateString.stringByReplacingOccurrencesOfString("T", withString: " ") let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SS" if let date = dateFormatter.dateFromString(timestamp) { dateFormatter.dateFormat = "MM/dd/yyyy" return dateFormatter.stringFromDate(date) } else { println("Error converting datetime to NSDate: \(timestamp)") return nil } } func parseDateComponents(dateString : String) -> NSDateComponents? { if let date = parseDate(dateString) { return dateComponents(date) } else { return nil } } func dateComponents(date: NSDate) -> NSDateComponents { return NSCalendar.currentCalendar().components(.DayCalendarUnit | .MonthCalendarUnit | .YearCalendarUnit, fromDate: date) } func getDayOfWeek(dateString: String) -> String? { var timestamp = dateString.stringByReplacingOccurrencesOfString("T", withString: " ") let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SS" if let date = dateFormatter.dateFromString(timestamp) { return getDayOfWeek(date) } else { println("Error converting datetime to NSDate: \(timestamp)") return nil } } func getDayOfWeek(date: NSDate) -> String? { let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "EEEE" return dateFormatter.stringFromDate(date) } extension NSDate { func isGreaterThanDate(dateToCompare : NSDate) -> Bool { //Declare Variables var isGreater = false //Compare Values if self.compare(dateToCompare) == NSComparisonResult.OrderedDescending { isGreater = true } //Return Result return isGreater } func isLessThanDate(dateToCompare : NSDate) -> Bool { //Declare Variables var isLess = false //Compare Values if self.compare(dateToCompare) == NSComparisonResult.OrderedAscending { isLess = true } //Return Result return isLess } func addDays(daysToAdd : Int) -> NSDate { var secondsInDays : NSTimeInterval = Double(daysToAdd) * 60 * 60 * 24 var dateWithDaysAdded : NSDate = self.dateByAddingTimeInterval(secondsInDays) //Return Result return dateWithDaysAdded } func addHours(hoursToAdd : Int) -> NSDate { var secondsInHours : NSTimeInterval = Double(hoursToAdd) * 60 * 60 var dateWithHoursAdded : NSDate = self.dateByAddingTimeInterval(secondsInHours) //Return Result return dateWithHoursAdded } } infix operator ~> {} /** Executes the lefthand closure on a background thread and, upon completion, the righthand closure on the main thread. */ func ~> ( backgroundClosure: () -> (), mainClosure: () -> ()) { dispatch_async(queue) { backgroundClosure() dispatch_async(dispatch_get_main_queue(), mainClosure) } } /** Executes the lefthand closure on a background thread and, upon completion, the righthand closure on the main thread. Passes the background closure's output to the main closure. */ func ~> <R> ( backgroundClosure: () -> R, mainClosure: (result: R) -> ()) { dispatch_async(queue) { let result = backgroundClosure() dispatch_async(dispatch_get_main_queue(), { mainClosure(result: result) }) } } /** Serial dispatch queue used by the ~> operator. */ private let queue = dispatch_queue_create("serial-worker", DISPATCH_QUEUE_SERIAL) extension UIViewController { func setViewWidth(view : UIView, width : CGFloat) { let viewsDictionary = ["view":view] let metricsDictionary = ["viewWidth":width - 16] let constraint:Array = NSLayoutConstraint.constraintsWithVisualFormat("H:[view(viewWidth)]", options: NSLayoutFormatOptions(0), metrics: metricsDictionary, views: viewsDictionary) view.addConstraints(constraint) } } // // FMDB Extensions // // This extension inspired by http://stackoverflow.com/a/24187932/1271826 extension FMDatabase { /// Private generic function used for the variadic renditions of the FMDatabaseAdditions methods /// /// :param: sql The SQL statement to be used. /// :param: values The NSArray of the arguments to be bound to the ? placeholders in the SQL. /// :param: completionHandler The closure to be used to call the appropriate FMDatabase method to return the desired value. /// /// :returns: This returns the T value if value is found. Returns nil if column is NULL or upon error. private func valueForQuery<T>(sql: String, values: [AnyObject]?, completionHandler:(FMResultSet)->(T!)) -> T! { var result: T! if let rs = executeQuery(sql, withArgumentsInArray: values) { if rs.next() { let obj: AnyObject! = rs.objectForColumnIndex(0) if !(obj is NSNull) { result = completionHandler(rs) } } rs.close() } return result } /// This is a rendition of stringForQuery that handles Swift variadic parameters /// for the values to be bound to the ? placeholders in the SQL. /// /// :param: sql The SQL statement to be used. /// :param: values The values to be bound to the ? placeholders /// /// :returns: This returns string value if value is found. Returns nil if column is NULL or upon error. func stringForQuery(sql: String, _ values: AnyObject...) -> String! { return valueForQuery(sql, values: values) { $0.stringForColumnIndex(0) } } /// This is a rendition of intForQuery that handles Swift variadic parameters /// for the values to be bound to the ? placeholders in the SQL. /// /// :param: sql The SQL statement to be used. /// :param: values The values to be bound to the ? placeholders /// /// :returns: This returns integer value if value is found. Returns nil if column is NULL or upon error. func intForQuery(sql: String, _ values: AnyObject...) -> Int32! { return valueForQuery(sql, values: values) { $0.intForColumnIndex(0) } } /// This is a rendition of longForQuery that handles Swift variadic parameters /// for the values to be bound to the ? placeholders in the SQL. /// /// :param: sql The SQL statement to be used. /// :param: values The values to be bound to the ? placeholders /// /// :returns: This returns long value if value is found. Returns nil if column is NULL or upon error. func longForQuery(sql: String, _ values: AnyObject...) -> Int! { return valueForQuery(sql, values: values) { $0.longForColumnIndex(0) } } /// This is a rendition of boolForQuery that handles Swift variadic parameters /// for the values to be bound to the ? placeholders in the SQL. /// /// :param: sql The SQL statement to be used. /// :param: values The values to be bound to the ? placeholders /// /// :returns: This returns Bool value if value is found. Returns nil if column is NULL or upon error. func boolForQuery(sql: String, _ values: AnyObject...) -> Bool! { return valueForQuery(sql, values: values) { $0.boolForColumnIndex(0) } } /// This is a rendition of doubleForQuery that handles Swift variadic parameters /// for the values to be bound to the ? placeholders in the SQL. /// /// :param: sql The SQL statement to be used. /// :param: values The values to be bound to the ? placeholders /// /// :returns: This returns Double value if value is found. Returns nil if column is NULL or upon error. func doubleForQuery(sql: String, _ values: AnyObject...) -> Double! { return valueForQuery(sql, values: values) { $0.doubleForColumnIndex(0) } } /// This is a rendition of dateForQuery that handles Swift variadic parameters /// for the values to be bound to the ? placeholders in the SQL. /// /// :param: sql The SQL statement to be used. /// :param: values The values to be bound to the ? placeholders /// /// :returns: This returns NSDate value if value is found. Returns nil if column is NULL or upon error. func dateForQuery(sql: String, _ values: AnyObject...) -> NSDate! { return valueForQuery(sql, values: values) { $0.dateForColumnIndex(0) } } /// This is a rendition of dataForQuery that handles Swift variadic parameters /// for the values to be bound to the ? placeholders in the SQL. /// /// :param: sql The SQL statement to be used. /// :param: values The values to be bound to the ? placeholders /// /// :returns: This returns NSData value if value is found. Returns nil if column is NULL or upon error. func dataForQuery(sql: String, _ values: AnyObject...) -> NSData! { return valueForQuery(sql, values: values) { $0.dataForColumnIndex(0) } } /// This is a rendition of executeQuery that handles Swift variadic parameters /// for the values to be bound to the ? placeholders in the SQL. /// /// :param: sql The SQL statement to be used. /// :param: values The values to be bound to the ? placeholders /// /// :returns: This returns FMResultSet if successful. Returns nil upon error. func executeQuery(sql:String, _ values: AnyObject...) -> FMResultSet? { return executeQuery(sql, withArgumentsInArray: values as [AnyObject]); } /// This is a rendition of executeUpdate that handles Swift variadic parameters /// for the values to be bound to the ? placeholders in the SQL. /// /// :param: sql The SQL statement to be used. /// :param: values The values to be bound to the ? placeholders /// /// :returns: This returns true if successful. Returns false upon error. func executeUpdate(sql:String, _ values: AnyObject...) -> Bool { return executeUpdate(sql, withArgumentsInArray: values as [AnyObject]); } }
mit
Acidburn0zzz/firefox-ios
RustFxA/PushNotificationSetup.swift
1
2061
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Shared import SwiftKeychainWrapper import MozillaAppServices open class PushNotificationSetup { private var pushClient: PushClient? private var pushRegistration: PushRegistration? public func didRegister(withDeviceToken deviceToken: Data) { // If we've already registered this push subscription, we don't need to do it again. let apnsToken = deviceToken.hexEncodedString let keychain = KeychainWrapper.sharedAppContainerKeychain guard keychain.string(forKey: KeychainKey.apnsToken, withAccessibility: .afterFirstUnlock) != apnsToken else { return } RustFirefoxAccounts.shared.accountManager.uponQueue(.main) { accountManager in let config = PushConfigurationLabel(rawValue: AppConstants.scheme)!.toConfiguration() self.pushClient = PushClient(endpointURL: config.endpointURL, experimentalMode: false) self.pushClient?.register(apnsToken).uponQueue(.main) { [weak self] result in guard let pushReg = result.successValue else { return } self?.pushRegistration = pushReg keychain.set(apnsToken, forKey: KeychainKey.apnsToken, withAccessibility: .afterFirstUnlock) let subscription = pushReg.defaultSubscription let devicePush = DevicePushSubscription(endpoint: subscription.endpoint.absoluteString, publicKey: subscription.p256dhPublicKey, authKey: subscription.authKey) accountManager.deviceConstellation()?.setDevicePushSubscription(sub: devicePush) keychain.set(pushReg as NSCoding, forKey: KeychainKey.fxaPushRegistration, withAccessibility: .afterFirstUnlock) } } } public func unregister() { if let reg = pushRegistration { _ = pushClient?.unregister(reg) } } }
mpl-2.0
caronae/caronae-ios
Caronae/Categories/UIViewController+isVisible.swift
1
142
extension UIViewController { public func isVisible() -> Bool { return self.isViewLoaded && (self.view.window != nil) } }
gpl-3.0
kingslay/KSSwiftExtension
Core/Source/Extension/UIWindow.swift
1
512
// // UIWindow.swift // PolyGe // // Created by king on 15/6/27. // Copyright © 2015年 king. All rights reserved. // import UIKit extension Swifty where Base: UIWindow { static public func topWindow() -> UIWindow { //有inputView或者键盘时,避免提示被挡住,应该选择这个 UITextEffectsWindow 来显示 return UIApplication.sharedApplication().windows.filter{ $0.ks.className() == "UITextEffectsWindow" }.first ?? UIApplication.sharedApplication().keyWindow! } }
mit
manavgabhawala/CocoaMultipeer
iOS/ViewController.swift
1
2161
// // ViewController.swift // iOS // // Created by Manav Gabhawala on 13/07/15. // // import UIKit import MultipeerCocoaiOS class ViewController: UIViewController { var session : MGSession! var browser: MGNearbyServiceBrowser! @IBOutlet var textView : UITextView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. let peer = MGPeerID(displayName: UIDevice.currentDevice().name) session = MGSession(peer: peer) session.delegate = self browser = MGNearbyServiceBrowser(peer: peer, serviceType: "peer-demo") textView.delegate = self } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) if session.connectedPeers.count == 0 { displayPicker() } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } private func displayPicker() { let browserVC = MGBrowserViewController(browser: browser, session: session) presentViewController(browserVC, animated: true, completion: nil) } } extension ViewController : MGSessionDelegate { func session(session: MGSession, peer peerID: MGPeerID, didChangeState state: MGSessionState) { print("State of connection to \(peerID) is \(state)") if session.connectedPeers.count == 0 { displayPicker() } } func session(session: MGSession, didReceiveData data: NSData, fromPeer peerID: MGPeerID) { guard let recievedText = NSString(data: data, encoding: NSUTF8StringEncoding) else { print("Could not parse data \(data)") return } textView.text = "\(textView.text)\n\(recievedText)" } } extension ViewController : UITextViewDelegate { func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool { if text == "\n" { guard let stringToSend = textView.text?.componentsSeparatedByString("\n").last else { return true } do { try session.sendData(stringToSend.dataUsingEncoding(NSUTF8StringEncoding)!, toPeers: session.connectedPeers) } catch { print(error) } } return true } }
apache-2.0
fgengine/quickly
Quickly/Views/Image/QImageCache.swift
1
4824
// // Quickly // public class QImageCache { public private(set) var name: String public private(set) var memory: [String: UIImage] public private(set) var url: URL private var _fileManager: FileManager private var _queue: DispatchQueue public init(name: String) throws { self.name = name self.memory = [:] self._fileManager = FileManager.default self._queue = DispatchQueue(label: name) if let cachePath = self._fileManager.urls(for: .cachesDirectory, in: .userDomainMask).first { self.url = cachePath } else { self.url = URL(fileURLWithPath: NSHomeDirectory()) } self.url.appendPathComponent(name) if self._fileManager.fileExists(atPath: self.url.path) == false { try self._fileManager.createDirectory(at: self.url, withIntermediateDirectories: true, attributes: nil) } NotificationCenter.default.addObserver(self, selector: #selector(self._didReceiveMemoryWarning(_:)), name: UIApplication.didReceiveMemoryWarningNotification, object: nil) } deinit { NotificationCenter.default.removeObserver(self) } public func isExist(url: URL, filter: IQImageLoaderFilter? = nil) -> Bool { guard let key = self._key(url: url, filter: filter) else { return false } let memoryImage = self._queue.sync(execute: { return self.memory[key] }) if memoryImage != nil { return true } let url = self.url.appendingPathComponent(key) return self._fileManager.fileExists(atPath: url.path) } public func image(url: URL, filter: IQImageLoaderFilter? = nil) -> UIImage? { guard let key = self._key(url: url, filter: filter) else { return nil } let memoryImage = self._queue.sync(execute: { return self.memory[key] }) if let image = memoryImage { return image } let url = self.url.appendingPathComponent(key) if let image = UIImage(contentsOfFile: url.path) { self._queue.sync(execute: { self.memory[key] = image }) return image } return nil } public func set(data: Data, image: UIImage, url: URL, filter: IQImageLoaderFilter? = nil) throws { guard let key = self._key(url: url, filter: filter) else { return } let url = self.url.appendingPathComponent(key) do { try data.write(to: url, options: .atomic) self._queue.sync(execute: { self.memory[key] = image }) } catch let error { throw error } } public func remove(url: URL, filter: IQImageLoaderFilter? = nil) throws { guard let key = self._key(url: url, filter: filter) else { return } self._queue.sync(execute: { _ = self.memory.removeValue(forKey: key) }) let url = self.url.appendingPathComponent(key) if self._fileManager.fileExists(atPath: url.path) == true { do { try self._fileManager.removeItem(at: url) } catch let error { throw error } } } public func cleanup(before: TimeInterval) { self._queue.sync(execute: { self.memory.removeAll() }) let now = Date() if let urls = try? self._fileManager.contentsOfDirectory(at: self.url, includingPropertiesForKeys: nil, options: [ .skipsHiddenFiles ]) { for url in urls { guard let attributes = try? self._fileManager.attributesOfItem(atPath: url.path), let modificationDate = attributes[FileAttributeKey.modificationDate] as? Date else { continue } let delta = now.timeIntervalSince1970 - modificationDate.timeIntervalSince1970 if delta > before { try? self._fileManager.removeItem(at: url) } } } } @objc private func _didReceiveMemoryWarning(_ notification: NSNotification) { self._queue.sync(execute: { self.memory.removeAll() }) } } private extension QImageCache { func _key(url: URL, filter: IQImageLoaderFilter?) -> String? { var unique: String var path: String if url.isFileURL == true { path = url.lastPathComponent } else { path = url.absoluteString } if let filter = filter { unique = "{\(filter.name)}{\(path)}" } else { unique = path } if let key = unique.sha256 { return key } return nil } }
mit
ps2/rileylink_ios
MinimedKit/Messages/Models/GlucoseEventType.swift
1
2092
// // GlucoseEventType.swift // RileyLink // // Created by Timothy Mecklem on 10/16/16. // Copyright © 2016 Pete Schwamb. All rights reserved. // import Foundation public enum GlucoseEventType: UInt8 { case dataEnd = 0x01 case sensorWeakSignal = 0x02 case sensorCal = 0x03 case sensorPacket = 0x04 case sensorError = 0x05 case sensorDataLow = 0x06 case sensorDataHigh = 0x07 case sensorTimestamp = 0x08 case batteryChange = 0x0a case sensorStatus = 0x0b case dateTimeChange = 0x0c case sensorSync = 0x0d case calBGForGH = 0x0e case sensorCalFactor = 0x0f case tenSomething = 0x10 case nineteenSomething = 0x13 public var eventType: GlucoseEvent.Type { switch self { case .dataEnd: return DataEndGlucoseEvent.self case .sensorWeakSignal: return SensorWeakSignalGlucoseEvent.self case .sensorCal: return SensorCalGlucoseEvent.self case .sensorPacket: return SensorPacketGlucoseEvent.self case .sensorError: return SensorErrorGlucoseEvent.self case .sensorDataLow: return SensorDataLowGlucoseEvent.self case .sensorDataHigh: return SensorDataHighGlucoseEvent.self case .sensorTimestamp: return SensorTimestampGlucoseEvent.self case .batteryChange: return BatteryChangeGlucoseEvent.self case .sensorStatus: return SensorStatusGlucoseEvent.self case .dateTimeChange: return DateTimeChangeGlucoseEvent.self case .sensorSync: return SensorSyncGlucoseEvent.self case .calBGForGH: return CalBGForGHGlucoseEvent.self case .sensorCalFactor: return SensorCalFactorGlucoseEvent.self case .tenSomething: return TenSomethingGlucoseEvent.self case .nineteenSomething: return NineteenSomethingGlucoseEvent.self } } }
mit
ps2/rileylink_ios
MinimedKit/Messages/BolusCarelinkMessageBody.swift
1
1118
// // BolusCarelinkMessageBody.swift // Naterade // // Created by Nathan Racklyeft on 3/5/16. // Copyright © 2016 Nathan Racklyeft. All rights reserved. // import Foundation public class BolusCarelinkMessageBody: CarelinkLongMessageBody { public convenience init(units: Double, insulinBitPackingScale: Int = 10) { let length: Int let scrollRate: Int if insulinBitPackingScale >= 40 { length = 2 // 40-stroke pumps scroll faster for higher unit values switch units { case let u where u > 10: scrollRate = 4 case let u where u > 1: scrollRate = 2 default: scrollRate = 1 } } else { length = 1 scrollRate = 1 } let strokes = Int(units * Double(insulinBitPackingScale / scrollRate)) * scrollRate let data = Data(hexadecimalString: String(format: "%02x%0\(2 * length)x", length, strokes))! self.init(rxData: data)! } }
mit
erinshihshih/ETripTogether
ETripTogether/HomeTableViewCell.swift
2
400
// // HomeTableViewCell.swift // ETrip // // Created by Erin Shih on 2016/9/29. // Copyright © 2016年 Erin Shih. All rights reserved. // import UIKit class HomeTableViewCell: UITableViewCell { @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var countryLabel: UILabel! @IBOutlet weak var startDateLabel: UILabel! @IBOutlet weak var returnDateLabel: UILabel! }
mit
cubixlabs/SocialGIST
Pods/GISTFramework/GISTFramework/Classes/Controls/FloatingLabelTextField.swift
1
18936
// // FloatingLabelTextField.swift // GISTFramework // // Created by Shoaib Abdul on 14/03/2017. // Copyright © 2017 Social Cubix. All rights reserved. // import UIKit open class FloatingLabelTextField: ValidatedTextField { // MARK: Animation timing /// The value of the title appearing duration open var titleFadeInDuration:TimeInterval = 0.2 /// The value of the title disappearing duration open var titleFadeOutDuration:TimeInterval = 0.3 // MARK: Title /// The String to display when the textfield is not editing and the input is not empty. @IBInspectable open var title:String? { didSet { self.updateControl(); } } //P.E. /// The String to display when the textfield is editing and the input is not empty. @IBInspectable open var titleSelected:String? { didSet { self.updateControl(); } } //P.E. // MARK: Font Style /// Font size/style key from Sync Engine. @IBInspectable open var titleFontStyle:String = GIST_CONFIG.fontStyle { didSet { self.titleLabel.fontStyle = self.titleFontStyle; } } //P.E. // MARK: Colors /// A UIColor value that determines the text color of the title label when in the normal state @IBInspectable open var titleColor:String? { didSet { self.updateTitleColor(); } } /// A UIColor value that determines the text color of the title label when editing @IBInspectable open var titleColorSelected:String? { didSet { self.updateTitleColor(); } } /// A UIColor value that determines the color of the bottom line when in the normal state @IBInspectable open var lineColor:String? { didSet { self.updateLineView(); } } /// A UIColor value that determines the color of the line in a selected state @IBInspectable open var lineColorSelected:String? { didSet { self.updateLineView(); } } //P.E. /// A UIColor value that determines the color used for the title label and the line when the error message is not `nil` @IBInspectable open var errorColor:String? { didSet { self.updateColors(); } } //P.E. // MARK: Title Case /// Flag for upper case formatting @IBInspectable open var uppercaseTitle:Bool = false { didSet { self.updateControl(); } } // MARK: Line height /// A CGFloat value that determines the height for the bottom line when the control is in the normal state @IBInspectable open var lineHeight:CGFloat = 0.5 { didSet { self.updateLineView(); self.setNeedsDisplay(); } } //P.E. /// A CGFloat value that determines the height for the bottom line when the control is in a selected state @IBInspectable open var lineHeightSelected:CGFloat = 1.0 { didSet { self.updateLineView(); self.setNeedsDisplay(); } } // MARK: View components /// The internal `UIView` to display the line below the text input. open var lineView:UIView! /// The internal `UILabel` that displays the selected, deselected title or the error message based on the current state. open var titleLabel:BaseUILabel! // MARK: Properties /** Identifies whether the text object should hide the text being entered. */ override open var isSecureTextEntry:Bool { set { super.isSecureTextEntry = newValue; self.fixCaretPosition(); } get { return super.isSecureTextEntry; } } /// A String value for the error message to display. private var errorMessage:String? { didSet { self.updateControl(true); } } /// The backing property for the highlighted property fileprivate var _highlighted = false; /// A Boolean value that determines whether the receiver is highlighted. When changing this value, highlighting will be done with animation override open var isHighlighted:Bool { get { return _highlighted } set { _highlighted = newValue; self.updateTitleColor(); self.updateLineView(); } } /// A Boolean value that determines whether the textfield is being edited or is selected. open var editingOrSelected:Bool { get { return super.isEditing || self.isSelected; } } /// A Boolean value that determines whether the receiver has an error message. open var hasErrorMessage:Bool { get { return self.errorMessage != nil && self.errorMessage != ""; } } //P.E. fileprivate var _renderingInInterfaceBuilder:Bool = false /// The text content of the textfield override open var text:String? { didSet { self.updateControl(false); } } /** The String to display when the input field is empty. The placeholder can also appear in the title label when both `title` `selectedTitle` and are `nil`. */ override open var placeholder:String? { didSet { self.setNeedsDisplay(); self.updateTitleLabel(); } } // Determines whether the field is selected. When selected, the title floats above the textbox. open override var isSelected:Bool { didSet { self.updateControl(true); } } override open var fontName: String { didSet { self.titleLabel.fontName = self.fontName; } } // P.E. // MARK: - Initializers /** Initializes the control - parameter frame the frame of the control */ override public init(frame: CGRect) { super.init(frame: frame) self.setupFloatingLabel(); } /** Intialzies the control by deserializing it - parameter coder the object to deserialize the control from */ required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder); self.setupFloatingLabel(); } // MARK: - Overridden Methods /// Overridden property to get text changes. /// /// - Parameter textField: UITextField open override func textFieldDidEndEditing(_ textField: UITextField) { super.textFieldDidEndEditing(textField); self.errorMessage = (self.isValid == false) ? self.validityMsg:nil; } //F.E. // MARK: - Methods fileprivate final func setupFloatingLabel() { self.borderStyle = .none; self.createTitleLabel(); self.createLineView(); self.updateColors(); self.addEditingChangedObserver(); } fileprivate func addEditingChangedObserver() { self.addTarget(self, action: #selector(editingChanged), for: .editingChanged) } /** Invoked when the editing state of the textfield changes. Override to respond to this change. */ open func editingChanged() { self.updateControl(true); self.updateTitleLabel(true); } /** The formatter to use before displaying content in the title label. This can be the `title`, `selectedTitle` or the `errorMessage`. The default implementation converts the text to uppercase. */ private func titleFormatter(_ txt:String) -> String { let rtnTxt:String = SyncedText.text(forKey: txt); return (self.uppercaseTitle == true) ? rtnTxt.uppercased():rtnTxt; } //F.E. // MARK: create components private func createTitleLabel() { let titleLabel = BaseUILabel() titleLabel.autoresizingMask = [.flexibleWidth, .flexibleHeight] titleLabel.fontName = self.fontName; titleLabel.alpha = 0.0 self.addSubview(titleLabel) self.titleLabel = titleLabel } private func createLineView() { if self.lineView == nil { let lineView = UIView() lineView.isUserInteractionEnabled = false; self.lineView = lineView self.configureDefaultLineHeight() } lineView.autoresizingMask = [.flexibleWidth, .flexibleTopMargin] self.addSubview(lineView) } private func configureDefaultLineHeight() { let onePixel:CGFloat = 1.0 / UIScreen.main.scale self.lineHeight = 2.0 * onePixel self.lineHeightSelected = 2.0 * self.lineHeight } // MARK: Responder handling /** Attempt the control to become the first responder - returns: True when successfull becoming the first responder */ @discardableResult override open func becomeFirstResponder() -> Bool { let result = super.becomeFirstResponder() self.updateControl(true) return result } /** Attempt the control to resign being the first responder - returns: True when successfull resigning being the first responder */ @discardableResult override open func resignFirstResponder() -> Bool { let result = super.resignFirstResponder() self.updateControl(true) return result } // MARK: - View updates private func updateControl(_ animated:Bool = false) { self.updateColors() self.updateLineView() self.updateTitleLabel(animated) } private func updateLineView() { if let lineView = self.lineView { lineView.frame = self.lineViewRectForBounds(self.bounds, editing: self.editingOrSelected) } self.updateLineColor() } // MARK: - Color updates /// Update the colors for the control. Override to customize colors. open func updateColors() { self.updateLineColor() self.updateTitleColor() self.updateTextColor() } private func updateLineColor() { if self.hasErrorMessage { self.lineView.backgroundColor = UIColor.color(forKey: self.errorColor) ?? UIColor.red; } else { self.lineView.backgroundColor = UIColor.color(forKey: (self.editingOrSelected && self.lineColorSelected != nil) ? (self.lineColorSelected) : self.lineColor); } } private func updateTitleColor() { if self.hasErrorMessage { self.titleLabel.textColor = UIColor.color(forKey: self.errorColor) ?? UIColor.red; } else { if ((self.editingOrSelected || self.isHighlighted) && self.titleColorSelected != nil) { self.titleLabel.textColor = UIColor.color(forKey: self.titleColorSelected); } else { self.titleLabel.textColor = UIColor.color(forKey: self.titleColor); } } } private func updateTextColor() { if self.hasErrorMessage { super.textColor = UIColor.color(forKey: self.errorColor); } else { super.textColor = UIColor.color(forKey: self.fontColorStyle); } } // MARK: - Title handling private func updateTitleLabel(_ animated:Bool = false) { var titleText:String? = nil if self.hasErrorMessage { titleText = self.titleFormatter(self.validityMsg!) } else { if self.editingOrSelected { titleText = self.selectedTitleOrTitlePlaceholder() if titleText == nil { titleText = self.titleOrPlaceholder() } } else { titleText = self.titleOrPlaceholder() } } self.titleLabel.text = titleText self.updateTitleVisibility(animated) } private var _titleVisible = false /* * Set this value to make the title visible */ open func setTitleVisible(_ titleVisible:Bool, animated:Bool = false, animationCompletion: ((_ completed: Bool) -> Void)? = nil) { if(_titleVisible == titleVisible) { return } _titleVisible = titleVisible self.updateTitleColor() self.updateTitleVisibility(animated, completion: animationCompletion) } /** Returns whether the title is being displayed on the control. - returns: True if the title is displayed on the control, false otherwise. */ open func isTitleVisible() -> Bool { return self.hasText || self.hasErrorMessage || _titleVisible } fileprivate func updateTitleVisibility(_ animated:Bool = false, completion: ((_ completed: Bool) -> Void)? = nil) { let alpha:CGFloat = self.isTitleVisible() ? 1.0 : 0.0 let frame:CGRect = self.titleLabelRectForBounds(self.bounds, editing: self.isTitleVisible()) let updateBlock = { () -> Void in self.titleLabel.alpha = alpha self.titleLabel.frame = frame } if animated { let animationOptions:UIViewAnimationOptions = .curveEaseOut; let duration = self.isTitleVisible() ? titleFadeInDuration : titleFadeOutDuration UIView.animate(withDuration: duration, delay: 0, options: animationOptions, animations: { () -> Void in updateBlock() }, completion: completion) } else { updateBlock() completion?(true) } } // MARK: - UITextField text/placeholder positioning overrides /** Calculate the rectangle for the textfield when it is not being edited - parameter bounds: The current bounds of the field - returns: The rectangle that the textfield should render in */ override open func textRect(forBounds bounds: CGRect) -> CGRect { _ = super.textRect(forBounds: bounds); let titleHeight = self.titleHeight() let lineHeight = self.lineHeightSelected let rect = CGRect(x: 0, y: titleHeight, width: bounds.size.width, height: bounds.size.height - titleHeight - lineHeight) return rect } /** Calculate the rectangle for the textfield when it is being edited - parameter bounds: The current bounds of the field - returns: The rectangle that the textfield should render in */ override open func editingRect(forBounds bounds: CGRect) -> CGRect { let titleHeight = self.titleHeight() let lineHeight = self.lineHeightSelected let rect = CGRect(x: 0, y: titleHeight, width: bounds.size.width, height: bounds.size.height - titleHeight - lineHeight) return rect } /** Calculate the rectangle for the placeholder - parameter bounds: The current bounds of the placeholder - returns: The rectangle that the placeholder should render in */ override open func placeholderRect(forBounds bounds: CGRect) -> CGRect { let titleHeight = self.titleHeight() let lineHeight = self.lineHeightSelected let rect = CGRect(x: 0, y: titleHeight, width: bounds.size.width, height: bounds.size.height - titleHeight - lineHeight) return rect } // MARK: - Positioning Overrides /** Calculate the bounds for the title label. Override to create a custom size title field. - parameter bounds: The current bounds of the title - parameter editing: True if the control is selected or highlighted - returns: The rectangle that the title label should render in */ open func titleLabelRectForBounds(_ bounds:CGRect, editing:Bool) -> CGRect { let titleHeight = self.titleHeight() if editing { return CGRect(x: 0, y: 0, width: bounds.size.width, height: titleHeight) } return CGRect(x: 0, y: titleHeight, width: bounds.size.width, height: titleHeight) } /** Calculate the bounds for the bottom line of the control. Override to create a custom size bottom line in the textbox. - parameter bounds: The current bounds of the line - parameter editing: True if the control is selected or highlighted - returns: The rectangle that the line bar should render in */ open func lineViewRectForBounds(_ bounds:CGRect, editing:Bool) -> CGRect { let lineHeight:CGFloat = editing ? CGFloat(self.lineHeightSelected) : CGFloat(self.lineHeight) return CGRect(x: 0, y: bounds.size.height - lineHeight, width: bounds.size.width, height: lineHeight); } /** Calculate the height of the title label. -returns: the calculated height of the title label. Override to size the title with a different height */ open func titleHeight() -> CGFloat { if let titleLabel = self.titleLabel, let font = titleLabel.font { return font.lineHeight } return 15.0 } /** Calcualte the height of the textfield. -returns: the calculated height of the textfield. Override to size the textfield with a different height */ open func textHeight() -> CGFloat { return self.font!.lineHeight + 7.0 } // MARK: - Layout /// Invoked when the interface builder renders the control override open func prepareForInterfaceBuilder() { if #available(iOS 8.0, *) { super.prepareForInterfaceBuilder() } self.borderStyle = .none self.isSelected = true _renderingInInterfaceBuilder = true self.updateControl(false) self.invalidateIntrinsicContentSize() } /// Invoked by layoutIfNeeded automatically override open func layoutSubviews() { super.layoutSubviews() self.titleLabel.frame = self.titleLabelRectForBounds(self.bounds, editing: self.isTitleVisible() || _renderingInInterfaceBuilder) self.lineView.frame = self.lineViewRectForBounds(self.bounds, editing: self.editingOrSelected || _renderingInInterfaceBuilder) } /** Calculate the content size for auto layout - returns: the content size to be used for auto layout */ override open var intrinsicContentSize : CGSize { return CGSize(width: self.bounds.size.width, height: self.titleHeight() + self.textHeight()) } // MARK: - Helpers fileprivate func titleOrPlaceholder() -> String? { if let title = self.title ?? self.placeholder { return self.titleFormatter(title) } return nil } fileprivate func selectedTitleOrTitlePlaceholder() -> String? { if let title = self.titleSelected ?? self.title ?? self.placeholder { return self.titleFormatter(title) } return nil } } //CLS END
gpl-3.0
gaurav1981/eidolon
KioskTests/Models/BidderPositionTests.swift
7
842
import Quick import Nimble @testable import Kiosk class BidderPositionTests: QuickSpec { override func spec() { it("converts from JSON") { let id = "saf32sadasd" let maxBidAmountCents = 123123123 let bidID = "saf32sadasd" let bidAmount = 100000 let bidData:[String: AnyObject] = ["id": bidID, "amount_cents" : bidAmount ] let data:[String: AnyObject] = ["id":id , "max_bid_amount_cents" : maxBidAmountCents, "highest_bid":bidData] let position = BidderPosition.fromJSON(data) as! BidderPosition expect(position.id) == id expect(position.maxBidAmountCents) == maxBidAmountCents expect(position.highestBid!.id) == bidID expect(position.highestBid!.amountCents) == bidAmount } } }
mit
roothybrid7/SharedKit
Sources/SharedKit/Views/ViewHitTestable.swift
1
788
// // ViewHitTestable.swift // SharedKit // // Created by SATOSHI OHKI on 1/23/17. // // import Foundation #if os(iOS) || os(tvOS) import UIKit #elseif os(macOS) import AppKit #endif @available(iOS 8, macOS 10.7, tvOS 9, *) public protocol ViewHitTestable { var isHittable: Bool { get } } #if os(iOS) || os(tvOS) @available(iOS 8, tvOS 9, *) extension UIView: ViewHitTestable { public var isVisible: Bool { return !isHidden && alpha > 0.01 } public var isHittable: Bool { return isUserInteractionEnabled && isVisible } } #elseif os(macOS) @available(macOS 10.7, *) extension NSView: ViewHitTestable { public var isHittable: Bool { return !isHidden } } #endif
mit
xiankuncheng/ContactList
ContactListUITests/ContactListUITests.swift
1
1329
// // ContactListUITests.swift // ContactListUITests // // Created by XiankunCheng on 25/07/17. // Copyright © 2017 Xiankun Cheng. All rights reserved. // import XCTest class ContactListUITests: XCTestCase { override func setUp() { super.setUp() continueAfterFailure = false XCUIApplication().launch() } override func tearDown() { super.tearDown() } func testMainUIFlow() { XCUIDevice.shared().orientation = .portrait XCUIDevice.shared().orientation = .landscapeLeft XCUIDevice.shared().orientation = .portrait let app = XCUIApplication() app.tables.children(matching: .cell).matching(identifier: "listContactCell").element(boundBy: 0).staticTexts["emailLabel"].tap() XCUIDevice.shared().orientation = .landscapeLeft XCUIDevice.shared().orientation = .portrait XCUIDevice.shared().orientation = .portrait let backBtn = app.navigationBars.buttons["Contacts"] // Plus devices will go back to ContactsList View, thus don't have backBtn if backBtn.exists { backBtn.tap() } let refreshButton = app.navigationBars["Contacts"].buttons["Refresh"] refreshButton.tap() refreshButton.tap() } }
mit
DanielOrmeno/PeriodicLocation
src/ios/DataManager.swift
1
11353
/******************************************************************************************************************* | File: DataManager.swift | Proyect: swiftLocations cordova plugin | | Description: - DataManager class. Manages the location records in memory through the NSUserDefaults. It handles | the location updates received by the LocationManager and stores them in memory based on a set of rules. | | Only 32 records are stored in memory at all times (4 records per hour for 8 hours). Location records are based | on the LocationData class, see plugin ios project setup instructions for more information. *******************************************************************************************************************/ import CoreData import UIKit import CoreLocation class DataManager { // ===================================== INSTANCE VARIABLES / PROPERTIES =============================// //- MaxNumber of records allowed var MaxNoOfRecords:Int = 10 //- Date Format let DATEFORMAT = "dd-MM-yyyy, HH:mm:ss" //- Class keys let LocationRecords_Key = "LOCATION_RECORDS" let LocationData_Key = "LOCATION_DATA" //- Array of LocationData encoded objects var locationRecords : NSArray? //- User Defaults let UserDefaults: NSUserDefaults = NSUserDefaults.standardUserDefaults() // ===================================== CLASS CONSTRUCTORS =========================================// init () {} // ===================================== Accessors & Mutators =================================================// func setNumberOfRecords(numberOfRecords: Int){self.MaxNoOfRecords = numberOfRecords} func getNumberOfRecords() -> Int {return self.MaxNoOfRecords} // ===================================== CLASS METHODS ===================================================// /******************************************************************************************************************** METHOD NAME: savelocationRecords INPUT PARAMETERS: array of LocationData Objects RETURNS: None OBSERVATIONS: Saves an array of LocationData as a NSArray of NSData objects in the NSUserDefaults by deleting old instance and saving array from argument. ********************************************************************************************************************/ func saveLocationRecords (records: [LocationData]) { //- Create NSArray of NSData var NSDataArray: [NSData] = [] //- Populate NSDataArray for eachRecord in records { //- Convert LocationData to NSData let Data = NSKeyedArchiver.archivedDataWithRootObject(eachRecord) NSDataArray.append(Data) } //- NSArray to comply with NSUserDefaults self.locationRecords = NSArray(array: NSDataArray) //- Update old array from UserDefaults self.UserDefaults.removeObjectForKey(LocationRecords_Key) self.UserDefaults.setObject(self.locationRecords, forKey: LocationRecords_Key) self.UserDefaults.synchronize() } /******************************************************************************************************************** METHOD NAME: getUpdatedRecords INPUT PARAMETERS: NONE RETURNS: Array of LOcationData records OBSERVATIONS: Gets NSArray of NSData objects from NSUserDefaults and returns them as an array of LocationData objects ********************************************************************************************************************/ func getUpdatedRecords () -> [LocationData]? { // - Fetch all Records in memoryif if let RECORDS: [NSData] = self.UserDefaults.arrayForKey(LocationRecords_Key) as? [NSData] { //- Empty array of LocationData objects var locationRecords = [LocationData]() for eachRecord in RECORDS { //- Convert from NSData back to LocationData object let newRecord = NSKeyedUnarchiver.unarchiveObjectWithData(eachRecord) as! LocationData //- Append Record locationRecords.append(newRecord) } //- Sort Location Records locationRecords.sortInPlace({ $0.timestamp.compare($1.timestamp) == NSComparisonResult.OrderedAscending}) //- Return records if any, if not return nil return locationRecords } else { return nil } } /******************************************************************************************************************** METHOD NAME: deleteOldestLocationRecord INPUT PARAMETERS: None RETURNS: None OBSERVATIONS: Gets [LocationData] from NSUserDefaults through the getUpdatedRecords method, deletes oldest record and saves array to memory through the savelocationRecords method ********************************************************************************************************************/ func deleteOldestLocationRecord() { //- Fetch records from memory and store on mutable array var sortedRecords = [LocationData]() if let fetchedRecords = self.getUpdatedRecords() { //- Array needs to be mutable sortedRecords = fetchedRecords //- Delete Oldest Record sortedRecords.removeAtIndex(0) self.saveLocationRecords(sortedRecords) } } /******************************************************************************************************************** METHOD NAME: getLastRecord INPUT PARAMETERS: None RETURNS: LocationData object OBSERVATIONS: Gets [LocationData] from NSUserDefaults through the getUpdatedRecords method, and returns the newest record if any ********************************************************************************************************************/ func getLastRecord() -> LocationData? { //- Fetch records from memory and return newest if let fetchedRecords = self.getUpdatedRecords() { let newestRecord = fetchedRecords.last return newestRecord } else { return nil } } /******************************************************************************************************************** METHOD NAME: addNewLocationRecord INPUT PARAMETERS: CLLocation Object RETURNS: None OBSERVATIONS: Converts CLLocation object to LocationData object, adds new record to [LocationData] from the getUpdatedRecords method and saves modified array to memory. ********************************************************************************************************************/ func addNewLocationRecord (newRecord: CLLocation) { //- Get CLLocation properties let lat:NSNumber = newRecord.coordinate.latitude let lon: NSNumber = newRecord.coordinate.longitude let time: NSDate = newRecord.timestamp let newLocationDataRecord = LocationData() newLocationDataRecord.latitude = lat newLocationDataRecord.longitude = lon newLocationDataRecord.timestamp = time //- Fetch records from memory and store on mutable array var sortedRecords = [LocationData]() if let fetchedRecords = self.getUpdatedRecords() { for records in fetchedRecords { sortedRecords.append(records) } } //- Append new record sortedRecords.append(newLocationDataRecord) //- Sort Records sortedRecords.sortInPlace({ $0.timestamp.compare($1.timestamp) == NSComparisonResult.OrderedAscending }) //- Save new record self.saveLocationRecords(sortedRecords) } /******************************************************************************************************************** METHOD NAME: updateLocationRecords INPUT PARAMETERS: CLLocation Object RETURNS: None OBSERVATIONS: Manages number of records when new record is received, only 32 location records are store in memory (4 updates per hour, for 8 hours) ********************************************************************************************************************/ func updateLocationRecords (newLocation: CLLocation) { var numberOfRecords: Int? //- Perform initial fetch Request if let fetchResults = getUpdatedRecords() { switch fetchResults.count { case 0...(self.MaxNoOfRecords-1): //- Adds new location record if less than 32 records exist addNewLocationRecord(newLocation) case self.MaxNoOfRecords...99: //- If six or more records exist, reduce the number of records until size of five has been reached repeat { deleteOldestLocationRecord() //- new fetch for updated count result numberOfRecords = getUpdatedRecords()?.count } while (numberOfRecords>self.MaxNoOfRecords-1) //- Adds last knwon location to record addNewLocationRecord(newLocation) default: print("Error") } } else { //- NO RECORDS EXIST - CONDITIONAL UNWRAPING print("No records exist in memory, adding new record") addNewLocationRecord(newLocation) } //- FOR TESTING ----------- print(":::::: updated records ::::::") if let fetchResults = getUpdatedRecords() { for each in fetchResults { print(self.fixDateFormat(each.timestamp)) } } print("-----------") //- FOR TESTING above ----- } /******************************************************************************************************************** METHOD NAME: fixDateFormat INPUT PARAMETERS: NSDate object RETURNS: NSstring OBSERVATIONS: Fixes date format for debuggin and parsing, adds timezone and returns as NSString ********************************************************************************************************************/ func fixDateFormat(date: NSDate) -> NSString { let dateFormatter = NSDateFormatter() //- Format parameters dateFormatter.timeStyle = NSDateFormatterStyle.MediumStyle dateFormatter.dateStyle = NSDateFormatterStyle.ShortStyle //- Force date format to garantee consistency throught devices dateFormatter.dateFormat = DATEFORMAT dateFormatter.timeZone = NSTimeZone() return dateFormatter.stringFromDate(date) } }
mit
mownier/photostream
Photostream/UI/Shared/ActivityTableCell/ActivityTableCommentCell.swift
1
4102
// // ActivityTableCommentCell.swift // Photostream // // Created by Mounir Ybanez on 26/12/2016. // Copyright © 2016 Mounir Ybanez. All rights reserved. // import UIKit protocol ActivityTableCommentCellDelegate: class { func didTapPhoto(cell: UITableViewCell) func didTapAvatar(cell: UITableViewCell) } @objc protocol ActivityTableCommentCellAction: class { func didTapPhoto() func didTapAvatar() } class ActivityTableCommentCell: UITableViewCell, ActivityTableCommentCellAction { weak var delegate: ActivityTableCommentCellDelegate? var avatarImageView: UIImageView! var photoImageView: UIImageView! var contentLabel: UILabel! convenience init() { self.init(style: .default, reuseIdentifier: ActivityTableCommentCell.reuseId) } override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) initSetup() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) initSetup() } func initSetup() { avatarImageView = UIImageView() avatarImageView.contentMode = .scaleAspectFill avatarImageView.backgroundColor = UIColor.lightGray avatarImageView.cornerRadius = avatarDimension / 2 photoImageView = UIImageView() photoImageView.contentMode = .scaleAspectFill photoImageView.backgroundColor = UIColor.lightGray photoImageView.clipsToBounds = true contentLabel = UILabel() contentLabel.numberOfLines = 0 contentLabel.font = UIFont.systemFont(ofSize: 12) var tap = UITapGestureRecognizer(target: self, action: #selector(self.didTapPhoto)) tap.numberOfTapsRequired = 1 photoImageView.isUserInteractionEnabled = true photoImageView.addGestureRecognizer(tap) tap = UITapGestureRecognizer(target: self, action: #selector(self.didTapAvatar)) tap.numberOfTapsRequired = 1 avatarImageView.isUserInteractionEnabled = true avatarImageView.addGestureRecognizer(tap) addSubview(avatarImageView) addSubview(photoImageView) addSubview(contentLabel) } override func layoutSubviews() { var rect = CGRect.zero rect.origin.x = spacing rect.origin.y = (frame.height - avatarDimension) / 2 rect.size.width = avatarDimension rect.size.height = avatarDimension avatarImageView.frame = rect rect.origin.x = frame.width - photoDimension - spacing rect.origin.y = (frame.height - photoDimension) / 2 rect.size.width = photoDimension rect.size.height = photoDimension photoImageView.frame = rect rect.origin.x = avatarImageView.frame.maxX rect.origin.x += spacing rect.size.width = frame.width - rect.origin.x rect.size.width -= photoImageView.frame.width rect.size.width -= (spacing * 2) rect.size.height = contentLabel.sizeThatFits(rect.size).height rect.origin.y = (frame.height - rect.size.height) / 2 contentLabel.frame = rect } func didTapPhoto() { delegate?.didTapPhoto(cell: self) } func didTapAvatar() { delegate?.didTapAvatar(cell: self) } } extension ActivityTableCommentCell { var spacing: CGFloat { return 4 } var avatarDimension: CGFloat { return 32 } var photoDimension: CGFloat { return 40 } } extension ActivityTableCommentCell { static var reuseId: String { return "ActivityTableCommentCell" } } extension ActivityTableCommentCell { class func dequeue(from view: UITableView) -> ActivityTableCommentCell? { return view.dequeueReusableCell(withIdentifier: self.reuseId) as? ActivityTableCommentCell } class func register(in view: UITableView) { view.register(self, forCellReuseIdentifier: self.reuseId) } }
mit
siemensikkema/Fairness
Fairness/CostTextFieldController.swift
1
1192
import UIKit class CostTextFieldController: NSObject { @IBOutlet weak var costTextField: UITextField! var costDidChangeCallbackOrNil: ((Double) -> ())? private let notificationCenter: FairnessNotificationCenter override convenience init() { self.init(notificationCenter: NotificationCenter()) } init(notificationCenter: FairnessNotificationCenter) { self.notificationCenter = notificationCenter super.init() notificationCenter.observeTransactionDidStart { self.costTextField.userInteractionEnabled = true self.costTextField.becomeFirstResponder() } notificationCenter.observeTransactionDidEnd { self.costTextField.userInteractionEnabled = false self.costTextField.resignFirstResponder() self.costTextField.text = "" } } @IBAction func costDidChange() { // untested let balanceFormatter = BalanceFormatter.sharedInstance balanceFormatter.numberFromString(costTextField.text) let cost = balanceFormatter.numberFromString(costTextField.text)?.doubleValue costDidChangeCallbackOrNil?(cost ?? 0) } }
mit
HarwordLiu/Ing.
Ing/Ing/Protocol/CloudKitProtocols.swift
1
2228
// // CloudKitProtocols.swift // Ing // // Created by 刘浩 on 2017/9/7. // Copyright © 2017年 刘浩. All rights reserved. // import Foundation import CloudKit import CoreData @objc protocol CloudKitRecordIDObject { var recordID: NSData? { get set } } extension CloudKitRecordIDObject { func cloudKitRecordID() -> CKRecordID? { guard let recordID = recordID else { return nil } return NSKeyedUnarchiver.unarchiveObject(with: recordID as Data) as? CKRecordID } } @objc protocol CloudKitManagedObject: CloudKitRecordIDObject { var lastUpdate: Date? { get set } var recordName: String? { get set } var recordType: String { get } func managedObjectToRecord(_ record: CKRecord?) -> CKRecord func updateWithRecord(_ record: CKRecord) } extension CloudKitManagedObject { func cloudKitRecord(_ record: CKRecord?, parentRecordZoneID: CKRecordZoneID?) -> CKRecord { if let record = record { return record } var recordZoneID: CKRecordZoneID if parentRecordZoneID != .none { recordZoneID = parentRecordZoneID! } else { guard let cloudKitZone = CloudKitZone(recordType: recordType) else { fatalError("Attempted to create a CKRecord with an unknown zone") } recordZoneID = cloudKitZone.recordZoneID() } let uuid = UUID() let recordName = recordType + "." + uuid.uuidString let recordID = CKRecordID(recordName: recordName, zoneID: recordZoneID) return CKRecord(recordType: recordType, recordID: recordID) } func addDeletedCloudKitObject() { if let managedObject = self as? NSManagedObject, let managedObjectContext = managedObject.managedObjectContext, let recordID = recordID, let deletedCloudKitObject = NSEntityDescription.insertNewObject(forEntityName: "DeletedCloudKitObject", into: managedObjectContext) as? DeletedCloudKitObject { deletedCloudKitObject.recordID = recordID deletedCloudKitObject.recordType = recordType } } }
mit
happylance/MacKey
MacKeyUnit/Domain/SimpleReducibleState.swift
1
624
// // SimpleReducible.swift // MacKey // // Created by Liu Liang on 5/12/18. // Copyright © 2018 Liu Liang. All rights reserved. // import RxSwift import RxCocoa protocol SimpleReducibleState { associatedtype InputAction func reduce(_ action:InputAction) -> Self } extension SimpleReducibleState { func getState(actions: PublishRelay<InputAction>, disposeBag: DisposeBag) -> BehaviorRelay<Self> { let state = BehaviorRelay<Self>(value: self) actions .scan(self) { $0.reduce($1) } .bind(to: state) .disposed(by: disposeBag) return state } }
mit
LittleRockInGitHub/LLRegex
Tests/LLRegexTests/NamedCaptureGroupsTests.swift
1
7487
// // NamedCaptureGroupsTests.swift // LLRegex // // Created by Rock Yang on 2017/6/21. // Copyright © 2017年 Rock Young. All rights reserved. // import XCTest @testable import LLRegex class NamedCaptureGroupsTests: 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 testExtraction() { XCTAssertEqual(extractNamedCaptureGroups(in: "\\d", expectedGroupsCount: 0)!, [:]) XCTAssertEqual(extractNamedCaptureGroups(in: "()", expectedGroupsCount: 1)!, [:]) XCTAssertEqual(extractNamedCaptureGroups(in: "(?<name>abc)", expectedGroupsCount: 1)!, ["name": 1]) XCTAssertEqual(extractNamedCaptureGroups(in: "(?<name>abc)-(?<number1>\\d+)", expectedGroupsCount: 2)!, ["name": 1, "number1": 2]) XCTAssertEqual(extractNamedCaptureGroups(in: "(\\d)(?<name>abc)-(?<number1>\\d+)", expectedGroupsCount: 3)!, ["name": 2, "number1": 3]) XCTAssertEqual(extractNamedCaptureGroups(in: "(\\d(?<name>abc)-(?<number1>\\d+))", expectedGroupsCount: 3)!, ["name": 2, "number1": 3]) XCTAssertEqual(extractNamedCaptureGroups(in: "(\\d(?<name>abc((?<number1>\\d+)1)))", expectedGroupsCount: 4)!, ["name": 2, "number1": 4]) XCTAssertEqual(extractNamedCaptureGroups(in: "(?:\\d)", expectedGroupsCount: 0)!, [:]) XCTAssertEqual(extractNamedCaptureGroups(in: "(?<!>)", expectedGroupsCount: 0)!, [:]) XCTAssertEqual(extractNamedCaptureGroups(in: "(?<=)", expectedGroupsCount: 0)!, [:]) XCTAssertEqual(extractNamedCaptureGroups(in: "(?!)", expectedGroupsCount: 0)!, [:]) XCTAssertEqual(extractNamedCaptureGroups(in: "(?=)", expectedGroupsCount: 0)!, [:]) XCTAssertEqual(extractNamedCaptureGroups(in: "(?#)", expectedGroupsCount: 0)!, [:]) XCTAssertEqual(extractNamedCaptureGroups(in: "(?>)", expectedGroupsCount: 0)!, [:]) XCTAssertEqual(extractNamedCaptureGroups(in: "\\(\\)", expectedGroupsCount: 0)!, [:]) XCTAssertEqual(extractNamedCaptureGroups(in: "\\\\()", expectedGroupsCount: 1)!, [:]) XCTAssertEqual(extractNamedCaptureGroups(in: "\\(?<name>\\)", expectedGroupsCount: 0)!, [:]) XCTAssertEqual(extractNamedCaptureGroups(in: "\\\\(?<name>)", expectedGroupsCount: 1)!, ["name": 1]) } func testNamdCaptureGroupsTypes() { guard #available(iOS 9, *) else { return } XCTAssertEqual(Regex("\\d", options: [.namedCaptureGroups]).namedCaptureGroupsInfo!.count, 0) XCTAssertEqual(Regex("()", options: [.namedCaptureGroups]).namedCaptureGroupsInfo!.count, 0) XCTAssertEqual(Regex("(?<name>abc)", options: [.namedCaptureGroups]).namedCaptureGroupsInfo!.count, 1) XCTAssertEqual(Regex("(?<name>abc)-(?<number1>\\d+)", options: [.namedCaptureGroups]).namedCaptureGroupsInfo!.count, 2) XCTAssertEqual(Regex("(\\d)(?<name>abc)-(?<number1>\\d+)", options: [.namedCaptureGroups]).namedCaptureGroupsInfo!.count, 2) XCTAssertEqual(Regex("(\\d(?<name>abc)-(?<number1>\\d+))", options: [.namedCaptureGroups]).namedCaptureGroupsInfo!.count, 2) XCTAssertEqual(Regex("(\\d(?<name>abc((?<number1>\\d+)1)))", options: [.namedCaptureGroups]).namedCaptureGroupsInfo!.count, 2) XCTAssertEqual(Regex("(\\d(?<name>abc((?<number1>\\d+)1)))", options: [.namedCaptureGroups]).namedCaptureGroupsInfo!.count, 2) XCTAssertEqual(Regex("(\\d(?<name>abc((?<number1>\\d+)1)))", options: [.namedCaptureGroups]).namedCaptureGroupsInfo!.count, 2) XCTAssertEqual(Regex("(\\d(?<name>abc((?<number1>\\d+)1)))", options: [.namedCaptureGroups]).namedCaptureGroupsInfo!.count, 2) XCTAssertEqual(Regex("(\\d(?<name>abc((?<number1>\\d+)1)))", options: [.namedCaptureGroups]).namedCaptureGroupsInfo!.count, 2) XCTAssertEqual(Regex("(?:\\d)", options: [.namedCaptureGroups]).namedCaptureGroupsInfo!.count, 0) XCTAssertEqual(Regex("(?<!>)", options: [.namedCaptureGroups]).namedCaptureGroupsInfo!.count, 0) XCTAssertEqual(Regex("(?<=)", options: [.namedCaptureGroups]).namedCaptureGroupsInfo!.count, 0) XCTAssertEqual(Regex("(?!)", options: [.namedCaptureGroups]).namedCaptureGroupsInfo!.count, 0) XCTAssertEqual(Regex("(?=)", options: [.namedCaptureGroups]).namedCaptureGroupsInfo!.count, 0) XCTAssertEqual(Regex("(?#)", options: [.namedCaptureGroups]).namedCaptureGroupsInfo!.count, 0) XCTAssertEqual(Regex("(?>)", options: [.namedCaptureGroups]).namedCaptureGroupsInfo!.count, 0) XCTAssertEqual(Regex("\\(\\)", options: [.namedCaptureGroups]).namedCaptureGroupsInfo!.count, 0) XCTAssertEqual(Regex("\\\\()", options: [.namedCaptureGroups]).namedCaptureGroupsInfo!.count, 0) XCTAssertEqual(Regex("\\(?<name>\\)", options: [.namedCaptureGroups]).namedCaptureGroupsInfo!.count, 0) XCTAssertEqual(Regex("\\\\(?<name>)", options: [.namedCaptureGroups]).namedCaptureGroupsInfo!.count, 1) } func testNamdCaptureGroups() { guard #available(iOS 9, *) else { return } let s = "123 normal NAMED (Nested) atomic non-capture 456" let regex = Regex("(?#comment)(?<!a)(?<=123) (?i)(NORMAL) (?<name>named) (\\((?<nested>nested)\\)) (?>atomic) (?:non-capture) (?=456)(?!a)", options: [.namedCaptureGroups]) XCTAssertEqual(regex.namedCaptureGroupsInfo!, ["name": 2, "nested": 4]) let match = regex.matches(in: s).first! XCTAssertEqual(match.groups["name"]!.matched, "NAMED") XCTAssertEqual(match.groups["nested"]!.matched, "Nested") XCTAssertNil(match.groups[""]) } func testReplacement() { guard #available(iOS 9, *) else { return } let date = "1978-12-24" let named = Regex("((?<year>\\d+)-(?<month>\\d+)-(?<day>\\d+))", options: .namedCaptureGroups) let nonNamed = Regex("((?<year>\\d+)-(?<month>\\d+)-(?<day>\\d+))") let namedMatch = named.matches(in: date).first! let nonNamedMatch = nonNamed.matches(in: date).first! XCTAssertEqual(namedMatch.replacement(withTemplate: "$2$3$4"), "19781224") XCTAssertEqual(namedMatch.replacement(withTemplate: "${year}${month}${day}"), "19781224") XCTAssertEqual(namedMatch.replacement(withTemplate: "\\${year}${month}\\\\${day}"), "${year}12\\24") XCTAssertEqual(namedMatch.replacement(withTemplate: "$9${unknown}!"), "!") XCTAssertEqual(nonNamedMatch.replacement(withTemplate: "$2$3$4"), "19781224") XCTAssertEqual(nonNamedMatch.replacement(withTemplate: "${year}${month}${day}"), "${year}${month}${day}") XCTAssertEqual(nonNamedMatch.replacement(withTemplate: "$9${unknown}!"), "${unknown}!") } func testComment() { guard #available(iOS 9, *) else { return } let s = "1234567890" let regex = Regex("(\\d{1,2})(?<suffix>\\d)(?x) # (\\d+)", options: .namedCaptureGroups) XCTAssertNil(regex.namedCaptureGroupsInfo) XCTAssertEqual(regex.matches(in: s).first!.replacement(withTemplate: "$1${suffix}"), "12") } }
mit
benlangmuir/swift
test/IDE/complete_with_closure_param.swift
13
1857
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=COMPLETE | %FileCheck %s typealias FunctionTypealias = (Int, Int) -> Bool typealias OptionalFunctionTypealias = ((Int, Int) -> Bool)? struct FooStruct { func instanceMethod1(_ callback: (Int, Int) -> Void) {} func instanceMethod2(_ callback: ((Int, Int) -> Void)?) {} func instanceMethod3(_ callback: ((Int, Int) -> Void)??) {} func instanceMethod4(_ callback: ((Int, Int) -> Void)!) {} func instanceMethod5(_ callback: FunctionTypealias) {} func instanceMethod6(_ callback: FunctionTypealias?) {} func instanceMethod7(_ callback: OptionalFunctionTypealias) {} } FooStruct().#^COMPLETE^# // CHECK: Begin completions, 8 items // CHECK-DAG: Decl[InstanceMethod]/CurrNominal: instanceMethod1({#(callback): (Int, Int) -> Void##(Int, Int) -> Void#})[#Void#]; name=instanceMethod1(:){{$}} // CHECK-DAG: Decl[InstanceMethod]/CurrNominal: instanceMethod2({#(callback): ((Int, Int) -> Void)?##(Int, Int) -> Void#})[#Void#]{{; name=.+$}} // CHECK-DAG: Decl[InstanceMethod]/CurrNominal: instanceMethod3({#(callback): ((Int, Int) -> Void)??##(Int, Int) -> Void#})[#Void#]{{; name=.+$}} // CHECK-DAG: Decl[InstanceMethod]/CurrNominal: instanceMethod4({#(callback): ((Int, Int) -> Void)!##(Int, Int) -> Void#})[#Void#]{{; name=.+$}} // CHECK-DAG: Decl[InstanceMethod]/CurrNominal: instanceMethod5({#(callback): (Int, Int) -> Bool##(Int, Int) -> Bool#})[#Void#]{{; name=.+$}} // CHECK-DAG: Decl[InstanceMethod]/CurrNominal: instanceMethod6({#(callback): FunctionTypealias?##(Int, Int) -> Bool#})[#Void#]{{; name=.+$}} // CHECK-DAG: Decl[InstanceMethod]/CurrNominal: instanceMethod7({#(callback): OptionalFunctionTypealias##(Int, Int) -> Bool#})[#Void#]{{; name=.+$}} // CHECK-DAG: Keyword[self]/CurrNominal: self[#FooStruct#]; name=self // CHECK: End completions
apache-2.0
square/Valet
Valet macOS Test Host App/AppDelegate.swift
1
742
// Created by Dan Federman on 9/19/17. // Copyright © 2017 Square, Inc. // // 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 Cocoa @NSApplicationMain final class AppDelegate: NSObject, NSApplicationDelegate {}
apache-2.0
takeo-asai/math-puzzle
problems/49.swift
1
4402
struct Circle { let n: Int var values: [Bool] init(_ v: [Bool]) { self.values = v self.n = values.count } func reverse(a: Int) -> Circle { var next = self //let m = self.n / 2 for i in 0 ..< 3 { next[a+i] = !next[a+i] } return next } func reverses(a: [Int]) -> Circle { var next = self for x in a { next = next.reverse(x) } return next } func isFinished() -> Bool { if self.n <= 2 { return false } var present = self.values[0] for i in 1 ..< n { let next = self.values[i] if present == next { return false } present = next } return true } subscript(i: Int) -> Bool { get { return self.values[i%n] } set(b) { self.values[i%n] = b } } } extension Array { // ExSwift // // Created by pNre on 03/06/14. // Copyright (c) 2014 pNre. All rights reserved. // // https://github.com/pNre/ExSwift/blob/master/ExSwift/Array.swift // https://github.com/pNre/ExSwift/blob/master/LICENSE /** - parameter length: The length of each permutation - returns: All permutations of a given length within an array */ func permutation (length: Int) -> [[Element]] { if length < 0 || length > self.count { return [] } else if length == 0 { return [[]] } else { var permutations: [[Element]] = [] let combinations = combination(length) for combination in combinations { var endArray: [[Element]] = [] var mutableCombination = combination permutations += self.permutationHelper(length, array: &mutableCombination, endArray: &endArray) } return permutations } } private func permutationHelper(n: Int, inout array: [Element], inout endArray: [[Element]]) -> [[Element]] { if n == 1 { endArray += [array] } for var i = 0; i < n; i++ { permutationHelper(n - 1, array: &array, endArray: &endArray) let j = n % 2 == 0 ? i : 0 let temp: Element = array[j] array[j] = array[n - 1] array[n - 1] = temp } return endArray } func combination (length: Int) -> [[Element]] { if length < 0 || length > self.count { return [] } var indexes: [Int] = (0..<length).reduce([]) {$0 + [$1]} var combinations: [[Element]] = [] let offset = self.count - indexes.count while true { var combination: [Element] = [] for index in indexes { combination.append(self[index]) } combinations.append(combination) var i = indexes.count - 1 while i >= 0 && indexes[i] == i + offset { i-- } if i < 0 { break } i++ let start = indexes[i-1] + 1 for j in (i-1)..<indexes.count { indexes[j] = start + j - i + 1 } } return combinations } /** - parameter length: The length of each permutations - returns: All of the permutations of this array of a given length, allowing repeats */ func repeatedPermutation(length: Int) -> [[Element]] { if length < 1 { return [] } var indexes: [[Int]] = [] indexes.repeatedPermutationHelper([], length: length, arrayLength: self.count, indexes: &indexes) return indexes.map({ $0.map({ i in self[i] }) }) } private func repeatedPermutationHelper(seed: [Int], length: Int, arrayLength: Int, inout indexes: [[Int]]) { if seed.count == length { indexes.append(seed) return } for i in (0..<arrayLength) { var newSeed: [Int] = seed newSeed.append(i) self.repeatedPermutationHelper(newSeed, length: length, arrayLength: arrayLength, indexes: &indexes) } } } let n = 8 let idxes = Array(0 ..< 2*n) let initial = Circle(Array(count: n, repeatedValue: true) + Array(count: n, repeatedValue: false)) loop: for i in 1 ..< 2*n { for r in idxes.combination(i) { let c = initial.reverses(r) if c.isFinished() { print(r) print(i) break loop } } }
mit
josefdolezal/fit-cvut
BI-IOS/semester-project/What2Do/What2Do/NSDateExtension.swift
1
943
import Foundation extension NSDate { func timeComponent() -> NSDateComponents { let calendar = NSCalendar.currentCalendar() return calendar.components([.Hour, .Minute], fromDate: self) } func timeDelta(date: NSDate) -> (hours: Int, minutes: Int) { let lowerTime = self.timeComponent() let biggerTime = date.timeComponent() // Easier difference if lowerTime.minute > biggerTime.minute { biggerTime.minute += 60 lowerTime.hour += 1 } // Over midnight if lowerTime.hour > biggerTime.hour { biggerTime.hour += 24 } return (biggerTime.hour - lowerTime.hour, biggerTime.minute - lowerTime.minute) } func timeDelta(date: NSDate, lessThan min: Int) -> Bool { let time = self.timeDelta(date) return (time.hours * 60 + time.minutes) < min } }
mit
mpurland/Morpheus
Morpheus/CollectionDataSource.swift
1
1072
import UIKit import ReactiveCocoa public protocol CollectionDataSource: CollectionViewDataSource { var collectionView: UICollectionView { get } } public class CollectionModelDataSource<Model> { public typealias ReuseTransformer = Model -> ReuseIdentifier public typealias CellConfigurerTransformer = Model -> CollectionCellConfigurer<Model> public let collectionView: UICollectionView public let collectionModel: CollectionModel<Model> public let reuseTransformer: ReuseTransformer public let cellConfigurerTransformer: CellConfigurerTransformer init(collectionView otherCollectionView: UICollectionView, collectionModel otherCollectionModel: CollectionModel<Model>, reuseTransformer otherReuseTransformer: ReuseTransformer, cellConfigurerTransformer otherCellConfigurerTransformer: CellConfigurerTransformer) { collectionView = otherCollectionView collectionModel = otherCollectionModel reuseTransformer = otherReuseTransformer cellConfigurerTransformer = otherCellConfigurerTransformer } }
bsd-3-clause
thomasvl/swift-protobuf
Reference/google/protobuf/duration.pb.swift
2
7400
// DO NOT EDIT. // swift-format-ignore-file // // Generated by the Swift generator plugin for the protocol buffer compiler. // Source: google/protobuf/duration.proto // // For information on using the generated types, please see the documentation: // https://github.com/apple/swift-protobuf/ // Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // 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. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // 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 // If the compiler emits an error on this type, it is because this file // was generated by a version of the `protoc` Swift plug-in that is // incompatible with the version of SwiftProtobuf to which you are linking. // Please ensure that you are building against the same version of the API // that was used to generate this file. fileprivate struct _GeneratedWithProtocGenSwiftVersion: ProtobufAPIVersionCheck { struct _3: ProtobufAPIVersion_3 {} typealias Version = _3 } /// A Duration represents a signed, fixed-length span of time represented /// as a count of seconds and fractions of seconds at nanosecond /// resolution. It is independent of any calendar and concepts like "day" /// or "month". It is related to Timestamp in that the difference between /// two Timestamp values is a Duration and it can be added or subtracted /// from a Timestamp. Range is approximately +-10,000 years. /// /// # Examples /// /// Example 1: Compute Duration from two Timestamps in pseudo code. /// /// Timestamp start = ...; /// Timestamp end = ...; /// Duration duration = ...; /// /// duration.seconds = end.seconds - start.seconds; /// duration.nanos = end.nanos - start.nanos; /// /// if (duration.seconds < 0 && duration.nanos > 0) { /// duration.seconds += 1; /// duration.nanos -= 1000000000; /// } else if (duration.seconds > 0 && duration.nanos < 0) { /// duration.seconds -= 1; /// duration.nanos += 1000000000; /// } /// /// Example 2: Compute Timestamp from Timestamp + Duration in pseudo code. /// /// Timestamp start = ...; /// Duration duration = ...; /// Timestamp end = ...; /// /// end.seconds = start.seconds + duration.seconds; /// end.nanos = start.nanos + duration.nanos; /// /// if (end.nanos < 0) { /// end.seconds -= 1; /// end.nanos += 1000000000; /// } else if (end.nanos >= 1000000000) { /// end.seconds += 1; /// end.nanos -= 1000000000; /// } /// /// Example 3: Compute Duration from datetime.timedelta in Python. /// /// td = datetime.timedelta(days=3, minutes=10) /// duration = Duration() /// duration.FromTimedelta(td) /// /// # JSON Mapping /// /// In JSON format, the Duration type is encoded as a string rather than an /// object, where the string ends in the suffix "s" (indicating seconds) and /// is preceded by the number of seconds, with nanoseconds expressed as /// fractional seconds. For example, 3 seconds with 0 nanoseconds should be /// encoded in JSON format as "3s", while 3 seconds and 1 nanosecond should /// be expressed in JSON format as "3.000000001s", and 3 seconds and 1 /// microsecond should be expressed in JSON format as "3.000001s". struct Google_Protobuf_Duration { // SwiftProtobufCore.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. /// Signed seconds of the span of time. Must be from -315,576,000,000 /// to +315,576,000,000 inclusive. Note: these bounds are computed from: /// 60 sec/min * 60 min/hr * 24 hr/day * 365.25 days/year * 10000 years var seconds: Int64 = 0 /// Signed fractions of a second at nanosecond resolution of the span /// of time. Durations less than one second are represented with a 0 /// `seconds` field and a positive or negative `nanos` field. For durations /// of one second or more, a non-zero value for the `nanos` field must be /// of the same sign as the `seconds` field. Must be from -999,999,999 /// to +999,999,999 inclusive. var nanos: Int32 = 0 var unknownFields = UnknownStorage() init() {} } #if swift(>=5.5) && canImport(_Concurrency) extension Google_Protobuf_Duration: @unchecked Sendable {} #endif // swift(>=5.5) && canImport(_Concurrency) // MARK: - Code below here is support for the SwiftProtobuf runtime. fileprivate let _protobuf_package = "google.protobuf" extension Google_Protobuf_Duration: Message, _MessageImplementationBase, _ProtoNameProviding { static let protoMessageName: String = _protobuf_package + ".Duration" static let _protobuf_nameMap: _NameMap = [ 1: .same(proto: "seconds"), 2: .same(proto: "nanos"), ] mutating func decodeMessage<D: Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularInt64Field(value: &self.seconds) }() case 2: try { try decoder.decodeSingularInt32Field(value: &self.nanos) }() default: break } } } func traverse<V: Visitor>(visitor: inout V) throws { if self.seconds != 0 { try visitor.visitSingularInt64Field(value: self.seconds, fieldNumber: 1) } if self.nanos != 0 { try visitor.visitSingularInt32Field(value: self.nanos, fieldNumber: 2) } try unknownFields.traverse(visitor: &visitor) } static func ==(lhs: Google_Protobuf_Duration, rhs: Google_Protobuf_Duration) -> Bool { if lhs.seconds != rhs.seconds {return false} if lhs.nanos != rhs.nanos {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } }
apache-2.0
ZackKingS/Tasks
task/Classes/Others/Lib/TakePhoto/UICollectionView+Extension.swift
3
730
// // UICollectionView+Extension.swift // PhotoPicker // // Created by liangqi on 16/3/10. // Copyright © 2016年 dailyios. All rights reserved. // import Foundation import UIKit extension UICollectionView { func aapl_indexPathsForElementsInRect(rect: CGRect) -> [IndexPath]? { let allLayoutAttributes = self.collectionViewLayout.layoutAttributesForElements(in: rect) if allLayoutAttributes == nil || allLayoutAttributes!.count == 0 { return nil } var indexPaths = [IndexPath]() for layoutAttributes in allLayoutAttributes! { let indexPath = layoutAttributes.indexPath indexPaths.append(indexPath) } return indexPaths; } }
apache-2.0
fishcafe/SunnyHiddenBar
SunnyHiddenBar/Classes/UIViewController+SunnyHiddenBar.swift
1
4326
// // UIViewController+SunnyHiddenBar.swift // SunnyHiddenBar // // Created by amaker on 16/4/19. // Copyright © 2016年 CocoaPods. All rights reserved. // import Foundation import UIKit /** SunnyHiddenBar Extends UIViewController */ //定义关联的Key let key = "keyScrollView" let navBarBackgroundImageKey = "navBarBackgroundImage" let isLeftAlphaKey = "isLeftAlpha" let isRightAlphaKey = "isRightAlpha" let isTitleAlphaKey = "isTitleAlpha" var alpha:CGFloat = 0; public extension UIViewController { var keyScrollView:UIScrollView?{ set{ objc_setAssociatedObject(self, key, keyScrollView, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } get{ return objc_getAssociatedObject(self, key) as? UIScrollView } } var navBarBackgroundImage:UIImage?{ set{ objc_setAssociatedObject(self, navBarBackgroundImageKey, navBarBackgroundImage, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } get{ return objc_getAssociatedObject(self, navBarBackgroundImageKey) as? UIImage } } var isLeftAlpha:Bool?{ set{ return objc_setAssociatedObject(self, isLeftAlphaKey, (isLeftAlpha), .OBJC_ASSOCIATION_ASSIGN) } get{ return objc_getAssociatedObject(self, isLeftAlphaKey) as? Bool } } var isRightAlpha:Bool?{ set{ return objc_setAssociatedObject(self, isRightAlphaKey, (isRightAlpha), .OBJC_ASSOCIATION_ASSIGN) } get{ return objc_getAssociatedObject(self, isRightAlphaKey) as? Bool } } var isTitleAlpha:Bool?{ set{ return objc_setAssociatedObject(self, isTitleAlphaKey, (isTitleAlpha), .OBJC_ASSOCIATION_ASSIGN) } get{ return objc_getAssociatedObject(self, isTitleAlphaKey) as? Bool } } func scrollControlByOffsetY(offsetY:CGFloat){ if self.getScrollerView() != Optional.None{ let scrollerView = self.getScrollerView() alpha = scrollerView.contentOffset.y/offsetY }else { return } alpha = (alpha <= 0) ? 0 : alpha alpha = (alpha >= 1) ? 1 : alpha //TODO: titleView alpha no fix self.navigationItem.leftBarButtonItem?.customView?.alpha = (self.isLeftAlpha != nil) ? alpha : 1 self.navigationItem.titleView?.alpha = (self.isTitleAlpha != nil) ? alpha : 1 self.navigationItem.rightBarButtonItem?.customView?.alpha = (self.isRightAlpha != nil) ? alpha : 1 self.navigationController?.navigationBar.subviews.first?.alpha = alpha } func setInViewWillAppear() { struct Static { static var onceToken: dispatch_once_t = 0 } dispatch_once(&Static.onceToken) { self.navBarBackgroundImage = self.navigationController?.navigationBar.backgroundImageForBarMetrics(.Default) } self.navigationController?.navigationBar.shadowImage = UIImage() self.navigationController?.navigationBar.subviews.first?.alpha = 0 if self.keyScrollView != nil { self.getScrollerView().contentOffset = CGPointMake(0, self.keyScrollView!.contentOffset.y - 1) self.getScrollerView().contentOffset = CGPointMake(0, self.keyScrollView!.contentOffset.y + 1) } } func setInViewWillDisappear() { self.navigationController?.navigationBar.subviews.first?.alpha = 1 self.navigationController?.navigationBar.setBackgroundImage(nil, forBarMetrics: .Default) self.navigationController?.navigationBar.shadowImage = nil } func getScrollerView() -> UIScrollView{ if self.isKindOfClass(UITableViewController) || self.isKindOfClass(UICollectionViewController) { return self.view as! UIScrollView } else { for myView in self.view.subviews { if myView.isEqual(self.keyScrollView) && myView.isKindOfClass(UIScrollView) || myView.isEqual(self.keyScrollView) && view.isKindOfClass(UIScrollView){ return myView as! UIScrollView } } } return Optional.None! } }
mit
phatblat/realm-cocoa
examples/ios/swift/Backlink/AppDelegate.swift
2
2120
//////////////////////////////////////////////////////////////////////////// // // Copyright 2014 Realm Inc. // // 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 UIKit import RealmSwift class Dog: Object { @Persisted var name: String @Persisted var age: Int // Define "owners" as the inverse relationship to Person.dogs @Persisted(originProperty: "dogs") var owners: LinkingObjects<Person> } class Person: Object { @Persisted var name: String @Persisted var dogs: List<Dog> } @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil) -> Bool { window = UIWindow(frame: UIScreen.main.bounds) window?.rootViewController = UIViewController() window?.makeKeyAndVisible() _ = try! Realm.deleteFiles(for: Realm.Configuration.defaultConfiguration) let realm = try! Realm() try! realm.write { realm.create(Person.self, value: ["John", [["Fido", 1]]]) realm.create(Person.self, value: ["Mary", [["Rex", 2]]]) } // Log all dogs and their owners using the "owners" inverse relationship let allDogs = realm.objects(Dog.self) for dog in allDogs { let ownerNames = Array(dog.owners.map(\.name)) print("\(dog.name) has \(ownerNames.count) owners (\(ownerNames))") } return true } }
apache-2.0
PerfectExamples/staffDirectory
Sources/staffDirectory/utility/PageHandlers.swift
2
1651
// // PageHandlers.swift // Perfect-App-Template // // Created by Jonathan Guthrie on 2017-02-20. // Copyright (C) 2017 PerfectlySoft, Inc. // //===----------------------------------------------------------------------===// // // This source file is part of the Perfect.org open source project // // Copyright (c) 2015 - 2016 PerfectlySoft Inc. and the Perfect project authors // Licensed under Apache License v2.0 // // See http://perfect.org/licensing.html for license information // //===----------------------------------------------------------------------===// // import PerfectMustache import PerfectHTTP public struct MustacheHandler: MustachePageHandler { var context: [String: Any] public func extendValuesForResponse(context contxt: MustacheWebEvaluationContext, collector: MustacheEvaluationOutputCollector) { contxt.extendValues(with: context) do { contxt.webResponse.setHeader(.contentType, value: "text/html") try contxt.requestCompleted(withCollector: collector) } catch { let response = contxt.webResponse response.status = .internalServerError response.appendBody(string: "\(error)") response.completed() } } public init(context: [String: Any] = [String: Any]()) { self.context = context } } extension HTTPResponse { public func render(template: String, context: [String: Any] = [String: Any]()) { mustacheRequest(request: self.request, response: self, handler: MustacheHandler(context: context), templatePath: request.documentRoot + "/\(template).mustache") } public func redirect(path: String) { self.status = .found self.addHeader(.location, value: path) self.completed() } }
apache-2.0
00aney/Briefinsta
Briefinsta/Sources/Module/Base/BaseWireframe.swift
1
1374
// // BaseWireframe.swift // Briefinsta // // Created by aney on 2017. 10. 24.. // Copyright © 2017년 Ted Kim. All rights reserved. // import UIKit class BaseWireframe { weak var view: UIViewController! func show(_ viewController: UIViewController, with type: TransitionType, animated: Bool = true) { switch type { case .push: guard let navigationController = view.navigationController else { fatalError("Can't push without a navigation controller") } navigationController.pushViewController(viewController, animated: animated) case .present(let sender): sender.present(viewController, animated: animated) case .root(let window): window.rootViewController = viewController } } func pop(animated: Bool) { if let navigationController = view.navigationController { guard navigationController.popViewController(animated: animated) != nil else { if let presentingView = view.presentingViewController { return presentingView.dismiss(animated: animated) } else { fatalError("Can't navigate back from \(view)") } } } else if let presentingView = view.presentingViewController { presentingView.dismiss(animated: animated) } else { fatalError("Neither modal nor navigation! Can't navigate back from \(view)") } } }
mit
drewag/text-transformers
Tests/TextTransformersTests/RangeTests.swift
1
3105
// // RangeTests.swift // TextTransformers // // Created by Andrew J Wagner on 4/11/16. // Copyright © 2016 Drewag. 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 XCTest import TextTransformers class RangeTests: XCTestCase { let elements = "0,1,2,3".split(Separator(",")) func testFixedEnds() throws { let output = try self.elements .filter(Range(start: .FromBeginning(1), end: .FromEnd(1))) .reduce(Separator("")) .string() XCTAssertEqual(output, "12") } func testFromBeginning() throws { let output = try self.elements .filter(Range(start: .FromBeginning(1), end: .FromBeginning(2))) .reduce(Separator("")) .string() XCTAssertEqual(output, "12") } func testFromEnd() throws { let output = try self.elements .filter(Range(start: .FromEnd(2), end: .FromEnd(1))) .reduce(Separator("")) .string() XCTAssertEqual(output, "12") } func testFromOposites() throws { let output = try self.elements .filter(Range(start: .FromEnd(2), end: .FromBeginning(2))) .reduce(Separator("")) .string() XCTAssertEqual(output, "12") } func testAll() throws { let output = try self.elements .filter(Range(start: .FromBeginning(0), end: .FromEnd(0))) .reduce(Separator("")) .string() XCTAssertEqual(output, "0123") } func testSingleFromBeginning() throws { let output = try self.elements .filter(Range(start: .FromBeginning(1), end: .FromBeginning(1))) .reduce(Separator("")) .string() XCTAssertEqual(output, "1") } func testSingleFromEnd() throws { let output = try self.elements .filter(Range(start: .FromEnd(1), end: .FromEnd(1))) .reduce(Separator("1")) .string() XCTAssertEqual(output, "2") } }
mit
natecook1000/swift-compiler-crashes
crashes-duplicates/17276-no-stacktrace.swift
11
220
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing { case var d = [ { var a { for in a { class case ,
mit
ifels/swiftDemo
MaterialDemo/Pods/NBMaterialDialogIOS/Pod/Classes/NBMaterialDialog.swift
1
19999
// // NBMaterialDialog.swift // NBMaterialDialogIOS // // Created by Torstein Skulbru on 02/05/15. // Copyright (c) 2015 Torstein Skulbru. All rights reserved. // // The MIT License (MIT) // // Copyright (c) 2015 Torstein Skulbru // // 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 BFPaperButton /** Simple material dialog class */ @objc open class NBMaterialDialog : UIViewController { // MARK: - Class variables fileprivate var overlay: UIView? fileprivate var titleLabel: UILabel? fileprivate var containerView: UIView = UIView() fileprivate var contentView: UIView = UIView() fileprivate var okButton: BFPaperButton? fileprivate var cancelButton: BFPaperButton? fileprivate var tapGesture: UITapGestureRecognizer! fileprivate var backgroundColor: UIColor! fileprivate var windowView: UIView! fileprivate var tappableView: UIView = UIView() fileprivate var isStacked: Bool = false fileprivate let kBackgroundTransparency: CGFloat = 0.7 fileprivate let kPadding: CGFloat = 16.0 fileprivate let kWidthMargin: CGFloat = 40.0 fileprivate let kHeightMargin: CGFloat = 24.0 internal var kMinimumHeight: CGFloat { return 120.0 } fileprivate var _kMaxHeight: CGFloat? internal var kMaxHeight: CGFloat { if _kMaxHeight == nil { let window = UIScreen.main.bounds _kMaxHeight = window.height - kHeightMargin - kHeightMargin } return _kMaxHeight! } internal var strongSelf: NBMaterialDialog? internal var userAction: ((_ isOtherButton: Bool) -> Void)? internal var constraintViews: [String: AnyObject]! // MARK: - Constructors public convenience init() { self.init(color: UIColor.white) } public convenience init(color: UIColor) { self.init(nibName: nil, bundle:nil) view.frame = UIScreen.main.bounds view.autoresizingMask = [UIViewAutoresizing.flexibleHeight, UIViewAutoresizing.flexibleWidth] view.backgroundColor = UIColor(red:0, green:0, blue:0, alpha:kBackgroundTransparency) tappableView.backgroundColor = UIColor.clear tappableView.frame = view.frame view.addSubview(tappableView) backgroundColor = color setupContainerView() view.addSubview(containerView) //Retaining itself strongly so can exist without strong refrence strongSelf = self } override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName:nibNameOrNil, bundle:nibBundleOrNil) } public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Dialog Lifecycle /** Hides the dialog */ open func hideDialog() { hideDialog(-1) } /** Hides the dialog, sending a callback if provided when dialog was shown :params: buttonIndex The tag index of the button which was clicked */ internal func hideDialog(_ buttonIndex: Int) { if buttonIndex >= 0 { if let userAction = userAction { userAction(buttonIndex > 0) } } tappableView.removeGestureRecognizer(tapGesture) for childView in view.subviews { childView.removeFromSuperview() } view.removeFromSuperview() strongSelf = nil } /** Displays a simple dialog using a title and a view with the content you need - parameter windowView: The window which the dialog is to be attached - parameter title: The dialog title - parameter content: A custom content view */ open func showDialog(_ windowView: UIView, title: String?, content: UIView) -> NBMaterialDialog { return showDialog(windowView, title: title, content: content, dialogHeight: nil, okButtonTitle: nil, action: nil, cancelButtonTitle: nil, stackedButtons: false) } /** Displays a simple dialog using a title and a view with the content you need - parameter windowView: The window which the dialog is to be attached - parameter title: The dialog title - parameter content: A custom content view - parameter dialogHeight: The height of the dialog */ open func showDialog(_ windowView: UIView, title: String?, content: UIView, dialogHeight: CGFloat?) -> NBMaterialDialog { return showDialog(windowView, title: title, content: content, dialogHeight: dialogHeight, okButtonTitle: nil, action: nil, cancelButtonTitle: nil, stackedButtons: false) } /** Displays a simple dialog using a title and a view with the content you need - parameter windowView: The window which the dialog is to be attached - parameter title: The dialog title - parameter content: A custom content view - parameter dialogHeight: The height of the dialog - parameter okButtonTitle: The title of the last button (far-most right), normally OK, CLOSE or YES (positive response). */ open func showDialog(_ windowView: UIView, title: String?, content: UIView, dialogHeight: CGFloat?, okButtonTitle: String?) -> NBMaterialDialog { return showDialog(windowView, title: title, content: content, dialogHeight: dialogHeight, okButtonTitle: okButtonTitle, action: nil, cancelButtonTitle: nil, stackedButtons: false) } /** Displays a simple dialog using a title and a view with the content you need - parameter windowView: The window which the dialog is to be attached - parameter title: The dialog title - parameter content: A custom content view - parameter dialogHeight: The height of the dialog - parameter okButtonTitle: The title of the last button (far-most right), normally OK, CLOSE or YES (positive response). - parameter action: The action you wish to invoke when a button is clicked */ open func showDialog(_ windowView: UIView, title: String?, content: UIView, dialogHeight: CGFloat?, okButtonTitle: String?, action: ((_ isOtherButton: Bool) -> Void)?) -> NBMaterialDialog { return showDialog(windowView, title: title, content: content, dialogHeight: dialogHeight, okButtonTitle: okButtonTitle, action: action, cancelButtonTitle: nil, stackedButtons: false) } /** Displays a simple dialog using a title and a view with the content you need - parameter windowView: The window which the dialog is to be attached - parameter title: The dialog title - parameter content: A custom content view - parameter dialogHeight: The height of the dialog - parameter okButtonTitle: The title of the last button (far-most right), normally OK, CLOSE or YES (positive response). - parameter action: The action you wish to invoke when a button is clicked */ open func showDialog(_ windowView: UIView, title: String?, content: UIView, dialogHeight: CGFloat?, okButtonTitle: String?, action: ((_ isOtherButton: Bool) -> Void)?, cancelButtonTitle: String?) -> NBMaterialDialog { return showDialog(windowView, title: title, content: content, dialogHeight: dialogHeight, okButtonTitle: okButtonTitle, action: action, cancelButtonTitle: cancelButtonTitle, stackedButtons: false) } /** Displays a simple dialog using a title and a view with the content you need - parameter windowView: The window which the dialog is to be attached - parameter title: The dialog title - parameter content: A custom content view - parameter dialogHeight: The height of the dialog - parameter okButtonTitle: The title of the last button (far-most right), normally OK, CLOSE or YES (positive response). - parameter action: The action you wish to invoke when a button is clicked - parameter cancelButtonTitle: The title of the first button (the left button), normally CANCEL or NO (negative response) - parameter stackedButtons: Defines if a stackd button view should be used */ open func showDialog(_ windowView: UIView, title: String?, content: UIView, dialogHeight: CGFloat?, okButtonTitle: String?, action: ((_ isOtherButton: Bool) -> Void)?, cancelButtonTitle: String?, stackedButtons: Bool) -> NBMaterialDialog { isStacked = stackedButtons var totalButtonTitleLength: CGFloat = 0.0 self.windowView = windowView let windowSize = windowView.bounds windowView.addSubview(view) view.frame = windowView.bounds tappableView.frame = view.frame tapGesture = UITapGestureRecognizer(target: self, action: #selector(NBMaterialDialog.tappedBg)) tappableView.addGestureRecognizer(tapGesture) setupContainerView() // Add content to contentView contentView = content setupContentView() if let title = title { setupTitleLabelWithTitle(title) } if let okButtonTitle = okButtonTitle { totalButtonTitleLength += (okButtonTitle.uppercased() as NSString).size(attributes: [NSFontAttributeName: UIFont.robotoMediumOfSize(14)]).width + 8 if let cancelButtonTitle = cancelButtonTitle { totalButtonTitleLength += (cancelButtonTitle.uppercased() as NSString).size(attributes: [NSFontAttributeName: UIFont.robotoMediumOfSize(14)]).width + 8 } // Calculate if the combined button title lengths are longer than max allowed for this dialog, if so use stacked buttons. let buttonTotalMaxLength: CGFloat = (windowSize.width - (kWidthMargin*2)) - 16 - 16 - 8 if totalButtonTitleLength > buttonTotalMaxLength { isStacked = true } } // Always display a close/ok button, but setting a title is optional. if let okButtonTitle = okButtonTitle { setupButtonWithTitle(okButtonTitle, button: &okButton, isStacked: isStacked) if let okButton = okButton { okButton.tag = 0 okButton.addTarget(self, action: #selector(NBMaterialDialog.pressedAnyButton(_:)), for: UIControlEvents.touchUpInside) } } if let cancelButtonTitle = cancelButtonTitle { setupButtonWithTitle(cancelButtonTitle, button: &cancelButton, isStacked: isStacked) if let cancelButton = cancelButton { cancelButton.tag = 1 cancelButton.addTarget(self, action: #selector(NBMaterialDialog.pressedAnyButton(_:)), for: UIControlEvents.touchUpInside) } } userAction = action setupViewConstraints() // To get dynamic width to work we need to comment this out and uncomment the stuff in setupViewConstraints. But its currently not working.. containerView.frame = CGRect(x: kWidthMargin, y: (windowSize.height - (dialogHeight ?? kMinimumHeight)) / 2, width: windowSize.width - (kWidthMargin*2), height: fmin(kMaxHeight, (dialogHeight ?? kMinimumHeight))) containerView.clipsToBounds = true return self } // MARK: - View lifecycle open override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() var sz = UIScreen.main.bounds.size let sver = UIDevice.current.systemVersion as NSString let ver = sver.floatValue if ver < 8.0 { // iOS versions before 7.0 did not switch the width and height on device roration if UIInterfaceOrientationIsLandscape(UIApplication.shared.statusBarOrientation) { let ssz = sz sz = CGSize(width:ssz.height, height:ssz.width) } } } // MARK: - User interaction /** Invoked when the user taps the background (anywhere except the dialog) */ internal func tappedBg() { hideDialog(-1) } /** Invoked when a button is pressed - parameter sender: The button clicked */ internal func pressedAnyButton(_ sender: AnyObject) { self.hideDialog((sender as! UIButton).tag) } // MARK: - View Constraints /** Sets up the constraints which defines the dialog */ internal func setupViewConstraints() { if constraintViews == nil { constraintViews = ["content": contentView, "containerView": containerView, "window": windowView] } containerView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-24-[content]-24-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: constraintViews)) if let titleLabel = self.titleLabel { constraintViews["title"] = titleLabel containerView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-24-[title]-24-[content]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: constraintViews)) containerView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-24-[title]-24-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: constraintViews)) } else { containerView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-24-[content]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: constraintViews)) } if okButton != nil || cancelButton != nil { if isStacked { setupStackedButtonsConstraints() } else { setupButtonConstraints() } } else { containerView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:[content]-24-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: constraintViews)) } // TODO: Fix constraints for the containerView so we can remove the dialogheight var // // let margins = ["kWidthMargin": kWidthMargin, "kMinimumHeight": kMinimumHeight, "kMaxHeight": kMaxHeight] // view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-(>=kWidthMargin)-[containerView(>=80@1000)]-(>=kWidthMargin)-|", options: NSLayoutFormatOptions(0), metrics: margins, views: constraintViews)) // view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-(>=kWidthMargin)-[containerView(>=48@1000)]-(>=kWidthMargin)-|", options: NSLayoutFormatOptions(0), metrics: margins, views: constraintViews)) // view.addConstraint(NSLayoutConstraint(item: containerView, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0)) // view.addConstraint(NSLayoutConstraint(item: containerView, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: 0)) } /** Sets up the constraints for normal horizontal styled button layout */ internal func setupButtonConstraints() { if let okButton = self.okButton { constraintViews["okButton"] = okButton containerView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:[content]-24-[okButton(==36)]-8-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: constraintViews)) // The cancel button is only shown when the ok button is visible if let cancelButton = self.cancelButton { constraintViews["cancelButton"] = cancelButton containerView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:[cancelButton(==36)]-8-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: constraintViews)) containerView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:[cancelButton(>=64)]-8-[okButton(>=64)]-8-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: constraintViews)) } else { containerView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:[okButton(>=64)]-8-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: constraintViews)) } } } /** Sets up the constraints for stacked vertical styled button layout */ internal func setupStackedButtonsConstraints() { constraintViews["okButton"] = okButton! constraintViews["cancelButton"] = cancelButton! containerView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:[content]-24-[okButton(==48)]-[cancelButton(==48)]-8-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: constraintViews)) containerView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-[okButton]-16-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: constraintViews)) containerView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-[cancelButton]-16-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: constraintViews)) } // MARK: Private view helpers / initializers fileprivate func setupContainerView() { containerView.backgroundColor = backgroundColor containerView.layer.cornerRadius = 2.0 containerView.layer.masksToBounds = true containerView.layer.borderWidth = 0.5 containerView.layer.borderColor = UIColor(hex: 0xCCCCCC, alpha: 1.0).cgColor view.addSubview(containerView) } fileprivate func setupTitleLabelWithTitle(_ title: String) { titleLabel = UILabel() if let titleLabel = titleLabel { titleLabel.translatesAutoresizingMaskIntoConstraints = false titleLabel.font = UIFont.robotoMediumOfSize(20) titleLabel.textColor = UIColor(white: 0.13, alpha: 1.0) titleLabel.numberOfLines = 0 titleLabel.text = title containerView.addSubview(titleLabel) } } fileprivate func setupButtonWithTitle(_ title: String, button: inout BFPaperButton?, isStacked: Bool) { if button == nil { button = BFPaperButton() } if let button = button { button.translatesAutoresizingMaskIntoConstraints = false button.setTitle(title.uppercased(), for: UIControlState()) button.setTitleColor(NBConfig.AccentColor, for: UIControlState()) button.isRaised = false button.titleLabel?.font = UIFont.robotoMediumOfSize(14) if isStacked { button.contentHorizontalAlignment = UIControlContentHorizontalAlignment.right button.contentEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 20) } else { button.contentEdgeInsets = UIEdgeInsetsMake(0, 8, 0, 8) } containerView.addSubview(button) } } fileprivate func setupContentView() { contentView.backgroundColor = UIColor.clear contentView.translatesAutoresizingMaskIntoConstraints = false containerView.addSubview(contentView) } }
apache-2.0
natecook1000/swift-compiler-crashes
crashes-duplicates/27777-swift-clangimporter-loadextensions.swift
4
204
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing func a{if{if{class a}}enum a<T:T.B
mit
travelbird/react-native-navigation
lib/ios/TBNativeNavigation/ReactEventListener.swift
1
208
// // ReactEventListener.swift // NativeNavigation // // Created by Vlad Smoc on 23-10-2017. // class ReactEventListener { var onEvent:((_ eventName: String, _ props: [String : Any]) -> Void)? }
mit
airspeedswift/swift-compiler-crashes
crashes-fuzzing/01790-swift-constraints-constraintgraph-unbindtypevariable.swift
1
219
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing let end = [ ] struct Q<T where h: T { var _ = a<b
mit
sourcebitsllc/Asset-Generator-Mac
XCAssetGenerator/StringExtension.swift
1
1056
// // StringExtension.swift // XCAssetGenerator // // Created by Bader on 4/8/15. // Copyright (c) 2015 Bader Alabdulrazzaq. All rights reserved. // import Foundation extension String { func remove(strings: [String]) -> String { var v = self for s in strings { v = v.stringByReplacingOccurrencesOfString(s, withString: "") } return v } // TODO: Swift 2.0 func replace(characters: [Character], withCharacter character: Character) -> String { return String(map(self) { find(characters, $0) == nil ? $0 : character }) } func contains(substring: String) -> Bool { return self.rangeOfString(substring) != nil } func removeAssetSetsComponent() -> String { return self.pathComponents.filter { !$0.isAssetSet() } |> String.pathWithComponents } func removeTrailingSlash() -> String { var v = self if v.hasSuffix("/") { v.removeAtIndex(v.endIndex.predecessor()) } return v } }
mit
therealbnut/swift
test/PrintAsObjC/enums.swift
2
5264
// RUN: rm -rf %t // RUN: mkdir -p %t // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -enable-source-import -emit-module -emit-module-doc -o %t %s -import-objc-header %S/Inputs/enums.h -disable-objc-attr-requires-foundation-module // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -parse-as-library %t/enums.swiftmodule -typecheck -emit-objc-header-path %t/enums.h -import-objc-header %S/Inputs/enums.h -disable-objc-attr-requires-foundation-module // RUN: %FileCheck %s < %t/enums.h // RUN: %FileCheck -check-prefix=NEGATIVE %s < %t/enums.h // RUN: %check-in-clang %t/enums.h // RUN: %check-in-clang -fno-modules -Qunused-arguments %t/enums.h -include Foundation.h -include ctypes.h -include CoreFoundation.h // REQUIRES: objc_interop import Foundation // NEGATIVE-NOT: NSMalformedEnumMissingTypedef : // NEGATIVE-NOT: enum EnumNamed // CHECK-LABEL: enum FooComments : NSInteger; // CHECK-LABEL: enum NegativeValues : int16_t; // CHECK-LABEL: enum ObjcEnumNamed : NSInteger; // CHECK-LABEL: @interface AnEnumMethod // CHECK-NEXT: - (enum NegativeValues)takeAndReturnEnum:(enum FooComments)foo SWIFT_WARN_UNUSED_RESULT; // CHECK-NEXT: - (void)acceptPlainEnum:(enum NSMalformedEnumMissingTypedef)_; // CHECK-NEXT: - (enum ObjcEnumNamed)takeAndReturnRenamedEnum:(enum ObjcEnumNamed)foo SWIFT_WARN_UNUSED_RESULT; // CHECK-NEXT: - (void)acceptTopLevelImportedWithA:(enum TopLevelRaw)a b:(TopLevelEnum)b c:(TopLevelOptions)c d:(TopLevelTypedef)d e:(TopLevelAnon)e; // CHECK-NEXT: - (void)acceptMemberImportedWithA:(enum MemberRaw)a b:(enum MemberEnum)b c:(MemberOptions)c d:(enum MemberTypedef)d e:(MemberAnon)e ee:(MemberAnon2)ee; // CHECK: @end @objc class AnEnumMethod { @objc func takeAndReturnEnum(_ foo: FooComments) -> NegativeValues { return .Zung } @objc func acceptPlainEnum(_: NSMalformedEnumMissingTypedef) {} @objc func takeAndReturnRenamedEnum(_ foo: EnumNamed) -> EnumNamed { return .A } @objc func acceptTopLevelImported(a: TopLevelRaw, b: TopLevelEnum, c: TopLevelOptions, d: TopLevelTypedef, e: TopLevelAnon) {} @objc func acceptMemberImported(a: Wrapper.Raw, b: Wrapper.Enum, c: Wrapper.Options, d: Wrapper.Typedef, e: Wrapper.Anon, ee: Wrapper.Anon2) {} } // CHECK-LABEL: typedef SWIFT_ENUM_NAMED(NSInteger, ObjcEnumNamed, "EnumNamed") { // CHECK-NEXT: ObjcEnumNamedA = 0, // CHECK-NEXT: ObjcEnumNamedB = 1, // CHECK-NEXT: ObjcEnumNamedC = 2, // CHECK-NEXT: ObjcEnumNamedD = 3, // CHECK-NEXT: ObjcEnumNamedHelloDolly = 4, // CHECK-NEXT: }; @objc(ObjcEnumNamed) enum EnumNamed: Int { case A, B, C, d, helloDolly } // CHECK-LABEL: typedef SWIFT_ENUM(NSInteger, EnumWithNamedConstants) { // CHECK-NEXT: kEnumA SWIFT_COMPILE_NAME("A") = 0, // CHECK-NEXT: kEnumB SWIFT_COMPILE_NAME("B") = 1, // CHECK-NEXT: kEnumC SWIFT_COMPILE_NAME("C") = 2, // CHECK-NEXT: }; @objc enum EnumWithNamedConstants: Int { @objc(kEnumA) case A @objc(kEnumB) case B @objc(kEnumC) case C } // CHECK-LABEL: typedef SWIFT_ENUM(unsigned int, ExplicitValues) { // CHECK-NEXT: ExplicitValuesZim = 0, // CHECK-NEXT: ExplicitValuesZang = 219, // CHECK-NEXT: ExplicitValuesZung = 220, // CHECK-NEXT: }; // NEGATIVE-NOT: ExplicitValuesDomain @objc enum ExplicitValues: CUnsignedInt { case Zim, Zang = 219, Zung func methodNotExportedToObjC() {} } // CHECK: /** // CHECK-NEXT: Foo: A feer, a female feer. // CHECK-NEXT: */ // CHECK-NEXT: typedef SWIFT_ENUM(NSInteger, FooComments) { // CHECK: /** // CHECK-NEXT: Zim: A zeer, a female zeer. // CHECK: */ // CHECK-NEXT: FooCommentsZim = 0, // CHECK-NEXT: FooCommentsZang = 1, // CHECK-NEXT: FooCommentsZung = 2, // CHECK-NEXT: }; /// Foo: A feer, a female feer. @objc public enum FooComments: Int { /// Zim: A zeer, a female zeer. case Zim case Zang, Zung } // CHECK-LABEL: typedef SWIFT_ENUM(int16_t, NegativeValues) { // CHECK-NEXT: Zang = -219, // CHECK-NEXT: Zung = -218, // CHECK-NEXT: }; @objc enum NegativeValues: Int16 { case Zang = -219, Zung func methodNotExportedToObjC() {} } // CHECK-LABEL: typedef SWIFT_ENUM(NSInteger, SomeError) { // CHECK-NEXT: SomeErrorBadness = 9001, // CHECK-NEXT: SomeErrorWorseness = 9002, // CHECK-NEXT: }; // CHECK-NEXT: static NSString * _Nonnull const SomeErrorDomain = @"enums.SomeError"; @objc enum SomeError: Int, Error { case Badness = 9001 case Worseness } // CHECK-LABEL: typedef SWIFT_ENUM(NSInteger, SomeOtherError) { // CHECK-NEXT: SomeOtherErrorDomain = 0, // CHECK-NEXT: }; // NEGATIVE-NOT: NSString * _Nonnull const SomeOtherErrorDomain @objc enum SomeOtherError: Int, Error { case Domain // collision! } // CHECK-LABEL: typedef SWIFT_ENUM_NAMED(NSInteger, ObjcErrorType, "SomeRenamedErrorType") { // CHECK-NEXT: ObjcErrorTypeBadStuff = 0, // CHECK-NEXT: }; // CHECK-NEXT: static NSString * _Nonnull const ObjcErrorTypeDomain = @"enums.SomeRenamedErrorType"; @objc(ObjcErrorType) enum SomeRenamedErrorType: Int, Error { case BadStuff } // CHECK-NOT: enum {{[A-Z]+}} // CHECK-LABEL: @interface ZEnumMethod // CHECK-NEXT: - (enum NegativeValues)takeAndReturnEnum:(enum FooComments)foo SWIFT_WARN_UNUSED_RESULT; // CHECK: @end @objc class ZEnumMethod { @objc func takeAndReturnEnum(_ foo: FooComments) -> NegativeValues { return .Zung } }
apache-2.0
buyiyang/iosstar
iOSStar/Scenes/Discover/Controllers/VideoHistoryVC.swift
3
6317
// // VideoHistoryVC.swift // iOSStar // // Created by mu on 2017/8/19. // Copyright © 2017年 YunDian. All rights reserved. // import UIKit import SVProgressHUD class VideoHistoryCell: OEZTableViewCell { @IBOutlet weak var voiceCountLabel: UILabel! @IBOutlet weak var contentLabel: UILabel! @IBOutlet weak var timeLabel: UILabel! @IBOutlet var status: UILabel! @IBOutlet var name: UILabel! @IBOutlet var header: UIImageView! @IBOutlet var askBtn: UIButton! override func awakeFromNib() { } override func update(_ data: Any!) { if let response = data as? UserAskDetailList{ contentLabel.text = response.uask timeLabel.text = Date.yt_convertDateStrWithTimestempWithSecond(Int(response.ask_t), format: "YYYY-MM-dd") voiceCountLabel.text = "\(response.s_total)看过" askBtn.isHidden = response.video_url == "" ? true : false if response.isall == 1{ if response.answer_t == 0{ status.text = "明星未回复" }else{ status.text = "已定制" } StartModel.getStartName(startCode: response.starcode) { [weak self](response) in if let star = response as? StartModel { self?.header.kf.setImage(with: URL(string:ShareDataModel.share().qiniuHeader + star.pic_url_tail)) self?.name.text = star.name } } } } } @IBAction func seeAnswer(_ sender: Any) { didSelectRowAction(1, data: nil) } @IBAction func seeAsk(_ sender: Any) { didSelectRowAction(2, data: nil) } } class VideoHistoryVC: BasePageListTableViewController,OEZTableViewDelegate { @IBOutlet weak var titlesView: UIView! @IBOutlet weak var closeButton: UIButton! @IBOutlet weak var openButton: UIButton! var starModel: StarSortListModel = StarSortListModel() var type = true private var selectedButton: UIButton? override func viewDidLoad() { super.viewDidLoad() title = "历史提问" titleViewButtonAction(openButton) } func tableView(_ tableView: UITableView!, rowAt indexPath: IndexPath!, didAction action: Int, data: Any!){ if action == 1{ if let model = dataSource?[indexPath.row] as? UserAskDetailList{ if model.answer_t == 0{ SVProgressHUD.showErrorMessage(ErrorMessage: "明星还没回复", ForDuration: 2, completion: nil) return } self.pushViewController(pushSreing: PlaySingleVC.className(), videdoUrl: (ShareDataModel.share().qiniuHeader + model.sanswer), pushModel: model, withImg: model.thumbnailS != "" ? model.thumbnailS : "1123.png", complete: { (result) in if let vc = UIStoryboard.init(name: "Discover", bundle: nil).instantiateViewController(withIdentifier: "VideoAskQuestionsVC") as? VideoAskQuestionsVC{ self.navigationController?.pushViewController(vc, animated: true) } }) } } if action == 2{ if let model = dataSource?[indexPath.row] as? UserAskDetailList{ if model.video_url == ""{ SVProgressHUD.showErrorMessage(ErrorMessage: "没有提问视频问题", ForDuration: 2, completion: nil) return } self.pushViewController(pushSreing: PlaySingleVC.className(), videdoUrl: (ShareDataModel.share().qiniuHeader + model.video_url), pushModel: model, withImg: model.thumbnail != "" ? model.thumbnail : "1123.png", complete: { (result) in if let vc = UIStoryboard.init(name: "Discover", bundle: nil).instantiateViewController(withIdentifier: "VideoAskQuestionsVC") as? VideoAskQuestionsVC{ vc.starModel = self.starModel self.navigationController?.pushViewController(vc, animated: true) } }) } } } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { if let model = dataSource?[indexPath.row] as? UserAskDetailList{ return model.cellHeight } return 175 } @IBAction func titleViewButtonAction(_ sender: UIButton) { if self.dataSource != nil{ self.dataSource?.removeAll() self.tableView.reloadData() } self.selectedButton?.isSelected = false self.selectedButton?.backgroundColor = UIColor.clear sender.backgroundColor = UIColor(hexString: "ffffff") self.selectedButton = sender if selectedButton == closeButton{ type = false }else{ type = true } self.didRequest(1) } override func didRequest(_ pageIndex: Int) { let model = UserAskRequestModel() model.aType = 1 if starModel.symbol == ""{ }else{ model.starcode = starModel.symbol } model.pos = pageIndex == 1 ? 1 : dataSource?.count ?? 0 model.pType = type ? 1 : 0 model.pos = (pageIndex - 1) * 10 AppAPIHelper.discoverAPI().useraskQuestion(requestModel: model, complete: { [weak self](result) in if let response = result as? UserAskList { for model in response.circle_list!{ model.calculateCellHeight() } self?.didRequestComplete(response.circle_list as AnyObject ) } }) { (error) in self.didRequestComplete(nil) } } override func tableView(_ tableView: UITableView, cellIdentifierForRowAtIndexPath indexPath: IndexPath) -> String? { let model = dataSource?[indexPath.row] as! UserAskDetailList if model.isall == 1{ return "VideoShowImgCell" } // return VideoHistoryCell.className() } }
gpl-3.0
zarghol/ViewDeckSwift
CNViewDeck/CNPresentationController.swift
1
1879
// // CNPresentationController.swift // CNViewDeck // // Created by Clément NONN on 06/06/2014. // Copyright (c) 2014 Clément NONN. All rights reserved. // import UIKit class CNPresentationController: UIPresentationController { override func presentationTransitionWillBegin(){ let containerView = self.containerView let presentedViewController = self.presentedViewController //a voir let dimmingView = presentedViewController.view presentedView().frame = containerView.bounds presentedView().alpha = 0.0 containerView.insertSubview(presentedViewController.view, atIndex:0) presentedViewController.transitionCoordinator().animateAlongsideTransition(test, completion:nil) } func test(coord : UIViewControllerTransitionCoordinatorContext!){ presentedView().alpha = 0.0 } func test2(coord : UIViewControllerTransitionCoordinatorContext!){ presentedView().alpha = 1.0 } override func dismissalTransitionWillBegin(){ self.presentedViewController.transitionCoordinator().animateAlongsideTransition(test2, completion:nil) } override func sizeForChildContentContainer(container:UIContentContainer, withParentContainerSize parentSize:CGSize) -> CGSize{ return CGSizeMake(parentSize.width/3.0, parentSize.height) } override func containerViewWillLayoutSubviews(){ presentedView().frame = self.containerView.bounds } override func frameOfPresentedViewInContainerView() -> CGRect{ let presentedViewFrame = CGRectZero let containerBounds = self.containerView.bounds // missing code let bla:UIContentContainer = self.presentedView() let size:CGSize = self.sizeForChildContentContainer(, withParentContainerSize:containerBounds.size) } }
lgpl-2.1
JudoPay/JudoKit
Source/Receipt.swift
3
3728
// // Receipt.swift // Judo // // Copyright (c) 2016 Alternative Payments Ltd // // 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 open class Receipt { /// the receipt ID - nil for a list of all receipts fileprivate (set) var receiptId: String? /// The current Session to access the Judo API open var APISession: Session? /** Initialization for a Receipt Object If you want to use the receipt function, you need to enable it in your judo Dashboard - Parameter receiptId: the receipt ID as a String - if nil, completion function will return a list of all transactions - Returns: a Receipt Object for reactive usage - Throws: LuhnValidationError if the receiptId does not match */ init(receiptId: String? = nil) throws { // luhn check the receipt id self.receiptId = receiptId } /** apiSession caller - this method sets the session variable and returns itself for further use - Parameter session: the API session which is used to call the Judo endpoints - Returns: reactive self */ open func apiSession(_ session: Session) -> Self { self.APISession = session return self } /** Completion caller - this method will automatically trigger a Session Call to the judo REST API and execute the request based on the information that were set in the previous methods. - Parameter block: a completion block that is called when the request finishes - Returns: reactive self */ open func completion(_ block: @escaping JudoCompletionBlock) -> Self { var path = "transactions" if let rec = self.receiptId { path += "/\(rec)" } self.APISession?.GET(path, parameters: nil) { (dictionary, error) -> () in block(dictionary, error) } return self } /** This method will return a list of receipts See [List all transactions](<https://www.judopay.com/docs/v4_1/restful-api/api-reference/#transactions>) for more information. - Parameter pagination: The offset, number of items and order in which to return the items - Parameter block: a completion block that is called when the request finishes */ open func list(_ pagination: Pagination, block: @escaping JudoCompletionBlock) { let path = "transactions?pageSize=\(pagination.pageSize)&offset=\(pagination.offset)&sort=\(pagination.sort.rawValue)" self.APISession?.GET(path, parameters: nil) { (dictionary, error) -> () in block(dictionary, error) } } }
mit
AnRanScheme/magiGlobe
magi/magiGlobe/Pods/CryptoSwift/Sources/CryptoSwift/BatchedCollection.swift
13
1680
// // BatchedCollection.swift // CryptoSwift // // Created by Marcin Krzyzanowski on 08/01/2017. // Copyright © 2017 Marcin Krzyzanowski. All rights reserved. // struct BatchedCollectionIndex<Base: Collection> { let range: Range<Base.Index> } extension BatchedCollectionIndex: Comparable { static func ==<Base: Collection>(lhs: BatchedCollectionIndex<Base>, rhs: BatchedCollectionIndex<Base>) -> Bool { return lhs.range.lowerBound == rhs.range.lowerBound } static func < <Base: Collection>(lhs: BatchedCollectionIndex<Base>, rhs: BatchedCollectionIndex<Base>) -> Bool { return lhs.range.lowerBound < rhs.range.lowerBound } } protocol BatchedCollectionType: Collection { associatedtype Base: Collection } struct BatchedCollection<Base: Collection>: Collection { let base: Base let size: Base.IndexDistance typealias Index = BatchedCollectionIndex<Base> private func nextBreak(after idx: Base.Index) -> Base.Index { return base.index(idx, offsetBy: size, limitedBy: base.endIndex) ?? base.endIndex } var startIndex: Index { return Index(range: base.startIndex..<nextBreak(after: base.startIndex)) } var endIndex: Index { return Index(range: base.endIndex..<base.endIndex) } func index(after idx: Index) -> Index { return Index(range: idx.range.upperBound..<nextBreak(after: idx.range.upperBound)) } subscript(idx: Index) -> Base.SubSequence { return base[idx.range] } } extension Collection { func batched(by size: IndexDistance) -> BatchedCollection<Self> { return BatchedCollection(base: self, size: size) } }
mit
amujic5/AFEA
AFEA-StarterProject/AFEA-StarterProject/Extensions/UIView+CircleBorder.swift
1
234
import UIKit extension UIView { func createCircleBorder(with color: UIColor, width: CGFloat = 6) { layer.cornerRadius = frame.width / 2 layer.borderWidth = width layer.borderColor = color.cgColor } }
mit
Monits/swift-compiler-crashes
fixed/22156-swift-constraints-constraint-create.swift
11
242
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing [ ] let a { if true { case let { if true { class d { class case c, for (
mit
adolfrank/Swift_practise
07-day/07-day/Spring/HomeViewController.swift
1
559
// // HomeViewController.swift // 07-day // // Created by Hongbo Yu on 16/3/21. // Copyright © 2016年 Frank. All rights reserved. // import UIKit class HomeViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func prefersStatusBarHidden() -> Bool { return false } override func preferredStatusBarUpdateAnimation() -> UIStatusBarAnimation { return UIStatusBarAnimation.Slide } }
mit
rtoal/polyglot
swift/string_to_int_with_guard.swift
2
210
for s in ["42", "dog", "3xy", "-2E3", "-1"] { guard let i = Int(s) else { print("\"\(s)\" can't be parsed to an integer") continue } print("\"\(s)\" parsed as an integer is \(i)") }
mit
goRestart/restart-backend-app
Sources/Domain/Model/Product/ProductRepositoryProtocol.swift
1
126
import Foundation public protocol ProductRepositoryProtocol { func add(_ request: AddProductRequest) throws -> Product }
gpl-3.0
salqadri/tipper
Tipper/SettingsViewController.swift
1
1352
// // SettingsViewController.swift // Tipper // // Created by Syed Salman Qadri on 9/4/14. // Copyright (c) 2014 Yahoo Inc. All rights reserved. // import UIKit class SettingsViewController: UIViewController { @IBOutlet weak var segmented: UISegmentedControl! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. var defaults = NSUserDefaults.standardUserDefaults() var intValue = defaults.integerForKey("tip_default") segmented.selectedSegmentIndex = intValue; } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func tipChanged(sender: UISegmentedControl) { var defaults = NSUserDefaults.standardUserDefaults() defaults.setInteger(sender.selectedSegmentIndex, forKey: "tip_default") defaults.synchronize() } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
dreamsxin/swift
test/1_stdlib/FloatingPointIR.swift
2
2645
// RUN: %target-build-swift -emit-ir %s | FileCheck -check-prefix=%target-cpu %s // RUN: %target-build-swift -O -emit-ir %s | FileCheck -check-prefix=%target-cpu %s // RUN: %target-build-swift -Ounchecked -emit-ir %s | FileCheck -check-prefix=%target-cpu %s var globalFloat32 : Float32 = 0.0 var globalFloat64 : Float64 = 0.0 #if arch(i386) || arch(x86_64) var globalFloat80 : Float80 = 0.0 #endif @inline(never) func acceptFloat32(_ a: Float32) { globalFloat32 = a } @inline(never) func acceptFloat64(_ a: Float64) { globalFloat64 = a } #if arch(i386) || arch(x86_64) @inline(never) func acceptFloat80(_ a: Float80) { globalFloat80 = a } #endif func testConstantFoldFloatLiterals() { acceptFloat32(1.0) acceptFloat64(1.0) #if arch(i386) || arch(x86_64) acceptFloat80(1.0) #endif } // i386: call void @{{.*}}_TF15FloatingPointIR13acceptFloat32FSfT_(float 1.000000e+00) // i386: call void @{{.*}}_TF15FloatingPointIR13acceptFloat64FSdT_(double 1.000000e+00) // i386: call void @{{.*}}_TF15FloatingPointIR13acceptFloat80FVs7Float80T_(x86_fp80 0xK3FFF8000000000000000) // x86_64: call void @{{.*}}_TF15FloatingPointIR13acceptFloat32FSfT_(float 1.000000e+00) // x86_64: call void @{{.*}}_TF15FloatingPointIR13acceptFloat64FSdT_(double 1.000000e+00) // x86_64: call void @{{.*}}_TF15FloatingPointIR13acceptFloat80FVs7Float80T_(x86_fp80 0xK3FFF8000000000000000) // armv7: call void @{{.*}}_TF15FloatingPointIR13acceptFloat32FSfT_(float 1.000000e+00) // armv7: call void @{{.*}}_TF15FloatingPointIR13acceptFloat64FSdT_(double 1.000000e+00) // armv7s: call void @{{.*}}_TF15FloatingPointIR13acceptFloat32FSfT_(float 1.000000e+00) // armv7s: call void @{{.*}}_TF15FloatingPointIR13acceptFloat64FSdT_(double 1.000000e+00) // armv7k: call void @{{.*}}_TF15FloatingPointIR13acceptFloat32FSfT_(float 1.000000e+00) // armv7k: call void @{{.*}}_TF15FloatingPointIR13acceptFloat64FSdT_(double 1.000000e+00) // arm64: call void @{{.*}}_TF15FloatingPointIR13acceptFloat32FSfT_(float 1.000000e+00) // arm64: call void @{{.*}}_TF15FloatingPointIR13acceptFloat64FSdT_(double 1.000000e+00) // powerpc64: call void @{{.*}}_TF15FloatingPointIR13acceptFloat32FSfT_(float 1.000000e+00) // powerpc64: call void @{{.*}}_TF15FloatingPointIR13acceptFloat64FSdT_(double 1.000000e+00) // powerpc64le: call void @{{.*}}_TF15FloatingPointIR13acceptFloat32FSfT_(float 1.000000e+00) // powerpc64le: call void @{{.*}}_TF15FloatingPointIR13acceptFloat64FSdT_(double 1.000000e+00) // s390x: call void @{{.*}}_TF15FloatingPointIR13acceptFloat32FSfT_(float 1.000000e+00) // s390x: call void @{{.*}}_TF15FloatingPointIR13acceptFloat64FSdT_(double 1.000000e+00)
apache-2.0
bigL055/Routable
Example/Pods/BLFoundation/Sources/Tools/RunTime.swift
1
4135
// // BLFoundation // // Copyright (c) 2017 linhay - https://github.com/linhay // // 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 import Foundation public class RunTime { /// 交换方法 /// /// - Parameters: /// - target: 被交换的方法名 /// - replace: 用于交换的方法名 /// - classType: 所属类型 public class func exchangeMethod(target: String, replace: String, class classType: AnyClass) { exchangeMethod(selector: Selector(target), replace: Selector(replace), class: classType) } /// 交换方法 /// /// - Parameters: /// - selector: 被交换的方法 /// - replace: 用于交换的方法 /// - classType: 所属类型 public class func exchangeMethod(selector: Selector, replace: Selector, class classType: AnyClass) { let select1 = selector let select2 = replace let select1Method = class_getInstanceMethod(classType, select1) let select2Method = class_getInstanceMethod(classType, select2) let didAddMethod = class_addMethod(classType, select1, method_getImplementation(select2Method!), method_getTypeEncoding(select2Method!)) if didAddMethod { class_replaceMethod(classType, select2, method_getImplementation(select1Method!), method_getTypeEncoding(select1Method!)) }else { method_exchangeImplementations(select1Method!, select2Method!) } } /// 获取方法列表 /// /// - Parameter classType: 所属类型 /// - Returns: 方法列表 public class func methods(from classType: AnyClass) -> [Method] { var methodNum: UInt32 = 0 var list = [Method]() let methods = class_copyMethodList(classType, &methodNum) for index in 0..<numericCast(methodNum) { if let met = methods?[index] { list.append(met) } } free(methods) return list } /// 获取属性列表 /// /// - Parameter classType: 所属类型 /// - Returns: 属性列表 public class func properties(from classType: AnyClass) -> [objc_property_t] { var propNum: UInt32 = 0 let properties = class_copyPropertyList(classType, &propNum) var list = [objc_property_t]() for index in 0..<Int(propNum) { if let prop = properties?[index]{ list.append(prop) } } free(properties) return list } /// 成员变量列表 /// /// - Parameter classType: 类型 /// - Returns: 成员变量 public class func ivars(from classType: AnyClass) -> [Ivar] { var ivarNum: UInt32 = 0 let ivars = class_copyIvarList(classType, &ivarNum) var list = [Ivar]() for index in 0..<numericCast(ivarNum) { if let ivar: objc_property_t = ivars?[index] { list.append(ivar) } } free(ivars) return list } }
mit
lyft/SwiftLint
Source/SwiftLintFramework/Extensions/Configuration+IndentationStyle.swift
1
773
public extension Configuration { enum IndentationStyle: Equatable { case tabs case spaces(count: Int) public static var `default` = spaces(count: 4) internal init?(_ object: Any?) { switch object { case let value as Int: self = .spaces(count: value) case let value as String where value == "tabs": self = .tabs default: return nil } } // MARK: Equatable public static func == (lhs: IndentationStyle, rhs: IndentationStyle) -> Bool { switch (lhs, rhs) { case (.tabs, .tabs): return true case let (.spaces(lhs), .spaces(rhs)): return lhs == rhs case (_, _): return false } } } }
mit
0xfeedface1993/Xs8-Safari-Block-Extension-Mac
Sex8BlockExtension/Sex8BlockExtension/ViewController.swift
1
8551
// // ViewController.swift // Sex8BlockExtension // // Created by virus1993 on 2017/6/13. // Copyright © 2017年 ascp. All rights reserved. // import Cocoa import WebShell let StopFetchName = NSNotification.Name.init("stopFetching") let ShowExtennalTextName = NSNotification.Name.init("showExtennalText") let UploadName = NSNotification.Name.init("UploadName") let DownloadAddressName = NSNotification.Name.init("com.ascp.dowload.address.click") let RemoteDownloadAddressName = NSNotification.Name.init("com.ascp.remote.dowload.address.click") var searchText : String? class ViewController: NSViewController, UpdateProtocol { @IBOutlet weak var save: NSButton! @IBOutlet weak var collectionView: NSView! @IBOutlet weak var head: TapImageView! @IBOutlet weak var username: NSTextField! @IBOutlet weak var userprofile: NSTextField! @IBOutlet weak var extenalText: NSTextField! @IBOutlet weak var searchArea: NSSearchField! @IBOutlet weak var downloadButton: NSButton! lazy var downloadViewController : ContentViewController = storyboard!.instantiateController(withIdentifier: "com.ascp.contenView") as! ContentViewController lazy var popver : NSPopover = { let popver = NSPopover() popver.appearance = NSAppearance(named: NSAppearance.Name.aqua) let vc = self.downloadViewController vc.view.wantsLayer = true vc.view.layer?.cornerRadius = 10 popver.contentViewController = vc popver.behavior = .transient return popver }() var downloadURL : URL? let login = NSStoryboard(name: "LoginStoryboard", bundle: Bundle.main).instantiateInitialController() as! NSWindowController override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. unselect() NotificationCenter.default.addObserver(self, selector: #selector(ViewController.select), name: SelectItemName, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(ViewController.unselect), name: UnSelectItemName, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(ViewController.stopFetch), name: StopFetchName, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(ViewController.showExtennalText(notification:)), name: ShowExtennalTextName, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(resetSearchValue(notification:)), name: NSControl.textDidChangeNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(changeDownloadState(notification: )), name: DownloadAddressName, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(download(_:)), name: RemoteDownloadAddressName, object: nil) head.tapBlock = { [weak self] image in // let app = NSApp.delegate as! AppDelegate // if let _ = app.user { // // } else { // self.login.showWindow(nil) // } self?.popver.show(relativeTo: image.bounds, of: image, preferredEdge: .maxY) } searchArea.delegate = self upload.isHidden = true // extract.isHidden = true } deinit { NotificationCenter.default.removeObserver(self, name: SelectItemName, object: nil) NotificationCenter.default.removeObserver(self, name: UnSelectItemName, object: nil) NotificationCenter.default.removeObserver(self, name: StopFetchName, object: nil) NotificationCenter.default.removeObserver(self, name: ShowExtennalTextName, object: nil) NotificationCenter.default.removeObserver(self, name: DownloadAddressName, object: nil) NotificationCenter.default.removeObserver(self, name: RemoteDownloadAddressName, object: nil) NotificationCenter.default.removeObserver(self, name: NSControl.textDidChangeNotification, object: nil) } override func viewDidAppear() { super.viewDidAppear() } @IBOutlet weak var extract: NSButton! override var representedObject: Any? { didSet { // Update the view, if already loaded. } } @IBAction func save(_ sender: Any) { let app = NSApplication.shared.delegate as! AppDelegate app.resetAllRecords(in: "NetDisk") } @IBAction func extract(_ sender: Any) { let fetchButton = sender as! NSButton if fetchButton.tag == 110 { stopFetch() } else { fetchButton.tag = 110 fetchButton.title = "停止" } NotificationCenter.default.post(name: TableViewRefreshName, object: fetchButton) } @objc func stopFetch() { extract.tag = 112 extract.title = "获取前十页" self.extenalText.stringValue = "(已停止)" + self.extenalText.stringValue } @IBAction func deleteAction(_ sender: Any) { NotificationCenter.default.post(name: DeleteActionName, object: nil) } @objc func select() { } @objc func unselect() { } @IBOutlet weak var upload: NSButton! @IBAction func uploadAction(_ sender: Any) { if upload.title == "上传" { upload.title = "停止" NotificationCenter.default.post(name: UploadName, object: nil) } else { upload.title = "上传" NotificationCenter.default.post(name: UploadName, object: 444) } } @objc func showExtennalText(notification: NSNotification?) { if let text = notification?.object as? String { self.extenalText.stringValue = text } } //MARK: - 下载 @IBAction func download(_ sender: Any) { defer { downloadButton.isEnabled = false } guard let link = downloadURL else { print("dowloadURL is nil!") return } let pipline = PCPipeline.share pipline.delegate = self let app = NSApp.delegate as! AppDelegate let password = "\(app.selectItem?.passwod ?? "")" let firendName = "\(app.selectItem?.title?.replacingOccurrences(of: "/", with: "-").replacingOccurrences(of: ".", with: "-") ?? "")" if let _ = pipline.add(url: link.absoluteString, password: password, friendName: firendName) { // riffle.downloadStateController = downloadViewController.resultArrayContriller view.toast("成功添加下载任务") } } @objc func changeDownloadState(notification: Notification) { guard let linkString = notification.object as? String else { print("none string object!") downloadButton.isEnabled = false downloadURL = nil return } guard let linkURL = URL(string: linkString) else { print("none URL string!") downloadButton.isEnabled = false downloadURL = nil return } downloadURL = linkURL downloadButton.isEnabled = true } } // MARK: - Login Fun extension ViewController { } // MARK: - TextFieldDelegate extension ViewController : NSSearchFieldDelegate { func searchFieldDidStartSearching(_ sender: NSSearchField) { print("start search!") } func searchFieldDidEndSearching(_ sender: NSSearchField) { print("end search") } @objc func resetSearchValue(notification: NSNotification?) { print("change text value \(searchArea.stringValue)") } } extension ViewController : PCPiplineDelegate { func pipline(didAddRiffle riffle: PCWebRiffle) { let vc = downloadViewController print("found \(vc)") vc.add(riffle: riffle) } func pipline(didUpdateTask task: PCDownloadTask) { let vc = downloadViewController vc.update(task: task) } func pipline(didFinishedTask task: PCDownloadTask) { let vc = downloadViewController vc.finished(task: task) } func pipline(didFinishedRiffle riffle: PCWebRiffle) { let vc = downloadViewController if let task = PCDownloadManager.share.allTasks.first(where: { $0.request.riffle == riffle }) { vc.finished(task: task) } else { vc.finished(riffle: riffle) } } }
apache-2.0
RocketChat/Rocket.Chat.iOS
Rocket.Chat/Extensions/UIColorExtension.swift
1
5854
// // UIColorExtension.swift // Rocket.Chat // // Created by Rafael K. Streit on 8/4/16. // Copyright © 2016 Rocket.Chat. All rights reserved. // import UIKit enum SystemMessageColor { case warning case danger case good case unknown(String) init(rawValue: String) { switch rawValue { case SystemMessageColor.warning.rawValue: self = .warning case SystemMessageColor.danger.rawValue: self = .danger case SystemMessageColor.good.rawValue: self = .good default: self = .unknown(rawValue) } } var rawValue: String { return String(describing: self) } var color: UIColor { switch self { case .warning: return UIColor(rgb: 0xFCB316, alphaVal: 1) case .danger: return UIColor(rgb: 0xD30230, alphaVal: 1) case .good: return UIColor(rgb: 0x35AC19, alphaVal: 1) case .unknown(let string): return UIColor(hex: string) } } } extension UIColor { convenience init(rgb: Int, alphaVal: CGFloat) { self.init( red: CGFloat((rgb & 0xFF0000) >> 16) / 255.0, green: CGFloat((rgb & 0x00FF00) >> 8) / 255.0, blue: CGFloat(rgb & 0x0000FF) / 255.0, alpha: CGFloat(alphaVal) ) } // MARK: Avatar Colors static var avatarColors: [UIColor] { return [ 0xF44336, 0xE91E63, 0x9C27B0, 0x673AB7, 0x3F51B5, 0x2196F3, 0x03A9F4, 0x00BCD4, 0x009688, 0x4CAF50, 0x8BC34A, 0xCDDC39, 0xFFC107, 0xFF9800, 0xFF5722, 0x795548, 0x9E9E9E, 0x607D8B ].map { UIColor(rgb: $0, alphaVal: 1.0) } } static func forName(_ name: String) -> UIColor { return avatarColors[name.count % avatarColors.count] } // MARK: Color from strings static func normalizeColorFromString(string: String) -> UIColor { return SystemMessageColor(rawValue: string).color } // MARK: Status static func RCOnline() -> UIColor { return UIColor(rgb: 0x2DE0A5, alphaVal: 1) } static func RCAway() -> UIColor { return UIColor(rgb: 0xFFD21F, alphaVal: 1) } static func RCBusy() -> UIColor { return UIColor(rgb: 0xF5455C, alphaVal: 1) } static func RCInvisible() -> UIColor { return UIColor(rgb: 0xCBCED1, alphaVal: 1) } // MARK: Theme color static func RCNavigationBarColor() -> UIColor { return UIColor(rgb: 0xF8F8F8, alphaVal: 1) } static func RCBackgroundColor() -> UIColor { return UIColor(rgb: 0x2F343D, alphaVal: 1) } static func RCEditingAvatarColor() -> UIColor { return UIColor(rgb: 0xEAEAEA, alphaVal: 0.75) } static func RCTextFieldGray() -> UIColor { return UIColor(rgb: 10396328, alphaVal: 1) } static func RCTextFieldBorderGray() -> UIColor { return UIColor(rgb: 15199218, alphaVal: 1) } static func RCButtonBorderGray() -> UIColor { return UIColor(rgb: 14804456, alphaVal: 1) } static func RCDarkGray() -> UIColor { return UIColor(rgb: 0x333333, alphaVal: 1) } static func RCGray() -> UIColor { return UIColor(rgb: 0x9EA2A8, alphaVal: 1) } static func RCNavBarGray() -> UIColor { return UIColor(rgb: 3355443, alphaVal: 1) } static func RCLightGray() -> UIColor { return UIColor(rgb: 0xCBCED1, alphaVal: 1) } static func RCSeparatorGrey() -> UIColor { return UIColor(rgb: 0xC2C2C2, alphaVal: 0.5) } static func RCSkyBlue() -> UIColor { return UIColor(rgb: 1930485, alphaVal: 1) } static func RCDarkBlue() -> UIColor { return UIColor(rgb: 0x0a4469, alphaVal: 1) } static func RCLightBlue() -> UIColor { return UIColor(rgb: 0x9EA2A8, alphaVal: 1) } static func RCBlue() -> UIColor { return UIColor(rgb: 0x1D74F5, alphaVal: 1) } // MARK: Function color static func RCFavoriteMark() -> UIColor { return UIColor(rgb: 0xF8B62B, alphaVal: 1.0) } static func RCFavoriteUnmark() -> UIColor { return UIColor.lightGray } // MARK: Colors from Web Version static let primaryAction = UIColor(rgb: 0x1D74F5, alphaVal: 1) static let secondAction = UIColor(rgb: 0xD3E3FC, alphaVal: 1) static let attention = UIColor(rgb: 0xF5455C, alphaVal: 1) static var code: UIColor { return UIColor(rgb: 0x333333, alphaVal: 1.0) } static var codeBackground: UIColor { return UIColor(rgb: 0xF8F8F8, alphaVal: 1.0) } // MARK: Mention Color static func background(for mention: Mention) -> UIColor { if mention.username == AuthManager.currentUser()?.username { return .primaryAction } if mention.username == "all" || mention.username == "here" { return .attention } return .white } static func font(for mention: Mention) -> UIColor { if mention.username == AuthManager.currentUser()?.username { return .white } if mention.username == "all" || mention.username == "here" { return .white } return .primaryAction } } // MARK: UIKit default colors extension UIColor { static var placeholderGray: UIColor { return UIColor(red: 199/255, green: 199/255, blue: 205/255, alpha: 1) } static var backgroundWhite: UIColor { return UIColor(red: 247/255, green: 247/255, blue: 247/255, alpha: 1) } } // MARK: Utils extension UIColor { func isBrightColor() -> Bool { guard let components = cgColor.components else { return false } let brightness = ((components[0] * 299) + (components[1] * 587) + (components[2] * 114)) / 1000 return brightness < 0.5 ? false : true } }
mit
ThryvInc/subway-ios
SubwayMap/DatabaseLoader.swift
2
3249
// // DatabaseLoader.swift // SubwayMap // // Created by Elliot Schrock on 8/2/15. // Copyright (c) 2015 Thryv. All rights reserved. // import UIKit import GTFSStations import SubwayStations import ZipArchive class DatabaseLoader: NSObject { static var isDatabaseReady: Bool = false static var stationManager: StationManager! static var navManager: StationManager! static let NYCDatabaseLoadedNotification = "NYCDatabaseLoadedNotification" static var documentsDirectory: String { return NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] } static var destinationPath: String { return self.documentsDirectory + "/" + "gtfs.db" } static var navDbDestinationPath: String { return self.documentsDirectory + "/" + "nav.db" } class func loadDb() { unzipDBToDocDirectoryIfNeeded() do { stationManager = try NYCStationManager(sourceFilePath: destinationPath) navManager = try NYCStationManager(sourceFilePath: navDbDestinationPath) DispatchQueue.main.async (execute: { () -> Void in self.isDatabaseReady = true NotificationCenter.default.post(name: Notification.Name(rawValue: self.NYCDatabaseLoadedNotification), object: nil) }) }catch let error as NSError { print(error.debugDescription) } } class func unzipDBToDocDirectoryIfNeeded(){ if shouldUnzip(defaultsKey: "version", path: destinationPath) { unzipScheduleToDocDirectory() } if shouldUnzip(defaultsKey: "nav_version", path: navDbDestinationPath) { unzipNavToDocDirectory() } } class func shouldUnzip(defaultsKey: String, path: String) -> Bool { var shouldUnzip = !FileManager.default.fileExists(atPath: path) if let storedVersion = UserDefaults.standard.string(forKey: defaultsKey) { shouldUnzip = shouldUnzip || VersionChecker.isNewVersion(version: storedVersion) } else { shouldUnzip = true } return shouldUnzip } class func unzipScheduleToDocDirectory() { unzipDBToDocDirectory(resourceName: "gtfs.db", destination: destinationPath, defaultsKey: "version") } class func unzipNavToDocDirectory() { unzipDBToDocDirectory(resourceName: "nav.db", destination: navDbDestinationPath, defaultsKey: "nav_version") } class func unzipDBToDocDirectory(resourceName: String, destination: String, defaultsKey: String){ let sourcePath = Bundle.main.path(forResource: resourceName, ofType: "zip") var error: NSError? let unzipper = ZipArchive() unzipper.unzipOpenFile(sourcePath) unzipper.unzipFile(to: documentsDirectory, overWrite: true) let fileUrl = URL(fileURLWithPath: destinationPath) do { try (fileUrl as NSURL).setResourceValue(NSNumber(value: true as Bool), forKey: URLResourceKey.isExcludedFromBackupKey) } catch let error1 as NSError { error = error1 } UserDefaults.standard.set(VersionChecker.bundleVersion(), forKey: defaultsKey) } }
mit
Zewo/HTTP
Tests/HTTPTests/Middleware/BufferServerContentNegotiationMiddlewareTests.swift
5
5931
import XCTest @testable import HTTP public class BufferServerContentNegotiationMiddlewareTests : XCTestCase { let contentNegotiation = ContentNegotiationMiddleware(mediaTypes: [.json, .urlEncodedForm], serializationMode: .buffer) func testJSONRequestDefaultResponse() throws { let request = Request( headers: [ "Content-Type": "application/json; charset=utf-8" ], body: "{\"foo\":\"bar\"}" ) let responder = BasicResponder { request in XCTAssertEqual(request.content, ["foo": "bar"]) return Response(content: ["fuu": "baz"]) } let response = try contentNegotiation.respond(to: request, chainingTo: responder) // Because there was no Accept header we serializer with the first media type in the // content negotiation middleware media type list. In this case JSON. XCTAssertEqual(response.headers["Content-Type"], "application/json; charset=utf-8") XCTAssertEqual(response.body, .buffer(Buffer("{\"fuu\":\"baz\"}"))) XCTAssertNil(response.transferEncoding) } func testJSONRequestResponse() throws { let request = Request( headers: [ "Content-Type": "application/json; charset=utf-8", "Accept": "application/json" ], body: "{\"foo\":\"bar\"}" ) let responder = BasicResponder { request in XCTAssertEqual(request.content, ["foo": "bar"]) return Response(content: ["fuu": "baz"]) } let response = try contentNegotiation.respond(to: request, chainingTo: responder) XCTAssertEqual(response.headers["Content-Type"], "application/json; charset=utf-8") XCTAssertEqual(response.body, .buffer(Buffer("{\"fuu\":\"baz\"}"))) XCTAssertNil(response.transferEncoding) } func testJSONRequestURLEncodedFormResponse() throws { let request = Request( headers: [ "Content-Type": "application/json; charset=utf-8", "Accept": "application/x-www-form-urlencoded" ], body: "{\"foo\":\"bar\"}" ) let responder = BasicResponder { request in XCTAssertEqual(request.content, ["foo": "bar"]) return Response(content: ["fuu": "baz"]) } let response = try contentNegotiation.respond(to: request, chainingTo: responder) XCTAssertEqual(response.headers["Content-Type"], "application/x-www-form-urlencoded; charset=utf-8") XCTAssertEqual(response.body, .buffer(Buffer("fuu=baz"))) XCTAssertNil(response.transferEncoding) } func testURLEncodedFormRequestDefaultResponse() throws { let request = Request( headers: [ "Content-Type": "application/x-www-form-urlencoded; charset=utf-8" ], body: "foo=bar" ) let responder = BasicResponder { request in XCTAssertEqual(request.content, ["foo": "bar"]) return Response(content: ["fuu": "baz"]) } let response = try contentNegotiation.respond(to: request, chainingTo: responder) // Because there was no Accept header we serializer with the first media type in the // content negotiation middleware media type list. In this case JSON. XCTAssertEqual(response.headers["Content-Type"], "application/json; charset=utf-8") XCTAssertEqual(response.body, .buffer(Buffer("{\"fuu\":\"baz\"}"))) XCTAssertNil(response.transferEncoding) } func testURLEncodedFormRequestResponse() throws { let request = Request( headers: [ "Content-Type": "application/x-www-form-urlencoded; charset=utf-8", "Accept": "application/x-www-form-urlencoded" ], body: "foo=bar" ) let responder = BasicResponder { request in XCTAssertEqual(request.content, ["foo": "bar"]) return Response(content: ["fuu": "baz"]) } let response = try contentNegotiation.respond(to: request, chainingTo: responder) XCTAssertEqual(response.headers["Content-Type"], "application/x-www-form-urlencoded; charset=utf-8") XCTAssertEqual(response.body, .buffer(Buffer("fuu=baz"))) XCTAssertNil(response.transferEncoding) } func testURLEncodedFormRequestJSONResponse() throws { let request = Request( headers: [ "Content-Type": "application/x-www-form-urlencoded; charset=utf-8", "Accept": "application/json" ], body: "foo=bar" ) let responder = BasicResponder { request in XCTAssertEqual(request.content, ["foo": "bar"]) return Response(content: ["fuu": "baz"]) } let response = try contentNegotiation.respond(to: request, chainingTo: responder) XCTAssertEqual(response.headers["Content-Type"], "application/json; charset=utf-8") XCTAssertEqual(response.body, .buffer(Buffer("{\"fuu\":\"baz\"}"))) XCTAssertNil(response.transferEncoding) } } extension BufferServerContentNegotiationMiddlewareTests { public static var allTests: [(String, (BufferServerContentNegotiationMiddlewareTests) -> () throws -> Void)] { return [ ("testJSONRequestDefaultResponse", testJSONRequestDefaultResponse), ("testJSONRequestResponse", testJSONRequestResponse), ("testJSONRequestURLEncodedFormResponse", testJSONRequestURLEncodedFormResponse), ("testURLEncodedFormRequestDefaultResponse", testURLEncodedFormRequestDefaultResponse), ("testURLEncodedFormRequestResponse", testURLEncodedFormRequestResponse), ("testURLEncodedFormRequestJSONResponse", testURLEncodedFormRequestJSONResponse), ] } }
mit
emilstahl/swift
validation-test/compiler_crashers_fixed/0379-swift-type-transform.swift
13
365
// RUN: not %target-swift-frontend %s -parse // Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing func c<i>() -> (i, i -> i) -> i { k b k.i = { } { i) { k } } protocol c { clas F>(f: B<T>) { } } struct d<f : e, g: e where g.h == f.h> { func f<T>(
apache-2.0
aulas-lab/ads-mobile
swift/Catalogo/Catalogo/MercadoriaCellView.swift
1
561
// // MercadoriaCellView.swift // Catalogo // // Created by Mobitec on 24/05/16. // Copyright (c) 2016 Unopar. All rights reserved. // import UIKit class MercadoriaCellView: UITableViewCell { @IBOutlet weak var nome: UILabel! @IBOutlet weak var preco: UILabel! override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
mit
ben-ng/swift
validation-test/compiler_crashers_fixed/25728-swift-modulefile-maybereadgenericparams.swift
1
469
// 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 enum S{enum S<a{{}func g{class a{struct S<T where g:T{enum e{{}class B
apache-2.0
rnystrom/GitHawk
Pods/StyledTextKit/Source/StyledText.swift
1
5067
// // StyledTextKit.swift // StyledTextKit // // Created by Ryan Nystrom on 12/12/17. // Copyright © 2017 Ryan Nystrom. All rights reserved. // import Foundation import UIKit public class StyledText: Hashable, Equatable { public struct ImageFitOptions: OptionSet { public let rawValue: Int public init(rawValue: Int) { self.rawValue = rawValue } public static let fit = ImageFitOptions(rawValue: 1 << 0) public static let center = ImageFitOptions(rawValue: 2 << 0) } public enum Storage: Hashable, Equatable { case text(String) case attributedText(NSAttributedString) case image(UIImage, [ImageFitOptions]) // MARK: Hashable public var hashValue: Int { switch self { case .text(let text): return text.hashValue case .attributedText(let text): return text.hashValue case .image(let image, _): return image.hashValue } } // MARK: Equatable public static func ==(lhs: Storage, rhs: Storage) -> Bool { switch lhs { case .text(let lhsText): switch rhs { case .text(let rhsText): return lhsText == rhsText case .attributedText, .image: return false } case .attributedText(let lhsText): switch rhs { case .text, .image: return false case .attributedText(let rhsText): return lhsText == rhsText } case .image(let lhsImage, let lhsOptions): switch rhs { case .text, .attributedText: return false case .image(let rhsImage, let rhsOptions): return lhsImage == rhsImage && lhsOptions == rhsOptions } } } } public let storage: Storage public let style: TextStyle public init(storage: Storage = .text(""), style: TextStyle = TextStyle()) { self.storage = storage self.style = style } public convenience init(text: String, style: TextStyle = TextStyle()) { self.init(storage: .text(text), style: style) } internal var text: String { switch storage { case .text(let text): return text case .attributedText(let text): return text.string case .image: return "" } } internal func render(contentSizeCategory: UIContentSizeCategory) -> NSAttributedString { var attributes = style.attributes let font = style.font(contentSizeCategory: contentSizeCategory) attributes[.font] = font switch storage { case .text(let text): return NSAttributedString(string: text, attributes: attributes) case .attributedText(let text): guard text.length > 0 else { return text } let mutable = text.mutableCopy() as? NSMutableAttributedString ?? NSMutableAttributedString() let range = NSRange(location: 0, length: mutable.length) for (k, v) in attributes { // avoid overwriting attributes set by the stored string if mutable.attribute(k, at: 0, effectiveRange: nil) == nil { mutable.addAttribute(k, value: v, range: range) } } return mutable case .image(let image, let options): let attachment = NSTextAttachment() attachment.image = image var bounds = attachment.bounds let size = image.size if options.contains(.fit) { let ratio = size.width / size.height let fontHeight = min(ceil(font.pointSize), size.height) bounds.size.width = ratio * fontHeight bounds.size.height = fontHeight } else { bounds.size = size } if options.contains(.center) { bounds.origin.y = round((font.capHeight - bounds.height) / 2) } attachment.bounds = bounds // non-breaking space so the color hack doesn't wrap let attributedString = NSMutableAttributedString(string: "\u{00A0}") attributedString.append(NSAttributedString(attachment: attachment)) // replace attributes to 0 size font so no actual space taken attributes[.font] = UIFont.systemFont(ofSize: 0) // override all attributes so color actually tints image attributedString.addAttributes( attributes, range: NSRange(location: 0, length: attributedString.length) ) return attributedString } } // MARK: Hashable public var hashValue: Int { return storage .combineHash(with: style) } // MARK: Equatable public static func ==(lhs: StyledText, rhs: StyledText) -> Bool { return lhs.storage == rhs.storage && lhs.style == rhs.style } }
mit
ben-ng/swift
validation-test/compiler_crashers_fixed/01741-swift-constraints-constraintsystem-simplifymemberconstraint.swift
1
492
// 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 ([() enum B : A { f<T>(x) -> { } } protocol A { protocol a { } func d typealias b : b = b[1 s
apache-2.0
ben-ng/swift
validation-test/compiler_crashers_fixed/00587-swift-pattern-foreachvariable.swift
1
504
// 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 protocol b { protocol A : a { var d { } func a: ().dynamicType.e<T> { } })] = ") } for (start, object2: b
apache-2.0
ben-ng/swift
validation-test/compiler_crashers_fixed/25459-swift-declcontext-lookupqualified.swift
1
431
// 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 enum A{class A<T:A{}func b<D:D.c
apache-2.0
ben-ng/swift
validation-test/compiler_crashers_fixed/00087-swift-archetypebuilder-resolvearchetype.swift
1
972
// 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 u<w>() { enum b { n) -> n { r !(u) } func u(b: Any, k: Any) -> (((Any, Any) -> Any) -> Any) { r { (x: (Any, Any) -> Any) -> Any s r x(b, k) } } func b(q: (((Any, Any) -> Any) -> Any)) -> Any { r q({ (p: Any, l:Any) -> Any s r p }) } b(u(v, u(t, y))) class u { typealias b = b } class i: i { } class o : cb { } typealias cb = o ({}) a a<p : i, cb: i j cb.l == p.l> { } x i { typealias l } x u { class func l() } class b: u { class func l() { } } (b() b u).dc.l() func u(b: Int var p: w
apache-2.0