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 |
---|---|---|---|---|---|
austinzheng/swift-compiler-crashes | crashes-duplicates/17117-getselftypeforcontainer.swift | 11 | 227 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
if true {
let end = 1
protocol A {
func a
typealias f : a
| mit |
austinzheng/swift-compiler-crashes | crashes-duplicates/26458-swift-constraints-constraintsystem-simplifymemberconstraint.swift | 7 | 179 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
{nil...{(
| mit |
recursivestep/RSSnapGridSwift | RSDraggableFlowLayoutTests/RSDraggableFlowLayoutTests.swift | 1 | 949 | //
// RSDraggableFlowLayoutTests.swift
// RSDraggableFlowLayoutTests
//
// Created by Mark Williams on 07/08/2014.
// Copyright (c) 2014 Mark Williams. All rights reserved.
//
import UIKit
import XCTest
class RSDraggableFlowLayoutTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
XCTAssert(true, "Pass")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock() {
// Put the code you want to measure the time of here.
}
}
}
| mit |
chernyog/CYWeibo | CYWeibo/CYWeibo/CYWeibo/Classes/UI/Compose/EmoteTextAttachment.swift | 1 | 691 | //
// EmoteTextAttachment.swift
// CYWeibo
//
// Created by 陈勇 on 15/3/14.
// Copyright (c) 2015年 zhssit. All rights reserved.
//
import UIKit
class EmoteTextAttachment: NSTextAttachment {
/// 表情对应的文本
var emoteString: String?
class func getAttributedString(emoticon: Emoticon, height: CGFloat) -> NSAttributedString
{
// 生成 attributedString
let attachment = EmoteTextAttachment()
attachment.image = UIImage(contentsOfFile: emoticon.imagePath!)
attachment.bounds = CGRectMake(0, -4, height, height)
attachment.emoteString = emoticon.chs
return NSAttributedString(attachment: attachment)
}
}
| mit |
mmrmmlrr/ExamMaster | Pods/ModelsTreeKit/ModelsTreeKit/Classes/Lists/UnorderedListDataAdapter.swift | 1 | 7015 | //
// UnorderedListDataAdapter.swift
// SessionSwift
//
// Created by aleksey on 16.10.15.
// Copyright © 2015 aleksey chernish. All rights reserved.
//
import Foundation
public class UnorderedListDataAdapter<ObjectType, GroupKeyType where
ObjectType: Hashable, ObjectType: Equatable,
GroupKeyType: Hashable, GroupKeyType: Comparable>: ObjectsDataSource<ObjectType> {
typealias Section = (objects: [ObjectType], key: GroupKeyType?)
typealias Sections = [Section]
public var groupingCriteria: (ObjectType -> GroupKeyType)?
public var groupsSortingCriteria: (GroupKeyType, GroupKeyType) -> Bool = { return $0 < $1 }
public var groupContentsSortingCriteria: ((ObjectType, ObjectType) -> Bool)?
private var sections = Sections()
private let pool = AutodisposePool()
public init(list: UnorderedList<ObjectType>) {
super.init()
list.beginUpdatesSignal.subscribeNext { [weak self] in self?.beginUpdates() }.putInto(pool)
list.endUpdatesSignal.subscribeNext { [weak self] in self?.endUpdates() }.putInto(pool)
list.didReplaceContentSignal.subscribeNext() { [weak self] objects in
guard let strongSelf = self else { return }
strongSelf.sections = strongSelf.arrangedSectionsFrom(objects)
}.putInto(pool)
list.didChangeContentSignal.subscribeNext { [weak self] insertions, deletions, updates in
guard let strongSelf = self else { return }
let oldSections = strongSelf.sections
strongSelf.applyInsertions(insertions, deletions: deletions, updates: updates)
strongSelf.pushInsertions(
insertions,
deletions: deletions,
updates: updates,
oldSections: oldSections)
}.putInto(pool)
}
//Helpers
public func fetchAllFrom(list: UnorderedList<ObjectType>) {
sections = arrangedSectionsFrom(list.objects)
}
public func indexPathFor(object: ObjectType) -> NSIndexPath? {
return indexPathFor(object, inSections: sections)
}
public func allObjects() -> [[ObjectType]] {
if sections.isEmpty { return [] }
return sections.map {return $0.objects}
}
public override func numberOfSections() -> Int {
return sections.count
}
public override func numberOfObjectsInSection(section: Int) -> Int {
return sections[section].objects.count
}
public override func objectAtIndexPath(indexPath: NSIndexPath) -> ObjectType? {
return objectAtIndexPath(indexPath, inSections: sections)
}
func objectAtIndexPath(indexPath: NSIndexPath, inSections sections: Sections) -> ObjectType? {
return sections[indexPath.section].objects[indexPath.row]
}
override func titleForSection(atIndex sectionIndex: Int) -> String? {
return sections[sectionIndex].key as? String
}
//Private
private func arrangedSectionsFrom(objects: Set<ObjectType>) -> Sections {
if objects.isEmpty { return [] }
guard let groupingBlock = groupingCriteria else {
if let sortingCriteria = groupContentsSortingCriteria {
return [(objects: objects.sort(sortingCriteria), key: nil)]
} else {
return [(objects: Array(objects), key: nil)]
}
}
var groupsDictionary = [GroupKeyType: [ObjectType]]()
for object in objects {
let key = groupingBlock(object)
if groupsDictionary[key] == nil {
groupsDictionary[key] = []
}
groupsDictionary[key]!.append(object)
}
let sortedKeys = groupsDictionary.keys.sort(groupsSortingCriteria)
var result = Sections()
for key in sortedKeys {
var objects = groupsDictionary[key]!
if let sortingCriteria = groupContentsSortingCriteria {
objects = objects.sort(sortingCriteria)
}
result.append((objects, key))
}
return result
}
private func applyInsertions(insertions: Set<ObjectType>, deletions: Set<ObjectType>, updates: Set<ObjectType>) {
var objects = allObjectsSet()
objects.unionInPlace(insertions.union(updates))
objects.subtractInPlace(deletions)
sections = arrangedSectionsFrom(objects)
}
private func pushInsertions(
insertions: Set<ObjectType>,
deletions: Set<ObjectType>,
updates: Set<ObjectType>,
oldSections: Sections) {
//Objects
for object in insertions {
didChangeObjectSignal.sendNext((
object: object,
changeType: .Insertion,
fromIndexPath: nil,
toIndexPath: indexPathFor(object, inSections: sections))
)
}
for object in deletions {
didChangeObjectSignal.sendNext((
object: object,
changeType: .Deletion,
fromIndexPath: indexPathFor(object, inSections: oldSections),
toIndexPath: nil)
)
}
for object in updates {
guard
let oldIndexPath = indexPathFor(object, inSections: oldSections),
let newIndexPath = indexPathFor(object, inSections: sections)
else {
continue
}
let changeType: ListChangeType = oldIndexPath == newIndexPath ? .Update : .Move
didChangeObjectSignal.sendNext((
object: object,
changeType: changeType,
fromIndexPath: oldIndexPath,
toIndexPath: newIndexPath)
)
}
//Sections
for (index, section) in oldSections.enumerate() {
if sections.filter({ return $0.key == section.key }).isEmpty {
didChangeSectionSignal.sendNext((
changeType: .Deletion,
fromIndex: index,
toIndex: nil)
)
}
}
for (index, section) in sections.enumerate() {
if oldSections.filter({ return $0.key == section.key }).isEmpty {
didChangeSectionSignal.sendNext((
changeType: .Insertion,
fromIndex: nil,
toIndex: index)
)
}
}
}
private func indexPathFor(object: ObjectType, inSections sections: Sections) -> NSIndexPath? {
var allObjects: [ObjectType] = []
for section in sections {
allObjects.appendContentsOf(section.objects)
}
if !allObjects.contains(object) { return nil }
var row = 0
var section = 0
var objectFound = false
for (index, sectionInfo) in sections.enumerate() {
if sectionInfo.objects.contains(object) {
objectFound = true
section = index
row = sectionInfo.objects.indexOf(object)!
break
}
}
return objectFound ? NSIndexPath(forRow: row, inSection: section) : nil
}
private func allObjectsSet() -> Set<ObjectType> {
var result: Set<ObjectType> = []
for section in sections {
result.unionInPlace(section.objects)
}
return result
}
private func beginUpdates() {
beginUpdatesSignal.sendNext()
}
private func endUpdates() {
endUpdatesSignal.sendNext()
}
private func rearrangeAndPushReload() {
sections = arrangedSectionsFrom(allObjectsSet())
reloadDataSignal.sendNext()
}
} | mit |
jtwp470/my-programming-learning-book | swift/day1/Hello/AppDelegate.swift | 1 | 2050 | //
// AppDelegate.swift
// Hello
//
// Created by 大津 真 on 2014/12/08.
// Copyright (c) 2014年 Gmachine. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| unlicense |
lukevanin/OCRAI | CardScanner/EditFieldViewController.swift | 1 | 3254 | //
// EditFieldViewController.swift
// CardScanner
//
// Created by Luke Van In on 2017/03/27.
// Copyright © 2017 Luke Van In. All rights reserved.
//
import UIKit
private let pickerIndexPath = IndexPath(row: 2, section: 0)
extension EditFieldViewController: UIPickerViewDataSource {
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return FieldType.all.count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return String(describing: FieldType.all[row])
}
}
extension EditFieldViewController: UIPickerViewDelegate {
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
updateTypeLabel()
}
}
extension EditFieldViewController: UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
}
class EditFieldViewController: UITableViewController {
var field: Field!
private var isTypePickerVisible = false
@IBOutlet weak var valueTextField: UITextField!
@IBOutlet weak var typeLabel: UILabel!
@IBOutlet weak var typePickerView: UIPickerView!
@IBAction func onTypeDropdownAction(_ sender: UIButton) {
valueTextField.resignFirstResponder()
setTypePickerVisible(!isTypePickerVisible, animated: true)
}
override func viewDidLoad() {
super.viewDidLoad()
tableView.tableFooterView = UIView()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
setTypePickerVisible(false, animated: false)
updateView()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
commitChanges()
}
private func commitChanges() {
let row = typePickerView.selectedRow(inComponent: 0)
field.type = FieldType.all[row]
field.value = valueTextField.text
coreData.saveNow()
}
private func setTypePickerVisible(_ visible: Bool, animated: Bool) {
tableView.beginUpdates()
isTypePickerVisible = visible
tableView.endUpdates()
}
private func updateView() {
valueTextField.text = field.value
let row = FieldType.all.index(of: field.type) ?? 0
typePickerView.selectRow(row, inComponent: 0, animated: false)
updateTypeLabel()
}
fileprivate func updateTypeLabel() {
let row = typePickerView.selectedRow(inComponent: 0)
let fieldName = String(describing: FieldType.all[row])
typeLabel.text = fieldName
valueTextField.placeholder = fieldName
}
// MARK: Table view
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if indexPath == pickerIndexPath, !isTypePickerVisible {
return 0
}
else {
return super.tableView(tableView, heightForRowAt: indexPath)
}
}
}
| mit |
vnu/vTweetz | vTweetz/TweetDataSource.swift | 1 | 863 | //
// TweetDataSource.swift
// vTweetz
//
// Created by Vinu Charanya on 2/27/16.
// Copyright © 2016 vnu. All rights reserved.
//
import UIKit
class TweetDataSource: NSObject, UITableViewDataSource, UITableViewDelegate {
//CELL Identifiers
let tweetCellId = "com.vnu.tweetcell"
//Model Vars
var user: User!
var tweets = [Tweet]()
var cellDelegate:TweetCellDelegate?
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(tweetCellId) as! TweetCell
cell.tweet = tweets[indexPath.row]
cell.delegate = cellDelegate
return cell
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return tweets.count
}
}
| apache-2.0 |
SnowdogApps/DateKit | DateKitTests/Shared Examples/OperationGettersSharedExample.swift | 1 | 1344 | //
// OperationGettersSharedExample.swift
// DateKit
//
// Created by Radoslaw Szeja on 03/05/15.
// Copyright (c) 2015 Radosław Szeja. All rights reserved.
//
import Nimble
import Quick
class OperationGettersExampleConfiguration : QuickConfiguration {
override class func configure(configuration: Configuration) {
sharedExamples("operation getters setters") { (sharedExampleContext: SharedExampleContext) in
var configDict = sharedExampleContext() as! [String: AnyObject]
let operation = configDict["operation"] as! Operation
let value = configDict["value"] as! Int
let getterString = configDict["getter"] as! String
var resultOperation: Operation? = operation.getterOperationByString(getterString)
it("should not return nil") {
expect(resultOperation).notTo(beNil())
}
describe("operation properties") {
itBehavesLike("operation properties tests") {
[
"operation": resultOperation!,
"value": value,
"date": operation.date,
"unit": operation.unit.rawValue
]
}
}
}
}
}
| mit |
noear/Snacks | ios/Snacks/Snacks/src/xml/XmlToken.swift | 1 | 264 | //
// XmlToken.swift
// snacks
//
// Created by noear on 16/2/21.
// Copyright © 2016年 noear. All rights reserved.
//
import Foundation
enum XmlToken{
case None
case End
case TargetStart
case TargetEnd
case Value
case CDATA
}
| apache-2.0 |
austinzheng/swift | test/type/tuple/labels.swift | 66 | 400 | // RUN: %target-swift-frontend -module-name TestModule -typecheck -verify %s
typealias Tuple1 = (a: Int,
b _: Int, // expected-error{{tuple element cannot have two labels}}{{22-24=}}
_ c: Int, // expected-error{{tuple element cannot have two labels}}{{21-26=}}
d e: Int) // expected-error{{tuple element cannot have two labels}}{{22-24=}}
| apache-2.0 |
ifabijanovic/firebase-messages-swift | Social/UI/Message/BBSMessageCollectionViewCell.swift | 2 | 4366 | //
// BBSMessageCollectionViewCell.swift
// Social
//
// Created by Ivan Fabijanović on 24/11/15.
// Copyright © 2015 Bellabeat. All rights reserved.
//
import UIKit
internal let CellIdentifierMessage = "messageCell"
internal class BBSMessageCollectionViewCell: BBSBaseCollectionViewCell {
// MARK: - Outlets
@IBOutlet weak var messageTextLabel: UILabel!
@IBOutlet weak var messageTimestampLabel: UILabel!
@IBOutlet weak var upvoteButton: UIButton!
@IBOutlet weak var messagePointsLabel: UILabel!
@IBOutlet weak var downvoteButton: UIButton!
@IBOutlet weak var clockImageView: UIImageView!
@IBOutlet weak var separatorView: UIView!
// MARK: - Properties
internal var message: BBSMessageModel? {
didSet {
self.observerContainer.dispose()
if let message = self.message {
weak var weakSelf = self
self.observerContainer.add(message.message.bindTo(self.messageTextLabel.rx_text))
self.observerContainer.add(message.timestamp.map {
let seconds = $0 - NSDate().timeIntervalSince1970
return BBSMessageCollectionViewCell.timeFormatter.stringForTimeInterval(seconds)
}.bindTo(self.messageTimestampLabel.rx_text))
self.observerContainer.add(message.points.map { "\($0)" }.bindTo(self.messagePointsLabel.rx_text))
self.observerContainer.add(message.points.bindNext { _ in
weakSelf!.updateAppearance()
})
self.observerContainer.add(self.upvoteButton.rx_controlEvents(.TouchUpInside).bindNext {
weakSelf!.message!.upvoteForUser(weakSelf!.userId)
})
self.observerContainer.add(self.downvoteButton.rx_controlEvents(.TouchUpInside).bindNext {
weakSelf!.message!.downvoteForUser(weakSelf!.userId)
})
}
}
}
internal var userId: String = ""
// MARK: - Private members
private static let timeFormatter = TTTTimeIntervalFormatter()
private static let clockImage = UIImage(named: "Clock")?.imageWithRenderingMode(.AlwaysTemplate)
private static let upvoteImage = UIImage(named: "Upvote")?.imageWithRenderingMode(.AlwaysTemplate)
private static let downvoteImage = UIImage(named: "Downvote")?.imageWithRenderingMode(.AlwaysTemplate)
private var textColor = UIColor.blackColor()
private var highlightColor = SystemTintColor
private var dimmedColor = UIColor.lightGrayColor()
// MARK: - Init
override func awakeFromNib() {
super.awakeFromNib()
self.updateAppearance()
}
// MARK: - Methods
internal override func applyTheme(theme: BBSUITheme) {
self.messageTextLabel.font = UIFont(name: theme.contentFontName, size: 18.0)
self.messageTimestampLabel.font = UIFont(name: theme.contentFontName, size: 16.0)
self.messagePointsLabel.font = UIFont(name: theme.contentFontName, size: 30.0)
self.textColor = theme.contentTextColor
self.highlightColor = theme.contentHighlightColor
self.dimmedColor = theme.contentDimmedColor
}
// MARK: - Private methods
private func updateAppearance() {
self.messageTextLabel.textColor = self.textColor
self.clockImageView.image = BBSMessageCollectionViewCell.clockImage
self.clockImageView.tintColor = self.dimmedColor
self.messageTimestampLabel.textColor = self.dimmedColor
self.messagePointsLabel.textColor = self.highlightColor
self.separatorView.backgroundColor = self.dimmedColor
self.upvoteButton.tintColor = self.dimmedColor
self.downvoteButton.tintColor = self.dimmedColor
self.upvoteButton.setImage(BBSMessageCollectionViewCell.upvoteImage, forState: .Normal)
self.downvoteButton.setImage(BBSMessageCollectionViewCell.downvoteImage, forState: .Normal)
if let message = self.message {
self.upvoteButton.tintColor = message.didUpvoteForUser(self.userId) ? self.highlightColor : self.dimmedColor
self.downvoteButton.tintColor = message.didDownvoteForUser(self.userId) ? self.highlightColor : self.dimmedColor
}
}
}
| mit |
svanimpe/around-the-table | Sources/Main/main.swift | 1 | 429 | import AroundTheTable
import Configuration
import HeliumLogger
import Kitura
let persistence = try! Persistence()
let router = Router()
Routes(persistence: persistence).configure(using: router)
HeliumLogger.use(.warning)
let configuration = ConfigurationManager().load(.environmentVariables)
Kitura.addHTTPServer(onPort: configuration.port, with: router)
print("Starting Kitura on port \(configuration.port)...")
Kitura.run()
| bsd-2-clause |
kousun12/RxSwift | RxSwift/Schedulers/MainScheduler.swift | 9 | 2103 | //
// MainScheduler.swift
// Rx
//
// Created by Krunoslav Zaher on 2/8/15.
// Copyright (c) 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
/**
Abstracts work that needs to be performed on `MainThread`. In case `schedule` methods are called from main thread, it will perform action immediately without scheduling.
This scheduler is usually used to perform UI work.
Main scheduler is a specialization of `SerialDispatchQueueScheduler`.
This scheduler is optimized for `observeOn` operator. To ensure observable sequence is subscribed on main thread using `subscribeOn`
operator please use `ConcurrentMainScheduler` because it is more optimized for that purpose.
*/
public final class MainScheduler : SerialDispatchQueueScheduler {
private let _mainQueue: dispatch_queue_t
var numberEnqueued: Int32 = 0
private init() {
_mainQueue = dispatch_get_main_queue()
super.init(serialQueue: _mainQueue)
}
/**
Singleton instance of `MainScheduler`
*/
public static let sharedInstance = MainScheduler()
/**
In case this method is called on a background thread it will throw an exception.
*/
public class func ensureExecutingOnScheduler() {
if !NSThread.currentThread().isMainThread {
rxFatalError("Executing on backgound thread. Please use `MainScheduler.sharedInstance.schedule` to schedule work on main thread.")
}
}
override func scheduleInternal<StateType>(state: StateType, action: StateType -> Disposable) -> Disposable {
let currentNumberEnqueued = OSAtomicIncrement32(&numberEnqueued)
if NSThread.currentThread().isMainThread && currentNumberEnqueued == 1 {
let disposable = action(state)
OSAtomicDecrement32(&numberEnqueued)
return disposable
}
let cancel = SingleAssignmentDisposable()
dispatch_async(_mainQueue) {
if !cancel.disposed {
action(state)
}
OSAtomicDecrement32(&self.numberEnqueued)
}
return cancel
}
}
| mit |
domenicosolazzo/practice-swift | CoreMotion/Ball/BallTests/BallTests.swift | 1 | 881 | //
// BallTests.swift
// BallTests
//
// Created by Domenico on 02/05/15.
// Copyright (c) 2015 Domenico. All rights reserved.
//
import UIKit
import XCTest
class BallTests: 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.measure() {
// Put the code you want to measure the time of here.
}
}
}
| mit |
alvaromb/EventBlankApp | EventBlank/Extensions/Ext.swift | 3 | 760 | //
// Ext.swift
// EventBlank
//
// Created by Marin Todorov on 3/12/15.
// Copyright (c) 2015 Underplot ltd. All rights reserved.
//
import Foundation
import UIKit
func delay(#seconds: Double, completion:()->Void) {
let popTime = dispatch_time(DISPATCH_TIME_NOW, Int64( Double(NSEC_PER_SEC) * seconds ))
dispatch_after(popTime, dispatch_get_main_queue()) {
completion()
}
}
func backgroundQueue(block: ()->Void, completion:(()->Void)? = nil) {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
block()
if let completion = completion {
mainQueue(completion)
}
})
}
func mainQueue(block: ()->Void) {
dispatch_async(dispatch_get_main_queue(), block)
} | mit |
toshiapp/toshi-ios-client | Tests/NSDecimalNumber+AdditionsTests.swift | 1 | 1628 | // Copyright (c) 2018 Token Browser, Inc
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
@testable import Toshi
import XCTest
class NSDecimalNumberAdditionsTests: XCTestCase {
func testDecimalNumberFromHexadecimalString() {
XCTAssertEqual(NSDecimalNumber(hexadecimalString: "0x150d52c424663ea"), 94809978241967082)
}
func testIsGreaterOrEqualThan() {
let bigNumber: NSDecimalNumber = 10000
let smallNumber: NSDecimalNumber = 1
XCTAssertTrue(bigNumber.isGreaterOrEqualThan(value: smallNumber))
XCTAssertTrue(bigNumber.isGreaterOrEqualThan(value: bigNumber))
XCTAssertFalse(smallNumber.isGreaterOrEqualThan(value: bigNumber))
}
func testIsGreaterThan() {
let bigNumber: NSDecimalNumber = 10000
let smallNumber: NSDecimalNumber = 1
XCTAssertTrue(bigNumber.isGreaterThan(value: smallNumber))
XCTAssertFalse(bigNumber.isGreaterThan(value: bigNumber))
XCTAssertFalse(smallNumber.isGreaterThan(value: bigNumber))
}
}
| gpl-3.0 |
blockchain/My-Wallet-V3-iOS | Modules/FeatureCardIssuing/Sources/FeatureCardIssuingDomain/Services/ProductsServiceAPI.swift | 1 | 223 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import Combine
import Errors
import Foundation
public protocol ProductsServiceAPI {
func fetchProducts() -> AnyPublisher<[Product], NabuNetworkError>
}
| lgpl-3.0 |
victoraliss0n/FireRecord | FireRecord/Source/Extensions/Database/Filterable+FirebaseModel.swift | 2 | 3630 | //
// Filterable+Extension.swift
// FireRecord
//
// Created by Victor Alisson on 18/08/17.
//
import Foundation
import FirebaseCommunity
public extension Filterable where Self: FirebaseModel {
static func findFirst(when propertyEventType: PropertyEventType, completion: @escaping (_ object: Self) -> Void) {
if let fireRecordQuery = Self.fireRecordQuery?.queryLimited(toFirst: 1) {
Self.executeGenericFind(with: fireRecordQuery, and: propertyEventType, completion: { firebaseModel in
completion(firebaseModel)
})
} else {
let fireRecordQuery = Self.classPath.queryLimited(toFirst: 1)
Self.executeGenericFind(with: fireRecordQuery, and: propertyEventType, completion: { firebaseModel in
completion(firebaseModel)
})
}
}
fileprivate static func executeGenericFind(with reference: DatabaseQuery, and propertyEventType: PropertyEventType, completion: @escaping (_ object: Self) -> Void) {
reference.observeSingleEvent(of: propertyEventType.rawValue) { snapshot in
if let firebaseModel = Self.getFirebaseModels(snapshot).first {
completion(firebaseModel)
}
}
}
fileprivate static func executeFind(with databaseQuery: DatabaseQuery, and propertyEventType: PropertyEventType, completion: @escaping (_ objects: [Self]) -> Void) {
databaseQuery.observeSingleEvent(of: propertyEventType.rawValue) { snapshot in
let firebaseModels = Self.getFirebaseModels(snapshot)
completion(firebaseModels)
}
}
static func findLast(when propertyEventType: PropertyEventType, completion: @escaping (_ object: Self) -> Void) {
if let fireRecordQuery = Self.fireRecordQuery?.queryLimited(toLast: 1) {
Self.executeGenericFind(with: fireRecordQuery, and: propertyEventType, completion: { firebaseModel in
completion(firebaseModel)
})
} else {
let fireRecordQuery = Self.classPath.queryLimited(toLast: 1)
Self.executeGenericFind(with: fireRecordQuery, and: propertyEventType, completion: { firebaseModel in
completion(firebaseModel)
})
}
}
static func findFirst(when propertyEventType: PropertyEventType, _ toFirst: UInt, completion: @escaping (_ object: [Self]) -> Void) {
if let fireRecordQuery = Self.fireRecordQuery?.queryLimited(toFirst: toFirst) {
Self.executeFind(with: fireRecordQuery, and: propertyEventType, completion: { firebaseModels in
completion(firebaseModels)
})
} else {
let fireRecordQuery = Self.classPath.queryLimited(toFirst: toFirst)
Self.executeFind(with: fireRecordQuery, and: propertyEventType, completion: { firebaseModels in
completion(firebaseModels)
})
}
}
static func findLast(when propertyEventType: PropertyEventType, _ toLast: UInt, completion: @escaping (_ object: [Self]) -> Void) {
if let fireRecordQuery = Self.fireRecordQuery?.queryLimited(toLast: toLast) {
Self.executeFind(with: fireRecordQuery, and: propertyEventType, completion: { firebaseModels in
completion(firebaseModels)
})
} else {
let fireRecordQuery = Self.classPath.queryLimited(toLast: toLast)
Self.executeFind(with: fireRecordQuery, and: propertyEventType, completion: { firebaseModels in
completion(firebaseModels)
})
}
}
}
| mit |
kaneshin/ActiveRecord | Tests/TestCoreDataStack.swift | 1 | 4294 | // TestCoreDataStack.swift
//
// Copyright (c) 2014 Kenji Tayama
// Copyright (c) 2014 Shintaro Kaneko
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
import CoreData
import ActiveRecord
class ___TestCoreDataStack : NSObject, Context {
override init() {
super.init()
}
private lazy var lazyDefaultManagedObjectContext: NSManagedObjectContext? = {
let coordinator = self.persistentStoreCoordinator
if coordinator == nil {
return nil
}
var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
managedObjectContext.parentContext = self.writerManagedObjectContext
managedObjectContext.mergePolicy = NSOverwriteMergePolicy
return managedObjectContext
}()
/// Main queue context
var defaultManagedObjectContext: NSManagedObjectContext? {
get {
return self.lazyDefaultManagedObjectContext
}
set {}
}
private lazy var lazyWriterManagedObjectContext: NSManagedObjectContext? = {
let coordinator = self.persistentStoreCoordinator
if coordinator == nil {
return nil
}
var managedObjectContext = NSManagedObjectContext(concurrencyType: NSManagedObjectContextConcurrencyType.PrivateQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
managedObjectContext.mergePolicy = NSOverwriteMergePolicy
return managedObjectContext
}()
/// Context for writing to the PersistentStore
var writerManagedObjectContext: NSManagedObjectContext? {
get {
return self.lazyWriterManagedObjectContext
}
set { }
}
lazy var lazyPersistentStoreCoordinator: NSPersistentStoreCoordinator? = {
if let managedObjectModel = self.managedObjectModel {
var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: managedObjectModel)
var error: NSError? = nil
if coordinator?.addPersistentStoreWithType(NSInMemoryStoreType, configuration: nil, URL: nil, options: nil, error: &error) == true {
println("could not add persistent store : \(error?.localizedDescription)")
}
return coordinator
}
return nil;
}()
/// PersistentStoreCoordinator
var persistentStoreCoordinator: NSPersistentStoreCoordinator? {
get {
return self.lazyPersistentStoreCoordinator
}
set { }
}
lazy var lazyManagedObjectModel: NSManagedObjectModel? = {
let testsBundle: NSBundle = NSBundle(forClass: self.dynamicType)
let modelURL: NSURL? = testsBundle.URLForResource("ActiveRecordTests", withExtension: "momd")
if let managedObjectModel = NSManagedObjectModel(contentsOfURL: modelURL!) {
return managedObjectModel
}
return nil
}()
/// ManagedObjectModel
var managedObjectModel: NSManagedObjectModel? {
get {
return self.lazyManagedObjectModel
}
set { }
}
/// Store URL
var storeURL: NSURL? {
return nil
}
} | mit |
bromas/ActivityViewController | ApplicationVCSample/AuthenticationVC.swift | 1 | 2424 | //
// AuthenticationVC.swift
// ApplicationVCSample
//
// Created by Brian Thomas on 11/23/14.
// Copyright (c) 2014 Brian Thomas. All rights reserved.
//
import Foundation
import UIKit
import ActivityViewController
class AuthenticationVC : UIViewController {
@IBOutlet var activities: ActivityViewController!
var timesPresented = -1
@IBAction func buttonTap() { actionOnButtonTap() }
var actionOnButtonTap : () -> Void = {
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "activities" {
self.activities = segue.destination as? ActivityViewController
self.activities.registerGenerator("Generator") { () -> UIViewController in
return NoXibController()
}
}
}
override func viewDidLoad() {
self.navigationController?.isNavigationBarHidden = true
self.actionOnButtonTap = {
var operation = ActivityOperation(rule: .new, identifier: "Launch", animator: ShrinkAnimator())
operation.completionBlock = {
print("ohhhh yea")
}
self.activities.performActivityOperation(operation)
}
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
timesPresented += 1
}
@IBAction func backButtonTapped() {
switch timesPresented % 5 {
case 0:
let operation = ActivityOperation(identifier: "Launch", animator: CircleTransitionAnimator(direction: .outward, duration: 0.5))
ActivityViewController.rootController?.performActivityOperation(operation)
case 1:
let operation = ActivityOperation(identifier: "Launch", animator: CinematicWipeTransitionAnimator())
ActivityViewController.rootController?.performActivityOperation(operation)
case 2:
let operation = ActivityOperation(identifier: "Launch", animator: ShrinkAnimator())
ActivityViewController.rootController?.performActivityOperation(operation)
case 3:
let operation = ActivityOperation(identifier: "Launch", animationType: UIViewAnimationOptions.transitionCurlUp, duration: 0.5)
ActivityViewController.rootController?.performActivityOperation(operation)
default:
let operation = ActivityOperation(identifier: "Launch", animationType: UIViewAnimationOptions.transitionFlipFromLeft, duration: 0.5)
ActivityViewController.rootController?.performActivityOperation(operation)
}
}
}
| mit |
brentsimmons/Evergreen | iOS/IntentsExtension/IntentHandler.swift | 1 | 444 | //
// IntentHandler.swift
// NetNewsWire iOS Intents Extension
//
// Created by Maurice Parker on 10/18/19.
// Copyright © 2019 Ranchero Software. All rights reserved.
//
import Intents
class IntentHandler: INExtension {
override func handler(for intent: INIntent) -> Any {
switch intent {
case is AddWebFeedIntent:
return AddWebFeedIntentHandler()
default:
fatalError("Unhandled intent type: \(intent)")
}
}
}
| mit |
rmannion/RMCore | RMCore/Extensions/UIView+Extensions.swift | 1 | 1570 | //
// UIView+Extensions.swift
// RMCore
//
// Created by Ryan Mannion on 4/29/16.
// Copyright © 2016 Ryan Mannion. All rights reserved.
//
import UIKit
public extension UIView {
public var x: CGFloat {
get {
return frame.origin.x
}
set (newX) {
frame = CGRect(origin: CGPoint(x: newX, y: y), size: frame.size)
}
}
public var y: CGFloat {
get {
return frame.origin.y
}
set (newY) {
frame = CGRect(origin: CGPoint(x: x, y: newY), size: frame.size)
}
}
public var width: CGFloat {
get {
return frame.size.width
}
set (newWidth) {
frame = CGRect(origin: frame.origin, size: CGSize(width: newWidth, height: height))
}
}
public var height: CGFloat {
get {
return frame.size.height
}
set (newHeight) {
frame = CGRect(origin: frame.origin, size: CGSize(width: width, height: newHeight))
}
}
public var bottomY: CGFloat {
get {
return frame.maxY
}
}
public var rightX: CGFloat {
get{
return frame.maxX
}
}
@objc
public func removeAllSubviews() {
for subview in subviews {
subview.removeFromSuperview()
}
}
public func optionalSnapshotViewAfterScreenUpdates(afterUpdates: Bool = false) -> UIView? {
return snapshotView(afterScreenUpdates: afterUpdates)
}
}
| mit |
PLU-CS-Club/Swift-Demo | Calculator/AppDelegate.swift | 1 | 2139 | //
// AppDelegate.swift
// Calculator
//
// Created by admin on 3/11/15.
// Copyright (c) 2015 PLU CS Club All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| mit |
Shivam0911/IOS-Training-Projects | SliderDemo/SliderDemo/MainVC.swift | 1 | 2956 | //
// MainVC.swift
// SliderDemo
//
// Created by MAC on 23/02/17.
// Copyright © 2017 Appinventiv. All rights reserved.
//
import UIKit
class MainVC: UIViewController {
@IBOutlet weak var sliderButtonOutlet: UIButton!
var leftSliderController = LeftSliderVC()
override func viewDidLoad() {
super.viewDidLoad()
doSubViewLoad()
}
//MARK: doSubViewLoad Method
//=======================
fileprivate func doSubViewLoad() {
let storyBoardScene = UIStoryboard(name: "Main", bundle: Bundle.main)
leftSliderController = storyBoardScene.instantiateViewController(withIdentifier : "LeftSliderVCID") as! LeftSliderVC
view.addSubview(leftSliderController.view)
addChildViewController(leftSliderController)
leftSliderController.didMove(toParentViewController: self)
leftSliderController.view.frame = CGRect(x: -(self.view.frame.width - 100)
, y: 0, width: self.view.frame.width - 100, height: self.view.frame.height )
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension MainVC {
//MARK: chnageSubView Method
//=======================
func changeSubView( _ subViewController : UIViewController ) {
leftSliderController.removeFromParentViewController()
subViewController.view.frame = CGRect(x: 0, y: 0, width: self.view.frame.width , height: self.view.frame.height )
view.addSubview(subViewController.view)
addChildViewController(subViewController)
sliderButtonOutlet.isSelected = false
doSubViewLoad()
subViewController.view.frame = CGRect(x: 0 , y: 0, width: self.view.frame.width , height: self.view.frame.height )
}
//MARK: sliderButtonTapped Method
//==========================
@IBAction func sliderButtonTapped(_ sender: UIButton) {
sender.isSelected = !sender.isSelected
if sender.isSelected {
UIView.animate(withDuration: 1, delay: 0.1, options: .curveEaseOut, animations: {
self.leftSliderController.view.frame = CGRect(x: 0, y: 0, width: self.view.frame.width - 150, height: self.view.frame.height)
})
}
else {
UIView.animate(withDuration: 1, delay: 0.1, options: .curveEaseOut, animations: {
self.leftSliderController.view.frame = CGRect(x: -(self.view.frame.width - 150), y: 0, width: self.view.frame.width - 150, height: self.view.frame.height)
})
}
}
}
| mit |
Pluto-Y/SwiftyEcharts | SwiftyEcharts/Models/Axis/RadiusAxis.swift | 1 | 9127 | //
// RadiusAxis.swift
// SwiftyEcharts
//
// Created by Pluto Y on 05/02/2017.
// Copyright © 2017 com.pluto-y. All rights reserved.
//
/// 极坐标系的径向轴。
public final class RadiusAxis: Zable {
/// 径向轴所在的极坐标系的索引,默认使用第一个极坐标系。
public var polarIndex: UInt8?
/// 坐标轴类型。
public var type: AxisType?
/// 坐标轴名称。
public var name: String?
/// 坐标轴名称显示位置。
public var nameLocation: Position?
/// 坐标轴名称的文字样式。
public var nameTextStyle: TextStyle?
/// 坐标轴名称与轴线之间的距离。
public var nameGap: Float?
/// 坐标轴名字旋转,角度值。
public var nameRotate: Float?
/// 是否是反向坐标轴。ECharts 3 中新加。
public var inverse: Bool?
/// 坐标轴两边留白策略,类目轴和非类目轴的设置和表现不一样。
///
/// 类目轴中 boundaryGap 可以配置为 true 和 false。默认为 true,这时候刻度只是作为分隔线,标签和数据点都会在两个刻度之间的带(band)中间。
///
/// 非类目轴,包括时间,数值,对数轴,boundaryGap是一个两个值的数组,分别表示数据最小值和最大值的延伸范围,可以直接设置数值或者相对的百分比,在设置 min 和 max 后无效。 示例:
///
/// boundaryGap: ['20%', '20%']
public var boundaryGap: BoundaryGap?
/// 坐标轴刻度最小值。
///
/// 可以设置成特殊值 'dataMin',此时取数据在该轴上的最小值作为最小刻度。
///
/// 不设置时会自动计算最小值保证坐标轴刻度的均匀分布。
///
/// 在类目轴中,也可以设置为类目的序数(如类目轴 data: ['类A', '类B', '类C'] 中,序数 2 表示 '类C'。也可以设置为负数,如 -3)。
public var min: Float?
/// 坐标轴刻度最大值。
///
/// 可以设置成特殊值 'dataMax',此时取数据在该轴上的最大值作为最大刻度。
///
/// 不设置时会自动计算最大值保证坐标轴刻度的均匀分布。
///
/// 在类目轴中,也可以设置为类目的序数(如类目轴 data: ['类A', '类B', '类C'] 中,序数 2 表示 '类C'。也可以设置为负数,如 -3)。
public var max: Float?
/// 只在数值轴中(type: 'value')有效。
///
/// 是否是脱离 0 值比例。设置成 true 后坐标刻度不会强制包含零刻度。在双数值轴的散点图中比较有用。
///
/// 在设置 min 和 max 之后该配置项无效。
public var scale: Bool?
/// 坐标轴的分割段数,需要注意的是这个分割段数只是个预估值,最后实际显示的段数会在这个基础上根据分割后坐标轴刻度显示的易读程度作调整。
///
/// 在类目轴中无效。
public var splitNumber: UInt8?
/// 自动计算的坐标轴最小间隔大小。
///
/// 例如可以设置成1保证坐标轴分割刻度显示成整数。
///
/// {
/// minInterval: 1
/// }
///
/// 只在数值轴中(type: 'value')有效。
public var minInterval: Float?
/// 强制设置坐标轴分割间隔。
///
/// 因为 splitNumber 是预估的值,实际根据策略计算出来的刻度可能无法达到想要的效果,这时候可以使用 interval 配合 min、max 强制设定刻度划分,一般不建议使用。
///
/// 无法在类目轴中使用。在时间轴(type: 'time')中需要传时间戳,在对数轴(type: 'log')中需要传指数值。
public var interval: Float?
/// 对数轴的底数,只在对数轴中(type: 'log')有效。
public var logBase: Float?
/// 坐标轴是否是静态无法交互。
public var silent: Bool?
/// 坐标轴的标签是否响应和触发鼠标事件,默认不响应。
/// 事件参数如下:
/// {
/// // 组件类型,xAxis, yAxis, radiusAxis, angleAxis
/// // 对应组件类型都会有一个属性表示组件的 index,例如 xAxis 就是 xAxisIndex
/// componentType: string,
/// // 未格式化过的刻度值, 点击刻度标签有效
/// value: '',
/// // 坐标轴名称, 点击坐标轴名称有效
/// name: ''
/// }
public var triggerEvent: Bool?
/// 坐标轴轴线相关设置。
public var axisLine: AxisLine?
/// 坐标轴刻度相关设置。
public var axisTick: AxisTick?
/// 坐标轴刻度标签的相关设置。
public var axisLabel: AxisLabel?
/// 坐标轴在 grid 区域中的分隔线。
public var splitLine: SplitLine?
/// 坐标轴在 grid 区域中的分隔区域,默认不显示。
public var splitArea: SplitArea?
public var data: [Jsonable]?
public var axisPointer: AxisPointerForAxis?
/// MARK: - Zable
public var zlevel: Float?
public var z: Float?
}
extension RadiusAxis: Enumable {
public enum Enums {
case polarIndex(UInt8), type(AxisType), name(String), nameLocation(Position), nameTextStyle(TextStyle), nameGap(Float), nameRotate(Float), inverse(Bool), boundaryGap(BoundaryGap), min(Float), max(Float), scale(Bool), splitNumber(UInt8), minInterval(Float), interval(Float), logBase(Float), silent(Bool), triggerEvent(Bool), axisLine(AxisLine), axisTick(AxisTick), axisLabel(AxisLabel), splitLine(SplitLine), splitArea(SplitArea), data([Jsonable]), axisPointer(AxisPointerForAxis), zlevel(Float), z(Float)
}
public typealias ContentEnum = Enums
public convenience init(_ elements: Enums...) {
self.init()
for ele in elements {
switch ele {
case let .polarIndex(polarIndex):
self.polarIndex = polarIndex
case let .type(type):
self.type = type
case let .name(name):
self.name = name
case let .nameLocation(nameLocation):
self.nameLocation = nameLocation
case let .nameTextStyle(nameTextStyle):
self.nameTextStyle = nameTextStyle
case let .nameGap(nameGap):
self.nameGap = nameGap
case let .nameRotate(nameRotate):
self.nameRotate = nameRotate
case let .inverse(inverse):
self.inverse = inverse
case let .boundaryGap(boundaryGap):
self.boundaryGap = boundaryGap
case let .min(min):
self.min = min
case let .max(max):
self.max = max
case let .scale(scale):
self.scale = scale
case let .splitNumber(splitNumber):
self.splitNumber = splitNumber
case let .minInterval(minInterval):
self.minInterval = minInterval
case let .interval(interval):
self.interval = interval
case let .logBase(logBase):
self.logBase = logBase
case let .silent(silent):
self.silent = silent
case let .triggerEvent(triggerEvent):
self.triggerEvent = triggerEvent
case let .axisLine(axisLine):
self.axisLine = axisLine
case let .axisTick(axisTick):
self.axisTick = axisTick
case let .axisLabel(axisLabel):
self.axisLabel = axisLabel
case let .splitLine(splitLine):
self.splitLine = splitLine
case let .splitArea(splitArea):
self.splitArea = splitArea
case let .data(data):
self.data = data
case let .axisPointer(axisPointer):
self.axisPointer = axisPointer
case let .zlevel(zlevel):
self.zlevel = zlevel
case let .z(z):
self.z = z
}
}
}
}
extension RadiusAxis: Mappable {
public func mapping(_ map: Mapper) {
map["polarIndex"] = polarIndex
map["type"] = type
map["name"] = name
map["nameLocation"] = nameLocation
map["nameTextStyle"] = nameTextStyle
map["nameGap"] = nameGap
map["nameRotate"] = nameRotate
map["inverse"] = inverse
map["boundaryGap"] = boundaryGap
map["min"] = min
map["max"] = max
map["scale"] = scale
map["splitNumber"] = splitNumber
map["minInterval"] = minInterval
map["interval"] = interval
map["logBase"] = logBase
map["silent"] = silent
map["triggerEvent"] = triggerEvent
map["axisLine"] = axisLine
map["axisTick"] = axisTick
map["axisLabel"] = axisLabel
map["splitLine"] = splitLine
map["splitArea"] = splitArea
map["data"] = data
map["axisPointer"] = axisPointer
map["zlevel"] = zlevel
map["z"] = z
}
}
| mit |
apple/swift | validation-test/compiler_crashers_fixed/28545-swift-archetypebuilder-potentialarchetype-gettype-swift-archetypebuilder.swift | 65 | 448 | // 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
struct B<>:A
protocol A{
typealias d:A.B
class B<T>
| apache-2.0 |
modnovolyk/MAVLinkSwift | Sources/HwstatusArdupilotmegaMsg.swift | 1 | 1012 | //
// HwstatusArdupilotmegaMsg.swift
// MAVLink Protocol Swift Library
//
// Generated from ardupilotmega.xml, common.xml, uAvionix.xml on Tue Jan 17 2017 by mavgen_swift.py
// https://github.com/modnovolyk/MAVLinkSwift
//
import Foundation
/// Status of key hardware
public struct Hwstatus {
/// board voltage (mV)
public let vcc: UInt16
/// I2C error count
public let i2cerr: UInt8
}
extension Hwstatus: Message {
public static let id = UInt8(165)
public static var typeName = "HWSTATUS"
public static var typeDescription = "Status of key hardware"
public static var fieldDefinitions: [FieldDefinition] = [("vcc", 0, "UInt16", 0, "board voltage (mV)"), ("i2cerr", 2, "UInt8", 0, "I2C error count")]
public init(data: Data) throws {
vcc = try data.number(at: 0)
i2cerr = try data.number(at: 2)
}
public func pack() throws -> Data {
var payload = Data(count: 3)
try payload.set(vcc, at: 0)
try payload.set(i2cerr, at: 2)
return payload
}
}
| mit |
lorentey/swift | test/Sema/Inputs/accessibility_multi_other_module.swift | 38 | 751 | public struct PrivateConformance : PrivateProtocol, FilePrivateProtocol {}
private protocol PrivateProtocol {}
extension PrivateProtocol {
public func publicExtensionMember() {}
internal func internalExtensionMember() {}
}
fileprivate protocol FilePrivateProtocol {}
extension FilePrivateProtocol {
public func publicFPExtensionMember() {}
// expected-note@-1 {{'publicFPExtensionMember' declared here}}
internal func internalFPExtensionMember() {}
// expected-note@-1 {{'internalFPExtensionMember' declared here}}
}
public struct InternalConformance : InternalProtocol {}
internal protocol InternalProtocol {}
extension InternalProtocol {
public func publicExtensionMember() {}
internal func internalExtensionMember() {}
}
| apache-2.0 |
krzysztofzablocki/Sourcery | SourceryRuntime/Sources/Log.swift | 1 | 1939 | import Darwin
import Foundation
/// :nodoc:
public enum Log {
public enum Level: Int {
case errors
case warnings
case info
case verbose
}
public static var level: Level = .warnings
public static var logBenchmarks: Bool = false
public static var logAST: Bool = false
public static var stackMessages: Bool = false
public private(set) static var messagesStack = [String]()
public static func error(_ message: Any) {
log(level: .errors, "error: \(message)")
// to return error when running swift templates which is done in a different process
if ProcessInfo().processName != "Sourcery" {
fputs("\(message)", stderr)
}
}
public static func warning(_ message: Any) {
log(level: .warnings, "warning: \(message)")
}
public static func astWarning(_ message: Any) {
guard logAST else { return }
log(level: .warnings, "ast warning: \(message)")
}
public static func astError(_ message: Any) {
guard logAST else { return }
log(level: .errors, "ast error: \(message)")
}
public static func verbose(_ message: Any) {
log(level: .verbose, message)
}
public static func info(_ message: Any) {
log(level: .info, message)
}
public static func benchmark(_ message: Any) {
guard logBenchmarks else { return }
if stackMessages {
messagesStack.append("\(message)")
} else {
print(message)
}
}
private static func log(level logLevel: Level, _ message: Any) {
guard logLevel.rawValue <= Log.level.rawValue else { return }
if stackMessages {
messagesStack.append("\(message)")
} else {
print(message)
}
}
public static func output(_ message: String) {
print(message)
}
}
extension String: Error {}
| mit |
LawrenceHan/iOS-project-playground | ShotsApp_example/ShotsApp/font/Spring/Data.swift | 2 | 1808 | //
// Data.swift
// ShotsDemo
//
// Created by Meng To on 2014-07-04.
// Copyright (c) 2014 Meng To. All rights reserved.
//
import UIKit
func getData() -> Array<Dictionary<String,String>> {
var data = [
[
"title" : "Bug",
"author": "Mike | Creative Mints",
"image" : "image",
"avatar": "avatar",
"text" : "You guys, the new How To Draw: drawing and sketching objects and environments from your imagination book by S. Robertson is just amazing! I spent the whole weekend gobbling it up and of course I couldn't help but take the watercolors myself! :)\n\nFill up the gas tank and go check out the attachment!\n\nBehance"
],
[
"title": "Secret Trips",
"author": "Alexander Zaytsev",
"image": "image2",
"avatar": "avatar2",
"text" : "Hey,\n\nI'm working on app for tracking your trips.\n\nSee the attachments as always."
],
[
"title": "Ford Model T - Comic",
"author": "Konstantin Datz",
"image": "image3",
"avatar": "avatar3",
"text" : "hey guys,\n\nhope you are doing well :)\n\ni was working on a comic version of the old Ford Model T in my spare time. im still not 100% happy with the background but wanted to come to an end.\n\nalso atteched the large version and if you are interested a comparison of the rendering and the postwork.\n\nplease let me know if you like it ♥\n\ncheers!"
],
[
"title": "Music",
"author": "Rovane Durso",
"image": "image4",
"avatar": "avatar4",
"text" : "hope you all had a good weekend!\n\nbig pixel version attached."
],
]
return data
} | mit |
Tantalum73/XJodel | XJodel/XJodel/CacheController.swift | 1 | 593 | //
// CacheController.swift
// XJodel
//
// Created by Andreas Neusüß on 28.03.16.
// Copyright © 2016 Cocoawah. All rights reserved.
//
import Cocoa
class CacheController: NSObject {
static let sharedInstance = CacheController()
fileprivate override init() {}
fileprivate let cache = NSCache<NSString,NSImage>()
func imageForKey(_ key: String) -> NSImage? {
return cache.object(forKey: key as NSString)
}
func setImage(_ image: NSImage, forKey key: String) {
cache.setObject(image, forKey: key as NSString)
}
}
| mit |
zhuhaow/Soca-iOS | Pods/SocaCore/Pod/Classes/Socket/Adapter/Factory/HTTPAdapterFactory.swift | 2 | 563 | //
// HTTPAdapterFactory.swift
// Soca
//
// Created by Zhuhao Wang on 2/22/15.
// Copyright (c) 2015 Zhuhao Wang. All rights reserved.
//
import Foundation
class HTTPAdapterFactory : AuthenticationAdapterFactory {
override func canHandle(request: ConnectRequest) -> Bool {
return true
}
override func getAdapter(request: ConnectRequest, delegateQueue: dispatch_queue_t) -> Adapter {
return HTTPAdapter(request: request, delegateQueue: delegateQueue, serverHost: serverHost, serverPort: serverPort, auth: self.auth)
}
} | mit |
Pluto-Y/SwiftyEcharts | SwiftyEcharts/Models/Series/GraphSerie.swift | 1 | 38208 | //
// GraphSerie.swift
// SwiftyEcharts
//
// Created by Pluto Y on 26/10/2017.
// Copyright © 2017 com.pluto-y. All rights reserved.
//
/// 关系图
///
/// 用于展现节点以及节点之间的关系数据。
///
/// 注意: ECharts 2.x 中 force 类型的图表不再在 ECharts 3 中提供支持,转为统一使用 graph 去展现关系数据。如果要使用力引导布局,可以将 layout 配置项设为'force'。
///
/// 示例:http://www.echartsjs.com/gallery/editor.html?c=graph
public final class GraphSerie: Serie, Animatable, Symbolized, Zable {
/// 图的布局。
///
/// - none: 不采用任何布局,使用节点中提供的 x, y 作为节点的位置
/// - circular: 采用环形布局,见示例 Les Miserables,布局相关的配置项见 graph.circula
/// - force: 采用力引导布局,见示例 Force,布局相关的配置项见 graph.forc
public enum Layout: String, Jsonable {
case none = "none"
case circular = "circular"
case force = "force"
public var jsonString: String {
return self.rawValue.jsonString
}
}
/// 环形布局相关配置
public final class Circular {
/// 是否旋转标签,默认不旋转
public var rotateLabel: Bool?
}
/// 力引导布局相关的配置项,力引导布局是模拟弹簧电荷模型在每两个节点之间添加一个斥力,每条边的两个节点之间添加一个引力,每次迭代节点会在各个斥力和引力的作用下移动位置,多次迭代后节点会静止在一个受力平衡的位置,达到整个模型的能量最小化。
///
/// 力引导布局的结果有良好的对称性和局部聚合性,也比较美观。
public final class Force {
/// 进行力引导布局前的初始化布局,初始化布局会影响到力引导的效果。
///
/// 默认不进行任何布局,使用节点中提供的 x, y 作为节点的位置。如果不存在的话会随机生成一个位置。
///
/// 也可以选择使用环形布局 'circular'。
public var initLayout: String?
/// 节点之间的斥力因子。
///
/// 支持设置成数组表达斥力的范围,此时不同大小的值会线性映射到不同的斥力。值越大则斥力越大
public var repulsion: Float?
/// 节点受到的向中心的引力因子。该值越大节点越往中心点靠拢。
public var gravity: Float?
/// 边的两个节点之间的距离,这个距离也会受 repulsion。
///
/// 支持设置成数组表达边长的范围,此时不同大小的值会线性映射到不同的长度。值越小则长度越长。如下示例
///
/// // 值最大的边长度会趋向于 10,值最小的边长度会趋向于 50
/// edgeLength: [10, 50]
public var edgeLength: OneOrMore<Float>?
/// 因为力引导布局会在多次迭代后才会稳定,这个参数决定是否显示布局的迭代动画,在浏览器端节点数据较多(>100)的时候不建议关闭,布局过程会造成浏览器假死。
public var layoutAnimation: Bool?
}
/// 节点分类的类目,可选。
///
/// 如果节点有分类的话可以通过 data[i].category 指定每个节点的类目,类目的样式会被应用到节点样式上。图例也可以基于categories名字展现和筛选。
public final class Category: Symbolized {
/// 类目名称,用于和 legend 对应以及格式化 tooltip 的内容。
public var name: String?
/// 关系图节点标记的图形。
///
/// ECharts 提供的标记类型包括 'circle', 'rect', 'roundRect', 'triangle', 'diamond', 'pin', 'arrow'
///
/// 也可以通过 'image://url' 设置为图片,其中 url 为图片的链接,或者 dataURI。
///
/// 可以通过 'path://' 将图标设置为任意的矢量路径。这种方式相比于使用图片的方式,不用担心因为缩放而产生锯齿或模糊,而且可以设置为任意颜色。路径图形会自适应调整为合适的大小。路径的格式参见 SVG PathData。可以从 Adobe Illustrator 等工具编辑导出。
public var symbol: OneOrMore<Symbol>?
/// 关系图节点标记的大小,可以设置成诸如 10 这样单一的数字,也可以用数组分开表示宽和高,例如 [20, 10] 表示标记宽为20,高为10。
///
/// 如果需要每个数据的图形大小不一样,可以设置为如下格式的回调函数:
///
/// (value: Array|number, params: Object) => number|Array
///
/// 其中第一个参数 value 为 data 中的数据值。第二个参数params 是其它的数据项参数。
public var symbolSize: FunctionOrFloatOrPair?
/// 关系图节点标记的旋转角度。注意在 markLine 中当 symbol 为 'arrow' 时会忽略 symbolRotate 强制设置为切线的角度。
public var symbolRotate: Float?
/// 关系图节点标记相对于原本位置的偏移。默认情况下,标记会居中置放在数据对应的位置,但是如果 symbol 是自定义的矢量路径或者图片,就有可能不希望 symbol 居中。这时候可以使用该配置项配置 symbol 相对于原本居中的偏移,可以是绝对的像素值,也可以是相对的百分比。
///
/// 例如 [0, '50%'] 就是把自己向上移动了一半的位置,在 symbol 图形是气泡的时候可以让图形下端的箭头对准数据点。
public var symbolOffset: Point?
/// 该类目节点的样式。
public var itemStyle: ItemStyle?
/// 该类目节点标签的样式。
public var label: EmphasisLabel?
}
/// 关系图的节点数据列表。
///
/// data: [{
/// name: '1',
/// x: 10,
/// y: 10,
/// value: 10
/// }, {
/// name: '2',
/// x: 100,
/// y: 100,
/// value: 20,
/// symbolSize: 20,
/// itemStyle: {
/// normal: {
/// color: 'red'
/// }
/// }
/// }]
///
/// 注意: 节点的name不能重复。
public final class Data: Symbolized {
/// 数据项名称。
public var name: String?
/// 节点的初始 x 值。在不指定的时候需要指明layout属性选择布局方式。
public var x: Float?
/// 节点的初始 y 值。在不指定的时候需要指明layout属性选择布局方式。
public var y: Float?
/// 节点在力引导布局中是否固定。
public var fixed: Bool?
/// 数据项值。
public var value: OneOrMore<Float>?
/// 数据项所在类目的 index。
public var category: Float?
/// 关系图节点标记的图形。
///
/// ECharts 提供的标记类型包括 'circle', 'rect', 'roundRect', 'triangle', 'diamond', 'pin', 'arrow'
///
/// 也可以通过 'image://url' 设置为图片,其中 url 为图片的链接,或者 dataURI。
///
/// 可以通过 'path://' 将图标设置为任意的矢量路径。这种方式相比于使用图片的方式,不用担心因为缩放而产生锯齿或模糊,而且可以设置为任意颜色。路径图形会自适应调整为合适的大小。路径的格式参见 SVG PathData。可以从 Adobe Illustrator 等工具编辑导出。
public var symbol: OneOrMore<Symbol>?
/// 关系图节点标记的大小,可以设置成诸如 10 这样单一的数字,也可以用数组分开表示宽和高,例如 [20, 10] 表示标记宽为20,高为10。
///
/// 如果需要每个数据的图形大小不一样,可以设置为如下格式的回调函数:
///
/// (value: Array|number, params: Object) => number|Array
///
/// 其中第一个参数 value 为 data 中的数据值。第二个参数params 是其它的数据项参数。
public var symbolSize: FunctionOrFloatOrPair?
/// 关系图节点标记的旋转角度。注意在 markLine 中当 symbol 为 'arrow' 时会忽略 symbolRotate 强制设置为切线的角度。
public var symbolRotate: Float?
/// 关系图节点标记相对于原本位置的偏移。默认情况下,标记会居中置放在数据对应的位置,但是如果 symbol 是自定义的矢量路径或者图片,就有可能不希望 symbol 居中。这时候可以使用该配置项配置 symbol 相对于原本居中的偏移,可以是绝对的像素值,也可以是相对的百分比。
///
/// 例如 [0, '50%'] 就是把自己向上移动了一半的位置,在 symbol 图形是气泡的时候可以让图形下端的箭头对准数据点。
public var symbolOffset: Point?
/// 该节点的样式。
public var itemStyle: ItemStyle?
/// 该节点标签的样式。
public var label: EmphasisLabel?
/// 本系列每个数据项中特定的 tooltip 设定。
public var tooltip: Tooltip?
}
/// 节点间的关系数据。示例:
///
/// links: [{
/// source: 'n1',
/// target: 'n2'
/// }, {
/// source: 'n2',
/// target: 'n3'
/// }]
public final class Link {
/// 边的源节点名称的字符串,也支持使用数字表示源节点的索引。
public var source: Jsonable?
/// 边的目标节点名称的字符串,也支持使用数字表示源节点的索引。
public var target: Jsonable?
/// 边的数值,可以在力引导布局中用于映射到边的长度。
public var value: Float?
/// 关系边的线条样式。
public var lineStyle: EmphasisLineStyle?
/// 关系边的标签的样式。
public var label: EmphasisLabel?
/// 边两端的标记类型,可以是一个数组分别指定两端,也可以是单个统一指定。
public var symbol: OneOrMore<Symbol>?
/// 边两端的标记大小,可以是一个数组分别指定两端,也可以是单个统一指定。
public var symbolSize: FunctionOrFloatOrPair?
}
public var type: SerieType {
return .graph
}
/// 系列名称,用于tooltip的显示,legend 的图例筛选,在 setOption 更新数据和配置项时用于指定对应的系列。
public var name: String?
/// 是否启用图例 hover 时的联动高亮。
public var legendHoverLinek: Bool?
/// 该系列使用的坐标系
///
/// - cartesian2d: 使用二维的直角坐标系(也称笛卡尔坐标系),通过 xAxisIndex, yAxisIndex指定相应的坐标轴组件。
/// - polar: 使用极坐标系,通过 polarIndex 指定相应的极坐标组件
/// - geo: 使用地理坐标系,通过 geoIndex 指定相应的地理坐标系组件。
/// - none: 不使用坐标系。
public var coordinateSystem: CoordinateSystem?
/// 使用的 x 轴的 index,在单个图表实例中存在多个 x 轴的时候有用。
public var xAxisIndex: UInt8?
/// 使用的 y 轴的 index,在单个图表实例中存在多个 y轴的时候有用。
public var yAxisIndex: UInt8?
/// 使用的极坐标系的 index,在单个图表实例中存在多个极坐标系的时候有用。
public var polarIndex: UInt8?
/// 使用的地理坐标系的 index,在单个图表实例中存在多个地理坐标系的时候有用。
public var geoIndex: UInt8?
/// 使用的日历坐标系的 index,在单个图表实例中存在多个日历坐标系的时候有用。
public var calendarIndex: UInt8?
/// 是否开启鼠标 hover 节点的提示动画效果。
public var hoverAnimation: Bool?
/// 图的布局。
///
/// 可选:
///
/// - none: 不采用任何布局,使用节点中提供的 x, y 作为节点的位置。
/// - circular: 采用环形布局,见示例 Les Miserables,布局相关的配置项见 graph.circular
/// - force: 采用力引导布局,见示例 Force,布局相关的配置项见 graph.force
public var layout: Layout?
/// 环形布局相关配置
public var circular: Circular?
/// 力引导布局相关的配置项,力引导布局是模拟弹簧电荷模型在每两个节点之间添加一个斥力,每条边的两个节点之间添加一个引力,每次迭代节点会在各个斥力和引力的作用下移动位置,多次迭代后节点会静止在一个受力平衡的位置,达到整个模型的能量最小化。
/// 力引导布局的结果有良好的对称性和局部聚合性,也比较美观。
public var force: Force?
/// 是否开启鼠标缩放和平移漫游。默认不开启。如果只想要开启缩放或者平移,可以设置成 'scale' 或者 'move'。设置成 true 为都开启
public var roam: Roam?
/// 鼠标漫游缩放时节点的相应缩放比例,当设为0时节点不随着鼠标的缩放而缩放
public var nodeScaleRatio: Float?
/// 节点是否可拖拽,只在使用力引导布局的时候有用。
public var draggable: Bool?
/// 是否在鼠标移到节点上的时候突出显示节点以及节点的边和邻接节点。
public var focusNodeAdjacency: Bool?
/// 关系图节点标记的图形。
///
/// ECharts 提供的标记类型包括 'circle', 'rect', 'roundRect', 'triangle', 'diamond', 'pin', 'arrow'
///
/// 也可以通过 'image://url' 设置为图片,其中 url 为图片的链接,或者 dataURI。
///
/// 可以通过 'path://' 将图标设置为任意的矢量路径。这种方式相比于使用图片的方式,不用担心因为缩放而产生锯齿或模糊,而且可以设置为任意颜色。路径图形会自适应调整为合适的大小。路径的格式参见 SVG PathData。可以从 Adobe Illustrator 等工具编辑导出。
public var symbol: OneOrMore<Symbol>?
/// 关系图节点标记的大小,可以设置成诸如 10 这样单一的数字,也可以用数组分开表示宽和高,例如 [20, 10] 表示标记宽为20,高为10。
///
/// 如果需要每个数据的图形大小不一样,可以设置为如下格式的回调函数:
///
/// (value: Array|number, params: Object) => number|Array
///
/// 其中第一个参数 value 为 data 中的数据值。第二个参数params 是其它的数据项参数。
public var symbolSize: FunctionOrFloatOrPair?
/// 关系图节点标记的旋转角度。注意在 markLine 中当 symbol 为 'arrow' 时会忽略 symbolRotate 强制设置为切线的角度。
public var symbolRotate: Float?
/// 关系图节点标记相对于原本位置的偏移。默认情况下,标记会居中置放在数据对应的位置,但是如果 symbol 是自定义的矢量路径或者图片,就有可能不希望 symbol 居中。这时候可以使用该配置项配置 symbol 相对于原本居中的偏移,可以是绝对的像素值,也可以是相对的百分比。
///
/// 例如 [0, '50%'] 就是把自己向上移动了一半的位置,在 symbol 图形是气泡的时候可以让图形下端的箭头对准数据点。
public var symbolOffset: Point?
/// 边两端的标记类型,可以是一个数组分别指定两端,也可以是单个统一指定。默认不显示标记,常见的可以设置为箭头,如下:
///
/// edgeSymbol: ['circle', 'arrow']
public var edgeSymbol: OneOrMore<Symbol>?
/// 边两端的标记大小,可以是一个数组分别指定两端,也可以是单个统一指定。
public var edgeSymbolSize: FunctionOrFloatOrPair?
/// 鼠标悬浮时在图形元素上时鼠标的样式是什么。同 CSS 的 cursor。
public var cursor: String?
/// 图形样式,有 normal 和 emphasis 两个状态。normal 是图形在默认状态下的样式;emphasis 是图形在高亮状态下的样式,比如在鼠标悬浮或者图例联动高亮时。
public var itemStyle: ItemStyle?
/// 关系边的公用线条样式。其中 lineStyle.normal.color 支持设置为'source'或者'target'特殊值,此时边会自动取源节点或目标节点的颜色作为自己的颜色。
public var lineStyle: EmphasisLineStyle?
/// 图形上的文本标签,可用于说明图形的一些数据信息,比如值,名称等,label选项在 ECharts 2.x 中放置于itemStyle.normal下,在 ECharts 3 中为了让整个配置项结构更扁平合理,label 被拿出来跟 itemStyle 平级,并且跟 itemStyle 一样拥有 normal, emphasis 两个状态。
public var label: EmphasisLabel?
public var edgeLabel: EmphasisLabel?
/// 节点分类的类目,可选。
///
/// 如果节点有分类的话可以通过 data[i].category 指定每个节点的类目,类目的样式会被应用到节点样式上。图例也可以基于categories名字展现和筛选。
public var categories: [Category]?
/// 关系图的节点数据列表。
///
/// data: [{
/// name: '1',
/// x: 10,
/// y: 10,
/// value: 10
/// }, {
/// name: '2',
/// x: 100,
/// y: 100,
/// value: 20,
/// symbolSize: 20,
/// itemStyle: {
/// normal: {
/// color: 'red'
/// }
/// }
/// }]
///
/// 注意: 节点的name不能重复。
public var data: [Jsonable]?
/// 别名,同 data
public var nodes: [Jsonable]?
/// 节点间的关系数据。示例:
///
/// links: [{
/// source: 'n1',
/// target: 'n2'
/// }, {
/// source: 'n2',
/// target: 'n3'
/// }]
public var links: [Link]?
/// 别名,同 links
public var edges: [Link]?
/// 图表标注。
public var markPoint: MarkPoint?
/// 图表标线。
public var markLine: MarkLine?
/// 图表标域,常用于标记图表中某个范围的数据,例如标出某段时间投放了广告。
public var markArea: MarkArea?
/// 所有图形的 zlevel 值。
///
/// zlevel用于 Canvas 分层,不同zlevel值的图形会放置在不同的 Canvas 中,Canvas 分层是一种常见的优化手段。我们可以把一些图形变化频繁(例如有动画)的组件设置成一个单独的zlevel。需要注意的是过多的 Canvas 会引起内存开销的增大,在手机端上需要谨慎使用以防崩溃。
///
/// zlevel 大的 Canvas 会放在 zlevel 小的 Canvas 的上面。
public var zlevel: Float?
/// 组件的所有图形的z值。控制图形的前后顺序。z值小的图形会被z值大的图形覆盖。
///
/// z相比zlevel优先级更低,而且不会创建新的 Canvas。
public var z: Float?
/// 组件离容器左侧的距离。
///
/// left 的值可以是像 20 这样的具体像素值,可以是像 '20%' 这样相对于容器高宽的百分比,也可以是 'left', 'center', 'right'。
///
/// 如果 left 的值为'left', 'center', 'right',组件会根据相应的位置自动对齐。
public var left: Position?
/// 组件离容器上侧的距离。
///
/// top 的值可以是像 20 这样的具体像素值,可以是像 '20%' 这样相对于容器高宽的百分比,也可以是 'top', 'middle', 'bottom'。
///
/// 如果 top 的值为'top', 'middle', 'bottom',组件会根据相应的位置自动对齐。
public var top: Position?
/// 组件离容器右侧的距离。
///
/// right 的值可以是像 20 这样的具体像素值,可以是像 '20%' 这样相对于容器高宽的百分比。
///
/// 默认自适应。
public var right: Position?
/// 组件离容器下侧的距离。
///
/// bottom 的值可以是像 20 这样的具体像素值,可以是像 '20%' 这样相对于容器高宽的百分比。
///
/// 默认自适应。
public var bottom: Position?
/// 组件的宽度。
public var width: LengthValue?
/// 组件的高度。
public var height: LengthValue?
/// 图形是否不响应和触发鼠标事件,默认为 false,即响应和触发鼠标事件。
public var silent: Bool?
/// 是否开启动画。
public var animation: Bool?
/// 是否开启动画的阈值,当单个系列显示的图形数量大于这个阈值时会关闭动画。
public var animationThreshold: Float?
/// 初始动画的时长,支持回调函数,可以通过每个数据返回不同的 delay 时间实现更戏剧的初始动画效果:
///
/// animationDuration: function (idx) {
/// // 越往后的数据延迟越大
/// return idx * 100;
/// }
public var animationDuration: Time?
/// 初始动画的缓动效果。不同的缓动效果可以参考
public var animationEasing: EasingFunction?
/// 初始动画的延迟,支持回调函数,可以通过每个数据返回不同的 delay 时间实现更戏剧的初始动画效果。
///
/// 如下示例:
///
/// animationDuration: function (idx) {
/// // 越往后的数据延迟越大
/// return idx * 100;
/// }
public var animationDelay: Time?
/// 数据更新动画的时长。
/// 支持回调函数,可以通过每个数据返回不同的 delay 时间实现更戏剧的更新动画效果:
/// animationDurationUpdate: function (idx) {
/// // 越往后的数据延迟越大
/// return idx * 100;
/// }
public var animationDurationUpdate: Time?
/// 数据更新动画的缓动效果。
public var animationEasingUpdate: EasingFunction?
/// 数据更新动画的延迟,支持回调函数,可以通过每个数据返回不同的 delay 时间实现更戏剧的更新动画效果。
/// 如下示例:
///
/// animationDelayUpdate: function (idx) {
/// // 越往后的数据延迟越大
/// return idx * 100;
/// }
public var animationDelayUpdate: Time?
}
extension GraphSerie.Circular: Enumable {
public enum Enums {
case rotateLabel(Bool)
}
public typealias ContentEnum = Enums
public convenience init(_ elements: Enums...) {
self.init()
for ele in elements {
switch ele {
case let .rotateLabel(rotateLabel):
self.rotateLabel = rotateLabel
}
}
}
}
extension GraphSerie.Circular: Mappable {
public func mapping(_ map: Mapper) {
map["rotateLabel"] = rotateLabel
}
}
extension GraphSerie.Force: Enumable {
public enum Enums {
case initLayout(String), repulsion(Float), gravity(Float), edgeLength(Float), edgeLengths([Float]), layoutAnimation(Bool)
}
public typealias ContentEnum = Enums
public convenience init(_ elements: Enums...) {
self.init()
for ele in elements {
switch ele {
case let .initLayout(initLayout):
self.initLayout = initLayout
case let .repulsion(repulsion):
self.repulsion = repulsion
case let .gravity(gravity):
self.gravity = gravity
case let .edgeLength(edgeLength):
self.edgeLength = OneOrMore(one: edgeLength)
case let .edgeLengths(edgeLengths):
self.edgeLength = OneOrMore(more: edgeLengths)
case let .layoutAnimation(layoutAnimation):
self.layoutAnimation = layoutAnimation
}
}
}
}
extension GraphSerie.Force: Mappable {
public func mapping(_ map: Mapper) {
map["initLayout"] = initLayout
map["repulsion"] = repulsion
map["gravity"] = gravity
map["edgeLength"] = edgeLength
map["layoutAnimation"] = layoutAnimation
}
}
extension GraphSerie.Category: Enumable {
public enum Enums {
case name(String), symbol(Symbol), symbols([Symbol]), symbolSize(FunctionOrFloatOrPair), symbolRotate(Float), symbolOffset(Point), itemStyle(ItemStyle), label(EmphasisLabel)
}
public typealias ContentEnum = Enums
public convenience init(_ elements: Enums...) {
self.init()
for ele in elements {
switch ele {
case let .name(name):
self.name = name
case let .symbol(symbol):
self.symbol = OneOrMore(one: symbol)
case let .symbols(symbols):
self.symbol = OneOrMore(more: symbols)
case let .symbolSize(symbolSize):
self.symbolSize = symbolSize
case let .symbolRotate(symbolRotate):
self.symbolRotate = symbolRotate
case let .symbolOffset(symbolOffset):
self.symbolOffset = symbolOffset
case let .itemStyle(itemStyle):
self.itemStyle = itemStyle
case let .label(label):
self.label = label
}
}
}
}
extension GraphSerie.Category: Mappable {
public func mapping(_ map: Mapper) {
map["name"] = name
map["symbol"] = symbol
map["symbolSize"] = symbolSize
map["symbolRotate"] = symbolRotate
map["symbolOffset"] = symbolOffset
map["itemStyle"] = itemStyle
map["label"] = label
}
}
extension GraphSerie.Data: Enumable {
public enum Enums {
case name(String), x(Float), y(Float), fixed(Bool), value(Float), values([Float]), category(Float), symbol(Symbol), symbols([Symbol]), symbolSize(FunctionOrFloatOrPair), symbolRotate(Float), symbolOffset(Point), itemStyle(ItemStyle), label(EmphasisLabel), tooltip(Tooltip)
}
public typealias ContentEnum = Enums
public convenience init(_ elements: Enums...) {
self.init()
for ele in elements {
switch ele {
case let .name(name):
self.name = name
case let .x(x):
self.x = x
case let .y(y):
self.y = y
case let .fixed(fixed):
self.fixed = fixed
case let .value(value):
self.value = OneOrMore(one: value)
case let .values(values):
self.value = OneOrMore(more: values)
case let .category(category):
self.category = category
case let .symbol(symbol):
self.symbol = OneOrMore(one: symbol)
case let .symbols(symbols):
self.symbol = OneOrMore(more: symbols)
case let .symbolSize(symbolSize):
self.symbolSize = symbolSize
case let .symbolRotate(symbolRotate):
self.symbolRotate = symbolRotate
case let .symbolOffset(symbolOffset):
self.symbolOffset = symbolOffset
case let .itemStyle(itemStyle):
self.itemStyle = itemStyle
case let .label(label):
self.label = label
case let .tooltip(tooltip):
self.tooltip = tooltip
}
}
}
}
extension GraphSerie.Data: Mappable {
public func mapping(_ map: Mapper) {
map["name"] = name
map["x"] = x
map["y"] = y
map["fixed"] = fixed
map["value"] = value
map["category"] = category
map["symbol"] = symbol
map["symbolSize"] = symbolSize
map["symbolRotate"] = symbolRotate
map["symbolOffset"] = symbolOffset
map["itemStyle"] = itemStyle
map["label"] = label
map["tooltip"] = tooltip
}
}
extension GraphSerie.Link: Enumable {
public enum Enums {
case source(Jsonable), target(Jsonable), value(Float), lineStyle(EmphasisLineStyle), label(EmphasisLabel), symbol(Symbol), symbols([Symbol]), symbolSize(FunctionOrFloatOrPair)
}
public typealias ContentEnum = Enums
public convenience init(_ elements: Enums...) {
self.init()
for ele in elements {
switch ele {
case let .source(source):
self.source = source
case let .target(target):
self.target = target
case let .value(value):
self.value = value
case let .lineStyle(lineStyle):
self.lineStyle = lineStyle
case let .label(label):
self.label = label
case let .symbol(symbol):
self.symbol = OneOrMore(one: symbol)
case let .symbols(symbols):
self.symbol = OneOrMore(more: symbols)
case let .symbolSize(symbolSize):
self.symbolSize = symbolSize
}
}
}
}
extension GraphSerie.Link: Mappable {
public func mapping(_ map: Mapper) {
map["source"] = source
map["target"] = target
map["value"] = value
map["lineStyle"] = lineStyle
map["label"] = label
map["symbol"] = symbol
map["symbolSize"] = symbolSize
}
}
extension GraphSerie: Enumable {
public enum Enums {
case name(String), legendHoverLinek(Bool), coordinateSystem(CoordinateSystem), xAxisIndex(UInt8), yAxisIndex(UInt8), polarIndex(UInt8), geoIndex(UInt8), calendarIndex(UInt8), hoverAnimation(Bool), layout(Layout), circular(Circular), force(Force), roam(Roam), nodeScaleRatio(Float), draggable(Bool), focusNodeAdjacency(Bool), symbol(Symbol), symbols([Symbol]), symbolSize(FunctionOrFloatOrPair), symbolRotate(Float), symbolOffset(Point), edgeSymbol(Symbol), edgeSymbols([Symbol]), edgeSymbolSize(FunctionOrFloatOrPair), cursor(String), itemStyle(ItemStyle), lineStyle(EmphasisLineStyle), label(EmphasisLabel), edgeLabel(EmphasisLabel), categories([Category]), data([Jsonable]), nodes([Jsonable]), links([Link]), edges([Link]), markPoint(MarkPoint), markLine(MarkLine), markArea(MarkArea), zlevel(Float), z(Float), left(Position), top(Position), right(Position), bottom(Position), width(LengthValue), height(LengthValue), silent(Bool), animation(Bool), animationThreshold(Float), animationDuration(Time), animationEasing(EasingFunction), animationDelay(Time), animationDurationUpdate(Time), animationEasingUpdate(EasingFunction), animationDelayUpdate(Time)
}
public typealias ContentEnum = Enums
public convenience init(_ elements: Enums...) {
self.init()
for ele in elements {
switch ele {
case let .name(name):
self.name = name
case let .legendHoverLinek(legendHoverLinek):
self.legendHoverLinek = legendHoverLinek
case let .coordinateSystem(coordinateSystem):
self.coordinateSystem = coordinateSystem
case let .xAxisIndex(xAxisIndex):
self.xAxisIndex = xAxisIndex
case let .yAxisIndex(yAxisIndex):
self.yAxisIndex = yAxisIndex
case let .polarIndex(polarIndex):
self.polarIndex = polarIndex
case let .geoIndex(geoIndex):
self.geoIndex = geoIndex
case let .calendarIndex(calendarIndex):
self.calendarIndex = calendarIndex
case let .hoverAnimation(hoverAnimation):
self.hoverAnimation = hoverAnimation
case let .layout(layout):
self.layout = layout
case let .circular(circular):
self.circular = circular
case let .force(force):
self.force = force
case let .roam(roam):
self.roam = roam
case let .nodeScaleRatio(nodeScaleRatio):
self.nodeScaleRatio = nodeScaleRatio
case let .draggable(draggable):
self.draggable = draggable
case let .focusNodeAdjacency(focusNodeAdjacency):
self.focusNodeAdjacency = focusNodeAdjacency
case let .symbol(symbol):
self.symbol = OneOrMore(one: symbol)
case let .symbols(symbols):
self.symbol = OneOrMore(more: symbols)
case let .symbolSize(symbolSize):
self.symbolSize = symbolSize
case let .symbolRotate(symbolRotate):
self.symbolRotate = symbolRotate
case let .symbolOffset(symbolOffset):
self.symbolOffset = symbolOffset
case let .edgeSymbol(edgeSymbol):
self.edgeSymbol = OneOrMore(one: edgeSymbol)
case let .edgeSymbols(edgeSymbols):
self.edgeSymbol = OneOrMore(more: edgeSymbols)
case let .edgeSymbolSize(edgeSymbolSize):
self.edgeSymbolSize = edgeSymbolSize
case let .cursor(cursor):
self.cursor = cursor
case let .itemStyle(itemStyle):
self.itemStyle = itemStyle
case let .lineStyle(lineStyle):
self.lineStyle = lineStyle
case let .label(label):
self.label = label
case let .edgeLabel(edgeLabel):
self.edgeLabel = edgeLabel
case let .categories(categories):
self.categories = categories
case let .data(data):
self.data = data
case let .nodes(nodes):
self.nodes = nodes
case let .links(links):
self.links = links
case let .edges(edges):
self.edges = edges
case let .markPoint(markPoint):
self.markPoint = markPoint
case let .markLine(markLine):
self.markLine = markLine
case let .markArea(markArea):
self.markArea = markArea
case let .zlevel(zlevel):
self.zlevel = zlevel
case let .z(z):
self.z = z
case let .left(left):
self.left = left
case let .top(top):
self.top = top
case let .right(right):
self.right = right
case let .bottom(bottom):
self.bottom = bottom
case let .width(width):
self.width = width
case let .height(height):
self.height = height
case let .silent(silent):
self.silent = silent
case let .animation(animation):
self.animation = animation
case let .animationThreshold(animationThreshold):
self.animationThreshold = animationThreshold
case let .animationDuration(animationDuration):
self.animationDuration = animationDuration
case let .animationEasing(animationEasing):
self.animationEasing = animationEasing
case let .animationDelay(animationDelay):
self.animationDelay = animationDelay
case let .animationDurationUpdate(animationDurationUpdate):
self.animationDurationUpdate = animationDurationUpdate
case let .animationEasingUpdate(animationEasingUpdate):
self.animationEasingUpdate = animationEasingUpdate
case let .animationDelayUpdate(animationDelayUpdate):
self.animationDelayUpdate = animationDelayUpdate
}
}
}
}
extension GraphSerie: Mappable {
public func mapping(_ map: Mapper) {
map["type"] = type
map["name"] = name
map["legendHoverLinek"] = legendHoverLinek
map["coordinateSystem"] = coordinateSystem
map["xAxisIndex"] = xAxisIndex
map["yAxisIndex"] = yAxisIndex
map["polarIndex"] = polarIndex
map["geoIndex"] = geoIndex
map["calendarIndex"] = calendarIndex
map["hoverAnimation"] = hoverAnimation
map["layout"] = layout
map["circular"] = circular
map["force"] = force
map["roam"] = roam
map["nodeScaleRatio"] = nodeScaleRatio
map["draggable"] = draggable
map["focusNodeAdjacency"] = focusNodeAdjacency
map["symbol"] = symbol
map["symbolSize"] = symbolSize
map["symbolRotate"] = symbolRotate
map["symbolOffset"] = symbolOffset
map["edgeSymbol"] = edgeSymbol
map["edgeSymbolSize"] = edgeSymbolSize
map["cursor"] = cursor
map["itemStyle"] = itemStyle
map["lineStyle"] = lineStyle
map["label"] = label
map["edgeLabel"] = edgeLabel
map["categories"] = categories
map["data"] = data
map["nodes"] = nodes
map["links"] = links
map["edges"] = edges
map["markPoint"] = markPoint
map["markLine"] = markLine
map["markArea"] = markArea
map["zlevel"] = zlevel
map["z"] = z
map["left"] = left
map["top"] = top
map["right"] = right
map["bottom"] = bottom
map["width"] = width
map["height"] = height
map["silent"] = silent
map["animation"] = animation
map["animationThreshold"] = animationThreshold
map["animationDuration"] = animationDuration
map["animationEasing"] = animationEasing
map["animationDelay"] = animationDelay
map["animationDurationUpdate"] = animationDurationUpdate
map["animationEasingUpdate"] = animationEasingUpdate
map["animationDelayUpdate"] = animationDelayUpdate
}
}
| mit |
edopelawi/CascadingTableDelegate | Example/Tests/CascadingTableDelegate/CascadingSectionTableDelegateSpec.swift | 1 | 4415 | //
// CascadingSectionTableDelegateSpec.swift
// CascadingTableDelegate
//
// Created by Ricardo Pramana Suranta on 10/12/16.
// Copyright © 2016 Ricardo Pramana Suranta. All rights reserved.
//
import Quick
import Nimble
@testable import CascadingTableDelegate
class CascadingSectionTableDelegateSpec: QuickSpec {
override func spec() {
var sectionTableDelegate: CascadingSectionTableDelegate!
var childDelegates: [CascadingTableDelegateStub]!
beforeEach {
childDelegates = [
CascadingTableDelegateBareStub(index: 0, childDelegates: []),
CascadingTableDelegateCompleteStub(index: 0, childDelegates: [])
]
sectionTableDelegate = CascadingSectionTableDelegate(
index: 0,
childDelegates: childDelegates.map({ $0 as CascadingTableDelegate }),
propagationMode: .section
)
}
it("should have .row as its default propagationMode, even if the initializer requests .section") {
let expectedMode = PropagatingTableDelegate.PropagationMode.row
expect(sectionTableDelegate.propagationMode).to(equal(expectedMode))
}
it("should have .row as its propagationMode, even it's being set to another value.") {
sectionTableDelegate.propagationMode = .section
let expectedMode = PropagatingTableDelegate.PropagationMode.row
expect(sectionTableDelegate.propagationMode).to(equal(expectedMode))
}
describe("prepare(tableView:)") {
var tableView: UITableView!
beforeEach({
tableView = UITableView()
sectionTableDelegate.prepare(tableView: tableView)
})
afterEach({
childDelegates.forEach({ delegate in
delegate.resetRecordedParameters()
})
})
it("should call its childs' prepare(tableView:) too", closure: {
for delegate in childDelegates {
expect(delegate.prepareCalled).to(beTrue())
}
})
it("should not set itself as passed tableView's delegate and dataSource", closure: {
expect(tableView.delegate).to(beNil())
expect(tableView.dataSource).to(beNil())
})
}
it("should sort out its child delegate's indexes again when its childDelegates is changed") {
let newDelegate = CascadingTableDelegateBareStub(index: 0, childDelegates: [])
sectionTableDelegate.childDelegates.append(newDelegate)
let expectedIndex = sectionTableDelegate.childDelegates.count - 1
let lastDelegateIndex = sectionTableDelegate.childDelegates.last?.index
expect(lastDelegateIndex).to(equal(expectedIndex))
}
describe("reloadModeOnChildDelegatesChanged value on changed childDelegates") {
var testableTableView: TestableTableView!
beforeEach({
testableTableView = TestableTableView()
sectionTableDelegate.prepare(tableView: testableTableView)
})
afterEach({
sectionTableDelegate.childDelegates = childDelegates.map({ $0 as CascadingTableDelegate })
testableTableView.resetRecordedParameters()
})
it("should not call its tableView's `reloadData()` or `reloadSections(_:withRowAnimation)` for `None`", closure: {
sectionTableDelegate.reloadModeOnChildDelegatesChanged = .none
sectionTableDelegate.childDelegates = []
expect(testableTableView.reloadDataCalled).to(beFalse())
expect(testableTableView.reloadSectionsCalled).to(beFalse())
})
it("should only call its tableView's `reloadData()` for `Whole` ", closure: {
sectionTableDelegate.reloadModeOnChildDelegatesChanged = .whole
sectionTableDelegate.childDelegates = []
expect(testableTableView.reloadDataCalled).to(beTrue())
expect(testableTableView.reloadSectionsCalled).to(beFalse())
})
it("should only call its tableView's `reloadSections(_:withRowAnimation)` using its index for `Section(animation:)` ", closure: {
let expectedAnimation = UITableView.RowAnimation.automatic
let expectedIndex = NSIndexSet(index: sectionTableDelegate.index)
sectionTableDelegate.reloadModeOnChildDelegatesChanged = .section(animation: expectedAnimation)
sectionTableDelegate.childDelegates = []
expect(testableTableView.reloadDataCalled).to(beFalse())
expect(testableTableView.reloadSectionsCalled).to(beTrue())
expect(testableTableView.passedReloadSectionsIndexSet).to(equal(expectedIndex as IndexSet))
expect(testableTableView.passedReloadSectionsAnimation).to(equal(expectedAnimation))
})
}
}
}
| mit |
El-Fitz/ImageSlideshow | Pod/Classes/InputSources/AFURLSource.swift | 1 | 967 | //
// AFURLSource.swift
// ImageSlideshow
//
// Created by Petr Zvoníček on 30.07.15.
//
import AFNetworking
public class AFURLSource: NSObject, InputSource {
var url: URL
var placeholder: UIImage?
public init(url: URL) {
self.url = url
super.init()
}
public init(url: URL, placeholder: UIImage) {
self.url = url
self.placeholder = placeholder
super.init()
}
public init?(urlString: String) {
if let validUrl = URL(string: urlString) {
self.url = validUrl
super.init()
} else {
return nil
}
}
public func load(to imageView: UIImageView, with callback: @escaping (UIImage) -> ()) {
imageView.setImageWith(URLRequest(url: url), placeholderImage: self.placeholder, success: { (_, _, image: UIImage) in
imageView.image = image
callback(image)
}, failure: nil)
}
}
| mit |
lanjing99/RxSwiftDemo | 13-intermediate-rxcocoa/challenges/Wundercast/Controllers/ApiController.swift | 1 | 7878 | /*
* Copyright (c) 2014-2016 Razeware LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
import Foundation
import RxSwift
import RxCocoa
import SwiftyJSON
import CoreLocation
import MapKit
class ApiController {
/// The shared instance
static var shared = ApiController()
/// The api key to communicate with openweathermap.org
/// Create you own on https://home.openweathermap.org/users/sign_up
private let apiKey = "b7df09399978c6080aa16b2af36a5f32"//"[YOUR KEY]"
/// API base URL
let baseURL = URL(string: "http://api.openweathermap.org/data/2.5")!
init() {
Logging.URLRequests = { request in
return true
}
}
//MARK: - Api Calls
func currentWeather(city: String) -> Observable<Weather> {
return buildRequest(pathComponent: "weather", params: [("q", city)]).map() { json in
return Weather(
cityName: json["name"].string ?? "Unknown",
temperature: json["main"]["temp"].int ?? -1000,
humidity: json["main"]["humidity"].int ?? 0,
icon: iconNameToChar(icon: json["weather"][0]["icon"].string ?? "e"),
lat: json["coord"]["lat"].double ?? 0,
lon: json["coord"]["lon"].double ?? 0
)
}
}
func currentWeather(lat: Double, lon: Double) -> Observable<Weather> {
return buildRequest(pathComponent: "weather", params: [("lat", "\(lat)"), ("lon", "\(lon)")]).map() { json in
return Weather(
cityName: json["name"].string ?? "Unknown",
temperature: json["main"]["temp"].int ?? -1000,
humidity: json["main"]["humidity"].int ?? 0,
icon: iconNameToChar(icon: json["weather"][0]["icon"].string ?? "e"),
lat: json["coord"]["lat"].double ?? 0,
lon: json["coord"]["lon"].double ?? 0
)
}
}
func currentWeatherAround(lat: Double, lon: Double) -> Observable<[Weather]> {
var weathers = [Observable<Weather>]()
for i in -1...1 {
for j in -1...1 {
weathers.append(currentWeather(lat: lat + Double(i), lon: lon + Double(j)))
}
}
return Observable.from(weathers)
.merge()
.toArray()
}
//MARK: - Private Methods
/**
* Private method to build a request with RxCocoa
*/
private func buildRequest(method: String = "GET", pathComponent: String, params: [(String, String)]) -> Observable<JSON> {
let url = baseURL.appendingPathComponent(pathComponent)
var request = URLRequest(url: url)
let keyQueryItem = URLQueryItem(name: "appid", value: apiKey)
let unitsQueryItem = URLQueryItem(name: "units", value: "metric")
let urlComponents = NSURLComponents(url: url, resolvingAgainstBaseURL: true)!
if method == "GET" {
var queryItems = params.map { URLQueryItem(name: $0.0, value: $0.1) }
queryItems.append(keyQueryItem)
queryItems.append(unitsQueryItem)
urlComponents.queryItems = queryItems
} else {
urlComponents.queryItems = [keyQueryItem, unitsQueryItem]
let jsonData = try! JSONSerialization.data(withJSONObject: params, options: .prettyPrinted)
request.httpBody = jsonData
}
request.url = urlComponents.url!
request.httpMethod = method
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
let session = URLSession.shared
return session.rx.data(request: request).map { JSON(data: $0) }
}
/**
* Weather information and map overlay
*/
struct Weather {
let cityName: String
let temperature: Int
let humidity: Int
let icon: String
let lat: Double
let lon: Double
static let empty = Weather(
cityName: "Unknown",
temperature: -1000,
humidity: 0,
icon: iconNameToChar(icon: "e"),
lat: 0,
lon: 0
)
static let dummy = Weather(
cityName: "RxCity",
temperature: 20,
humidity: 90,
icon: iconNameToChar(icon: "01d"),
lat: 0,
lon: 0
)
var coordinate: CLLocationCoordinate2D {
return CLLocationCoordinate2D(latitude: lat, longitude: lon)
}
func overlay() -> Overlay {
let coordinates: [CLLocationCoordinate2D] = [
CLLocationCoordinate2D(latitude: lat - 0.25, longitude: lon - 0.25),
CLLocationCoordinate2D(latitude: lat + 0.25, longitude: lon + 0.25)
]
let points = coordinates.map { MKMapPointForCoordinate($0) }
let rects = points.map { MKMapRect(origin: $0, size: MKMapSize(width: 0, height: 0)) }
let fittingRect = rects.reduce(MKMapRectNull, MKMapRectUnion)
return Overlay(icon: icon, coordinate: coordinate, boundingMapRect: fittingRect)
}
public class Overlay: NSObject, MKOverlay {
var coordinate: CLLocationCoordinate2D
var boundingMapRect: MKMapRect
let icon: String
init(icon: String, coordinate: CLLocationCoordinate2D, boundingMapRect: MKMapRect) {
self.coordinate = coordinate
self.boundingMapRect = boundingMapRect
self.icon = icon
}
}
public class OverlayView: MKOverlayRenderer {
var overlayIcon: String
init(overlay:MKOverlay, overlayIcon:String) {
self.overlayIcon = overlayIcon
super.init(overlay: overlay)
}
public override func draw(_ mapRect: MKMapRect, zoomScale: MKZoomScale, in context: CGContext) {
let imageReference = imageFromText(text: overlayIcon as NSString, font: UIFont(name: "Flaticon", size: 32.0)!).cgImage
let theMapRect = overlay.boundingMapRect
let theRect = rect(for: theMapRect)
context.scaleBy(x: 1.0, y: -1.0)
context.translateBy(x: 0.0, y: -theRect.size.height)
context.draw(imageReference!, in: theRect)
}
}
}
}
/**
* Maps an icon information from the API to a local char
* Source: http://openweathermap.org/weather-conditions
*/
public func iconNameToChar(icon: String) -> String {
switch icon {
case "01d":
return "\u{f11b}"
case "01n":
return "\u{f110}"
case "02d":
return "\u{f112}"
case "02n":
return "\u{f104}"
case "03d", "03n":
return "\u{f111}"
case "04d", "04n":
return "\u{f111}"
case "09d", "09n":
return "\u{f116}"
case "10d", "10n":
return "\u{f113}"
case "11d", "11n":
return "\u{f10d}"
case "13d", "13n":
return "\u{f119}"
case "50d", "50n":
return "\u{f10e}"
default:
return "E"
}
}
fileprivate func imageFromText(text: NSString, font: UIFont) -> UIImage {
let size = text.size(attributes: [NSFontAttributeName: font])
if (UIGraphicsBeginImageContextWithOptions != nil) {
UIGraphicsBeginImageContextWithOptions(size, false, 0.0)
} else {
UIGraphicsBeginImageContext(size)
}
text.draw(at: CGPoint(x: 0, y:0), withAttributes: [NSFontAttributeName: font])
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image ?? UIImage()
}
| mit |
njdehoog/Spelt | Sources/Spelt/SpeltKit.swift | 1 | 79 | public let SpeltKitBundleIdentifier = Bundle(for: Site.self).bundleIdentifier!
| mit |
Alecrim/AlecrimCoreData | Sources/Core/Persistent Container/PersistentContainerType.swift | 1 | 3406 | //
// PersistentContainerType.swift
// AlecrimCoreData
//
// Created by Vanderlei Martinelli on 20/05/18.
// Copyright © 2018 Alecrim. All rights reserved.
//
import Foundation
import CoreData
// MARK: -
public protocol PersistentContainerType: AnyObject {
associatedtype ManagedObjectContextType: ManagedObjectContext
var viewContext: ManagedObjectContextType { get }
var backgroundContext: ManagedObjectContextType { get }
}
extension PersistentContainer: PersistentContainerType {}
extension CustomPersistentContainer: PersistentContainerType {}
// MARK: - helper static methods
extension PersistentContainerType {
public static func managedObjectModel(withName name: String? = nil, in bundle: Bundle? = nil) throws -> NSManagedObjectModel {
let bundle = bundle ?? Bundle(for: Self.self)
let name = name ?? bundle.bundleURL.deletingPathExtension().lastPathComponent
let managedObjectModelURL = try self.managedObjectModelURL(withName: name, in: bundle)
guard let managedObjectModel = NSManagedObjectModel(contentsOf: managedObjectModelURL) else {
throw PersistentContainerError.managedObjectModelNotFound
}
return managedObjectModel
}
private static func managedObjectModelURL(withName name: String, in bundle: Bundle) throws -> URL {
let resourceURL = bundle.url(forResource: name, withExtension: "momd") ?? bundle.url(forResource: name, withExtension: "mom")
guard let managedObjectModelURL = resourceURL else {
throw PersistentContainerError.invalidManagedObjectModelURL
}
return managedObjectModelURL
}
}
extension PersistentContainerType {
public static func persistentStoreURL(withName name: String? = nil, inPath path: String? = nil) throws -> URL {
guard let applicationSupportURL = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).last else {
throw PersistentContainerError.applicationSupportDirectoryNotFound
}
let name = name ?? Bundle.main.bundleURL.deletingPathExtension().lastPathComponent
let path = path ?? name
let persistentStoreURL = applicationSupportURL
.appendingPathComponent(path, isDirectory: true)
.appendingPathComponent("CoreData", isDirectory: true)
.appendingPathComponent(name, isDirectory: false)
.appendingPathExtension("sqlite")
return persistentStoreURL
}
public static func persistentStoreURL(withName name: String, inPath path: String? = nil, forSecurityApplicationGroupIdentifier applicationGroupIdentifier: String) throws -> URL {
guard let containerURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: applicationGroupIdentifier) else {
throw PersistentContainerError.invalidGroupContainerURL
}
let path = path ?? name
let persistentStoreURL = containerURL
.appendingPathComponent("Library", isDirectory: true)
.appendingPathComponent("Application Support", isDirectory: true)
.appendingPathComponent(path, isDirectory: true)
.appendingPathComponent("CoreData", isDirectory: true)
.appendingPathComponent(name, isDirectory: false)
.appendingPathExtension("sqlite")
return persistentStoreURL
}
}
| mit |
ngageoint/mage-ios | Mage/LocationUtilities.swift | 1 | 11839 | //
// CoordinateDisplay.swift
// MAGE
//
// Created by Daniel Barela on 7/10/20.
// Copyright © 2020 National Geospatial Intelligence Agency. All rights reserved.
//
import Foundation
import CoreLocation
struct DMSCoordinate {
var degrees: Int?
var minutes: Int?
var seconds: Int?
var direction: String?
}
public class LocationUtilities: NSObject {
override public init() { }
// Need to parse the following formats:
// 1. 112233N 0112244W
// 2. N 11 ° 22'33 "- W 11 ° 22'33
// 3. 11 ° 22'33 "N - 11 ° 22'33" W
// 4. 11° 22'33 N 011° 22'33 W
static func parseDMS(coordinate: String, addDirection: Bool = false, latitude: Bool = false) -> DMSCoordinate {
var dmsCoordinate: DMSCoordinate = DMSCoordinate()
var coordinateToParse = coordinate.trimmingCharacters(in: .whitespacesAndNewlines)
if addDirection {
// check if the first character is negative
if coordinateToParse.firstIndex(of: "-") == coordinateToParse.startIndex {
dmsCoordinate.direction = latitude ? "S" : "W"
} else {
dmsCoordinate.direction = latitude ? "N" : "E"
}
}
var charactersToKeep = CharacterSet()
charactersToKeep.formUnion(.decimalDigits)
charactersToKeep.insert(charactersIn: ".NSEWnsew")
coordinateToParse = coordinate.components(separatedBy: charactersToKeep.inverted).joined()
if let direction = coordinateToParse.last {
// the last character might be a direction not a number
if let _ = direction.wholeNumberValue {
} else {
dmsCoordinate.direction = "\(direction)".uppercased()
coordinateToParse = "\(coordinateToParse.dropLast(1))"
}
}
if let direction = coordinateToParse.first {
// the first character might be a direction not a number
if let _ = direction.wholeNumberValue {
} else {
dmsCoordinate.direction = "\(direction)".uppercased()
coordinateToParse = "\(coordinateToParse.dropFirst(1))"
}
}
// remove all characers except numbers and decimal points
charactersToKeep = CharacterSet()
charactersToKeep.formUnion(.decimalDigits)
charactersToKeep.insert(charactersIn: ".")
coordinateToParse = coordinate.components(separatedBy: charactersToKeep.inverted).joined()
// split the numbers before the decimal seconds
if coordinateToParse.isEmpty {
return dmsCoordinate
}
let split = coordinateToParse.split(separator: ".")
coordinateToParse = "\(split[0])"
let decimalSeconds = split.count == 2 ? Int(split[1]) : nil
dmsCoordinate.seconds = Int(coordinateToParse.suffix(2))
coordinateToParse = "\(coordinateToParse.dropLast(2))"
dmsCoordinate.minutes = Int(coordinateToParse.suffix(2))
dmsCoordinate.degrees = Int(coordinateToParse.dropLast(2))
if dmsCoordinate.degrees == nil {
if dmsCoordinate.minutes == nil {
dmsCoordinate.degrees = dmsCoordinate.seconds
dmsCoordinate.seconds = nil
} else {
dmsCoordinate.degrees = dmsCoordinate.minutes
dmsCoordinate.minutes = dmsCoordinate.seconds
dmsCoordinate.seconds = nil
}
}
if dmsCoordinate.minutes == nil && dmsCoordinate.seconds == nil && decimalSeconds != nil {
// this would be the case if a decimal degrees was passed in ie 11.123
let decimal = Double(".\(decimalSeconds ?? 0)") ?? 0.0
dmsCoordinate.minutes = Int(abs((decimal.truncatingRemainder(dividingBy: 1) * 60.0)))
let seconds = abs(((decimal.truncatingRemainder(dividingBy: 1) * 60.0).truncatingRemainder(dividingBy: 1) * 60.0))
dmsCoordinate.seconds = Int(seconds.rounded())
if dmsCoordinate.seconds == 60 {
dmsCoordinate.minutes = (dmsCoordinate.minutes ?? 0) + 1
dmsCoordinate.seconds = 0
}
if dmsCoordinate.minutes == 60 {
dmsCoordinate.degrees = (dmsCoordinate.degrees ?? 0) + 1
dmsCoordinate.minutes = 0
}
} else if let decimalSeconds = decimalSeconds {
// add the decimal seconds to seconds and round
dmsCoordinate.seconds = Int(Double("\((dmsCoordinate.seconds ?? 0)).\(decimalSeconds)")?.rounded() ?? 0)
}
return dmsCoordinate
}
@objc public static func validateLatitudeFromDMS(latitude: String?) -> Bool {
return validateCoordinateFromDMS(coordinate: latitude, latitude: true)
}
@objc public static func validateLongitudeFromDMS(longitude: String?) -> Bool {
return validateCoordinateFromDMS(coordinate: longitude, latitude: false)
}
@objc public static func validateCoordinateFromDMS(coordinate: String?, latitude: Bool) -> Bool {
guard let coordinate = coordinate else {
return false
}
var validCharacters = CharacterSet()
validCharacters.formUnion(.decimalDigits)
validCharacters.insert(charactersIn: ".NSEWnsew °\'\"")
if coordinate.rangeOfCharacter(from: validCharacters.inverted) != nil {
return false
}
var charactersToKeep = CharacterSet()
charactersToKeep.formUnion(.decimalDigits)
charactersToKeep.insert(charactersIn: ".NSEWnsew")
var coordinateToParse = coordinate.components(separatedBy: charactersToKeep.inverted).joined()
// There must be a direction as the last character
if let direction = coordinateToParse.last {
// the last character must be either N or S not a number
if let _ = direction.wholeNumberValue {
return false
} else {
if latitude && direction.uppercased() != "N" && direction.uppercased() != "S" {
return false
}
if !latitude && direction.uppercased() != "E" && direction.uppercased() != "W" {
return false
}
coordinateToParse = "\(coordinateToParse.dropLast(1))"
}
} else {
return false
}
// split the numbers before the decimal seconds
let split = coordinateToParse.split(separator: ".")
if split.isEmpty {
return false
}
coordinateToParse = "\(split[0])"
// there must be either 5 or 6 digits for latitude (1 or 2 degrees, 2 minutes, 2 seconds)
// or 5, 6, 7 digits for longitude
if latitude && (coordinateToParse.count < 5 || coordinateToParse.count > 6) {
return false
}
if !latitude && (coordinateToParse.count < 5 || coordinateToParse.count > 7) {
return false
}
var decimalSeconds = 0
if split.count == 2 {
if let decimalSecondsInt = Int(split[1]) {
decimalSeconds = decimalSecondsInt
} else {
return false
}
}
let seconds = Int(coordinateToParse.suffix(2))
coordinateToParse = "\(coordinateToParse.dropLast(2))"
let minutes = Int(coordinateToParse.suffix(2))
let degrees = Int(coordinateToParse.dropLast(2))
if let degrees = degrees {
if latitude && (degrees < 0 || degrees > 90) {
return false
}
if !latitude && (degrees < 0 || degrees > 180) {
return false
}
} else {
return false
}
if let minutes = minutes, let degrees = degrees {
if (minutes < 0 || minutes > 59) || (latitude && degrees == 90 && minutes != 0) || (!latitude && degrees == 180 && minutes != 0) {
return false
}
} else {
return false
}
if let seconds = seconds, let degrees = degrees {
if (seconds < 0 || seconds > 59) || (latitude && degrees == 90 && (seconds != 0 || decimalSeconds != 0)) || (!latitude && degrees == 180 && (seconds != 0 || decimalSeconds != 0)) {
return false
}
} else {
return false
}
return true
}
// attempts to parse what was passed in to DDD° MM' SS.sss" (NS) or returns "" if unparsable
@objc public static func parseToDMSString(_ string: String?, addDirection: Bool = false, latitude: Bool = false) -> String? {
guard let string = string else {
return nil
}
if string.isEmpty {
return ""
}
let parsed = parseDMS(coordinate: string, addDirection: addDirection, latitude: latitude)
let direction = parsed.direction ?? ""
var seconds = ""
if let parsedSeconds = parsed.seconds {
seconds = String(format: "%02d", parsedSeconds)
}
var minutes = ""
if let parsedMinutes = parsed.minutes {
minutes = String(format: "%02d", parsedMinutes)
}
var degrees = ""
if let parsedDegrees = parsed.degrees {
if string.starts(with: "0") && parsedDegrees != 0 {
degrees = "0\(parsedDegrees)"
} else {
degrees = "\(parsedDegrees)"
}
}
if !degrees.isEmpty {
degrees = "\(degrees)° "
}
if !minutes.isEmpty {
minutes = "\(minutes)\' "
}
if !seconds.isEmpty {
seconds = "\(seconds)\" "
}
return "\(degrees)\(minutes)\(seconds)\(direction)"
}
// TODO: update this when non @objc to take an optional and return nil
@objc public static func latitudeDMSString(coordinate: CLLocationDegrees) -> String {
let nf = NumberFormatter()
nf.maximumFractionDigits = 0
nf.minimumIntegerDigits = 2
var latDegrees: Int = Int(coordinate)
var latMinutes = Int(abs((coordinate.truncatingRemainder(dividingBy: 1) * 60.0)))
var latSeconds = abs(((coordinate.truncatingRemainder(dividingBy: 1) * 60.0).truncatingRemainder(dividingBy: 1) * 60.0)).rounded()
if latSeconds == 60 {
latSeconds = 0
latMinutes += 1
}
if latMinutes == 60 {
latDegrees += 1
latMinutes = 0
}
return "\(abs(latDegrees))° \(nf.string(for: latMinutes) ?? "")\' \(nf.string(for: latSeconds) ?? "")\" \(latDegrees >= 0 ? "N" : "S")"
}
@objc public static func longitudeDMSString(coordinate: CLLocationDegrees) -> String {
let nf = NumberFormatter()
nf.maximumFractionDigits = 0
nf.minimumIntegerDigits = 2
var lonDegrees: Int = Int(coordinate)
var lonMinutes = Int(abs((coordinate.truncatingRemainder(dividingBy: 1) * 60.0)))
var lonSeconds = abs(((coordinate.truncatingRemainder(dividingBy: 1) * 60.0).truncatingRemainder(dividingBy: 1) * 60.0)).rounded()
if lonSeconds == 60 {
lonSeconds = 0
lonMinutes += 1
}
if lonMinutes == 60 {
lonDegrees += 1
lonMinutes = 0
}
return "\(abs(lonDegrees))° \(nf.string(for: lonMinutes) ?? "")\' \(nf.string(for: lonSeconds) ?? "")\" \(lonDegrees >= 0 ? "E" : "W")"
}
}
| apache-2.0 |
fqhuy/minimind | minimind/random.swift | 1 | 3787 | //
// SwiftRandom.swift
//
// Created by Furkan Yilmaz on 7/10/15.
// Copyright (c) 2015 Furkan Yilmaz. All rights reserved.
//
//import UIKit
import Foundation
public func rand<T: BinaryFloatingPoint>(_ lower: T = 0.0, _ upper: T = 1.0) -> T {
return (T(arc4random()) / 0xFFFFFFFF) * (upper - lower) + lower
}
public extension Bool {
/// SwiftRandom extension
public static func random() -> Bool {
return Int.random() % 2 == 0
}
}
public extension Int {
/// SwiftRandom extension
public static func random(_ range: Range<Int>) -> Int {
#if swift(>=3)
return random(range.lowerBound, range.upperBound - 1)
#else
return random(range.upperBound, range.lowerBound)
#endif
}
/// SwiftRandom extension
public static func random(_ range: ClosedRange<Int>) -> Int {
return random(range.lowerBound, range.upperBound)
}
/// SwiftRandom extension
public static func random(_ lower: Int = 0, _ upper: Int = 100) -> Int {
return lower + Int(arc4random_uniform(UInt32(upper - lower + 1)))
}
}
public extension Int32 {
/// SwiftRandom extension
public static func random(_ range: Range<Int>) -> Int32 {
return random(range.upperBound, range.lowerBound)
}
/// SwiftRandom extension
///
/// - note: Using `Int` as parameter type as we usually just want to write `Int32.random(13, 37)` and not `Int32.random(Int32(13), Int32(37))`
public static func random(_ lower: Int = 0, _ upper: Int = 100) -> Int32 {
let r = arc4random_uniform(UInt32(Int64(upper) - Int64(lower)))
return Int32(Int64(r) + Int64(lower))
}
}
public extension Double {
/// SwiftRandom extension
public static func random(_ lower: Double = 0, _ upper: Double = 100) -> Double {
return (Double(arc4random()) / 0xFFFFFFFF) * (upper - lower) + lower
}
}
public extension Float {
/// SwiftRandom extension
public static func random(_ lower: Float = 0, _ upper: Float = 100) -> Float {
return (Float(arc4random()) / 0xFFFFFFFF) * (upper - lower) + lower
}
}
public extension Array {
/// SwiftRandom extension
public func randomItem() -> Element? {
guard self.count > 0 else {
return nil
}
let index = Int(arc4random_uniform(UInt32(self.count)))
return self[index]
}
}
public extension ArraySlice {
/// SwiftRandom extension
public func randomItem() -> Element? {
guard self.count > 0 else {
return nil
}
#if swift(>=3)
let index = Int.random(self.startIndex, self.count - 1)
#else
let index = Int.random(self.startIndex, self.endIndex)
#endif
return self[index]
}
}
public struct Randoms {
public static func randomBool() -> Bool {
return Bool.random()
}
public static func randomInt(_ range: Range<Int>) -> Int {
return Int.random(range)
}
public static func randomInt(_ lower: Int = 0, _ upper: Int = 100) -> Int {
return Int.random(lower, upper)
}
public static func randomInt32(_ range: Range<Int>) -> Int32 {
return Int32.random(range)
}
public static func randomInt32(_ lower: Int = 0, _ upper: Int = 100) -> Int32 {
return Int32.random(lower, upper)
}
public static func randomPercentageisOver(_ percentage: Int) -> Bool {
return Int.random() > percentage
}
public static func randomDouble(_ lower: Double = 0, _ upper: Double = 100) -> Double {
return Double.random(lower, upper)
}
public static func randomFloat(_ lower: Float = 0, _ upper: Float = 100) -> Float {
return Float.random(lower, upper)
}
}
| mit |
ultimecia7/BestGameEver | Stick-Hero/ContactTableViewCell.swift | 1 | 368 | //
// ContactTableViewCell.swift
// Stick-Hero
//
// Created by YIZHONGQI on 12/21/15.
// Copyright © 2015 koofrank. All rights reserved.
//
import Foundation
import UIKit
class ContactTableViewCell : UITableViewCell {
@IBOutlet weak var user: UILabel!
@IBOutlet weak var normalhigh: UILabel!
@IBOutlet weak var speedhigh: UILabel!
} | mit |
Diego5529/tcc-swift3 | tcc-swift3/src/controllers/InviteFormViewController.swift | 1 | 10648 | //
// InviteFormViewController.swift
// tcc-swift3
//
// Created by Diego Oliveira on 27/05/17.
// Copyright © 2017 DO. All rights reserved.
//
import UIKit
import Former
import CoreData
class InviteFormViewController : FormViewController {
var delegate: AppDelegate!
var context: NSManagedObjectContext!
var companyEvent: CompanyBean!
var eventClass: EventBean!
var invitationClass: InvitationBean!
var userClass: UserBean!
override func viewDidLoad() {
super.viewDidLoad()
delegate = UIApplication.shared.delegate as! AppDelegate
context = self.delegate.managedObjectContext
if invitationClass == nil && eventClass != nil {
invitationClass = InvitationBean.init()
invitationClass.event_id = eventClass.event_id
invitationClass.host_user_id = (delegate.genericUser?.user_id)!
configureInviteRows()
addSaveButton()
}else {
self.dismiss(animated: true, completion: nil)
}
}
func addSaveButton(){
let addButton = UIBarButtonItem(barButtonSystemItem: .save, target: self, action: #selector(insertNewObject(_:)))
self.navigationItem.rightBarButtonItem = addButton
}
func insertNewObject(_ sender: Any) {
if self.invitationClass?.created_at == nil {
invitationClass?.created_at = NSDate.init()
}
DispatchQueue.global(qos: .default).async(execute: {() -> Void in
//
var idMaxUser = 0
let userBean = UserBean.getUserByEmail(context: self.context, email: self.invitationClass.email)
if (userBean.id == 0) {
let sync = Sync.init()
sync.getUserEmailOrID(user: userBean, email: self.invitationClass.email, id: self.invitationClass.id)
}
DispatchQueue.main.async(execute: {() -> Void in
//
if userBean.id > 0 {
self.invitationClass.guest_user_id = userBean.id
}else{
let userObj: NSManagedObject = NSEntityDescription.insertNewObject(forEntityName: "User", into: self.context)
idMaxUser = Int(UserBean.getMaxUser(context: self.context))
userObj.setValue(self.invitationClass.email, forKey: "email")
userObj.setValue(idMaxUser, forKey: "user_id")
self.invitationClass.guest_user_id = Int16(idMaxUser)
}
let message = self.invitationClass?.validateCreateInvitation()
if (message?.isEmpty)! {
self.navigationItem.rightBarButtonItem?.isEnabled = false
let idMaxInvitation = InvitationBean.getMaxInvitation(context: self.context)
self.invitationClass.invitation_id = idMaxInvitation
self.invitationClass.event_id = self.eventClass.event_id
self.invitationClass.host_user_id = (self.delegate.genericUser?.id)!
self.invitationClass.updated_at = NSDate.init()
do {
InvitationBean.saveInvitation(context: self.context, invitation: self.invitationClass)
try self.context.save()
print("save success!")
OperationQueue.main.addOperation {
}
}catch{
print("Salvou")
}
}else{
self.showMessage(message: message!, title: "Error", cancel: "")
}
})
})
}
override func viewDidAppear(_ animated: Bool) {
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func configureInviteRows (){
// Create RowFormers
// InviteRows
let inputAccessoryView = FormerInputAccessoryView(former: former)
// Create Headers and Footers
let createHeader: ((String) -> ViewFormer) = { text in
return LabelViewFormer<FormLabelHeaderView>()
.configure {
$0.text = text
$0.viewHeight = 44
}
}
//Create Rows
//User
let textFieldUserEvent = TextFieldRowFormer<FormTextFieldCell>() {
$0.titleLabel.text = "User"
$0.textField.keyboardType = .emailAddress
}.configure {
$0.placeholder = "Email"
}.onTextChanged {
print($0)
self.navigationItem.rightBarButtonItem?.isEnabled = true
self.invitationClass?.email = $0.lowercased()
}.onUpdate{
$0.text = self.invitationClass.email.lowercased()
}
//Invitation Type
let selectorInvitationTypePickerRow = SelectorPickerRowFormer<FormSelectorPickerCell, Any>() {
$0.titleLabel.text = "Invitation Type"
}.configure {
$0.pickerItems = [SelectorPickerItem(
title: "",
displayTitle: NSAttributedString(string: "Normal"),
value: nil)]
+ (1...20).map { SelectorPickerItem(title: "Type \($0)") }
}
// Create SectionFormers
let section0 = SectionFormer(rowFormer: textFieldUserEvent, selectorInvitationTypePickerRow)
.set(headerViewFormer: createHeader("Invite"))
former.append(sectionFormer: section0
).onCellSelected { _ in
inputAccessoryView.update()
}
}
private enum InsertPosition: Int {
case Below, Above
}
private var insertRowAnimation = UITableViewRowAnimation.left
private var insertSectionAnimation = UITableViewRowAnimation.fade
private var insertRowPosition: InsertPosition = .Below
private var insertSectionPosition: InsertPosition = .Below
private lazy var subRowFormers: [RowFormer] = {
return (1...2).map { index -> RowFormer in
return CheckRowFormer<FormCheckCell>() {
$0.titleLabel.text = "Check\(index)"
$0.titleLabel.textColor = .formerColor()
$0.titleLabel.font = .boldSystemFont(ofSize: 16)
$0.tintColor = .formerSubColor()
}
}
}()
private lazy var subSectionFormer: SectionFormer = {
return SectionFormer(rowFormers: [
CheckRowFormer<FormCheckCell>() {
$0.titleLabel.text = "Check3"
$0.titleLabel.textColor = .formerColor()
$0.titleLabel.font = .boldSystemFont(ofSize: 16)
$0.tintColor = .formerSubColor()
}
])
}()
private func insertRows(sectionTop: RowFormer, sectionBottom: RowFormer) -> (Bool) -> Void {
return { [weak self] insert in
guard let `self` = self else { return }
if insert {
if self.insertRowPosition == .Below {
self.former.insertUpdate(rowFormers: self.subRowFormers, below: sectionBottom, rowAnimation: self.insertRowAnimation)
} else if self.insertRowPosition == .Above {
self.former.insertUpdate(rowFormers: self.subRowFormers, above: sectionTop, rowAnimation: self.insertRowAnimation)
}
} else {
self.former.removeUpdate(rowFormers: self.subRowFormers, rowAnimation: self.insertRowAnimation)
}
}
}
private func insertSection(relate: SectionFormer) -> (Bool) -> Void {
return { [weak self] insert in
guard let `self` = self else { return }
if insert {
if self.insertSectionPosition == .Below {
self.former.insertUpdate(sectionFormers: [self.subSectionFormer], below: relate, rowAnimation: self.insertSectionAnimation)
} else if self.insertSectionPosition == .Above {
self.former.insertUpdate(sectionFormers: [self.subSectionFormer], above: relate, rowAnimation: self.insertSectionAnimation)
}
} else {
self.former.removeUpdate(sectionFormers: [self.subSectionFormer], rowAnimation: self.insertSectionAnimation)
}
}
}
private func sheetSelectorRowSelected(options: [String]) -> (RowFormer) -> Void {
return { [weak self] rowFormer in
if let rowFormer = rowFormer as? LabelRowFormer<FormLabelCell> {
let sheet = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
options.forEach { title in
sheet.addAction(UIAlertAction(title: title, style: .default, handler: { [weak rowFormer] _ in
rowFormer?.subText = title
rowFormer?.update()
})
)
}
sheet.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
self?.present(sheet, animated: true, completion: nil)
self?.former.deselect(animated: true)
}
}
}
//AlertView
func showMessage(message: String, title: String, cancel: String){
let alertController = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert)
if cancel.characters.count > 0 {
let DestructiveAction = UIAlertAction(title: cancel, style: UIAlertActionStyle.destructive) {
(result : UIAlertAction) -> Void in
print("Destructive")
}
alertController.addAction(DestructiveAction)
}
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default) {
(result : UIAlertAction) -> Void in
}
alertController.addAction(okAction)
OperationQueue.main.addOperation {
self.present(alertController, animated: false, completion: nil)
}
}
}
| mit |
kickerchen/KCPutton | Putton/ViewController.swift | 1 | 2569 | //
// ViewController.swift
// Putton
//
// Created by CHENCHIAN on 7/22/15.
// Copyright (c) 2015 KICKERCHEN. 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.
let startButton = PuttonItem(image: UIImage(named: "mushroom")!)
let itemButton1 = PuttonItem(image: UIImage(named: "mario")!)
itemButton1.addTarget(self, action: "hitOnMario1:", forControlEvents: .TouchUpInside)
let itemButton2 = PuttonItem(image: UIImage(named: "mario")!)
itemButton2.addTarget(self, action: "hitOnMario2:", forControlEvents: .TouchUpInside)
let itemButton3 = PuttonItem(image: UIImage(named: "mario")!)
itemButton3.addTarget(self, action: "hitOnMario3:", forControlEvents: .TouchUpInside)
let itemButton4 = PuttonItem(image: UIImage(named: "mario")!)
itemButton4.addTarget(self, action: "hitOnMario4:", forControlEvents: .TouchUpInside)
let itemButton5 = PuttonItem(image: UIImage(named: "mario")!)
itemButton5.addTarget(self, action: "hitOnMario5:", forControlEvents: .TouchUpInside)
let itemButton6 = PuttonItem(image: UIImage(named: "mario")!)
itemButton6.addTarget(self, action: "hitOnMario6:", forControlEvents: .TouchUpInside)
let items = NSArray(array: [itemButton1, itemButton2, itemButton3, itemButton4, itemButton5, itemButton6])
let putton = Putton(frame: CGRectMake(CGRectGetWidth(UIScreen.mainScreen().bounds)/2-26, CGRectGetHeight(UIScreen.mainScreen().bounds)/2-26, 52, 52), startItem: startButton, expandItems: items)
self.view.addSubview(putton)
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func hitOnMario1(sender: UIButton!){
println("Mario 1 is hit")
}
func hitOnMario2(sender: UIButton!){
println("Mario 2 is hit")
}
func hitOnMario3(sender: UIButton!){
println("Mario 3 is hit")
}
func hitOnMario4(sender: UIButton!){
println("Mario 4 is hit")
}
func hitOnMario5(sender: UIButton!){
println("Mario 5 is hit")
}
func hitOnMario6(sender: UIButton!){
println("Mario 6 is hit")
}
}
| mit |
SwiftAndroid/swift | test/Driver/linker.swift | 4 | 11078 | // RUN: %swiftc_driver -driver-print-jobs -target x86_64-apple-macosx10.9 %s 2>&1 > %t.simple.txt
// RUN: FileCheck %s < %t.simple.txt
// RUN: FileCheck -check-prefix SIMPLE %s < %t.simple.txt
// RUN: %swiftc_driver -driver-print-jobs -target x86_64-apple-ios7.1 %s 2>&1 > %t.simple.txt
// RUN: FileCheck -check-prefix IOS_SIMPLE %s < %t.simple.txt
// RUN: %swiftc_driver -driver-print-jobs -target x86_64-apple-tvos9.0 %s 2>&1 > %t.simple.txt
// RUN: FileCheck -check-prefix tvOS_SIMPLE %s < %t.simple.txt
// RUN: %swiftc_driver -driver-print-jobs -target i386-apple-watchos2.0 %s 2>&1 > %t.simple.txt
// RUN: FileCheck -check-prefix watchOS_SIMPLE %s < %t.simple.txt
// RUN: %swiftc_driver -driver-print-jobs -target x86_64-unknown-linux-gnu -Ffoo -framework bar -Lbaz -lboo -Xlinker -undefined %s 2>&1 > %t.linux.txt
// RUN: FileCheck -check-prefix LINUX-x86_64 %s < %t.linux.txt
// RUN: %swiftc_driver -driver-print-jobs -target armv6-unknown-linux-gnueabihf -Ffoo -framework bar -Lbaz -lboo -Xlinker -undefined %s 2>&1 > %t.linux.txt
// RUN: FileCheck -check-prefix LINUX-armv6 %s < %t.linux.txt
// RUN: %swiftc_driver -driver-print-jobs -target armv7-unknown-linux-gnueabihf -Ffoo -framework bar -Lbaz -lboo -Xlinker -undefined %s 2>&1 > %t.linux.txt
// RUN: FileCheck -check-prefix LINUX-armv7 %s < %t.linux.txt
// RUN: %swiftc_driver -driver-print-jobs -target thumbv7-unknown-linux-gnueabihf -Ffoo -framework bar -Lbaz -lboo -Xlinker -undefined %s 2>&1 > %t.linux.txt
// RUN: FileCheck -check-prefix LINUX-thumbv7 %s < %t.linux.txt
// RUN: %swiftc_driver -driver-print-jobs -target armv7-none-linux-androideabi -Ffoo -framework bar -Lbaz -lboo -Xlinker -undefined %s 2>&1 > %t.android.txt
// RUN: FileCheck -check-prefix ANDROID-armv7 %s < %t.android.txt
// RUN: FileCheck -check-prefix ANDROID-armv7-NEGATIVE %s < %t.android.txt
// RUN: %swiftc_driver -driver-print-jobs -target x86_64-unknown-windows-cygnus -Ffoo -framework bar -Lbaz -lboo -Xlinker -undefined %s 2>&1 > %t.cygwin.txt
// RUN: FileCheck -check-prefix CYGWIN-x86_64 %s < %t.cygwin.txt
// RUN: %swiftc_driver -driver-print-jobs -emit-library -target x86_64-apple-macosx10.9.1 %s -sdk %S/../Inputs/clang-importer-sdk -lfoo -framework bar -Lbaz -Fgarply -Xlinker -undefined -Xlinker dynamic_lookup -o sdk.out 2>&1 > %t.complex.txt
// RUN: FileCheck %s < %t.complex.txt
// RUN: FileCheck -check-prefix COMPLEX %s < %t.complex.txt
// RUN: %swiftc_driver -driver-print-jobs -target x86_64-apple-macosx10.9 -g %s | FileCheck -check-prefix DEBUG %s
// RUN: %swiftc_driver -driver-print-jobs -target x86_64-apple-macosx10.10 %s | FileCheck -check-prefix NO_ARCLITE %s
// RUN: %swiftc_driver -driver-print-jobs -target x86_64-apple-ios8.0 %s | FileCheck -check-prefix NO_ARCLITE %s
// RUN: rm -rf %t && mkdir %t
// RUN: touch %t/a.o
// RUN: %swiftc_driver -driver-print-jobs -target x86_64-apple-macosx10.9 %s %t/a.o -o linker 2>&1 | FileCheck -check-prefix COMPILE_AND_LINK %s
// RUN: %swiftc_driver -driver-print-jobs -target x86_64-apple-macosx10.9 %s %t/a.o -driver-use-filelists -o linker 2>&1 | FileCheck -check-prefix FILELIST %s
// RUN: %swiftc_driver -driver-print-jobs -target x86_64-apple-macosx10.9 -emit-library %s -module-name LINKER | FileCheck -check-prefix INFERRED_NAME %s
// RUN: %swiftc_driver -driver-print-jobs -target x86_64-apple-macosx10.9 -emit-library %s -o libLINKER.dylib | FileCheck -check-prefix INFERRED_NAME %s
// There are more RUN lines further down in the file.
// REQUIRES: X86
// FIXME: Need to set up a sysroot for osx so the DEBUG checks work on linux/freebsd
// rdar://problem/19692770
// XFAIL: freebsd, linux
// CHECK: swift
// CHECK: -o [[OBJECTFILE:.*]]
// CHECK-NEXT: bin/ld{{"? }}
// CHECK-DAG: [[OBJECTFILE]]
// CHECK-DAG: -L [[STDLIB_PATH:[^ ]+/lib/swift/macosx]]
// CHECK-DAG: -rpath [[STDLIB_PATH]]
// CHECK-DAG: -lSystem
// CHECK-DAG: -arch x86_64
// CHECK-DAG: -force_load {{[^ ]+/lib/arc/libarclite_macosx.a}} -framework CoreFoundation
// CHECK: -o {{[^ ]+}}
// SIMPLE: bin/ld{{"? }}
// SIMPLE-NOT: -syslibroot
// SIMPLE-DAG: -macosx_version_min 10.{{[0-9]+}}.{{[0-9]+}}
// SIMPLE-NOT: -syslibroot
// SIMPLE: -o linker
// IOS_SIMPLE: swift
// IOS_SIMPLE: -o [[OBJECTFILE:.*]]
// IOS_SIMPLE: bin/ld{{"? }}
// IOS_SIMPLE-DAG: [[OBJECTFILE]]
// IOS_SIMPLE-DAG: -L {{[^ ]+/lib/swift/iphonesimulator}}
// IOS_SIMPLE-DAG: -lSystem
// IOS_SIMPLE-DAG: -arch x86_64
// IOS_SIMPLE-DAG: -ios_simulator_version_min 7.1.{{[0-9]+}}
// IOS_SIMPLE: -o linker
// tvOS_SIMPLE: swift
// tvOS_SIMPLE: -o [[OBJECTFILE:.*]]
// tvOS_SIMPLE: bin/ld{{"? }}
// tvOS_SIMPLE-DAG: [[OBJECTFILE]]
// tvOS_SIMPLE-DAG: -L {{[^ ]+/lib/swift/appletvsimulator}}
// tvOS_SIMPLE-DAG: -lSystem
// tvOS_SIMPLE-DAG: -arch x86_64
// tvOS_SIMPLE-DAG: -tvos_simulator_version_min 9.0.{{[0-9]+}}
// tvOS_SIMPLE: -o linker
// watchOS_SIMPLE: swift
// watchOS_SIMPLE: -o [[OBJECTFILE:.*]]
// watchOS_SIMPLE: bin/ld{{"? }}
// watchOS_SIMPLE-DAG: [[OBJECTFILE]]
// watchOS_SIMPLE-DAG: -L {{[^ ]+/lib/swift/watchsimulator}}
// watchOS_SIMPLE-DAG: -lSystem
// watchOS_SIMPLE-DAG: -arch i386
// watchOS_SIMPLE-DAG: -watchos_simulator_version_min 2.0.{{[0-9]+}}
// watchOS_SIMPLE: -o linker
// LINUX-x86_64: swift
// LINUX-x86_64: -o [[OBJECTFILE:.*]]
// LINUX-x86_64: clang++{{"? }}
// LINUX-x86_64-DAG: [[OBJECTFILE]]
// LINUX-x86_64-DAG: -lswiftCore
// LINUX-x86_64-DAG: -L [[STDLIB_PATH:[^ ]+/lib/swift]]
// LINUX-x86_64-DAG: -Xlinker -rpath -Xlinker [[STDLIB_PATH]]
// LINUX-x86_64-DAG: -F foo
// LINUX-x86_64-DAG: -framework bar
// LINUX-x86_64-DAG: -L baz
// LINUX-x86_64-DAG: -lboo
// LINUX-x86_64-DAG: -Xlinker -undefined
// LINUX-x86_64: -o linker
// LINUX-armv6: swift
// LINUX-armv6: -o [[OBJECTFILE:.*]]
// LINUX-armv6: clang++{{"? }}
// LINUX-armv6-DAG: [[OBJECTFILE]]
// LINUX-armv6-DAG: -lswiftCore
// LINUX-armv6-DAG: -L [[STDLIB_PATH:[^ ]+/lib/swift]]
// LINUX-armv6-DAG: -target armv6-unknown-linux-gnueabihf
// LINUX-armv6-DAG: -Xlinker -rpath -Xlinker [[STDLIB_PATH]]
// LINUX-armv6-DAG: -F foo
// LINUX-armv6-DAG: -framework bar
// LINUX-armv6-DAG: -L baz
// LINUX-armv6-DAG: -lboo
// LINUX-armv6-DAG: -Xlinker -undefined
// LINUX-armv6: -o linker
// LINUX-armv7: swift
// LINUX-armv7: -o [[OBJECTFILE:.*]]
// LINUX-armv7: clang++{{"? }}
// LINUX-armv7-DAG: [[OBJECTFILE]]
// LINUX-armv7-DAG: -lswiftCore
// LINUX-armv7-DAG: -L [[STDLIB_PATH:[^ ]+/lib/swift]]
// LINUX-armv7-DAG: -target armv7-unknown-linux-gnueabihf
// LINUX-armv7-DAG: -Xlinker -rpath -Xlinker [[STDLIB_PATH]]
// LINUX-armv7-DAG: -F foo
// LINUX-armv7-DAG: -framework bar
// LINUX-armv7-DAG: -L baz
// LINUX-armv7-DAG: -lboo
// LINUX-armv7-DAG: -Xlinker -undefined
// LINUX-armv7: -o linker
// LINUX-thumbv7: swift
// LINUX-thumbv7: -o [[OBJECTFILE:.*]]
// LINUX-thumbv7: clang++{{"? }}
// LINUX-thumbv7-DAG: [[OBJECTFILE]]
// LINUX-thumbv7-DAG: -lswiftCore
// LINUX-thumbv7-DAG: -L [[STDLIB_PATH:[^ ]+/lib/swift]]
// LINUX-thumbv7-DAG: -target thumbv7-unknown-linux-gnueabihf
// LINUX-thumbv7-DAG: -Xlinker -rpath -Xlinker [[STDLIB_PATH]]
// LINUX-thumbv7-DAG: -F foo
// LINUX-thumbv7-DAG: -framework bar
// LINUX-thumbv7-DAG: -L baz
// LINUX-thumbv7-DAG: -lboo
// LINUX-thumbv7-DAG: -Xlinker -undefined
// LINUX-thumbv7: -o linker
// ANDROID-armv7: swift
// ANDROID-armv7: -o [[OBJECTFILE:.*]]
// ANDROID-armv7: clang++{{"? }}
// ANDROID-armv7-DAG: [[OBJECTFILE]]
// ANDROID-armv7-DAG: -lswiftCore
// ANDROID-armv7-DAG: -L [[STDLIB_PATH:[^ ]+/lib/swift]]
// ANDROID-armv7-DAG: -target armv7-none-linux-androideabi
// ANDROID-armv7-DAG: -F foo
// ANDROID-armv7-DAG: -framework bar
// ANDROID-armv7-DAG: -L baz
// ANDROID-armv7-DAG: -lboo
// ANDROID-armv7-DAG: -Xlinker -undefined
// ANDROID-armv7: -o linker
// ANDROID-armv7-NEGATIVE-NOT: -Xlinker -rpath
// CYGWIN-x86_64: swift
// CYGWIN-x86_64: -o [[OBJECTFILE:.*]]
// CYGWIN-x86_64: clang++{{"? }}
// CYGWIN-x86_64-DAG: [[OBJECTFILE]]
// CYGWIN-x86_64-DAG: -lswiftCore
// CYGWIN-x86_64-DAG: -L [[STDLIB_PATH:[^ ]+/lib/swift]]
// CYGWIN-x86_64-DAG: -Xlinker -rpath -Xlinker [[STDLIB_PATH]]
// CYGWIN-x86_64-DAG: -F foo
// CYGWIN-x86_64-DAG: -framework bar
// CYGWIN-x86_64-DAG: -L baz
// CYGWIN-x86_64-DAG: -lboo
// CYGWIN-x86_64-DAG: -Xlinker -undefined
// CYGWIN-x86_64: -o linker
// COMPLEX: bin/ld{{"? }}
// COMPLEX-DAG: -dylib
// COMPLEX-DAG: -syslibroot {{.*}}/Inputs/clang-importer-sdk
// COMPLEX-DAG: -lfoo
// COMPLEX-DAG: -framework bar
// COMPLEX-DAG: -L baz
// COMPLEX-DAG: -F garply
// COMPLEX-DAG: -undefined dynamic_lookup
// COMPLEX-DAG: -macosx_version_min 10.9.1
// COMPLEX: -o sdk.out
// DEBUG: bin/swift
// DEBUG-NEXT: bin/swift
// DEBUG-NEXT: bin/ld{{"? }}
// DEBUG: -add_ast_path {{.*}}/{{[^/]+}}.swiftmodule
// DEBUG: -o linker
// DEBUG-NEXT: bin/dsymutil
// DEBUG: linker
// DEBUG: -o linker.dSYM
// NO_ARCLITE: bin/ld{{"? }}
// NO_ARCLITE-NOT: arclite
// NO_ARCLITE: -o {{[^ ]+}}
// COMPILE_AND_LINK: bin/swift
// COMPILE_AND_LINK-NOT: /a.o
// COMPILE_AND_LINK: linker.swift
// COMPILE_AND_LINK-NOT: /a.o
// COMPILE_AND_LINK-NEXT: bin/ld{{"? }}
// COMPILE_AND_LINK-DAG: /a.o
// COMPILE_AND_LINK-DAG: .o
// COMPILE_AND_LINK: -o linker
// FILELIST: bin/ld{{"? }}
// FILELIST-NOT: .o
// FILELIST: -filelist {{"?[^-]}}
// FILELIST-NOT: .o
// FILELIST: /a.o
// FILELIST-NOT: .o
// FILELIST: -o linker
// INFERRED_NAME: bin/swift
// INFERRED_NAME: -module-name LINKER
// INFERRED_NAME: bin/ld{{"? }}
// INFERRED_NAME: -o libLINKER.dylib
// Test ld detection. We use hard links to make sure
// the Swift driver really thinks it's been moved.
// RUN: rm -rf %t
// RUN: mkdir -p %t/DISTINCTIVE-PATH/usr/bin/
// RUN: touch %t/DISTINCTIVE-PATH/usr/bin/ld
// RUN: chmod +x %t/DISTINCTIVE-PATH/usr/bin/ld
// RUN: ln %swift_driver_plain %t/DISTINCTIVE-PATH/usr/bin/swiftc
// RUN: %t/DISTINCTIVE-PATH/usr/bin/swiftc %s -### | FileCheck -check-prefix=RELATIVE-LINKER %s
// RELATIVE-LINKER: /DISTINCTIVE-PATH/usr/bin/swift
// RELATIVE-LINKER: /DISTINCTIVE-PATH/usr/bin/ld
// RELATIVE-LINKER: -o {{[^ ]+}}
// Also test arclite detection. This uses xcrun to find arclite when it's not
// next to Swift.
// RUN: mkdir -p %t/ANOTHER-DISTINCTIVE-PATH/usr/bin
// RUN: mkdir -p %t/ANOTHER-DISTINCTIVE-PATH/usr/lib/arc
// RUN: cp %S/Inputs/xcrun-return-self.sh %t/ANOTHER-DISTINCTIVE-PATH/usr/bin/xcrun
// RUN: env PATH=%t/ANOTHER-DISTINCTIVE-PATH/usr/bin %t/DISTINCTIVE-PATH/usr/bin/swiftc -target x86_64-apple-macosx10.9 %s -### | FileCheck -check-prefix=XCRUN_ARCLITE %s
// XCRUN_ARCLITE: bin/ld{{"? }}
// XCRUN_ARCLITE: /ANOTHER-DISTINCTIVE-PATH/usr/lib/arc/libarclite_macosx.a
// XCRUN_ARCLITE: -o {{[^ ]+}}
// RUN: mkdir -p %t/DISTINCTIVE-PATH/usr/lib/arc
// RUN: env PATH=%t/ANOTHER-DISTINCTIVE-PATH/usr/bin %t/DISTINCTIVE-PATH/usr/bin/swiftc -target x86_64-apple-macosx10.9 %s -### | FileCheck -check-prefix=RELATIVE_ARCLITE %s
// RELATIVE_ARCLITE: bin/ld{{"? }}
// RELATIVE_ARCLITE: /DISTINCTIVE-PATH/usr/lib/arc/libarclite_macosx.a
// RELATIVE_ARCLITE: -o {{[^ ]+}}
// Clean up the test executable because hard links are expensive.
// RUN: rm -rf %t/DISTINCTIVE-PATH/usr/bin/swiftc
| apache-2.0 |
nethergrim/xpolo | XPolo/Pods/BFKit-Swift/Sources/BFKit/Apple/UIKit/UIViewControllerExtension.swift | 1 | 3204 | //
// UIViewControllerExtension.swift
// BFKit
//
// The MIT License (MIT)
//
// Copyright (c) 2015 - 2017 Fabrizio Brancati. 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 Foundation
import UIKit
// MARK: - UIViewController extension
/// This extesion adds some useful functions to UIViewController.
extension UIViewController {
/// Use this in viewWillAppear(_:)
///
/// - Parameter tableView: UITableView to be delected.
func smoothlyDeselectRows(tableView: UITableView) {
let selectedIndexPaths = tableView.indexPathsForSelectedRows ?? []
if let coordinator = transitionCoordinator {
coordinator.animateAlongsideTransition(in: parent?.view, animation: { coordinatorContext in
selectedIndexPaths.forEach {
tableView.deselectRow(at: $0, animated: coordinatorContext.isAnimated)
}
}, completion: { coordinatorContext in
if coordinatorContext.isCancelled {
selectedIndexPaths.forEach {
tableView.selectRow(at: $0, animated: false, scrollPosition: .none)
}
}
})
} else {
selectedIndexPaths.forEach {
tableView.deselectRow(at: $0, animated: false)
}
}
}
/// Presents a UIAlertController with a title, message and a set of actions.
///
/// - parameter title: The title of the UIAlerController.
/// - parameter message: An optional String for the UIAlertController's message.
/// - parameter actions: An array of actions that will be added to the UIAlertController.
/// - parameter alertType: The style of the UIAlertController.
public func present(title: String, message: String, actions: [UIAlertAction], alertType: UIAlertControllerStyle = .alert) {
let errorAlert = UIAlertController(title: title, message: message, preferredStyle: alertType)
for action in actions {
errorAlert.addAction(action)
}
self.present(errorAlert, animated: true, completion: nil)
}
}
| gpl-3.0 |
ustwo/formvalidator-swift | Example/macOS/FormAccessibility.swift | 1 | 717 | //
// FormAccessibility.swift
// FormValidatorSwift
//
// Created by Aaron McTavish on 06/01/2017.
// Copyright © 2017 ustwo Fampany Ltd. All rights reserved.
//
import Foundation
enum FormAccessibility {
enum Identifiers {
static let EmailLabel = "EMAIL_LABEL"
static let EmailTextField = "EMAIL_TEXTFIELD"
static let ErrorLabel = "ERROR_LABEL"
static let NameLabel = "NAME_LABEL"
static let NameTextField = "NAME_TEXTFIELD"
static let TitleLabel = "TITLE_LABEL"
static let TitleTextField = "TITLE_TEXTFIELD"
static let SubmitButton = "SUBMIT_BUTTON"
}
}
| mit |
rolson/arcgis-runtime-samples-ios | arcgis-ios-sdk-samples/Layers/RGB renderer/RGBRendererTypeCell.swift | 1 | 1377 | //
// Copyright 2016 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 RGBRendererTypeCellDelegate: class {
func rgbRendererTypeCell(rgbRendererTypeCell: RGBRendererTypeCell, didUpdateType type: StretchType)
}
class RGBRendererTypeCell: UITableViewCell, HorizontalPickerDelegate {
@IBOutlet var horizontalPicker: HorizontalPicker!
weak var delegate: RGBRendererTypeCellDelegate?
override func awakeFromNib() {
super.awakeFromNib()
self.horizontalPicker.options = StretchType.allValues
self.horizontalPicker.delegate = self
}
//MARK: - HorizontalPickerDelegate
func horizontalPicker(horizontalPicker: HorizontalPicker, didUpdateSelectedIndex index: Int) {
self.delegate?.rgbRendererTypeCell(self, didUpdateType: StretchType(id: index)!)
}
}
| apache-2.0 |
richardpiazza/SOSwift | Tests/SOSwiftTests/AccessibilityControlTests.swift | 1 | 977 | import XCTest
@testable import SOSwift
class AccessibilityControlTests: XCTestCase {
static var allTests = [
("testCaseIterable", testCaseIterable),
("testDisplayValue", testDisplayValue),
]
func testCaseIterable() throws {
XCTAssertEqual(AccessibilityControl.allCases.count, 6)
}
func testDisplayValue() throws {
XCTAssertEqual(AccessibilityControl.fullKeyboardControl.displayValue, "Full Keyboard Control")
XCTAssertEqual(AccessibilityControl.fullMouseControl.displayValue, "Full Mouse Control")
XCTAssertEqual(AccessibilityControl.fullSwitchControl.displayValue, "Full Switch Control")
XCTAssertEqual(AccessibilityControl.fullTouchControl.displayValue, "Full Touch Control")
XCTAssertEqual(AccessibilityControl.fullVideoControl.displayValue, "Full Video Control")
XCTAssertEqual(AccessibilityControl.fullVoiceControl.displayValue, "Full Voice Control")
}
}
| mit |
jeffsuke/GlanceWordRainbowImage | GlanceWordRainbowImageExample/ViewController.swift | 1 | 523 | //
// ViewController.swift
// GlanceWordRainbowImageExample
//
// Created by Yusuke Kawanabe on 5/27/15.
// Copyright (c) 2015 JSK. 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 |
tidepool-org/nutshell-ios | Nutshell/ViewControllers/EventAddOrEditViewController.swift | 1 | 48054 | /*
* Copyright (c) 2015, Tidepool Project
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the associated License, which is identical to the BSD 2-Clause
* License as published by the Open Source Initiative at opensource.org.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the License for more details.
*
* You should have received a copy of the License along with this program; if
* not, you can obtain one from Tidepool Project at tidepool.org.
*/
import UIKit
import CoreData
import Photos
import MobileCoreServices
class EventAddOrEditViewController: BaseUIViewController, UINavigationControllerDelegate, UIImagePickerControllerDelegate {
var eventItem: NutEventItem?
var eventGroup: NutEvent?
var newEventItem: EventItem?
fileprivate var editExistingEvent = false
fileprivate var isWorkout: Bool = false
@IBOutlet weak var titleTextField: NutshellUITextField!
@IBOutlet weak var titleHintLabel: NutshellUILabel!
@IBOutlet weak var notesTextField: NutshellUITextField!
@IBOutlet weak var notesHintLabel: NutshellUILabel!
@IBOutlet weak var placeIconButton: UIButton!
@IBOutlet weak var photoIconButton: UIButton!
@IBOutlet weak var calendarIconButton: UIButton!
@IBOutlet weak var placeControlContainer: UIView!
@IBOutlet weak var calendarControlContainer: UIView!
@IBOutlet weak var photoControlContainer: UIView!
@IBOutlet weak var workoutCalorieContainer: UIView!
@IBOutlet weak var caloriesLabel: NutshellUILabel!
@IBOutlet weak var workoutDurationContainer: UIView!
@IBOutlet weak var durationLabel: NutshellUILabel!
@IBOutlet weak var headerForModalView: NutshellUIView!
@IBOutlet weak var sceneContainer: UIView!
@IBOutlet weak var saveButton: UIButton!
@IBOutlet weak var addSuccessView: NutshellUIView!
@IBOutlet weak var addSuccessImageView: UIImageView!
@IBOutlet weak var datePickerView: UIView!
@IBOutlet weak var datePicker: UIDatePicker!
@IBOutlet weak var locationTextField: UITextField!
@IBOutlet weak var date1Label: NutshellUILabel!
@IBOutlet weak var date2Label: NutshellUILabel!
@IBOutlet weak var picture0Image: UIImageView!
@IBOutlet weak var picture1Image: UIImageView!
@IBOutlet weak var picture2Image: UIImageView!
fileprivate var eventTime = Date()
// Note: time zone offset is only used for display; new items are always created with the offset for the current calendar time zone, and time zones are not editable!
fileprivate var eventTimeOffsetSecs: Int = 0
fileprivate var pictureImageURLs: [String] = []
@IBOutlet weak var bottomSectionContainer: UIView!
//
// MARK: - Base methods
//
override func viewDidLoad() {
super.viewDidLoad()
var saveButtonTitle = NSLocalizedString("saveButtonTitle", comment:"Save")
if let eventItem = eventItem {
editExistingEvent = true
eventTime = eventItem.time as Date
eventTimeOffsetSecs = eventItem.tzOffsetSecs
// hide location and photo controls for workouts
if let workout = eventItem as? NutWorkout {
isWorkout = true
placeControlContainer.isHidden = true
photoControlContainer.isHidden = true
if workout.duration > 0 {
workoutDurationContainer.isHidden = false
let dateComponentsFormatter = DateComponentsFormatter()
dateComponentsFormatter.unitsStyle = DateComponentsFormatter.UnitsStyle.abbreviated
durationLabel.text = dateComponentsFormatter.string(from: workout.duration)
}
if let calories = workout.calories {
if Int(calories) > 0 {
workoutCalorieContainer.isHidden = false
caloriesLabel.text = String(Int(calories)) + " Calories"
}
}
}
// hide modal header when used as a nav view
for c in headerForModalView.constraints {
if c.firstAttribute == NSLayoutAttribute.height {
c.constant = 0.0
break
}
}
} else {
eventTimeOffsetSecs = NSCalendar.current.timeZone.secondsFromGMT()
locationTextField.text = Styles.placeholderLocationString
saveButtonTitle = NSLocalizedString("saveAndEatButtonTitle", comment:"Save and eat!")
}
saveButton.setTitle(saveButtonTitle, for: UIControlState())
configureInfoSection()
titleHintLabel.text = Styles.titleHintString
notesHintLabel.text = Styles.noteHintString
let notificationCenter = NotificationCenter.default
notificationCenter.addObserver(self, selector: #selector(EventAddOrEditViewController.textFieldDidChange), name: NSNotification.Name.UITextFieldTextDidChange, object: nil)
notificationCenter.addObserver(self, selector: #selector(EventAddOrEditViewController.keyboardWillShow(_:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
notificationCenter.addObserver(self, selector: #selector(EventAddOrEditViewController.keyboardWillHide(_:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}
deinit {
let nc = NotificationCenter.default
nc.removeObserver(self, name: nil, object: nil)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
APIConnector.connector().trackMetric("Viewed Edit Screen (Edit Screen)")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//
// MARK: - Navigation
//
@IBAction func done(_ segue: UIStoryboardSegue) {
print("unwind segue to eventAddOrEdit done")
// Deal with possible delete/edit of photo from viewer...
if segue.identifier == EventViewStoryboard.SegueIdentifiers.UnwindSegueFromShowPhoto {
if let photoVC = segue.source as? ShowPhotoViewController {
// handle the case of a new photo replacing a new (not yet saved) photo: the older one should be immediately deleted since will be no reference to it left!
for url in pictureImageURLs {
if !preExistingPhoto(url) {
if !photoVC.photoURLs.contains(url) {
NutUtils.deleteLocalPhoto(url)
}
}
}
// new pending list of photos...
pictureImageURLs = photoVC.photoURLs
configurePhotos()
updateSaveButtonState()
}
}
}
//
// MARK: - Configuration
//
fileprivate func configureInfoSection() {
var titleText = Styles.placeholderTitleString
var notesText = Styles.placeholderNotesString
if let eventItem = eventItem {
if eventItem.title.characters.count > 0 {
titleText = eventItem.title
}
if eventItem.notes.characters.count > 0 {
notesText = eventItem.notes
}
picture0Image.isHidden = true
picture1Image.isHidden = true
picture2Image.isHidden = true
if let mealItem = eventItem as? NutMeal {
if !mealItem.location.isEmpty {
locationTextField.text = mealItem.location
} else {
locationTextField.text = Styles.placeholderLocationString
}
pictureImageURLs = mealItem.photoUrlArray()
} else {
// Add workout-specific items...
}
} else if let eventGroup = eventGroup {
titleText = eventGroup.title
locationTextField.text = eventGroup.location
}
titleTextField.text = titleText
notesTextField.text = notesText
configureTitleHint()
configureNotesHint()
configureDateView()
configurePhotos()
updateSaveButtonState()
}
fileprivate func configureTitleHint() {
let isBeingEdited = titleTextField.isFirstResponder
if isBeingEdited {
titleHintLabel.isHidden = false
} else {
let titleIsSet = titleTextField.text != "" && titleTextField.text != Styles.placeholderTitleString
titleHintLabel.isHidden = titleIsSet
}
}
fileprivate func configureNotesHint() {
let isBeingEdited = notesTextField.isFirstResponder
if isBeingEdited {
notesHintLabel.isHidden = false
} else {
let notesIsSet = notesTextField.text != "" && notesTextField.text != Styles.placeholderNotesString
notesHintLabel.isHidden = notesIsSet
}
}
fileprivate func configurePhotos() {
for item in 0...2 {
let picture = itemToPicture(item)
let url = itemToImageUrl(item)
if url.isEmpty {
picture.isHidden = true
} else {
picture.isHidden = false
NutUtils.loadImage(url, imageView: picture)
}
}
}
fileprivate func updateSaveButtonState() {
if !datePickerView.isHidden {
saveButton.isHidden = true
return
}
if editExistingEvent {
saveButton.isHidden = !existingEventChanged()
} else {
if !newEventChanged() || titleTextField.text?.characters.count == 0 || titleTextField.text == Styles.placeholderTitleString {
saveButton.isHidden = true
} else {
saveButton.isHidden = false
}
}
}
// When the keyboard is up, the save button moves up
fileprivate var viewAdjustAnimationTime: Float = 0.25
fileprivate func configureSaveViewPosition(_ bottomOffset: CGFloat) {
for c in sceneContainer.constraints {
if c.firstAttribute == NSLayoutAttribute.bottom {
if let secondItem = c.secondItem {
if secondItem as! NSObject == saveButton {
c.constant = bottomOffset
break
}
}
}
}
UIView.animate(withDuration: TimeInterval(viewAdjustAnimationTime), animations: {
self.saveButton.layoutIfNeeded()
})
}
fileprivate func hideDateIfOpen() {
if !datePickerView.isHidden {
cancelDatePickButtonHandler(self)
}
}
// Bold all but last suffixCnt characters of string (Note: assumes date format!
fileprivate func boldFirstPartOfDateString(_ dateStr: String, suffixCnt: Int) -> NSAttributedString {
let attrStr = NSMutableAttributedString(string: dateStr, attributes: [NSFontAttributeName: Styles.smallBoldFont, NSForegroundColorAttributeName: Styles.whiteColor])
attrStr.addAttribute(NSFontAttributeName, value: Styles.smallRegularFont, range: NSRange(location: attrStr.length - suffixCnt, length: suffixCnt))
return attrStr
}
fileprivate func updateDateLabels() {
let df = DateFormatter()
// Note: Time zones created with this method never have daylight savings, and the offset is constant no matter the date
df.timeZone = TimeZone(secondsFromGMT:eventTimeOffsetSecs)
df.dateFormat = "MMM d, yyyy"
date1Label.attributedText = boldFirstPartOfDateString(df.string(from: eventTime), suffixCnt: 6)
df.dateFormat = "h:mm a"
date2Label.attributedText = boldFirstPartOfDateString(df.string(from: eventTime), suffixCnt: 2)
}
fileprivate func configureDateView() {
updateDateLabels()
datePicker.date = eventTime
// Note: Time zones created with this method never have daylight savings, and the offset is constant no matter the date
datePicker.timeZone = TimeZone(secondsFromGMT: eventTimeOffsetSecs)
datePickerView.isHidden = true
}
// UIKeyboardWillShowNotification
func keyboardWillShow(_ notification: Notification) {
// adjust save button up when keyboard is up
let keyboardFrame = (notification.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
viewAdjustAnimationTime = notification.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! Float
self.configureSaveViewPosition(keyboardFrame.height)
}
// UIKeyboardWillHideNotification
func keyboardWillHide(_ notification: Notification) {
// reposition save button view if needed
self.configureSaveViewPosition(0.0)
}
//
// MARK: - Button and text field handlers
//
@IBAction func dismissKeyboard(_ sender: AnyObject) {
titleTextField.resignFirstResponder()
notesTextField.resignFirstResponder()
locationTextField.resignFirstResponder()
hideDateIfOpen()
}
@IBAction func titleTextLargeHitAreaButton(_ sender: AnyObject) {
titleTextField.becomeFirstResponder()
}
func textFieldDidChange() {
updateSaveButtonState()
}
@IBAction func titleEditingDidBegin(_ sender: AnyObject) {
hideDateIfOpen()
configureTitleHint()
if titleTextField.text == Styles.placeholderTitleString {
titleTextField.text = ""
}
if editExistingEvent {
APIConnector.connector().trackMetric("Edited Meal Name (Edit Screen)")
} else {
APIConnector.connector().trackMetric("Clicked to Add Meal Name (Add Meal Screen)")
}
}
@IBAction func titleEditingDidEnd(_ sender: AnyObject) {
updateSaveButtonState()
configureTitleHint()
if titleTextField.text == "" {
titleTextField.text = Styles.placeholderTitleString
}
}
@IBAction func notesTextLargeHitAreaButton(_ sender: AnyObject) {
notesTextField.becomeFirstResponder()
}
@IBAction func notesEditingDidBegin(_ sender: AnyObject) {
hideDateIfOpen()
configureNotesHint()
if notesTextField.text == Styles.placeholderNotesString {
notesTextField.text = ""
}
if editExistingEvent {
APIConnector.connector().trackMetric("Edited Notes (Edit Screen)")
} else {
APIConnector.connector().trackMetric("Clicked to Add Notes (Add Meal Screen)")
}
}
@IBAction func notesEditingDidEnd(_ sender: AnyObject) {
updateSaveButtonState()
configureNotesHint()
if notesTextField.text == "" {
notesTextField.text = Styles.placeholderNotesString
}
}
@IBAction func locationButtonHandler(_ sender: AnyObject) {
locationTextField.becomeFirstResponder()
}
@IBAction func locationEditingDidBegin(_ sender: AnyObject) {
hideDateIfOpen()
if locationTextField.text == Styles.placeholderLocationString {
locationTextField.text = ""
}
if editExistingEvent {
APIConnector.connector().trackMetric("Edited Location (Edit Screen)")
} else {
APIConnector.connector().trackMetric("Clicked to Add Location (Add Meal Screen)")
}
}
@IBAction func locationEditingDidEnd(_ sender: AnyObject) {
updateSaveButtonState()
locationTextField.resignFirstResponder()
if locationTextField.text == "" {
locationTextField.text = Styles.placeholderLocationString
}
}
@IBAction func saveButtonHandler(_ sender: AnyObject) {
if editExistingEvent {
updateCurrentEvent()
self.performSegue(withIdentifier: "unwindSegueToDone", sender: self)
return
} else {
updateNewEvent()
}
}
@IBAction func backButtonHandler(_ sender: AnyObject) {
// this is a cancel for the role of addEvent and editEvent
// for viewEvent, we need to check whether the title has changed
if editExistingEvent {
// cancel of edit
APIConnector.connector().trackMetric("Clicked Cancel (Edit Screen)")
if existingEventChanged() {
var alertString = NSLocalizedString("discardMealEditsAlertMessage", comment:"If you press discard, your changes to this meal will be lost.")
if let _ = eventItem as? NutWorkout {
alertString = NSLocalizedString("discardWorkoutEditsAlertMessage", comment:"If you press discard, your changes to this workout will be lost.")
}
alertOnCancelAndReturn(NSLocalizedString("discardEditsAlertTitle", comment:"Discard changes?"), alertMessage: alertString, okayButtonString: NSLocalizedString("discardAlertOkay", comment:"Discard"))
} else {
self.performSegue(withIdentifier: "unwindSegueToCancel", sender: self)
}
} else {
// cancel of add
APIConnector.connector().trackMetric("Clicked ‘X’ to Close (Add Screen)")
if newEventChanged() {
var alertTitle = NSLocalizedString("deleteMealAlertTitle", comment:"Are you sure?")
var alertMessage = NSLocalizedString("deleteMealAlertMessage", comment:"If you delete this meal, it will be gone forever.")
if let _ = eventItem as? NutWorkout {
alertTitle = NSLocalizedString("deleteWorkoutAlertTitle", comment:"Discard workout?")
alertMessage = NSLocalizedString("deleteWorkoutAlertMessage", comment:"If you close this workout, your workout will be lost.")
}
alertOnCancelAndReturn(alertTitle, alertMessage: alertMessage, okayButtonString: NSLocalizedString("deleteAlertOkay", comment:"Delete"))
} else {
self.performSegue(withIdentifier: "unwindSegueToCancel", sender: self)
}
}
}
@IBAction func deleteButtonHandler(_ sender: AnyObject) {
// this is a delete for the role of editEvent
APIConnector.connector().trackMetric("Clicked Trashcan to Discard (Edit Screen)")
alertOnDeleteAndReturn()
}
fileprivate func pictureUrlEmptySlots() -> Int {
return 3 - pictureImageURLs.count
}
fileprivate func itemToImageUrl(_ itemNum: Int) -> String {
if itemNum >= pictureImageURLs.count {
return ""
} else {
return pictureImageURLs[itemNum]
}
}
fileprivate func itemToPicture(_ itemNum: Int) -> UIImageView {
switch itemNum {
case 0:
return picture0Image
case 1:
return picture1Image
case 2:
return picture2Image
default:
NSLog("Error: asking for out of range picture image!")
return picture0Image
}
}
fileprivate func appendPictureUrl(_ url: String) {
if pictureImageURLs.count < 3 {
pictureImageURLs.append(url)
if !editExistingEvent {
switch pictureImageURLs.count {
case 1: APIConnector.connector().trackMetric("First Photo Added (Add Meal Screen)")
case 2: APIConnector.connector().trackMetric("Second Photo Added (Add Meal Screen)")
case 3: APIConnector.connector().trackMetric("Third Photo Added (Add Meal Screen)")
default: break
}
}
}
}
fileprivate func showPicture(_ itemNum: Int) -> Bool {
let pictureUrl = itemToImageUrl(itemNum)
if !pictureUrl.isEmpty {
if editExistingEvent {
APIConnector.connector().trackMetric("Clicked Photos (Edit Screen)")
}
let storyboard = UIStoryboard(name: "EventView", bundle: nil)
let photoVC = storyboard.instantiateViewController(withIdentifier: "ShowPhotoViewController") as! ShowPhotoViewController
photoVC.photoURLs = pictureImageURLs
photoVC.mealTitle = titleTextField.text
photoVC.imageIndex = itemNum
photoVC.editAllowed = true
if editExistingEvent {
self.navigationController?.pushViewController(photoVC, animated: true)
} else {
photoVC.modalPresentation = true
self.present(photoVC, animated: true, completion: nil)
}
return true
} else {
return false
}
}
@IBAction func picture0ButtonHandler(_ sender: AnyObject) {
if !showPicture(0) {
photoButtonHandler(sender)
}
}
@IBAction func picture1ButtonHandler(_ sender: AnyObject) {
if !showPicture(1) {
photoButtonHandler(sender)
}
}
@IBAction func picture2ButtonHandler(_ sender: AnyObject) {
if !showPicture(2) {
photoButtonHandler(sender)
}
}
@IBAction func photoButtonHandler(_ sender: AnyObject) {
if pictureUrlEmptySlots() == 0 {
simpleInfoAlert(NSLocalizedString("photoSlotsFullTitle", comment:"No empty photo slot"), alertMessage: NSLocalizedString("photoSlotsFullMessage", comment:"Three photos are supported. Please discard one before adding a new photo."))
} else {
if !editExistingEvent {
switch pictureImageURLs.count {
case 0: APIConnector.connector().trackMetric("Clicked to Add First Photo (Add Meal Screen)")
case 1: APIConnector.connector().trackMetric("Clicked to Add Second Photo (Add Meal Screen)")
case 2: APIConnector.connector().trackMetric("Clicked to Add Third Photo (Add Meal Screen)")
default: break
}
}
showPhotoActionSheet()
}
}
func showPhotoActionSheet() {
let photoActionSheet = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
photoActionSheet.modalPresentationStyle = .popover
photoActionSheet.addAction(UIAlertAction(title: NSLocalizedString("discardAlertCancel", comment:"Cancel"), style: .cancel, handler: { Void in
return
}))
photoActionSheet.addAction(UIAlertAction(title: "Photo Library", style: .default, handler: { Void in
let pickerC = UIImagePickerController()
pickerC.delegate = self
self.present(pickerC, animated: true, completion: nil)
}))
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.camera) {
photoActionSheet.addAction(UIAlertAction(title: "Take Photo", style: .default, handler: { Void in
let pickerC = UIImagePickerController()
pickerC.delegate = self
pickerC.sourceType = UIImagePickerControllerSourceType.camera
pickerC.mediaTypes = [kUTTypeImage as String]
self.present(pickerC, animated: true, completion: nil)
}))
}
if let popoverController = photoActionSheet.popoverPresentationController {
popoverController.sourceView = self.photoIconButton
popoverController.sourceRect = self.photoIconButton.bounds
}
self.present(photoActionSheet, animated: true, completion: nil)
}
//
// MARK: - UIImagePickerControllerDelegate
//
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
self.dismiss(animated: true, completion: nil)
print(info)
if let photoImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
//let compressedImage = NutUtils.compressImage(photoImage)
let photoUrl = NutUtils.urlForNewPhoto()
if let filePath = NutUtils.filePathForPhoto(photoUrl) {
// NOTE: we save photo with high compression, typically 0.2 to 0.4 MB
if let photoData = UIImageJPEGRepresentation(photoImage, 0.1) {
let savedOk = (try? photoData.write(to: URL(fileURLWithPath: filePath), options: [.atomic])) != nil
if !savedOk {
NSLog("Failed to save photo successfully!")
}
appendPictureUrl(photoUrl)
updateSaveButtonState()
configurePhotos()
}
}
}
}
//
// MARK: - Event updating
//
fileprivate func newEventChanged() -> Bool {
if let _ = eventGroup {
// for "eat again" new events, we already have a title and location from the NutEvent, so consider this "changed"
return true
}
if titleTextField.text != Styles.placeholderTitleString {
return true
}
if locationTextField.text != Styles.placeholderLocationString {
return true
}
if notesTextField.text != Styles.placeholderNotesString {
return true
}
if !pictureImageURLs.isEmpty {
return true
}
return false
}
fileprivate func existingEventChanged() -> Bool {
if let eventItem = eventItem {
if eventItem.title != titleTextField.text {
NSLog("title changed, enabling save")
return true
}
if eventItem.notes != notesTextField.text && notesTextField.text != Styles.placeholderNotesString {
NSLog("notes changed, enabling save")
return true
}
if eventItem.time as Date != eventTime {
NSLog("event time changed, enabling save")
return true
}
if let meal = eventItem as? NutMeal {
if meal.location != locationTextField.text && locationTextField.text != Styles.placeholderLocationString {
NSLog("location changed, enabling save")
return true
}
if meal.photo != itemToImageUrl(0) {
NSLog("photo1 changed, enabling save")
return true
}
if meal.photo2 != itemToImageUrl(1) {
NSLog("photo2 changed, enabling save")
return true
}
if meal.photo3 != itemToImageUrl(2) {
NSLog("photo3 changed, enabling save")
return true
}
}
}
return false
}
fileprivate func filteredLocationText() -> String {
var location = ""
if let locationText = locationTextField.text {
if locationText != Styles.placeholderLocationString {
location = locationText
}
}
return location
}
fileprivate func filteredNotesText() -> String {
var notes = ""
if let notesText = notesTextField.text {
if notesText != Styles.placeholderNotesString {
notes = notesText
}
}
return notes
}
fileprivate func updateCurrentEvent() {
if let mealItem = eventItem as? NutMeal {
let location = filteredLocationText()
let notes = filteredNotesText()
mealItem.title = titleTextField.text!
mealItem.time = eventTime
mealItem.notes = notes
mealItem.location = location
// first delete any photos going away...
for url in mealItem.photoUrlArray() {
if !pictureImageURLs.contains(url) {
NutUtils.deleteLocalPhoto(url)
}
}
// now update the event...
mealItem.photo = itemToImageUrl(0)
mealItem.photo2 = itemToImageUrl(1)
mealItem.photo3 = itemToImageUrl(2)
// Save the database
if mealItem.saveChanges() {
// note event changed as "new" event
newEventItem = mealItem.eventItem
updateItemAndGroupForNewEventItem()
} else {
newEventItem = nil
}
} else if let workoutItem = eventItem as? NutWorkout {
let location = filteredLocationText()
let notes = filteredNotesText()
workoutItem.title = titleTextField.text!
workoutItem.time = eventTime
workoutItem.notes = notes
workoutItem.location = location
// Save the database
if workoutItem.saveChanges() {
// note event changed as "new" event
newEventItem = workoutItem.eventItem
updateItemAndGroupForNewEventItem()
} else {
newEventItem = nil
}
}
}
var crashValue: String?
func testCrash() {
// force crash to test crash reporting...
if crashValue! == "crash" {
self.performSegue(withIdentifier: "unwindSegueToHome", sender: self)
return
}
}
fileprivate func updateNewEvent() {
if titleTextField.text!.localizedCaseInsensitiveCompare("test mode") == ComparisonResult.orderedSame {
AppDelegate.testMode = !AppDelegate.testMode
self.performSegue(withIdentifier: "unwindSegueToHome", sender: self)
return
}
// This is a good place to splice in demo and test data. For now, entering "demo" as the title will result in us adding a set of demo events to the model, and "delete" will delete all food events.
if titleTextField.text!.localizedCaseInsensitiveCompare("demo") == ComparisonResult.orderedSame {
DatabaseUtils.deleteAllNutEvents()
addDemoData()
self.performSegue(withIdentifier: "unwindSegueToHome", sender: self)
return
} else if titleTextField.text!.localizedCaseInsensitiveCompare("no demo") == ComparisonResult.orderedSame {
DatabaseUtils.deleteAllNutEvents()
self.performSegue(withIdentifier: "unwindSegueToHome", sender: self)
return
} else if titleTextField.text!.localizedCaseInsensitiveCompare("kill token") == ComparisonResult.orderedSame {
APIConnector.connector().sessionToken = "xxxx"
self.performSegue(withIdentifier: "unwindSegueToHome", sender: self)
return
}
if titleTextField.text!.localizedCaseInsensitiveCompare("test crash") == ComparisonResult.orderedSame {
self.testCrash()
}
// Note: we only create meal events in this app - workout events come from other apps via HealthKit...
newEventItem = NutEvent.createMealEvent(titleTextField.text!, notes: filteredNotesText(), location: filteredLocationText(), photo: itemToImageUrl(0), photo2: itemToImageUrl(1), photo3: itemToImageUrl(2), time: eventTime, timeZoneOffset: eventTimeOffsetSecs)
if newEventItem != nil {
if eventGroup == nil {
APIConnector.connector().trackMetric("New Meal Added (Add Meal Screen)")
} else {
APIConnector.connector().trackMetric("New Instance of Existing Meal (Add Meal Screen)")
}
updateItemAndGroupForNewEventItem()
showSuccessView()
} else {
// TODO: handle internal error...
NSLog("Error: Failed to save new event!")
}
}
fileprivate func updateItemAndGroupForNewEventItem() {
// Update eventGroup and eventItem based on new event created, for return values to calling VC
if let eventGroup = eventGroup, let newEventItem = newEventItem {
if newEventItem.nutEventIdString() == eventGroup.nutEventIdString() {
if let currentItem = eventItem {
// if we're editing an existing item...
if currentItem.nutEventIdString() == eventGroup.nutEventIdString() {
// if title/location haven't changed, we're done...
return
}
}
self.eventItem = eventGroup.addEvent(newEventItem)
} else {
// eventGroup is no longer valid, create a new one!
self.eventGroup = NutEvent(firstEvent: newEventItem)
self.eventItem = self.eventGroup?.itemArray[0]
}
}
}
fileprivate func preExistingPhoto(_ url: String) -> Bool {
var preExisting = false
// if we are editing a current event, don't delete the photo if it already exists in the event
if let eventItem = eventItem {
preExisting = eventItem.photoUrlArray().contains(url)
}
return preExisting
}
/// Delete new photos we may have created so we don't leave them orphaned in the local file system.
fileprivate func deleteNewPhotos() {
for url in pictureImageURLs {
if !preExistingPhoto(url) {
NutUtils.deleteLocalPhoto(url)
}
}
pictureImageURLs = []
}
fileprivate func deleteItemAndReturn() {
// first delete any new photos user may have added
deleteNewPhotos()
if let eventItem = eventItem, let eventGroup = eventGroup {
if eventItem.deleteItem() {
// now remove it from the group
eventGroup.itemArray = eventGroup.itemArray.filter() {
$0 != eventItem
}
// mark it as deleted so controller we return to can handle correctly...
self.eventItem = nil
if eventGroup.itemArray.isEmpty {
self.eventGroup = nil
// segue back to home as there are no events remaining...
self.performSegue(withIdentifier: "unwindSegueToHome", sender: self)
} else {
// segue back to home or group list viewer depending...
self.performSegue(withIdentifier: "unwindSegueToDoneItemDeleted", sender: self)
}
} else {
// TODO: handle delete error?
NSLog("Error: Failed to delete item!")
// segue back to home as this event probably was deleted out from under us...
self.performSegue(withIdentifier: "unwindSegueToHome", sender: self)
}
}
}
//
// MARK: - Alerts
//
fileprivate func simpleInfoAlert(_ alertTitle: String, alertMessage: String) {
// use dialog to confirm cancel with user!
let alert = UIAlertController(title: alertTitle, message: alertMessage, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: NSLocalizedString("notifyAlertOkay", comment:"OK"), style: .cancel, handler: { Void in
return
}))
self.present(alert, animated: true, completion: nil)
}
fileprivate func alertOnCancelAndReturn(_ alertTitle: String, alertMessage: String, okayButtonString: String) {
// use dialog to confirm cancel with user!
let alert = UIAlertController(title: alertTitle, message: alertMessage, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: NSLocalizedString("discardAlertCancel", comment:"Cancel"), style: .cancel, handler: { Void in
if self.editExistingEvent {
APIConnector.connector().trackMetric("Clicked Cancel Cancel to Stay on Edit (Edit Screen)")
}
return
}))
alert.addAction(UIAlertAction(title: okayButtonString, style: .default, handler: { Void in
if self.editExistingEvent {
APIConnector.connector().trackMetric("Clicked Discard Changes to Cancel (Edit Screen)")
}
self.deleteNewPhotos()
self.performSegue(withIdentifier: "unwindSegueToCancel", sender: self)
self.dismiss(animated: true, completion: nil)
}))
self.present(alert, animated: true, completion: nil)
}
fileprivate func alertOnDeleteAndReturn() {
if let nutItem = eventItem {
// use dialog to confirm delete with user!
var titleString = NSLocalizedString("deleteMealAlertTitle", comment:"Are you sure?")
var messageString = NSLocalizedString("deleteMealAlertMessage", comment:"If you delete this meal, it will be gone forever..")
if let _ = nutItem as? NutWorkout {
titleString = NSLocalizedString("deleteWorkoutAlertTitle", comment:"Are you sure?")
messageString = NSLocalizedString("deleteWorkoutAlertMessage", comment:"If you delete this workout, it will be gone forever.")
}
let alert = UIAlertController(title: titleString, message: messageString, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: NSLocalizedString("deleteAlertCancel", comment:"Cancel"), style: .cancel, handler: { Void in
APIConnector.connector().trackMetric("Clicked Cancel Discard (Edit Screen)")
return
}))
alert.addAction(UIAlertAction(title: NSLocalizedString("deleteAlertOkay", comment:"Delete"), style: .default, handler: { Void in
APIConnector.connector().trackMetric("Clicked Confirmed Delete (Edit Screen)")
self.deleteItemAndReturn()
}))
self.present(alert, animated: true, completion: nil)
}
}
//
// MARK: - Misc private funcs
//
fileprivate func showSuccessView() {
dismissKeyboard(self)
let animations: [UIImage]? = [UIImage(named: "addAnimation-01")!,
UIImage(named: "addAnimation-02")!,
UIImage(named: "addAnimation-03")!,
UIImage(named: "addAnimation-04")!,
UIImage(named: "addAnimation-05")!,
UIImage(named: "addAnimation-06")!]
addSuccessImageView.animationImages = animations
addSuccessImageView.animationDuration = 1.0
addSuccessImageView.animationRepeatCount = 1
addSuccessImageView.startAnimating()
addSuccessView.isHidden = false
NutUtils.delay(1.25) {
if let newEventItem = self.newEventItem, let eventGroup = self.eventGroup {
if newEventItem.nutEventIdString() != eventGroup.nutEventIdString() {
self.performSegue(withIdentifier: "unwindSegueToHome", sender: self)
return
}
}
self.performSegue(withIdentifier: "unwindSegueToDone", sender: self)
}
}
//
// MARK: - Date picking
//
fileprivate var savedTime: Date?
@IBAction func dateButtonHandler(_ sender: AnyObject) {
// user tapped on date, bring up date picker
if datePickerView.isHidden {
dismissKeyboard(self)
datePickerView.isHidden = false
savedTime = eventTime
updateSaveButtonState()
if editExistingEvent {
APIConnector.connector().trackMetric("Edited Datetime (Edit Screen)")
} else {
APIConnector.connector().trackMetric("Clicked to Update Datetime (Add Meal Screen)")
}
} else {
cancelDatePickButtonHandler(self)
}
}
@IBAction func cancelDatePickButtonHandler(_ sender: AnyObject) {
if let savedTime = savedTime {
eventTime = savedTime
}
configureDateView()
}
@IBAction func doneDatePickButtonHandler(_ sender: AnyObject) {
eventTime = datePicker.date
// Note: for new events, if the user creates a time in the past that crosses a daylight savings time zone boundary, we want to adjust the time zone offset from the local one, ASSUMING THE USER IS EDITING IN THE SAME TIME ZONE IN WHICH THEY HAD THE MEAL.
// Without this adjustment, they would create the time in the past, say at 9 pm, and return to the meal view and see it an hour different, because we show event times in the UI in the time zone offset in which the event is created.
// This is the one case we are basically allowing an event to be created in a different time zone offset from the present: if we provided a UI to allow the user to select a time zone, this might be handled more easily.
// We truly only know the actual time zone of meals when they are created and their times are not edited (well, unless they are on a plane): allowing this edit, while practical, does put in some question the actual time zone of the event! What is key is the GMT time since that is what will be used to show the meal relatively to the blood glucose and insulin events.
if !editExistingEvent {
let dstAdjust = NutUtils.dayLightSavingsAdjust(datePicker.date)
eventTimeOffsetSecs = NSCalendar.current.timeZone.secondsFromGMT() + dstAdjust
}
configureDateView()
updateSaveButtonState()
}
@IBAction func datePickerValueChanged(_ sender: AnyObject) {
eventTime = datePicker.date
updateDateLabels()
}
//
// MARK: - Test code!
//
// TODO: Move to NutshellTests!
fileprivate func addDemoData() {
let demoMeals = [
// brandon account
["Extended Bolus", "100% extended", "2015-10-30T03:03:00.000Z", "brandon", ""],
["Extended Bolus", "2% extended", "2015-10-31T08:08:00.000Z", "brandon", ""],
["Extended Bolus", "various extended", "2015-10-29T03:08:00.000Z", "brandon", ""],
["Extended Bolus", "various extended", "2015-10-28T21:00:00.000Z", "brandon", ""],
["Temp Basal", "Higher than scheduled", "2015-12-14T18:57:00.000Z", "brandon", ""],
["Temp Basal", "Shift in scheduled during temp", "2015-12-16T05:00:00.000Z", "brandon", ""],
["Interrupted Bolus", "Both regular and extended", "2015-11-17T04:00:00.000Z", "brandon", ""],
["Interrupted Bolus", "Extended, only 2%", "2015-10-11T08:00:00.000Z", "brandon", ""],
["Interrupted Bolus", "Extended, 63% delivered", "2015-10-10T04:00:00.000Z", "brandon", ""],
// larry account
["Overridden Bolus", "Suggested .15, delivered 1, suggested .2, delivered 2.5", "2015-08-15T04:47:00.000Z", "larry", ""],
["Overridden Bolus", "Suggested 1.2, overrode to .6, suggested 1.2, overrode to .8", "2015-08-09T19:14:00.000Z", "larry", ""],
["Interrupted Bolus", "3.8 delivered, 4.0 expected", "2015-08-09T11:03:21.000Z", "larry", ""],
["Interrupted Bolus", "Two 60 wizard bolus events, 1.4 (expected 6.1), 2.95", "2015-05-27T03:03:21.000Z", "larry", ""],
["Interrupted Bolus", "2.45 delivered, 2.5 expected", "2014-06-26T06:45:21.000Z", "larry", ""],
// Demo
["Three tacos", "with 15 chips & salsa", "2015-08-20T10:03:21.000Z", "238 Garrett St", "ThreeTacosDemoPic"],
["Three tacos", "after ballet", "2015-08-09T19:42:40.000Z", "238 Garrett St", "applejuicedemopic"],
["Three tacos", "Apple Juice before", "2015-07-29T04:55:27.000Z", "238 Garrett St", "applejuicedemopic"],
["Three tacos", "and horchata", "2015-07-28T14:25:21.000Z", "238 Garrett St", "applejuicedemopic"],
["CPK 5 cheese margarita", "", "2015-07-27T12:25:21.000Z", "", ""],
["Bagel & cream cheese fruit", "", "2015-07-27T16:25:21.000Z", "", ""],
["Birthday Party", "", "2015-07-26T14:25:21.000Z", "", ""],
["This is a meal with a very long title that should wrap onto multiple lines in most devices", "And these are notes about this meal, which are also very long and should certainly wrap as well. It might be more usual to see long notes!", "2015-07-26T14:25:21.000Z", "This is a long place name, something like Taco Place at 238 Garrett St, San Francisco, California", ""],
]
func addMeal(_ me: Meal, event: [String]) {
me.title = event[0]
me.notes = event[1]
if (event[2] == "") {
me.time = Date()
} else {
me.time = NutUtils.dateFromJSON(event[2])
}
me.location = event[3]
me.photo = event[4]
me.type = "meal"
me.id = ("demo" + UUID().uuidString) as NSString? // required!
me.userid = NutDataController.controller().currentUserId // required!
let now = Date()
me.createdTime = now
me.modifiedTime = now
// TODO: really should specify time zone offset in the data so we can test some time zone related issues
me.timezoneOffset = NSNumber(value: NSCalendar.current.timeZone.secondsFromGMT()/60)
}
let demoWorkouts = [
["Runs", "regular 3 mile", "2015-07-28T12:25:21.000Z", "6000"],
["Workout", "running in park", "2015-07-27T04:23:20.000Z", "2100"],
["Workout", "running around the neighborhood", "2015-07-24T02:43:20.000Z", "2100"],
["Workout", "running at Rancho San Antonio", "2015-07-21T03:53:20.000Z", "2100"],
["PE class", "some notes for this one", "2015-07-27T08:25:21.000Z", "3600"],
["Soccer Practice", "", "2015-07-25T14:25:21.000Z", "4800"],
]
func addWorkout(_ we: Workout, event: [String]) {
we.title = event[0]
we.notes = event[1]
if (event[2] == "") {
we.time = Date().addingTimeInterval(-60*60)
we.duration = NSNumber(value: (-60*60))
} else {
we.time = NutUtils.dateFromJSON(event[2])
we.duration = TimeInterval(event[3]) as NSNumber?
}
we.type = "workout"
we.id = ("demo" + UUID().uuidString) as NSString // required!
we.userid = NutDataController.controller().currentUserId // required!
let now = Date()
we.createdTime = now
we.modifiedTime = now
we.timezoneOffset = NSNumber(value: NSCalendar.current.timeZone.secondsFromGMT()/60)
}
let moc = NutDataController.controller().mocForNutEvents()!
if let entityDescription = NSEntityDescription.entity(forEntityName: "Meal", in: moc) {
for event in demoMeals {
let me = NSManagedObject(entity: entityDescription, insertInto: nil) as! Meal
addMeal(me, event: event)
moc.insert(me)
}
}
if AppDelegate.healthKitUIEnabled {
if let entityDescription = NSEntityDescription.entity(forEntityName: "Workout", in: moc) {
for event in demoWorkouts {
let we = NSManagedObject(entity: entityDescription, insertInto: nil) as! Workout
addWorkout(we, event: event)
moc.insert(we)
}
}
}
_ = DatabaseUtils.databaseSave(moc)
}
}
| bsd-2-clause |
wisonlin/OpenGLESTutorial | Hello-Metal_3_Starter/HelloMetal/Vertex.swift | 1 | 357 | //
// Vertex.swift
// HelloMetal
//
// Created by Andrew K. on 10/23/14.
// Copyright (c) 2014 Razeware LLC. All rights reserved.
//
struct Vertex{
var x,y,z: Float // position data
var r,g,b,a: Float // color data
var s,t: Float // texture coordinates
func floatBuffer() -> [Float] {
return [x,y,z,r,g,b,a,s,t]
}
};
| mit |
mrchenhao/VPNOn | VPNOnKit/VPNManager.swift | 1 | 6605 | //
// VPNManager.swift
// VPNOn
//
// Created by Lex Tang on 12/5/14.
// Copyright (c) 2014 LexTang.com. All rights reserved.
//
import Foundation
import NetworkExtension
import CoreData
let kAppGroupIdentifier = "group.VPNOn"
final public class VPNManager
{
lazy var _manager: NEVPNManager = {
return NEVPNManager.sharedManager()!
}()
lazy var _defaults: NSUserDefaults = {
return NSUserDefaults(suiteName: kAppGroupIdentifier)!
}()
public var status: NEVPNStatus {
get {
return _manager.connection.status
}
}
public class var sharedManager : VPNManager
{
struct Static
{
static let sharedInstance : VPNManager = {
let instance = VPNManager()
instance._manager.loadFromPreferencesWithCompletionHandler {
(error: NSError!) -> Void in
if let err = error {
println("Failed to load preferences: \(err.localizedDescription)")
}
}
instance._manager.localizedDescription = "VPN On"
instance._manager.enabled = true
return instance
}()
}
return Static.sharedInstance
}
public func connectIPSec(title: String, server: String, account: String?, group: String?, alwaysOn: Bool = true, passwordRef: NSData?, secretRef: NSData?, certificate: NSData?) {
// TODO: Add a tailing closure for callback.
let p = NEVPNProtocolIPSec()
p.authenticationMethod = NEVPNIKEAuthenticationMethod.None
p.useExtendedAuthentication = true
p.serverAddress = server
p.disconnectOnSleep = !alwaysOn
_manager.localizedDescription = "VPN On - \(title)"
if let grp = group {
p.localIdentifier = grp
} else {
p.localIdentifier = "VPN"
}
if let username = account {
p.username = username
}
if let password = passwordRef {
p.passwordReference = password
}
if let secret = secretRef {
p.authenticationMethod = NEVPNIKEAuthenticationMethod.SharedSecret
p.sharedSecretReference = secret
}
if let certficiateData = certificate {
p.authenticationMethod = NEVPNIKEAuthenticationMethod.Certificate
p.identityData = certficiateData
}
_manager.enabled = true
_manager.`protocol` = p
configOnDemand()
_manager.saveToPreferencesWithCompletionHandler {
(error: NSError!) -> Void in
if let err = error {
println("Failed to save profile: \(err.localizedDescription)")
} else {
var connectError : NSError?
self._manager.connection.startVPNTunnelAndReturnError(&connectError)
if let connectErr = connectError {
// println("Failed to start tunnel: \(connectErr.localizedDescription)")
} else {
// println("VPN tunnel started.")
}
}
}
}
public func connectIKEv2(title: String, server: String, account: String?, group: String?, alwaysOn: Bool = true, passwordRef: NSData?, secretRef: NSData?, certificate: NSData?) {
let p = NEVPNProtocolIKEv2()
p.authenticationMethod = NEVPNIKEAuthenticationMethod.None
p.useExtendedAuthentication = true
p.serverAddress = server
p.remoteIdentifier = server
p.disconnectOnSleep = !alwaysOn
p.deadPeerDetectionRate = NEVPNIKEv2DeadPeerDetectionRate.Medium
// TODO: Add an option into config page
_manager.localizedDescription = "VPN On - \(title)"
if let grp = group {
p.localIdentifier = grp
} else {
p.localIdentifier = "VPN"
}
if let username = account {
p.username = username
}
if let password = passwordRef {
p.passwordReference = password
}
if let secret = secretRef {
p.authenticationMethod = NEVPNIKEAuthenticationMethod.SharedSecret
p.sharedSecretReference = secret
}
if let certficiateData = certificate {
p.authenticationMethod = NEVPNIKEAuthenticationMethod.Certificate
p.serverCertificateCommonName = server
p.serverCertificateIssuerCommonName = server
p.identityData = certficiateData
}
_manager.enabled = true
_manager.`protocol` = p
configOnDemand()
_manager.saveToPreferencesWithCompletionHandler {
(error: NSError!) -> Void in
if let err = error {
println("Failed to save profile: \(err.localizedDescription)")
} else {
var connectError : NSError?
if self._manager.connection.startVPNTunnelAndReturnError(&connectError) {
if let connectErr = connectError {
println("Failed to start IKEv2 tunnel: \(connectErr.localizedDescription)")
} else {
println("IKEv2 tunnel started.")
}
} else {
println("Failed to connect: \(connectError?.localizedDescription)")
}
}
}
}
public func configOnDemand() {
if onDemandDomainsArray.count > 0 && onDemand {
let connectionRule = NEEvaluateConnectionRule(
matchDomains: onDemandDomainsArray,
andAction: NEEvaluateConnectionRuleAction.ConnectIfNeeded
)
let ruleEvaluateConnection = NEOnDemandRuleEvaluateConnection()
ruleEvaluateConnection.connectionRules = [connectionRule]
_manager.onDemandRules = [ruleEvaluateConnection]
_manager.onDemandEnabled = true
} else {
_manager.onDemandRules = [AnyObject]()
_manager.onDemandEnabled = false
}
}
public func disconnect() {
_manager.connection.stopVPNTunnel()
}
public func removeProfile() {
_manager.removeFromPreferencesWithCompletionHandler {
(error: NSError!) -> Void in
}
}
}
| mit |
viniciusaro/SwiftResolver | tutorial/Example1/Example1/Classes/RequestProvider/Scheduler.swift | 1 | 295 | import Foundation
protocol Scheduler {
func run(_ block: @escaping () -> Void) -> Void
}
final class MainScheduler: Scheduler {
static let instance = MainScheduler()
func run(_ block: @escaping () -> Void) {
DispatchQueue.main.async {
block()
}
}
}
| mit |
sarvex/SwiftRecepies | Data/Using Custom Data Types in Your Core Data Model/Using Custom Data Types in Your Core Data Model/ColorTransformer.swift | 1 | 1371 | //
// ColorTransformer.swift
// Using Custom Data Types in Your Core Data Model
//
// Created by vandad on 167//14.
// Copyright (c) 2014 Pixolity Ltd. All rights reserved.
//
import UIKit
class ColorTransformer: NSValueTransformer {
override class func allowsReverseTransformation() -> Bool{
return true
}
override class func transformedValueClass() -> AnyClass{
return NSData.classForCoder()
}
override func transformedValue(value: AnyObject!) -> AnyObject {
/* Transform color to data */
let color = value as! UIColor
var red: CGFloat = 0
var green: CGFloat = 0
var blue: CGFloat = 0
var alpha: CGFloat = 0
color.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
var components = [red, green, blue, alpha]
let dataFromColors = NSData(bytes: components,
length: sizeofValue(components))
return dataFromColors
}
override func reverseTransformedValue(value: AnyObject!) -> AnyObject {
/* Transform data to color */
let data = value as! NSData
var components = [CGFloat](count: 4, repeatedValue: 0.0)
data.getBytes(&components, length: sizeofValue(components))
let color = UIColor(red: components[0],
green: components[1],
blue: components[2],
alpha: components[3])
return color
}
}
| isc |
jasnig/ScrollPageView | ScrollViewController/可以在初始化或者返回页面的时候设置当前页为其他页/Vc9Controller.swift | 1 | 4855 | //
// Vc9Controller.swift
// ScrollViewController
//
// Created by jasnig on 16/4/22.
// Copyright © 2016年 ZeroJ. All rights reserved.
// github: https://github.com/jasnig
// 简书: http://www.jianshu.com/users/fb31a3d1ec30/latest_articles
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import UIKit
class Vc9Controller: UIViewController {
var scrollPageView: ScrollPageView!
override func viewDidLoad() {
super.viewDidLoad()
// 这个是必要的设置
automaticallyAdjustsScrollViewInsets = false
var style = SegmentStyle()
// 缩放文字
style.scaleTitle = true
// 颜色渐变
style.gradualChangeTitleColor = true
// 显示滚动条
style.showLine = true
// 天使遮盖
style.showCover = true
// segment可以滚动
style.scrollTitle = true
let titles = ["国内头条", "国际要闻", "趣事", "囧图", "明星八卦", "爱车", "国防要事", "科技频道", "手机专页", "风景图", "段子"]
scrollPageView = ScrollPageView(frame: CGRect(x: 0, y: 64, width: view.bounds.size.width, height: view.bounds.size.height - 64), segmentStyle: style, titles: titles, childVcs: setChildVcs(), parentViewController: self)
// 设置默认下标
scrollPageView.selectedIndex(2, animated: true)
view.addSubview(scrollPageView)
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
scrollPageView.frame = CGRect(x: 0, y: 64, width: view.bounds.size.width, height: view.bounds.size.height - 64)
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
print(navigationController?.interactivePopGestureRecognizer)
}
override func viewDidDisappear(animated: Bool) {
super.viewDidDisappear(animated)
print(navigationController?.interactivePopGestureRecognizer)
}
func setChildVcs() -> [UIViewController] {
let vc1 = storyboard!.instantiateViewControllerWithIdentifier("test")
let vc2 = UIViewController()
vc2.view.backgroundColor = UIColor.greenColor()
let vc3 = UIViewController()
vc3.view.backgroundColor = UIColor.redColor()
let vc4 = storyboard!.instantiateViewControllerWithIdentifier("test")
vc4.view.backgroundColor = UIColor.yellowColor()
let vc5 = UIViewController()
vc5.view.backgroundColor = UIColor.lightGrayColor()
let vc6 = UIViewController()
vc6.view.backgroundColor = UIColor.brownColor()
let vc7 = UIViewController()
vc7.view.backgroundColor = UIColor.orangeColor()
let vc8 = UIViewController()
vc8.view.backgroundColor = UIColor.blueColor()
let vc9 = UIViewController()
vc9.view.backgroundColor = UIColor.brownColor()
let vc10 = UIViewController()
vc10.view.backgroundColor = UIColor.orangeColor()
let vc11 = UIViewController()
vc11.view.backgroundColor = UIColor.blueColor()
return [vc1, vc2, vc3,vc4, vc5, vc6, vc7, vc8, vc9, vc10, vc11]
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit |
EvsenevDev/SmartReceiptsiOS | SmartReceipts/Modules/Edit Distance/EditDistanceView.swift | 2 | 2357 | //
// EditDistanceView.swift
// SmartReceipts
//
// Created by Bogdan Evsenev on 01/06/2017.
// Copyright © 2017 Will Baumann. All rights reserved.
//
import UIKit
import Viperit
import RxSwift
import RxCocoa
//MARK: - Public Interface Protocol
protocol EditDistanceViewInterface {
func setup(trip: WBTrip, distance: Distance?)
}
//MARK: EditDistance View
final class EditDistanceView: UserInterface {
private var formView: EditDistanceFormView!
override func viewDidLoad() {
super.viewDidLoad()
formView = EditDistanceFormView(trip: displayData.trip!, distance: displayData.distance)
addChild(formView)
formView.view.frame = view.bounds
view.addSubview(formView.view)
setupInitialState()
}
private func setupInitialState() {
let isEdit = displayData.distance != nil
navigationItem.title = isEdit ?
LocalizedString("dialog_mileage_title_update") :
LocalizedString("dialog_mileage_title_create")
}
//MARK: Actions
@IBAction private func onSaveTap() {
let errorsDescription = formView.validate()
if errorsDescription.isEmpty {
let distance = formView!.changedDistance!
presenter.save(distance: distance, asNewDistance: displayData.distance == nil)
} else {
let title = LocalizedString("generic_error_alert_title")
let alert = UIAlertController(title: title, message: errorsDescription, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: LocalizedString("generic_button_title_ok"), style: .cancel, handler: nil))
present(alert, animated: true, completion: nil)
}
}
@IBAction private func onCancelTap() {
presenter.close()
}
}
//MARK: - Public interface
extension EditDistanceView: EditDistanceViewInterface {
func setup(trip: WBTrip, distance: Distance?) {
displayData.trip = trip
displayData.distance = distance
}
}
// MARK: - VIPER COMPONENTS API (Auto-generated code)
private extension EditDistanceView {
var presenter: EditDistancePresenter {
return _presenter as! EditDistancePresenter
}
var displayData: EditDistanceDisplayData {
return _displayData as! EditDistanceDisplayData
}
}
| agpl-3.0 |
benlangmuir/swift | validation-test/IDE/print_stdlib_specialized.swift | 70 | 3762 | // Check interface produced for the standard library.
//
// REQUIRES: long_test
// REQUIRES: nonexecutable_test
//
// RUN: %target-swift-ide-test -print-module -module-group "Pointer" -synthesize-extension -module-to-print=Swift -source-filename %s -print-interface | %FileCheck %s -check-prefix=CHECK-FREQUENT-WORD
// RUN: %target-swift-ide-test -print-module -module-group "C" -synthesize-extension -module-to-print=Swift -source-filename %s -print-interface | %FileCheck %s -check-prefix=CHECK-FREQUENT-WORD
// RUN: %target-swift-ide-test -print-module -module-group "Protocols" -synthesize-extension -module-to-print=Swift -source-filename %s -print-interface | %FileCheck %s -check-prefix=CHECK-FREQUENT-WORD
// RUN: %target-swift-ide-test -print-module -module-group "Optional" -synthesize-extension -module-to-print=Swift -source-filename %s -print-interface | %FileCheck %s -check-prefix=CHECK-FREQUENT-WORD
// RUN: %target-swift-ide-test -print-module -module-group "Collection/Lazy Views" -synthesize-extension -module-to-print=Swift -source-filename %s -print-interface | %FileCheck %s -check-prefix=CHECK-FREQUENT-WORD
// RUN: %target-swift-ide-test -print-module -module-group "Math" -synthesize-extension -module-to-print=Swift -source-filename %s -print-interface | %FileCheck %s -check-prefix=CHECK-FREQUENT-WORD
// RUN: %target-swift-ide-test -print-module -module-group "Math/Floating" -synthesize-extension -module-to-print=Swift -source-filename %s -print-interface | %FileCheck %s -check-prefix=CHECK-FREQUENT-WORD
// RUN: %target-swift-ide-test -print-module -module-group "Math/Integers" -synthesize-extension -module-to-print=Swift -source-filename %s -print-interface | %FileCheck %s -check-prefix=CHECK-FREQUENT-WORD
// RUN: %target-swift-ide-test -print-module -module-group "Reflection" -synthesize-extension -module-to-print=Swift -source-filename %s -print-interface | %FileCheck %s -check-prefix=CHECK-FREQUENT-WORD
// RUN: %target-swift-ide-test -print-module -module-group "Misc" -synthesize-extension -module-to-print=Swift -source-filename %s -print-interface | %FileCheck %s -check-prefix=CHECK-FREQUENT-WORD
// RUN: %target-swift-ide-test -print-module -module-group "Collection" -synthesize-extension -module-to-print=Swift -source-filename %s -print-interface | %FileCheck %s -check-prefix=CHECK-COLLECTION-GROUP
// RUN: %target-swift-ide-test -print-module -module-group "Bool" -synthesize-extension -module-to-print=Swift -source-filename %s -print-interface | %FileCheck %s -check-prefix=CHECK-FREQUENT-WORD
// RUN: %target-swift-ide-test -print-module -module-group "Assert" -synthesize-extension -module-to-print=Swift -source-filename %s -print-interface | %FileCheck %s -check-prefix=CHECK-FREQUENT-WORD
// RUN: %target-swift-ide-test -print-module -module-group "String" -synthesize-extension -module-to-print=Swift -source-filename %s -print-interface | %FileCheck %s -check-prefix=CHECK-FREQUENT-WORD
// RUN: %target-swift-ide-test -print-module -module-group "Collection/Array" -synthesize-extension -module-to-print=Swift -source-filename %s -print-interface | %FileCheck %s -check-prefix=CHECK-FREQUENT-WORD
// RUN: %target-swift-ide-test -print-module -module-group "Collection/Type-erased" -synthesize-extension -module-to-print=Swift -source-filename %s -print-interface | %FileCheck %s -check-prefix=CHECK-FREQUENT-WORD
// RUN: %target-swift-ide-test -print-module -module-group "Collection/HashedCollections" -synthesize-extension -module-to-print=Swift -source-filename %s -print-interface | %FileCheck %s -check-prefix=CHECK-FREQUENT-WORD
// CHECK-FREQUENT-WORD: ///
// CHECK-FREQUENT-WORD-NOT: where Slice<Dictionary<Key, Value>> == Slice<Self>
// CHECK-COLLECTION-GROUP: extension MutableCollection
| apache-2.0 |
Remonder/Bloggable | Sources/Bloggable/Extensions/StandardLibrary/RandomAccessCollection+safeSubscribt.swift | 1 | 385 | //
// RandomAccessCollection+safeSubscribt.swift
// Bloggable
//
// Created by David Nadoba on 18.10.17.
//
import Foundation
extension RandomAccessCollection {
subscript(safe index: Index) -> Element? {
get {
guard index >= startIndex, index < self.endIndex else {
return nil
}
return self[index]
}
}
}
| mit |
gregomni/swift | stdlib/public/core/UIntBuffer.swift | 10 | 6397 | //===--- UIntBuffer.swift - Bounded Collection of Unsigned Integer --------===//
//
// 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
//
//===----------------------------------------------------------------------===//
//
// Stores a smaller unsigned integer type inside a larger one, with a limit of
// 255 elements.
//
//===----------------------------------------------------------------------===//
@frozen
public struct _UIntBuffer<Element: UnsignedInteger & FixedWidthInteger> {
public typealias Storage = UInt32
public var _storage: Storage
public var _bitCount: UInt8
@inlinable
@inline(__always)
public init(_storage: Storage, _bitCount: UInt8) {
self._storage = _storage
self._bitCount = _bitCount
}
@inlinable
@inline(__always)
public init(containing e: Element) {
_storage = Storage(truncatingIfNeeded: e)
_bitCount = UInt8(truncatingIfNeeded: Element.bitWidth)
}
}
extension _UIntBuffer: Sequence {
public typealias SubSequence = Slice<_UIntBuffer>
@frozen
public struct Iterator: IteratorProtocol, Sequence {
public var _impl: _UIntBuffer
@inlinable
@inline(__always)
public init(_ x: _UIntBuffer) { _impl = x }
@inlinable
@inline(__always)
public mutating func next() -> Element? {
if _impl._bitCount == 0 { return nil }
defer {
_impl._storage = _impl._storage &>> Element.bitWidth
_impl._bitCount = _impl._bitCount &- _impl._elementWidth
}
return Element(truncatingIfNeeded: _impl._storage)
}
}
@inlinable
@inline(__always)
public func makeIterator() -> Iterator {
return Iterator(self)
}
}
extension _UIntBuffer: Collection {
@frozen
public struct Index: Comparable {
@usableFromInline
internal var bitOffset: UInt8
@inlinable
internal init(bitOffset: UInt8) { self.bitOffset = bitOffset }
@inlinable
public static func == (lhs: Index, rhs: Index) -> Bool {
return lhs.bitOffset == rhs.bitOffset
}
@inlinable
public static func < (lhs: Index, rhs: Index) -> Bool {
return lhs.bitOffset < rhs.bitOffset
}
}
@inlinable
public var startIndex: Index {
@inline(__always)
get { return Index(bitOffset: 0) }
}
@inlinable
public var endIndex: Index {
@inline(__always)
get { return Index(bitOffset: _bitCount) }
}
@inlinable
@inline(__always)
public func index(after i: Index) -> Index {
return Index(bitOffset: i.bitOffset &+ _elementWidth)
}
@inlinable
internal var _elementWidth: UInt8 {
return UInt8(truncatingIfNeeded: Element.bitWidth)
}
@inlinable
public subscript(i: Index) -> Element {
@inline(__always)
get {
return Element(truncatingIfNeeded: _storage &>> i.bitOffset)
}
}
}
extension _UIntBuffer: BidirectionalCollection {
@inlinable
@inline(__always)
public func index(before i: Index) -> Index {
return Index(bitOffset: i.bitOffset &- _elementWidth)
}
}
extension _UIntBuffer: RandomAccessCollection {
public typealias Indices = DefaultIndices<_UIntBuffer>
@inlinable
@inline(__always)
public func index(_ i: Index, offsetBy n: Int) -> Index {
let x = Int(i.bitOffset) &+ n &* Element.bitWidth
return Index(bitOffset: UInt8(truncatingIfNeeded: x))
}
@inlinable
@inline(__always)
public func distance(from i: Index, to j: Index) -> Int {
return (Int(j.bitOffset) &- Int(i.bitOffset)) / Element.bitWidth
}
}
extension FixedWidthInteger {
@inline(__always)
@inlinable
internal func _fullShiftLeft<N: FixedWidthInteger>(_ n: N) -> Self {
return (self &<< ((n &+ 1) &>> 1)) &<< (n &>> 1)
}
@inline(__always)
@inlinable
internal func _fullShiftRight<N: FixedWidthInteger>(_ n: N) -> Self {
return (self &>> ((n &+ 1) &>> 1)) &>> (n &>> 1)
}
@inline(__always)
@inlinable
internal static func _lowBits<N: FixedWidthInteger>(_ n: N) -> Self {
return ~((~0 as Self)._fullShiftLeft(n))
}
}
extension Range {
@inline(__always)
@inlinable
internal func _contains_(_ other: Range) -> Bool {
return other.clamped(to: self) == other
}
}
extension _UIntBuffer: RangeReplaceableCollection {
@inlinable
@inline(__always)
public init() {
_storage = 0
_bitCount = 0
}
@inlinable
public var capacity: Int {
return Storage.bitWidth / Element.bitWidth
}
@inlinable
@inline(__always)
public mutating func append(_ newElement: Element) {
_debugPrecondition(count + 1 <= capacity)
_storage &= ~(Storage(Element.max) &<< _bitCount)
_storage |= Storage(newElement) &<< _bitCount
_bitCount = _bitCount &+ _elementWidth
}
@inlinable
@inline(__always)
@discardableResult
public mutating func removeFirst() -> Element {
_debugPrecondition(!isEmpty)
let result = Element(truncatingIfNeeded: _storage)
_bitCount = _bitCount &- _elementWidth
_storage = _storage._fullShiftRight(_elementWidth)
return result
}
@inlinable
@inline(__always)
public mutating func replaceSubrange<C: Collection>(
_ target: Range<Index>, with replacement: C
) where C.Element == Element {
_debugPrecondition(
(0..<_bitCount)._contains_(
target.lowerBound.bitOffset..<target.upperBound.bitOffset))
let replacement1 = _UIntBuffer(replacement)
let targetCount = distance(
from: target.lowerBound, to: target.upperBound)
let growth = replacement1.count &- targetCount
_debugPrecondition(count + growth <= capacity)
let headCount = distance(from: startIndex, to: target.lowerBound)
let tailOffset = distance(from: startIndex, to: target.upperBound)
let w = Element.bitWidth
let headBits = _storage & ._lowBits(headCount &* w)
let tailBits = _storage._fullShiftRight(tailOffset &* w)
_storage = headBits
_storage |= replacement1._storage &<< (headCount &* w)
_storage |= tailBits &<< ((tailOffset &+ growth) &* w)
_bitCount = UInt8(
truncatingIfNeeded: Int(_bitCount) &+ growth &* w)
}
}
extension _UIntBuffer: Sendable where Element: Sendable { }
| apache-2.0 |
BerrySang/BSCarouselFigureView | BSCarouselFigureView/AppDelegate.swift | 1 | 2176 | //
// AppDelegate.swift
// BSCarouselFigureView
//
// Created by Berry on 2017/1/7.
// Copyright © 2017年 Berry. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| mit |
yingDev/QingDict | QingDict/WordbookViewController.swift | 1 | 3114 | //
// WordbookController.swift
// QingDict
//
// Created by Ying on 15/12/10.
// Copyright © 2015年 YingDev.com. All rights reserved.
//
import Cocoa
class WordbookViewController : NSObject, NSTableViewDataSource, NSTableViewDelegate
{
private let dataController = WordbookDataController()
private var entries: [WordbookEntry]!
var view: NSTableView! = nil
{
didSet
{
view.setDataSource(self)
view.setDelegate(self)
reload()
}
}
var entryDoubleClickHandler: ((WordbookEntry)->())? = nil
//kvo compatible
dynamic private(set) var entryCount: Int = 0
func containsWord(word: String) -> Bool
{
return entries == nil ? false : entries.contains({ e -> Bool in
return word == e.keyword
})
}
func addEntry(entry: WordbookEntry)
{
dataController.add(entry)
reload()
}
func removeEntry(word: String)
{
dataController.remove(word)
reload()
}
func reload()
{
entries = dataController.fetchAll()
entryCount = entries.count
view.reloadData()
}
func clearSelection()
{
if view.selectedRow >= 0
{
let lastSelectedRow = view.rowViewAtRow(view.selectedRow, makeIfNecessary: false)! as! WordbookRowView;
lastSelectedRow.txtTrans.hidden = true;
lastSelectedRow.contentView.constraints.filter({ cons in cons.identifier == "centerY" })[0].priority = 751;
lastSelectedRow.txtTittle.textColor = NSColor.darkGrayColor();
view.selectRowIndexes(NSIndexSet(), byExtendingSelection: false)
}
}
func numberOfRowsInTableView(tableView: NSTableView) -> Int
{
return entryCount
}
func tableView(tableView: NSTableView, rowViewForRow row: Int) -> NSTableRowView?
{
let rowView = tableView.makeViewWithIdentifier("mainCell", owner: nil) as! WordbookRowView
let model = entries![row]
rowView.txtTittle.stringValue = model.keyword;
rowView.txtTrans.stringValue = model.trans == nil ? "" : model.trans!
rowView.txtTrans.hidden = true;
rowView.onSwiped = self.handleRowSwiped
rowView.onClicked = self.handleRowClicked
return rowView;
}
private func handleRowClicked(sender: WordbookRowView, clickCount: Int)
{
if clickCount == 1
{
clearSelection()
let indexes = NSIndexSet(index: view.rowForView(sender));
view.selectRowIndexes(indexes, byExtendingSelection: false);
sender.txtTrans.hidden = false;
sender.txtTittle.textColor = NSColor.blackColor()
sender.contentView.constraints.filter({ cons in cons.identifier == "centerY" })[0].priority = 749;
}else if clickCount == 2 //双击
{
let r = view.rowForView(sender)
self.entryDoubleClickHandler?(self.entries[r]);
print("double Click")
}
}
private func handleRowSwiped(sender: WordbookRowView)
{
let r = view.rowForView(sender)
let indexes = NSIndexSet(index: r);
view.removeRowsAtIndexes(indexes, withAnimation: [.EffectFade, .SlideUp])
self.dataController.remove(self.entries[r].keyword)
self.entries.removeAtIndex(r)
self.entryCount = self.entries.count
}
func selectionShouldChangeInTableView(tableView: NSTableView) -> Bool
{
return false;
}
}
| gpl-3.0 |
xhacker/swift-compiler-crashes | fixed/26181-swift-modulefile-getdecl.swift | 7 | 175 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
{&(&)
| mit |
FandyLiu/FDDemoCollection | Swift/WidgetDemo/SnapKitUtil/BaseLayoutable.swift | 1 | 3131 | //
// BaseLayoutable.swift
// WidgetDemo
//
// Created by QianTuFD on 2017/6/27.
// Copyright © 2017年 fandy. All rights reserved.
//
import UIKit
import SnapKit
// MARK: - Rect
/// RectLayoutable 带有 Rect 的布局协议
protocol WidthLayoutable {
var width: CGFloat { get }
var widthMultiplie: CGFloat { get }
var widthMargin: CGFloat { get }
@discardableResult
func width(_ maker: ConstraintMaker) -> Self
}
extension WidthLayoutable {
func width(_ maker: ConstraintMaker) -> Self {
maker.width.equalTo(self.width).multipliedBy(11).offset(<#T##amount: ConstraintOffsetTarget##ConstraintOffsetTarget#>)
return self
}
}
protocol HeightLayoutable {
var height: CGFloat { get }
@discardableResult
func height(_ maker: ConstraintMaker) -> Self
}
extension HeightLayoutable {
func height(_ maker: ConstraintMaker) -> Self {
maker.height.equalTo(self.height)
return self
}
}
protocol RectLayoutable: WidthLayoutable, HeightLayoutable {
@discardableResult
func rect(_ maker: ConstraintMaker) -> Self
}
extension RectLayoutable {
func rect(_ maker: ConstraintMaker) -> Self {
return self.height(maker).width(maker)
}
}
/// 正方形扩展协议
protocol SquareLayoutable {
var length: CGFloat { get }
}
extension SquareLayoutable where Self: RectLayoutable {
var width: CGFloat {
return length
}
var height: CGFloat {
return length
}
}
// MARK: - Margin
/// Margin
protocol LeftLayoutable {
var leftView: UIView? { get }
var leftMultiplie: CGFloat { get }
var leftMargin: CGFloat { get }
@discardableResult
func left(_ maker: ConstraintMaker) -> Self
}
extension LeftLayoutable {
func left(_ maker: ConstraintMaker) -> Self {
guard let leftView = leftView else {
maker.left.equalToSuperview().multipliedBy(leftMultiplie).offset(leftMargin)
return self
}
maker.left.equalTo(leftView.snp.leading).multipliedBy(leftMultiplie).offset(leftMargin)
return self
}
}
protocol RightLayoutable {
var rightView: UIView { get }
var rightMargin: CGFloat { get }
@discardableResult
func right(_ maker: ConstraintMaker) -> Self
}
extension RightLayoutable {
func right(_ maker: ConstraintMaker) -> Self {
maker.right.equalTo(self.rightView).offset(rightMargin)
return self
}
}
protocol TopLayoutable {
var topView: UIView { get }
var topMargin: CGFloat { get }
@discardableResult
func top(_ maker: ConstraintMaker) -> Self
}
extension TopLayoutable {
func top(_ maker: ConstraintMaker) -> Self {
maker.top.equalTo(self.topView).offset(topMargin)
return self
}
}
protocol BottomLayoutable {
var bottomView: UIView { get }
var bottomMargin: CGFloat { get }
@discardableResult
func bottom(_ maker: ConstraintMaker) -> Self
}
extension BottomLayoutable {
func bottom(_ maker: ConstraintMaker) -> Self {
maker.bottom.equalTo(self.bottomView).offset(bottomMargin)
return self
}
}
| mit |
alvinvarghese/ScaledVisibleCellsCollectionView | ScaledVisibleCellsCollectionViewExample/Tests/Tests.swift | 3 | 1199 | // https://github.com/Quick/Quick
import Quick
import Nimble
import ScaledVisibleCellsCollectionView
class TableOfContentsSpec: QuickSpec {
override func spec() {
describe("these will fail") {
it("can do maths") {
expect(1) == 2
}
it("can read") {
expect("number") == "string"
}
it("will eventually fail") {
expect("time").toEventually( equal("done") )
}
context("these will pass") {
it("can do maths") {
expect(23) == 23
}
it("can read") {
expect("🐮") == "🐮"
}
it("will eventually pass") {
var time = "passing"
dispatch_async(dispatch_get_main_queue()) {
time = "done"
}
waitUntil { done in
NSThread.sleepForTimeInterval(0.5)
expect(time) == "done"
done()
}
}
}
}
}
}
| mit |
zning1994/practice | Swift学习/code4xcode6/ch11/11.7.3统一性原则-4.playground/section-1.swift | 1 | 294 |
public class Employee {
var no : Int = 0
var name : String = ""
var job : String?
var salary : Double = 0
var dept : Department?
}
struct Department {
var no : Int = 0
var name : String = ""
}
func getEmpDept(emp : Employee)-> Department? {
return emp.dept
}
| gpl-2.0 |
Kruks/FindViewControl | FindViewControl/FindViewControl/VIewController/FindFilterTableViewController.swift | 1 | 5188 | //
// FindFilterTableViewController.swift
// MyCity311
//
// Created by Krutika Mac Mini on 12/23/16.
// Copyright © 2016 Kahuna Systems. All rights reserved.
//
import UIKit
import MFSideMenu
@objc protocol FindFilterTableViewControllerDelegate: class {
@objc optional func filtersTableViewController(selectedFilters: [FilterObject])
}
class FindFilterTableViewController: UITableViewController {
var filterArray: [FilterObject]!
var selectedFiltersArray: [FilterObject]!
@IBOutlet weak var barButtonItem: UIBarButtonItem!
@IBOutlet weak var barButtonItem1: UIBarButtonItem!
@IBOutlet weak var selectAll: UIBarButtonItem!
@IBOutlet weak var unselectAll: UIBarButtonItem!
weak var delegate: FindFilterTableViewControllerDelegate?
@IBOutlet weak var navTitleLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
if (selectedFiltersArray == nil) {
selectedFiltersArray = [FilterObject]()
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.navigationController?.setToolbarHidden(false, animated: false)
self.navigationController?.toolbar.setBackgroundImage(UIImage(named: "header_bg.png"), forToolbarPosition: .bottom, barMetrics: .default)
self.navigationController?.toolbar.tintColor = UIColor.white
self.navigationController?.toolbar.barTintColor = UIColor.darkGray
self.navTitleLabel.text = "filtersNavTitle".localized
let button1 = barButtonItem!.customView as! UIButton
button1.setTitle("CancelButtonLabel".localized, for: .normal)
let button2 = barButtonItem1!.customView as! UIButton
button2.setTitle("doneBtnTitle".localized, for: .normal)
self.selectAll.title = "selectAllButtonTitle".localized
self.unselectAll.title = "unselectAllButtonTitle".localized
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.filterArray.count
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 50.0
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell: UITableViewCell? = tableView.dequeueReusableCell(withIdentifier: "Cell")
let bundle = Bundle(identifier: FindConstants.findBundleID)
if cell == nil {
cell = UITableViewCell(style: .default, reuseIdentifier: "Cell")
let nib = bundle?.loadNibNamed("FilterCell", owner: self, options: nil)
if nib!.count > 0 {
cell = nib![0] as? UITableViewCell
}
}
let titleLabel: UILabel = cell!.viewWithTag(1) as! UILabel
let iconImage: UIImageView = cell!.viewWithTag(2) as! UIImageView
let filterType: FilterObject = self.filterArray[indexPath.row]
titleLabel.text = filterType.filterValue
if selectedFiltersArray.contains(filterType) {
iconImage.image = UIImage(named: "tick.png", in: bundle, compatibleWith: nil)
}
else {
iconImage.image = UIImage(named: "untick.png", in: bundle, compatibleWith: nil)
}
cell?.selectionStyle = UITableViewCellSelectionStyle.none
return cell!
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath as IndexPath, animated: true)
let bundle = Bundle(identifier: FindConstants.findBundleID)
let filterType: FilterObject = self.filterArray[indexPath.row]
let cell: UITableViewCell = tableView.cellForRow(at: indexPath as IndexPath)!
let iconImage: UIImageView = cell.viewWithTag(2) as! UIImageView
if selectedFiltersArray.contains(filterType) {
iconImage.image = UIImage(named: "untick.png", in: bundle, compatibleWith: nil)
if let index = selectedFiltersArray.index(of: filterType) {
selectedFiltersArray.remove(at: index)
}
}
else {
iconImage.image = UIImage(named: "tick.png", in: bundle, compatibleWith: nil)
selectedFiltersArray.append(filterType)
}
}
@IBAction func selectAllClicked() {
selectedFiltersArray.removeAll()
selectedFiltersArray = [FilterObject]()
selectedFiltersArray.append(contentsOf: self.filterArray)
self.tableView.reloadData()
}
@IBAction func unselectAllClicked() {
selectedFiltersArray.removeAll()
self.tableView.reloadData()
}
@IBAction func done_button_clicked() {
self.menuContainerViewController.toggleRightSideMenuCompletion({
DispatchQueue.main.async {
self.delegate?.filtersTableViewController!(selectedFilters: self.selectedFiltersArray)
}
})
}
@IBAction func cancel_button_clicked() {
self.menuContainerViewController.toggleRightSideMenuCompletion(nil)
}
}
| mit |
vknabel/Rock | Sources/rock/Commandant.swift | 1 | 235 | import Commandant
import Result
public func <| <T, ClientError>(
mode: CommandMode,
argument: (CommandMode) -> Result<T, CommandantError<ClientError>>
) -> Result<T, CommandantError<ClientError>> {
return argument(mode)
}
| mit |
ricardorachaus/pingaudio | Pingaudio/Pingaudio/PAAudioManager.swift | 1 | 1490 | //
// PAAudioManager.swift
// Pingaudio
//
// Created by Rachaus on 31/05/17.
// Copyright © 2017 Rachaus. All rights reserved.
//
import AVFoundation
public class PAAudioManager: PAAudioManagerDelegate {
var exporter: PAExporter!
init() {
exporter = PAExporter()
}
public func merge(audios: [PAAudio], completion: @escaping (_ output: URL?) -> Void) {
let composition = AVMutableComposition()
var time = kCMTimeZero
for audio in audios {
let asset = AVAsset(url: audio.path)
PAAudioManager.add(asset: asset, ofType: AVMediaTypeAudio, to: composition, at: time)
time = CMTimeAdd(time, asset.duration)
}
exporter.export(composition: composition) { (output: URL?) -> Void in
if let result = output {
completion(result)
} else {
completion(nil)
}
}
}
static func add(asset: AVAsset, ofType type: String, to composition: AVMutableComposition, at time: CMTime) {
let track = composition.addMutableTrack(withMediaType: type, preferredTrackID: kCMPersistentTrackID_Invalid)
let assetTrack = asset.tracks(withMediaType: type).first!
do {
try track.insertTimeRange(CMTimeRange(start: kCMTimeZero, duration: asset.duration), of: assetTrack, at: time)
} catch _ {
print("falha ao adicionar track a composition")
}
}
}
| mit |
airspeedswift/swift-compiler-crashes | crashes-fuzzing/00887-swift-archetypebuilder-resolvearchetype.swift | 1 | 321 | // 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 m<u {
{
}
{
{
}
}
{
}
{
}
class n
class e: n {
{
}
{
}
{
}
class d<c {
init(b: c) {
class A {
" " {
{
{
}
}
}
{
}
enum S {
func f<T> ( ) -> T -> T
| mit |
buyiyang/iosstar | iOSStar/Other/AppDelegate.swift | 3 | 13935 | //
// AppDelegate.swift
// iosblackcard
//
// Created by J-bb on 17/4/13.
// Copyright © 2017年 YunDian. All rights reserved.
//
import UIKit
import Fabric
import Crashlytics
import UserNotifications
import RealmSwift
import Alamofire
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate ,WXApiDelegate,GeTuiSdkDelegate,UNUserNotificationCenterDelegate{
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
AppConfigHelper.shared().registerServers()
// 个推
let mediaType = AVMediaTypeVideo
AVCaptureDevice.requestAccess(forMediaType: mediaType) { (result) in
}
let videoType = AVMediaTypeAudio
AVCaptureDevice.requestAccess(forMediaType: videoType) { (result) in
}
AppConfigHelper.shared().setupGeTuiSDK(sdkDelegate: self)
UIApplication.shared.statusBarStyle = .default
return true
}
func applicationWillResignActive(_ application: UIApplication) {
}
func applicationDidEnterBackground(_ application: UIApplication) {
}
func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
if (url.host == "safepay") {
AlipaySDK.defaultService().processOrder(withPaymentResult: url, standbyCallback: { (result) in
if let dataDic = result as? [String : AnyObject] {
NotificationCenter.default.post(name: NSNotification.Name(rawValue: AppConst.aliPay.aliPayCode), object:(Int.init((dataDic["resultStatus"] as! String))), userInfo:nil)
}
})
}else{
WXApi.handleOpen(url, delegate: self)
}
return true
}
func application(_ application: UIApplication, handleOpen url: URL) -> Bool {
WXApi.handleOpen(url, delegate: self)
return true
}
func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {
if (url.host == "safepay") {
AlipaySDK.defaultService().processOrder(withPaymentResult: url, standbyCallback: { (result) in
if let dataDic = result as? [String : AnyObject]{
NotificationCenter.default.post(name: NSNotification.Name(rawValue: AppConst.aliPay.aliPayCode), object:(Int.init((dataDic["resultStatus"] as! String))), userInfo:nil)
}
})
}
else {
WXApi.handleOpen(url, delegate: self)
}
return true
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
// 支付返回
func onResp(_ resp: BaseResp!) {
//微信登录返回
if resp.isKind(of: SendAuthResp.classForCoder()) {
let authResp:SendAuthResp = resp as! SendAuthResp
if authResp.errCode == 0{
accessToken(code: authResp.code)
}
return
}
else{
if resp.isKind(of: PayResp.classForCoder()) {
let authResp:PayResp = resp as! PayResp
NotificationCenter.default.post(name: NSNotification.Name(rawValue: AppConst.WechatPay.WechatKeyErrorCode), object: NSNumber.init(value: authResp.errCode), userInfo:nil)
return
}
}
}
func accessToken(code: String)
{
let param = [SocketConst.Key.appid : AppConst.WechatKey.Appid,
"code" : code,
SocketConst.Key.secret : AppConst.WechatKey.Secret,
SocketConst.Key.grant_type : "authorization_code"]
Alamofire.request(AppConst.WechatKey.AccessTokenUrl, method: .get, parameters: param).responseJSON { [weak self](result) in
if let resultJson = result.result.value as? [String: AnyObject] {
if let errCode = resultJson["errcode"] as? Int{
print(errCode)
}
if let access_token = resultJson[SocketConst.Key.accessToken] as? String {
if let openid = resultJson[SocketConst.Key.openid] as? String{
self?.wechatUserInfo(token: access_token, openid: openid)
}
}
}
}
}
func wechatUserInfo(token: String, openid: String)
{
let param = [SocketConst.Key.accessToken : token,
SocketConst.Key.openid : openid]
Alamofire.request(AppConst.WechatKey.wechetUserInfo, method: .get, parameters: param).responseJSON {(result) in
guard let resultJson = result.result.value as? [String: AnyObject] else{return}
if let errCode = resultJson["errcode"] as? Int{
print(errCode)
}
if let nickname = resultJson[SocketConst.Key.nickname] as? String {
ShareDataModel.share().wechatUserInfo[SocketConst.Key.nickname] = nickname
}
if let openid = resultJson[SocketConst.Key.openid] as? String{
ShareDataModel.share().wechatUserInfo[SocketConst.Key.openid] = openid
}
if let headimgurl = resultJson[SocketConst.Key.headimgurl] as? String{
ShareDataModel.share().wechatUserInfo[SocketConst.Key.headimgurl] = headimgurl
}
NotificationCenter.default.post(name: NSNotification.Name(rawValue: AppConst.WechatKey.ErrorCode), object: nil, userInfo:nil)
}
}
// MARK: - 远程通知(推送)回调
/** 远程通知注册成功委托 */
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
let deviceToken_ns = NSData.init(data: deviceToken); // 转换成NSData类型
var token = deviceToken_ns.description.trimmingCharacters(in: CharacterSet(charactersIn: "<>"));
token = token.replacingOccurrences(of: " ", with: "")
UserDefaults.standard.setValue(token, forKey: AppConst.Text.deviceToken)
print(token)
// [ GTSdk ]:向个推服务器注册deviceToken
GeTuiSdk.registerDeviceToken(token);
// 向云信服务注册deviceToken
NIMSDK.shared().updateApnsToken(deviceToken)
}
/** 远程通知注册失败委托 */
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
print("\n>>>[DeviceToken Error]:%@\n\n",error.localizedDescription);
}
func application(_ application: UIApplication, performFetchWithCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
// 唤醒
GeTuiSdk.resume()
completionHandler(UIBackgroundFetchResult.newData)
}
// MARK: - APP运行中接收到通知(推送)处理 - iOS 10 以下
/** APP已经接收到“远程”通知(推送) - (App运行在后台) */
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
application.applicationIconBadgeNumber = 0; // 标签
let vc = UIStoryboard.init(name: "Exchange", bundle: nil).instantiateViewController(withIdentifier: "SystemMessageVC")
let nav = UINavigationController.init(rootViewController: vc)
UIApplication.shared.keyWindow?.rootViewController?.present(nav, animated: true, completion: nil)
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
let vc = UIStoryboard.init(name: "Exchange", bundle: nil).instantiateViewController(withIdentifier: "SystemMessageVC")
let nav = UINavigationController.init(rootViewController: vc)
UIApplication.shared.keyWindow?.rootViewController?.present(nav, animated: true, completion: nil)
// [ GTSdk ]:将收到的APNs信息传给个推统计
GeTuiSdk.handleRemoteNotification(userInfo);
NSLog("\n>>>[Receive RemoteNotification]:%@\n\n",userInfo);
completionHandler(UIBackgroundFetchResult.newData);
}
@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
print("willPresentNotification: %@",notification.request.content.userInfo);
completionHandler([.badge,.sound,.alert]);
}
@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
// 此处接收到通知的userInfo
print("didReceiveNotificationResponse: %@",response.notification.request.content.userInfo);
UIApplication.shared.applicationIconBadgeNumber = 0;
// [ GTSdk ]:将收到的APNs信息传给个推统计
GeTuiSdk.handleRemoteNotification(response.notification.request.content.userInfo);
completionHandler();
}
// MARK: - GeTuiSdkDelegate
/** SDK启动成功返回cid */
func geTuiSdkDidRegisterClient(_ clientId: String!) {
// [4-EXT-1]: 个推SDK已注册,返回clientId
NSLog("\n>>>[GeTuiSdk RegisterClient]:%@\n\n", clientId);
}
/** SDK遇到错误回调 */
func geTuiSdkDidOccurError(_ error: Error!) {
// [EXT]:个推错误报告,集成步骤发生的任何错误都在这里通知,如果集成后,无法正常收到消息,查看这里的通知。
NSLog("\n>>>[GeTuiSdk error]:%@\n\n", error.localizedDescription);
}
/** SDK收到sendMessage消息回调 */
func geTuiSdkDidSendMessage(_ messageId: String!, result: Int32) {
// [4-EXT]:发送上行消息结果反馈
let msg:String = "sendmessage=\(messageId),result=\(result)";
NSLog("\n>>>[GeTuiSdk DidSendMessage]:%@\n\n",msg);
}
/** SDK收到透传消息回调 */
func geTuiSdkDidReceivePayloadData(_ payloadData: Data!, andTaskId taskId: String!, andMsgId msgId: String!, andOffLine offLine: Bool, fromGtAppId appId: String!) {
if((payloadData) != nil) {
if let msgDic = try? JSONSerialization.jsonObject(with: payloadData, options: .mutableContainers) as? NSDictionary{
if let starId = msgDic?["starId"] as? String{
if offLine{
self.geTuiPushStar(starId)
}else{
let alertView: TradingAlertView = Bundle.main.loadNibNamed("TradingAlertView", owner: nil, options: nil)?.first as! TradingAlertView
alertView.str = "有最新明星消息,请点击查看。"
alertView.showAlertView()
alertView.messageAction = {
self.geTuiPushStar(starId)
}
}
}
}
}
}
func geTuiPushStar(_ starId: String){
let param = StarRealtimeRequestModel()
param.starcode = starId
AppAPIHelper.marketAPI().requestStarRealTime(requestModel: param, complete: { (response) in
if let model = response as? StarSortListModel{
if model.pushlish_type == 0 || model.pushlish_type == 1{
if let controller = UIStoryboard.init(name: "Discover", bundle: nil).instantiateViewController(withIdentifier: "SellingViewController") as? SellingViewController{
controller.starModel = model
let nav = BaseNavigationController.init(rootViewController: controller)
UIApplication.shared.keyWindow?.rootViewController?.present(nav, animated: true, completion: nil)
}
}else{
if let controller = UIStoryboard.init(name: "Heat", bundle: nil).instantiateViewController(withIdentifier: "HeatDetailViewController") as? HeatDetailViewController{
let nav = BaseNavigationController.init(rootViewController: controller)
controller.starListModel = model
UIApplication.shared.keyWindow?.rootViewController?.present(nav, animated: true, completion: nil)
}
}
}
}, error: nil)
}
func geTuiSdkDidAliasAction(_ action: String!, result isSuccess: Bool, sequenceNum aSn: String!, error aError: Error!) {
if action == kGtResponseBindType{
if isSuccess {
print("绑定成功")
}else{
print(aError)
}
}
}
//
}
| gpl-3.0 |
Fenrikur/ef-app_ios | Eurofurence/Modules/Knowledge Groups/View/Abstraction/KnowledgeGroupScene.swift | 1 | 240 | import Foundation
protocol KnowledgeGroupScene {
func setKnowledgeGroupTitle(_ title: String)
func setKnowledgeGroupFontAwesomeCharacter(_ character: Character)
func setKnowledgeGroupDescription(_ groupDescription: String)
}
| mit |
jeevanRao7/Swift_Playgrounds | Swift Playgrounds/Design Patterns/Template Method.playground/Contents.swift | 1 | 1588 | /*
*********************************
Template Pattern
Reference : http://www.oodesign.com/template-method-pattern.html
Problem Statement : An app contains 2 screens. Each screen has got same header and footer design. Only screen content designed in individual screens.
********************************
*/
//Interface
protocol ScreenTemplate {
//Abstract method
func createContent()
}
//Abstract class
class AbstractScreenTemplate: ScreenTemplate {
func makeScreen() {
self.createHeader();
self.createContent();
self.createFooter();
}
func createContent() {
assertionFailure("Your Class must implement `createContent` method! ")
}
private func createHeader() {
print("Common Header Created")
}
private func createFooter() {
print("Common Footer Created \n")
}
}
//Concrete Class 1
class FirstScreen : AbstractScreenTemplate {
func loadFirstScreen() {
super.makeScreen();
}
override func createContent() {
print("First Screen Specific Content.");
}
}
//Concrete Class 2
class SecondScreen : AbstractScreenTemplate {
func loadSecondScreen() {
super.makeScreen();
}
override func createContent() {
print("Second Screen Specific Content.");
}
}
/* Main */
//Will create class `FirstScreen` level content along with common Header and Footer contents.
FirstScreen().loadFirstScreen();
//Do the same for 'SecondScreen' & So on...
SecondScreen().loadSecondScreen();
| mit |
dkarsh/SwiftGoal | Carthage/Checkouts/Argo/ArgoTests/Models/NSURL.swift | 20 | 351 | import Argo
import Foundation
extension NSURL: Decodable {
public typealias DecodedType = NSURL
public class func decode(j: JSON) -> Decoded<NSURL> {
switch j {
case .String(let urlString):
return NSURL(string: urlString).map(pure) ?? .typeMismatch("URL", actual: j)
default: return .typeMismatch("URL", actual: j)
}
}
}
| mit |
lllyyy/LY | U17-master/U17/Pods/Then/Sources/Then/Then.swift | 6 | 2692 | // The MIT License (MIT)
//
// Copyright (c) 2015 Suyeol Jeon (xoul.kr)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import Foundation
import CoreGraphics
#if os(iOS) || os(tvOS)
import UIKit.UIGeometry
#endif
public protocol Then {}
extension Then where Self: Any {
/// Makes it available to set properties with closures just after initializing and copying the value types.
///
/// let frame = CGRect().with {
/// $0.origin.x = 10
/// $0.size.width = 100
/// }
public func with(_ block: (inout Self) throws -> Void) rethrows -> Self {
var copy = self
try block(©)
return copy
}
/// Makes it available to execute something with closures.
///
/// UserDefaults.standard.do {
/// $0.set("devxoul", forKey: "username")
/// $0.set("devxoul@gmail.com", forKey: "email")
/// $0.synchronize()
/// }
public func `do`(_ block: (Self) throws -> Void) rethrows {
try block(self)
}
}
extension Then where Self: AnyObject {
/// Makes it available to set properties with closures just after initializing.
///
/// let label = UILabel().then {
/// $0.textAlignment = .Center
/// $0.textColor = UIColor.blackColor()
/// $0.text = "Hello, World!"
/// }
public func then(_ block: (Self) throws -> Void) rethrows -> Self {
try block(self)
return self
}
}
extension NSObject: Then {}
extension CGPoint: Then {}
extension CGRect: Then {}
extension CGSize: Then {}
extension CGVector: Then {}
#if os(iOS) || os(tvOS)
extension UIEdgeInsets: Then {}
extension UIOffset: Then {}
extension UIRectEdge: Then {}
#endif
| mit |
suzuki-0000/HoneycombView | HoneycombView/HoneycombPhoto.swift | 1 | 582 | //
// HoneycombPhoto.swift
// HoneycombViewExample
//
// Created by suzuki_keishi on 2015/10/01.
// Copyright © 2015 suzuki_keishi. All rights reserved.
//
import UIKit
// MARK: - HoneycombPhoto
public class HoneycombPhoto:NSObject {
var underlyingImage:UIImage!
override init() {
super.init()
}
convenience init(image: UIImage){
self.init()
underlyingImage = image
}
// MARK: - class func
class func photoWithImage(image: UIImage) -> HoneycombPhoto {
return HoneycombPhoto(image: image)
}
} | mit |
yonaskolb/SwagGen | Specs/PetstoreTest/generated/Swift/Sources/Requests/Pet/DeletePet.swift | 1 | 3302 | //
// Generated by SwagGen
// https://github.com/yonaskolb/SwagGen
//
import Foundation
extension PetstoreTest.Pet {
/** Deletes a pet */
public enum DeletePet {
public static let service = APIService<Response>(id: "deletePet", tag: "pet", method: "DELETE", path: "/pet/{petId}", hasBody: false, securityRequirements: [SecurityRequirement(type: "petstore_auth", scopes: ["write:pets", "read:pets"])])
public final class Request: APIRequest<Response> {
public struct Options {
public var apiKey: String?
/** Pet id to delete */
public var petId: Int
public init(apiKey: String? = nil, petId: Int) {
self.apiKey = apiKey
self.petId = petId
}
}
public var options: Options
public init(options: Options) {
self.options = options
super.init(service: DeletePet.service)
}
/// convenience initialiser so an Option doesn't have to be created
public convenience init(apiKey: String? = nil, petId: Int) {
let options = Options(apiKey: apiKey, petId: petId)
self.init(options: options)
}
public override var path: String {
return super.path.replacingOccurrences(of: "{" + "petId" + "}", with: "\(self.options.petId)")
}
override var headerParameters: [String: String] {
var headers: [String: String] = [:]
if let apiKey = options.apiKey {
headers["api_key"] = apiKey
}
return headers
}
}
public enum Response: APIResponseValue, CustomStringConvertible, CustomDebugStringConvertible {
public typealias SuccessType = Void
/** Invalid pet value */
case status400
public var success: Void? {
switch self {
default: return nil
}
}
public var response: Any {
switch self {
default: return ()
}
}
public var statusCode: Int {
switch self {
case .status400: return 400
}
}
public var successful: Bool {
switch self {
case .status400: return false
}
}
public init(statusCode: Int, data: Data, decoder: ResponseDecoder) throws {
switch statusCode {
case 400: self = .status400
default: throw APIClientError.unexpectedStatusCode(statusCode: statusCode, data: data)
}
}
public var description: String {
return "\(statusCode) \(successful ? "success" : "failure")"
}
public var debugDescription: String {
var string = description
let responseString = "\(response)"
if responseString != "()" {
string += "\n\(responseString)"
}
return string
}
}
}
}
| mit |
wchen02/Swift-2.0-learning-app | test/SearchResultsViewController.swift | 1 | 5781 | //
// SearchResultsViewController.swift
// test
//
// Created by nluo on 5/14/15.
// Copyright (c) 2015 nluo. All rights reserved.
//
import UIKit
import GoogleMobileAds
class SearchResultsViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, APIControllerProtocol, UISearchBarDelegate {
var api : APIController!
@IBOutlet var appsTableView: UITableView!
@IBOutlet weak var searchBar: UISearchBar!
@IBOutlet weak var menuButton: UIBarButtonItem!
var interstitial: GADInterstitial?
var albums = [Album]()
let kCellIdentifier: String = "SearchResultCell"
var imageCache = [String:UIImage]()
override func viewDidLoad() {
print("view did load")
super.viewDidLoad()
interstitial = DFPInterstitial(adUnitID: "/6499/example/interstitial")
let request = DFPRequest()
request.testDevices = [ kGADSimulatorID ];
interstitial!.loadRequest(request)
// Do any additional setup after loading the view, typically from a nib.
api = APIController(delegate: self)
searchBar.delegate = self
if self.revealViewController() != nil {
menuButton.target = self.revealViewController()
menuButton.action = "revealToggle:"
self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer())
}
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
api.searchItunesFor("Lady Gaga")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.albums.count;
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: UITableViewCell = tableView.dequeueReusableCellWithIdentifier(kCellIdentifier)!
let album: Album = self.albums[indexPath.row]
// Get the formatted price string for display in the subtitle
cell.detailTextLabel?.text = album.price
// Update the textLabel text to use the title from the Album model
cell.textLabel?.text = album.title
// Start by setting the cell's image to a static file
// Without this, we will end up without an image view!
cell.imageView?.image = UIImage(named: "Blank52")
let thumbnailURLString = album.thumbnailImageURL
let thumbnailURL = NSURL(string: thumbnailURLString)!
// If this image is already cached, don't re-download
if let img = imageCache[thumbnailURLString] {
cell.imageView?.image = img
}
else {
// The image isn't cached, download the img data
// We should perform this in a background thread
let request: NSURLRequest = NSURLRequest(URL: thumbnailURL)
let mainQueue = NSOperationQueue.mainQueue()
NSURLConnection.sendAsynchronousRequest(request, queue: mainQueue, completionHandler: { (response, data, error) -> Void in
if error == nil {
// Convert the downloaded data in to a UIImage object
let image = UIImage(data: data!)
// Store the image in to our cache
self.imageCache[thumbnailURLString] = image
// Update the cell
dispatch_async(dispatch_get_main_queue(), {
if let cellToUpdate = tableView.cellForRowAtIndexPath(indexPath) {
cellToUpdate.imageView?.image = image
}
})
}
else {
print("Error: \(error!.localizedDescription)")
}
})
}
return cell
}
func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
cell.layer.transform = CATransform3DMakeScale(0.1,0.1,1)
UIView.animateWithDuration(0.25, animations: {
cell.layer.transform = CATransform3DMakeScale(1,1,1)
})
}
func didReceiveAPIResults(results: NSArray) {
dispatch_async(dispatch_get_main_queue(), {
self.albums = Album.albumsWithJSON(results)
self.appsTableView!.reloadData()
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
})
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if (interstitial!.isReady) {
interstitial!.presentFromRootViewController(self)
}
if let detailsViewController: DetailsViewController = segue.destinationViewController as? DetailsViewController {
let albumIndex = appsTableView!.indexPathForSelectedRow!.row
let selectedAlbum = self.albums[albumIndex]
detailsViewController.album = selectedAlbum
}
}
//func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
func searchBarSearchButtonClicked(searchBar: UISearchBar) {
self.filterContentForSearchText(searchBar.text!)
}
func filterContentForSearchText(searchText: String) {
// Filter the array using the filter method
api.searchItunesFor(searchText)
}
func searchBar(searchBar: UISearchBar, selectedScopeButtonIndexDidChange selectedScope: Int) {
let scope = searchBar.scopeButtonTitles as [String]!
api.searchItunesFor(scope[selectedScope])
}
}
| mit |
Kijjakarn/Crease-Pattern-Analyzer | CreasePatternAnalyzer/main.swift | 1 | 314 | //
// main.swift
// CreasePatternAnalyzer
//
// Created by Kijjakarn Praditukrit on 8/8/17.
// Copyright © 2017 Kijjakarn Praditukrit. All rights reserved.
//
import Cocoa
let delegate = AppDelegate()
NSApplication.shared.delegate = delegate
_ = NSApplicationMain(CommandLine.argc, CommandLine.unsafeArgv)
| gpl-3.0 |
KeithPiTsui/Pavers | Pavers/Sources/FRP/Functional/Types/String+Functional.swift | 2 | 199 | extension String: Semigroup {
public func op(_ other: String) -> String {
return self + other
}
}
extension String: Monoid {
public static func identity() -> String {
return ""
}
}
| mit |
CCHSCodingClub/GameLib | GameLib/Game.swift | 1 | 1734 | //
// Game.swift
// GameLib
//
// The MIT License (MIT)
//
// Copyright (c) 2015 CCHS Coding Club
//
// 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
/// A game.
public class Game {
/// The game's player.
public let player: Player
/// The game's levels.
public let levels: [Level]
public init(player: Player, levels: [Level]) {
self.player = player
self.levels = levels
}
/// Runs the game and plays through each of the levels.
public func play() -> Bool {
for level in levels {
guard level.play(player) else {
return false
}
}
return true
}
}
| mit |
emlai/LLVM.swift | Package.swift | 1 | 181 | import PackageDescription
let package = Package(
name: "LLVM",
dependencies: [
.Package(url: "https://github.com/rxwei/LLVM_C", majorVersion: 2, minor: 0),
]
)
| mit |
haskellswift/swift-package-manager | Fixtures/ModuleMaps/Transitive/packageB/Package.swift | 2 | 850 | /**
* Copyright IBM Corporation 2016
* Copyright 2015 - 2016 Apple Inc. and the Swift project authors
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
import PackageDescription
let package = Package(
name: "packageB",
targets: [ Target(name: "y")],
dependencies: [
.Package(url: "../packageC", majorVersion: 1)
])
| apache-2.0 |
nahive/spotify-notify | SpotifyNotify/Models/NotificationViewModel.swift | 1 | 2201 | //
// Notification.swift
// SpotifyNotify
//
// Created by Paul Williamson on 07/03/2019.
// Copyright © 2019 Szymon Maślanka. All rights reserved.
//
import Foundation
/// A notification view model for setting up a notification
struct NotificationViewModel {
let identifier = NSUUID().uuidString
let title: String
let subtitle: String
let body: String
let artworkURL: URL?
/// Defaults to show if, for any reason, Spotify returns nil
private let unknownArtist = "Unknown Artist"
private let unknownAlbum = "Unknown Album"
private let unknownTrack = "Unknown Track"
init(track: Track, showSongProgress: Bool, songProgress: Double?) {
func progress(for track: Track) -> String {
guard let songProgress = songProgress, let duration = track.duration else {
return "00:00/00:00"
}
let percentage = songProgress / (Double(duration) / 1000.0)
let progressMax = 14
let currentProgress = Int(Double(progressMax) * percentage)
let progressString = "▪︎".repeated(currentProgress) + "⁃".repeated(progressMax - currentProgress)
let now = Int(songProgress).minutesSeconds
let length = (duration / 1000).minutesSeconds
let nowS = "\(now.minutes)".withLeadingZeroes + ":" + "\(now.seconds)".withLeadingZeroes
let lengthS = "\(length.minutes)".withLeadingZeroes + ":" + "\(length.seconds)".withLeadingZeroes
return "\(nowS) \(progressString) \(lengthS)"
}
let name = track.name ?? unknownTrack
let artist = track.artist ?? unknownArtist
let album = track.album ?? unknownAlbum
title = name
subtitle = showSongProgress ? "\(artist) - \(album)" : artist
body = showSongProgress ? progress(for: track) : album
artworkURL = track.artworkURL
}
}
private extension Int {
var minutesSeconds: (minutes: Int, seconds: Int) {
((self % 3600) / 60, (self % 3600) % 60)
}
}
private extension String {
func repeated(_ count: Int) -> String {
String(repeating: self, count: count)
}
}
| unlicense |
emilstahl/swift | validation-test/compiler_crashers_fixed/1200-swift-constraints-constraintsystem-gettypeofmemberreference.swift | 13 | 341 | // 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
class d<c>: NSObject {
init(b: c) {
class A {
class func a() -> String {
}
convenience init<T>(array: Array<T>) { self.init()
| apache-2.0 |
RocketChat/Rocket.Chat.iOS | Rocket.Chat/Models/Message/Channel.swift | 1 | 247 | //
// Channel.swift
// Rocket.Chat
//
// Created by Matheus Cardoso on 9/8/17.
// Copyright © 2017 Rocket.Chat. All rights reserved.
//
import Foundation
import RealmSwift
final class Channel: Object {
@objc dynamic var name: String?
}
| mit |
alickbass/ViewComponents | ViewComponentsTests/TestCALayerBorderStyle.swift | 1 | 1600 | //
// TestCALayerBorderStyle.swift
// ViewComponents
//
// Created by Oleksii on 10/05/2017.
// Copyright © 2017 WeAreReasonablePeople. All rights reserved.
//
import XCTest
@testable import ViewComponents
class TestCALayerBorderStyle: XCTestCase, ViewTestType {
static let allStyles: [AnyStyle<UIView>] = [
.border(cornerRadius: 12, width: 12, color: nil),
.border(cornerRadius: 12, width: 12, color: .red)
]
static var previousHashes: [Int : Any] { return TestCALayerShadowStyle.accumulatedHashes }
func testLayerBorderHashable() {
let border = LayerBorder(cornerRadius: 12, width: 12, color: nil)
XCTAssertEqual(border, border)
XCTAssertEqual(border.hashValue, border.hashValue)
XCTAssertNotEqual(LayerBorder(cornerRadius: 12, width: 12, color: .red).hashValue, border.hashValue)
}
func testAnyStyleSideEffects() {
let view = UIView()
AnyStyle<UIView>.border(cornerRadius: 12, width: 12, color: .red).sideEffect(on: view)
XCTAssertEqual(view.layer.cornerRadius, 12)
XCTAssertEqual(view.layer.borderWidth, 12)
XCTAssertEqual(view.layer.borderColor, UIColor.red.cgColor)
let layer = CALayer()
AnyStyle<CALayer>.border(cornerRadius: 12, width: 12, color: .red).sideEffect(on: layer)
XCTAssertEqual(layer.cornerRadius, 12)
XCTAssertEqual(layer.borderWidth, 12)
XCTAssertEqual(layer.borderColor, UIColor.red.cgColor)
}
func testHashValue() {
testAccumulatingHashes()
}
}
| mit |
ben-ng/swift | validation-test/compiler_crashers_fixed/00448-no-stacktrace.swift | 1 | 505 | // 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
import CoreData
extension NSSet {
let v: C {
for b : Int -> S((array: P {
}
}
convenience init(array: H) {
| apache-2.0 |
ben-ng/swift | validation-test/compiler_crashers_fixed/02019-swift-protocoltype-canonicalizeprotocols.swift | 1 | 632 | // 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
override func f<T? {
class A : Any, AnyObject) {
}
class d: A, let t: e?
let g : Int -> {
}
}
protocol a {
func ^(f: A {
return { self.Type) -> {
}
extension Array {
}
}
}
func a(a((s(t: Range(s() -> {
}
}
protocol a {
}
protocol A {
| apache-2.0 |
ben-ng/swift | test/SILGen/init_ref_delegation.swift | 1 | 8663 | // RUN: %target-swift-frontend -emit-silgen %s -disable-objc-attr-requires-foundation-module | %FileCheck %s
struct X { }
// Initializer delegation within a struct.
struct S {
// CHECK-LABEL: sil hidden @_TFV19init_ref_delegation1SC{{.*}} : $@convention(method) (@thin S.Type) -> S {
init() {
// CHECK: bb0([[SELF_META:%[0-9]+]] : $@thin S.Type):
// CHECK-NEXT: [[SELF_BOX:%[0-9]+]] = alloc_box $<τ_0_0> { var τ_0_0 } <S>
// CHECK-NEXT: [[PB:%.*]] = project_box [[SELF_BOX]]
// CHECK-NEXT: [[SELF:%[0-9]+]] = mark_uninitialized [delegatingself] [[PB]] : $*S
// CHECK: [[S_DELEG_INIT:%[0-9]+]] = function_ref @_TFV19init_ref_delegation1SC{{.*}} : $@convention(method) (X, @thin S.Type) -> S
// CHECK: [[X_CTOR:%[0-9]+]] = function_ref @_TFV19init_ref_delegation1XC{{.*}} : $@convention(method) (@thin X.Type) -> X
// CHECK-NEXT: [[X_META:%[0-9]+]] = metatype $@thin X.Type
// CHECK-NEXT: [[X:%[0-9]+]] = apply [[X_CTOR]]([[X_META]]) : $@convention(method) (@thin X.Type) -> X
// CHECK-NEXT: [[REPLACEMENT_SELF:%[0-9]+]] = apply [[S_DELEG_INIT]]([[X]], [[SELF_META]]) : $@convention(method) (X, @thin S.Type) -> S
self.init(x: X())
// CHECK-NEXT: assign [[REPLACEMENT_SELF]] to [[SELF]] : $*S
// CHECK-NEXT: [[SELF_BOX1:%[0-9]+]] = load [trivial] [[SELF]] : $*S
// CHECK-NEXT: destroy_value [[SELF_BOX]] : $<τ_0_0> { var τ_0_0 } <S>
// CHECK-NEXT: return [[SELF_BOX1]] : $S
}
init(x: X) { }
}
// Initializer delegation within an enum
enum E {
// We don't want the enum to be uninhabited
case Foo
// CHECK-LABEL: sil hidden @_TFO19init_ref_delegation1EC{{.*}} : $@convention(method) (@thin E.Type) -> E
init() {
// CHECK: bb0([[E_META:%[0-9]+]] : $@thin E.Type):
// CHECK: [[E_BOX:%[0-9]+]] = alloc_box $<τ_0_0> { var τ_0_0 } <E>
// CHECK: [[PB:%.*]] = project_box [[E_BOX]]
// CHECK: [[E_SELF:%[0-9]+]] = mark_uninitialized [delegatingself] [[PB]] : $*E
// CHECK: [[X_INIT:%[0-9]+]] = function_ref @_TFO19init_ref_delegation1EC{{.*}} : $@convention(method) (X, @thin E.Type) -> E
// CHECK: [[E_DELEG_INIT:%[0-9]+]] = function_ref @_TFV19init_ref_delegation1XC{{.*}} : $@convention(method) (@thin X.Type) -> X
// CHECK: [[X_META:%[0-9]+]] = metatype $@thin X.Type
// CHECK: [[X:%[0-9]+]] = apply [[E_DELEG_INIT]]([[X_META]]) : $@convention(method) (@thin X.Type) -> X
// CHECK: [[S:%[0-9]+]] = apply [[X_INIT]]([[X]], [[E_META]]) : $@convention(method) (X, @thin E.Type) -> E
// CHECK: assign [[S:%[0-9]+]] to [[E_SELF]] : $*E
// CHECK: [[E_BOX1:%[0-9]+]] = load [trivial] [[E_SELF]] : $*E
self.init(x: X())
// CHECK: destroy_value [[E_BOX]] : $<τ_0_0> { var τ_0_0 } <E>
// CHECK: return [[E_BOX1:%[0-9]+]] : $E
}
init(x: X) { }
}
// Initializer delegation to a generic initializer
struct S2 {
// CHECK-LABEL: sil hidden @_TFV19init_ref_delegation2S2C{{.*}} : $@convention(method) (@thin S2.Type) -> S2
init() {
// CHECK: bb0([[S2_META:%[0-9]+]] : $@thin S2.Type):
// CHECK: [[SELF_BOX:%[0-9]+]] = alloc_box $<τ_0_0> { var τ_0_0 } <S2>
// CHECK: [[PB:%.*]] = project_box [[SELF_BOX]]
// CHECK: [[SELF:%[0-9]+]] = mark_uninitialized [delegatingself] [[PB]] : $*S2
// CHECK: [[S2_DELEG_INIT:%[0-9]+]] = function_ref @_TFV19init_ref_delegation2S2C{{.*}} : $@convention(method) <τ_0_0> (@in τ_0_0, @thin S2.Type) -> S2
// CHECK: [[X_INIT:%[0-9]+]] = function_ref @_TFV19init_ref_delegation1XC{{.*}} : $@convention(method) (@thin X.Type) -> X
// CHECK: [[X_META:%[0-9]+]] = metatype $@thin X.Type
// CHECK: [[X:%[0-9]+]] = apply [[X_INIT]]([[X_META]]) : $@convention(method) (@thin X.Type) -> X
// CHECK: [[X_BOX:%[0-9]+]] = alloc_stack $X
// CHECK: store [[X]] to [trivial] [[X_BOX]] : $*X
// CHECK: [[SELF_BOX1:%[0-9]+]] = apply [[S2_DELEG_INIT]]<X>([[X_BOX]], [[S2_META]]) : $@convention(method) <τ_0_0> (@in τ_0_0, @thin S2.Type) -> S2
// CHECK: assign [[SELF_BOX1]] to [[SELF]] : $*S2
// CHECK: dealloc_stack [[X_BOX]] : $*X
// CHECK: [[SELF_BOX4:%[0-9]+]] = load [trivial] [[SELF]] : $*S2
self.init(t: X())
// CHECK: destroy_value [[SELF_BOX]] : $<τ_0_0> { var τ_0_0 } <S2>
// CHECK: return [[SELF_BOX4]] : $S2
}
init<T>(t: T) { }
}
class C1 {
var ivar: X
// CHECK-LABEL: sil hidden @_TFC19init_ref_delegation2C1c{{.*}} : $@convention(method) (X, @owned C1) -> @owned C1
convenience init(x: X) {
// CHECK: bb0([[X:%[0-9]+]] : $X, [[ORIG_SELF:%[0-9]+]] : $C1):
// CHECK: [[SELF_BOX:%[0-9]+]] = alloc_box $<τ_0_0> { var τ_0_0 } <C1>
// CHECK: [[PB:%.*]] = project_box [[SELF_BOX]]
// CHECK: [[SELF:%[0-9]+]] = mark_uninitialized [delegatingself] [[PB]] : $*C1
// CHECK: store [[ORIG_SELF]] to [init] [[SELF]] : $*C1
// CHECK: [[SELF_FROM_BOX:%[0-9]+]] = load_borrow [[SELF]] : $*C1
// CHECK: [[DELEG_INIT:%[0-9]+]] = class_method [[SELF_FROM_BOX]] : $C1, #C1.init!initializer.1 : (C1.Type) -> (X, X) -> C1 , $@convention(method) (X, X, @owned C1) -> @owned C1
// CHECK: [[SELFP:%[0-9]+]] = apply [[DELEG_INIT]]([[X]], [[X]], [[SELF_FROM_BOX]]) : $@convention(method) (X, X, @owned C1) -> @owned C1
// CHECK: store [[SELFP]] to [init] [[SELF]] : $*C1
// CHECK: [[SELFP:%[0-9]+]] = load [copy] [[SELF]] : $*C1
// CHECK: destroy_value [[SELF_BOX]] : $<τ_0_0> { var τ_0_0 } <C1>
// CHECK: return [[SELFP]] : $C1
self.init(x1: x, x2: x)
}
init(x1: X, x2: X) { ivar = x1 }
}
@objc class C2 {
var ivar: X
// CHECK-LABEL: sil hidden @_TFC19init_ref_delegation2C2c{{.*}} : $@convention(method) (X, @owned C2) -> @owned C2
convenience init(x: X) {
// CHECK: bb0([[X:%[0-9]+]] : $X, [[ORIG_SELF:%[0-9]+]] : $C2):
// CHECK: [[SELF_BOX:%[0-9]+]] = alloc_box $<τ_0_0> { var τ_0_0 } <C2>
// CHECK: [[PB:%.*]] = project_box [[SELF_BOX]]
// CHECK: [[UNINIT_SELF:%[0-9]+]] = mark_uninitialized [delegatingself] [[PB]] : $*C2
// CHECK: store [[ORIG_SELF]] to [init] [[UNINIT_SELF]] : $*C2
// SEMANTIC ARC TODO: Another case of us doing a borrow and passing
// something in @owned. I think we will need some special help for
// definite-initialization.
// CHECK: [[SELF:%[0-9]+]] = load_borrow [[UNINIT_SELF]] : $*C2
// CHECK: [[DELEG_INIT:%[0-9]+]] = class_method [[SELF]] : $C2, #C2.init!initializer.1 : (C2.Type) -> (X, X) -> C2 , $@convention(method) (X, X, @owned C2) -> @owned C2
// CHECK: [[REPLACE_SELF:%[0-9]+]] = apply [[DELEG_INIT]]([[X]], [[X]], [[SELF]]) : $@convention(method) (X, X, @owned C2) -> @owned C2
// CHECK: store [[REPLACE_SELF]] to [init] [[UNINIT_SELF]] : $*C2
// CHECK: [[VAR_15:%[0-9]+]] = load [copy] [[UNINIT_SELF]] : $*C2
// CHECK: destroy_value [[SELF_BOX]] : $<τ_0_0> { var τ_0_0 } <C2>
// CHECK: return [[VAR_15]] : $C2
self.init(x1: x, x2: x)
// CHECK-NOT: sil hidden @_TToFC19init_ref_delegation2C2c{{.*}} : $@convention(objc_method) (X, @owned C2) -> @owned C2 {
}
// CHECK-LABEL: sil hidden @_TFC19init_ref_delegation2C2C{{.*}} : $@convention(method) (X, X, @thick C2.Type) -> @owned C2 {
// CHECK-NOT: sil @_TToFC19init_ref_delegation2C2c{{.*}} : $@convention(objc_method) (X, X, @owned C2) -> @owned C2 {
init(x1: X, x2: X) { ivar = x1 }
}
var x: X = X()
class C3 {
var i: Int = 5
// CHECK-LABEL: sil hidden @_TFC19init_ref_delegation2C3c{{.*}} : $@convention(method) (@owned C3) -> @owned C3
convenience init() {
// CHECK: mark_uninitialized [delegatingself]
// CHECK-NOT: integer_literal
// CHECK: class_method [[SELF:%[0-9]+]] : $C3, #C3.init!initializer.1 : (C3.Type) -> (X) -> C3 , $@convention(method) (X, @owned C3) -> @owned C3
// CHECK-NOT: integer_literal
// CHECK: return
self.init(x: x)
}
init(x: X) { }
}
// Initializer delegation from a constructor defined in an extension.
class C4 { }
extension C4 {
convenience init(x1: X) {
self.init()
}
// CHECK: sil hidden @_TFC19init_ref_delegation2C4c{{.*}}
// CHECK: [[PEER:%[0-9]+]] = function_ref @_TFC19init_ref_delegation2C4c{{.*}}
// CHECK: apply [[PEER]]([[X:%[0-9]+]], [[OBJ:%[0-9]+]])
convenience init(x2: X) {
self.init(x1: x2)
}
}
// Initializer delegation to a constructor defined in a protocol extension.
protocol Pb {
init()
}
extension Pb {
init(d: Int) { }
}
class Sn : Pb {
required init() { }
convenience init(d3: Int) {
self.init(d: d3)
}
}
// Same as above but for a value type.
struct Cs : Pb {
init() { }
init(d3: Int) {
self.init(d: d3)
}
}
| apache-2.0 |
rcasanovan/Social-Feed | Social Feed/Social Feed/UI/Instagram Login/View/SFInstagramLoginView.swift | 1 | 2392 | //
// SFInstagramLoginView.swift
// Social Feed
//
// Created by Ricardo Casanova on 03/08/2017.
// Copyright © 2017 Social Feed. All rights reserved.
//
import UIKit
class SFInstagramLoginView: SFBaseView, UIWebViewDelegate {
//__ IBOutlets
@IBOutlet weak var loginWebView : UIWebView?
@IBOutlet weak var cancelButton : UIButton?
//__ Internal section
internal var delegate:SFInstagramLoginViewDelegate?
internal var viewModel:SFInstagramLoginViewModel? {
didSet {
//__ View model injection
//__ Use this code in order to inject all information to the view from view model
if ((viewModel?.instagramAuthUrl) != nil) {
configureLoginWebViewWith(viewModel: viewModel!)
}
}
}
override func awakeFromNib() {
super.awakeFromNib()
//__ Configure view
setupView()
}
//__ Method to setup the view
private func setupView() {
//__ Configure cancel button
cancelButton?.backgroundColor = UIColor.red
cancelButton?.setTitle(NSLocalizedString("log in cancel", comment: "login cancel action"), for: UIControlState.normal)
//__ Configure login web view
self.loginWebView?.delegate = self
self.loginWebView?.scrollView.bounces = false
}
//__ Method to start load request
public func configureLoginWebViewWith(viewModel: SFInstagramLoginViewModel) {
self.loginWebView?.loadRequest(NSURLRequest(url: viewModel.instagramAuthUrl! as URL) as URLRequest)
}
//__ Method to get the response from instagram login process
func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
delegate?.instagramLoginViewDelegateAuthenticationSuccess(url: request.url! as NSURL)
return true
}
//__ User actions
//__ Method to cancel login process
@IBAction func cancelButtonPressed(_ sender: UIButton) {
delegate?.instagramLoginViewDelegateCancel()
}
}
//__ View model class
class SFInstagramLoginViewModel: NSObject {
var instagramAuthUrl:NSURL? = nil
}
//__ Delegate method class
protocol SFInstagramLoginViewDelegate {
func instagramLoginViewDelegateCancel()
func instagramLoginViewDelegateAuthenticationSuccess(url: NSURL)
}
| apache-2.0 |
adrfer/swift | validation-test/compiler_crashers_fixed/27633-swift-inflightdiagnostic.swift | 4 | 307 | // 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
var b{class A{struct Q{class A{struct S{init()}}}}}class S<T{func a<h{func b<T where h.g=a{
| apache-2.0 |
adrfer/swift | test/decl/inherit/inherit.swift | 18 | 1297 | // RUN: %target-parse-verify-swift
class A { }
protocol P { }
// Duplicate inheritance
class B : A, A { } // expected-error{{duplicate inheritance from 'A'}}{{12-15=}}
// Duplicate inheritance from protocol
class B2 : P, P { } // expected-error{{duplicate inheritance from 'P'}}{{13-16=}}
// Multiple inheritance
class C : B, A { } // expected-error{{multiple inheritance from classes 'B' and 'A'}}
// Superclass in the wrong position
class D : P, A { } // expected-error{{superclass 'A' must appear first in the inheritance clause}}{{12-15=}}{{11-11=A, }}
// Struct inheriting a class
struct S : A { } // expected-error{{non-class type 'S' cannot inherit from class 'A'}}
// Protocol inheriting a class
protocol Q : A { } // expected-error{{non-class type 'Q' cannot inherit from class 'A'}}
// Extension inheriting a class
extension C : A { } // expected-error{{extension of type 'C' cannot inherit from class 'A'}}
class GenericBase<T> {}
class GenericSub<T> : GenericBase<T> {} // okay
class InheritGenericParam<T> : T {} // expected-error {{inheritance from non-protocol, non-class type 'T'}}
class InheritBody : T { // expected-error {{use of undeclared type 'T'}}
typealias T = A
}
class InheritBodyBad : fn { // expected-error {{use of undeclared type 'fn'}}
func fn() {}
}
| apache-2.0 |
adrfer/swift | validation-test/compiler_crashers_fixed/25847-emitsimpleassignment.swift | 13 | 223 | // RUN: %target-swift-frontend %s -emit-silgen
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
()=()
| apache-2.0 |
YasumasaSewake/cssButton | cssButton/cssButton.swift | 1 | 5536 | //
// cssButton.swift
// cssButton
//
// Created by sewakeyasumasa on 2016/05/01.
// Copyright © 2016年 Yasumasa Sewake. All rights reserved.
//
import Foundation
import UIKit
class cssButton : UIButton
{
private static let speed : CGFloat = 0.1
var annimationLayer : AnimationLayer = AnimationLayer()
var bottomLayer : BotLayer = BotLayer()
var _direction : Direction = .None
var _progress : CGFloat = 0
var _buttonStyle : Style = .FadeIn
var defaultColor : RGBA = RGBA( r:0.0, g:0.0, b:0.0, a:0.0)
private var _displayLink : CADisplayLink? = nil
required init?(coder aDecoder: NSCoder) {
super.init(coder:aDecoder)
self.layer.insertSublayer(annimationLayer, atIndex:1)
self.layer.insertSublayer(bottomLayer, atIndex:0)
// ここをコメントアウトして動かすとおおよそがわかるかも
self.layer.masksToBounds = true
// 基準の色として保存
self.titleLabel!.textColor!.getRed(&defaultColor.r, green:&defaultColor.g, blue:&defaultColor.b, alpha:&defaultColor.a)
_initDisplayLink()
}
override func layoutSubviews() {
super.layoutSubviews()
annimationLayer.frame = self.bounds
bottomLayer.frame = self.bounds
// 回転の時に必要(この処理がないと文字色が更新されなくなる)
self.setNeedsDisplay()
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?)
{
if nil != touches.first?.locationInView(self)
{
_transition( Direction.Normal )
}
}
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?)
{
if nil != touches.first?.locationInView(self)
{
_transition( Direction.Reverse )
}
}
override func drawRect(rect: CGRect)
{
super.drawRect(rect)
// タイトルカラーを変える
// ベースの色の調整
let p : CGFloat = _calcProgress(_progress)
let baseRgb : RGBA = RGBA(r:self.defaultColor.r - (self.defaultColor.r * p),
g:self.defaultColor.g - (self.defaultColor.g * p),
b:self.defaultColor.b - (self.defaultColor.b * p),
a:1)
let rgb : RGBA = self._getTextColor()
let goalRgb : RGBA = RGBA(r:rgb.r - (rgb.r * (1 - p)),
g:rgb.g - (rgb.g * (1 - p)),
b:rgb.b - (rgb.b * (1 - p)),
a:1)
let fixColor : UIColor = UIColor(red:baseRgb.r + goalRgb.r, green:baseRgb.g + goalRgb.g, blue:baseRgb.b + goalRgb.b, alpha:1)
self.titleLabel?.textColor = fixColor
}
func _getTextColor() -> RGBA
{
switch ( _buttonStyle )
{
case .FadeIn:
return ColorMap.white
case .FadeIn_Border:
return ColorMap.blue
case .Split_Vertical:
return ColorMap.blue
case .Split_Horizontal:
return ColorMap.blue
case .Slide_Upper:
return ColorMap.white
case .Slide_UpperLeft:
return ColorMap.white
case .Zoom:
return ColorMap.white
case .Spin:
return ColorMap.white
}
}
func _transition( direction : Direction )
{
self._direction = direction
_startDisplayLink()
}
func buttonStyle( style : Style )
{
_buttonStyle = style
annimationLayer.buttonStyle(style)
bottomLayer.buttonStyle(style)
}
//MARK:DisplayLink
private func _initDisplayLink()
{
self._displayLink = CADisplayLink.init(target:self, selector:#selector(cssButton._displayRefresh(_:)))
self._displayLink?.frameInterval = 1
self._displayLink?.addToRunLoop(NSRunLoop.currentRunLoop(), forMode:NSRunLoopCommonModes)
self._displayLink?.paused = true
}
private func _startDisplayLink()
{
self._displayLink?.paused = false
}
private func _stopDisplayLink()
{
self._displayLink?.paused = true
}
@objc private func _displayRefresh(displayLink:CADisplayLink)
{
var stop : Bool = false
if self._direction == .Normal
{
_progress += cssButton.speed
if _progress >= 1.0
{
_progress = 1.0
stop = true
}
}
else if self._direction == .Reverse
{
_progress -= cssButton.speed
if _progress <= 0.0
{
_progress = 0.0
stop = true
}
}
self.bottomLayer.progress = _progress
self.annimationLayer.progress = _calcProgress(_progress)
self.annimationLayer.setNeedsDisplay()
self.setNeedsDisplay()
switch ( _buttonStyle )
{
case .Split_Vertical:
bottomLayer.setNeedsDisplay()
case .Split_Horizontal:
bottomLayer.setNeedsDisplay()
case .Slide_Upper:
bottomLayer.setNeedsDisplay()
case .Slide_UpperLeft:
bottomLayer.setNeedsDisplay()
case .Zoom:
bottomLayer.setNeedsDisplay()
case .Spin:
bottomLayer.setNeedsDisplay()
default:
break;
}
if stop == true
{
_stopDisplayLink()
}
}
func _calcProgress( x : CGFloat ) -> CGFloat
{
let x1 : CGFloat = 0
let y1 : CGFloat = 0
let x2 : CGFloat = 0.4
let y2 : CGFloat = 0.7
let x3 : CGFloat = 1
let y3 : CGFloat = 1
let a : CGFloat = ((y1 - y2) * (x1 - x3) - (y1 - y3) * (x1 - x2)) / ((x1 - x2) * (x1 - x3) * (x2 - x3))
let b : CGFloat = (y1 - y2) / (x1 - x2) - a * (x1 + x2);
let c : CGFloat = y1 - a * x1 * x1 - b * x1;
let y : CGFloat = a * (x * x) + b * x + c
return y
}
} | mit |
KrishMunot/swift | test/Constraints/members.swift | 1 | 14892 | // RUN: %target-parse-verify-swift
import Swift
////
// Members of structs
////
struct X {
func f0(_ i: Int) -> X { }
func f1(_ i: Int) { }
mutating func f1(_ f: Float) { }
func f2<T>(_ x: T) -> T { }
}
struct Y<T> {
func f0(_: T) -> T {}
func f1<U>(_ x: U, y: T) -> (T, U) {}
}
var i : Int
var x : X
var yf : Y<Float>
func g0(_: (inout X) -> (Float) -> ()) {}
x.f0(i)
x.f0(i).f1(i)
g0(X.f1)
x.f0(x.f2(1))
x.f0(1).f2(i)
yf.f0(1)
yf.f1(i, y: 1)
// Members referenced from inside the struct
struct Z {
var i : Int
func getI() -> Int { return i }
mutating func incI() {}
func curried(_ x: Int) -> (Int) -> Int { return { y in x + y } }
subscript (k : Int) -> Int {
get {
return i + k
}
mutating
set {
i -= k
}
}
}
struct GZ<T> {
var i : T
func getI() -> T { return i }
func f1<U>(_ a: T, b: U) -> (T, U) {
return (a, b)
}
func f2() {
var f : Float
var t = f1(i, b: f)
f = t.1
var zi = Z.i; // expected-error{{instance member 'i' cannot be used on type 'Z'}}
var zj = Z.asdfasdf // expected-error {{type 'Z' has no member 'asdfasdf'}}
}
}
var z = Z(i: 0)
var getI = z.getI
var incI = z.incI // expected-error{{partial application of 'mutating'}}
var zi = z.getI()
var zcurried1 = z.curried
var zcurried2 = z.curried(0)
var zcurriedFull = z.curried(0)(1)
////
// Members of modules
////
// Module
Swift.print(3, terminator: "")
var format : String
format._splitFirstIf({ $0.isASCII })
////
// Unqualified references
////
////
// Members of literals
////
// FIXME: Crappy diagnostic
"foo".lower() // expected-error{{value of type 'String' has no member 'lower'}}
var tmp = "foo".debugDescription
////
// Members of enums
////
enum W {
case Omega
func foo(_ x: Int) {}
func curried(_ x: Int) -> (Int) -> () {}
}
var w = W.Omega
var foo = w.foo
var fooFull : () = w.foo(0)
var wcurried1 = w.curried
var wcurried2 = w.curried(0)
var wcurriedFull : () = w.curried(0)(1)
// Member of enum Type
func enumMetatypeMember(_ opt: Int?) {
opt.none // expected-error{{static member 'none' cannot be used on instance of type 'Int?'}}
}
////
// Nested types
////
// Reference a Type member. <rdar://problem/15034920>
class G<T> {
class In { // expected-error{{nested in generic type}}
class func foo() {}
}
}
func goo() {
G<Int>.In.foo()
}
////
// Members of archetypes
////
func id<T>(_ t: T) -> T { return t }
func doGetLogicValue<T : Boolean>(_ t: T) {
t.boolValue
}
protocol P {
init()
func bar(_ x: Int)
mutating func mut(_ x: Int)
static func tum()
}
extension P {
func returnSelfInstance() -> Self {
return self
}
func returnSelfOptionalInstance(_ b: Bool) -> Self? {
return b ? self : nil
}
func returnSelfIUOInstance(_ b: Bool) -> Self! {
return b ? self : nil
}
static func returnSelfStatic() -> Self {
return Self()
}
static func returnSelfOptionalStatic(_ b: Bool) -> Self? {
return b ? Self() : nil
}
static func returnSelfIUOStatic(_ b: Bool) -> Self! {
return b ? Self() : nil
}
}
protocol ClassP : class {
func bas(_ x: Int)
}
func generic<T: P>(_ t: T) {
var t = t
// Instance member of archetype
let _: Int -> () = id(t.bar)
let _: () = id(t.bar(0))
// Static member of archetype metatype
let _: () -> () = id(T.tum)
// Instance member of archetype metatype
let _: T -> Int -> () = id(T.bar)
let _: Int -> () = id(T.bar(t))
_ = t.mut // expected-error{{partial application of 'mutating' method is not allowed}}
_ = t.tum // expected-error{{static member 'tum' cannot be used on instance of type 'T'}}
// Instance member of extension returning Self)
let _: T -> () -> T = id(T.returnSelfInstance)
let _: () -> T = id(T.returnSelfInstance(t))
let _: T = id(T.returnSelfInstance(t)())
let _: () -> T = id(t.returnSelfInstance)
let _: T = id(t.returnSelfInstance())
let _: T -> Bool -> T? = id(T.returnSelfOptionalInstance)
let _: Bool -> T? = id(T.returnSelfOptionalInstance(t))
let _: T? = id(T.returnSelfOptionalInstance(t)(false))
let _: Bool -> T? = id(t.returnSelfOptionalInstance)
let _: T? = id(t.returnSelfOptionalInstance(true))
let _: T -> Bool -> T! = id(T.returnSelfIUOInstance)
let _: Bool -> T! = id(T.returnSelfIUOInstance(t))
let _: T! = id(T.returnSelfIUOInstance(t)(true))
let _: Bool -> T! = id(t.returnSelfIUOInstance)
let _: T! = id(t.returnSelfIUOInstance(true))
// Static member of extension returning Self)
let _: () -> T = id(T.returnSelfStatic)
let _: T = id(T.returnSelfStatic())
let _: Bool -> T? = id(T.returnSelfOptionalStatic)
let _: T? = id(T.returnSelfOptionalStatic(false))
let _: Bool -> T! = id(T.returnSelfIUOStatic)
let _: T! = id(T.returnSelfIUOStatic(true))
}
func genericClassP<T: ClassP>(_ t: T) {
// Instance member of archetype)
let _: Int -> () = id(t.bas)
let _: () = id(t.bas(0))
// Instance member of archetype metatype)
let _: T -> Int -> () = id(T.bas)
let _: Int -> () = id(T.bas(t))
let _: () = id(T.bas(t)(1))
}
////
// Members of existentials
////
func existential(_ p: P) {
var p = p
// Fully applied mutating method
p.mut(1)
_ = p.mut // expected-error{{partial application of 'mutating' method is not allowed}}
// Instance member of existential)
let _: Int -> () = id(p.bar)
let _: () = id(p.bar(0))
// Static member of existential metatype)
let _: () -> () = id(p.dynamicType.tum)
// Instance member of extension returning Self
let _: () -> P = id(p.returnSelfInstance)
let _: P = id(p.returnSelfInstance())
let _: P? = id(p.returnSelfOptionalInstance(true))
let _: P! = id(p.returnSelfIUOInstance(true))
}
func staticExistential(_ p: P.Type, pp: P.Protocol) {
let ppp: P = p.init()
_ = pp.init() // expected-error{{value of type 'P.Protocol' is a protocol; it cannot be instantiated}}
_ = P() // expected-error{{protocol type 'P' cannot be instantiated}}
// Instance member of metatype
let _: P -> Int -> () = P.bar
let _: Int -> () = P.bar(ppp)
P.bar(ppp)(5)
// Instance member of metatype value
let _: P -> Int -> () = pp.bar
let _: Int -> () = pp.bar(ppp)
pp.bar(ppp)(5)
// Static member of existential metatype value
let _: () -> () = p.tum
// Instance member of existential metatype -- not allowed
_ = p.bar // expected-error{{instance member 'bar' cannot be used on type 'P'}}
_ = p.mut // expected-error{{instance member 'mut' cannot be used on type 'P'}}
// Static member of metatype -- not allowed
_ = pp.tum // expected-error{{static member 'tum' cannot be used on instance of type 'P.Protocol'}}
_ = P.tum // expected-error{{static member 'tum' cannot be used on instance of type 'P.Protocol'}}
// Static member of extension returning Self)
let _: () -> P = id(p.returnSelfStatic)
let _: P = id(p.returnSelfStatic())
let _: Bool -> P? = id(p.returnSelfOptionalStatic)
let _: P? = id(p.returnSelfOptionalStatic(false))
let _: Bool -> P! = id(p.returnSelfIUOStatic)
let _: P! = id(p.returnSelfIUOStatic(true))
}
func existentialClassP(_ p: ClassP) {
// Instance member of existential)
let _: Int -> () = id(p.bas)
let _: () = id(p.bas(0))
// Instance member of existential metatype)
let _: ClassP -> Int -> () = id(ClassP.bas)
let _: Int -> () = id(ClassP.bas(p))
let _: () = id(ClassP.bas(p)(1))
}
// Partial application of curried protocol methods
protocol Scalar {}
protocol Vector {
func scale(_ c: Scalar) -> Self
}
protocol Functional {
func apply(_ v: Vector) -> Scalar
}
protocol Coalgebra {
func coproduct(_ f: Functional) -> (v1: Vector, v2: Vector) -> Scalar
}
// Make sure existential is closed early when we partially apply
func wrap<T>(_ t: T) -> T {
return t
}
func exercise(_ c: Coalgebra, f: Functional, v: Vector) {
let _: (Vector, Vector) -> Scalar = wrap(c.coproduct(f))
let _: Scalar -> Vector = v.scale
}
// Make sure existential isn't closed too late
protocol Copyable {
func copy() -> Self
}
func copyTwice(_ c: Copyable) -> Copyable {
return c.copy().copy()
}
////
// Misc ambiguities
////
// <rdar://problem/15537772>
struct DefaultArgs {
static func f(_ a: Int = 0) -> DefaultArgs {
return DefaultArgs()
}
init() {
self = .f()
}
}
class InstanceOrClassMethod {
func method() -> Bool { return true }
class func method(_ other: InstanceOrClassMethod) -> Bool { return false }
}
func testPreferClassMethodToCurriedInstanceMethod(_ obj: InstanceOrClassMethod) {
let result = InstanceOrClassMethod.method(obj)
let _: Bool = result // no-warning
let _: () -> Bool = InstanceOrClassMethod.method(obj)
}
protocol Numeric {
func +(x: Self, y: Self) -> Self
}
func acceptBinaryFunc<T>(_ x: T, _ fn: (T, T) -> T) { }
func testNumeric<T : Numeric>(_ x: T) {
acceptBinaryFunc(x, +)
}
/* FIXME: We can't check this directly, but it can happen with
multiple modules.
class PropertyOrMethod {
func member() -> Int { return 0 }
let member = false
class func methodOnClass(_ obj: PropertyOrMethod) -> Int { return 0 }
let methodOnClass = false
}
func testPreferPropertyToMethod(_ obj: PropertyOrMethod) {
let result = obj.member
let resultChecked: Bool = result
let called = obj.member()
let calledChecked: Int = called
let curried = obj.member as () -> Int
let methodOnClass = PropertyOrMethod.methodOnClass
let methodOnClassChecked: (PropertyOrMethod) -> Int = methodOnClass
}
*/
struct Foo { var foo: Int }
protocol ExtendedWithMutatingMethods { }
extension ExtendedWithMutatingMethods {
mutating func mutatingMethod() {}
var mutableProperty: Foo {
get { }
set { }
}
var nonmutatingProperty: Foo {
get { }
nonmutating set { }
}
var mutatingGetProperty: Foo {
mutating get { }
set { }
}
}
class ClassExtendedWithMutatingMethods: ExtendedWithMutatingMethods {}
class SubclassExtendedWithMutatingMethods: ClassExtendedWithMutatingMethods {}
func testClassExtendedWithMutatingMethods(_ c: ClassExtendedWithMutatingMethods, // expected-note* {{}}
sub: SubclassExtendedWithMutatingMethods) { // expected-note* {{}}
c.mutatingMethod() // expected-error{{cannot use mutating member on immutable value: 'c' is a 'let' constant}}
c.mutableProperty = Foo(foo: 0) // expected-error{{cannot assign to property}}
c.mutableProperty.foo = 0 // expected-error{{cannot assign to property}}
c.nonmutatingProperty = Foo(foo: 0)
c.nonmutatingProperty.foo = 0
c.mutatingGetProperty = Foo(foo: 0) // expected-error{{cannot use mutating}}
c.mutatingGetProperty.foo = 0 // expected-error{{cannot use mutating}}
_ = c.mutableProperty
_ = c.mutableProperty.foo
_ = c.nonmutatingProperty
_ = c.nonmutatingProperty.foo
// FIXME: diagnostic nondeterministically says "member" or "getter"
_ = c.mutatingGetProperty // expected-error{{cannot use mutating}}
_ = c.mutatingGetProperty.foo // expected-error{{cannot use mutating}}
sub.mutatingMethod() // expected-error{{cannot use mutating member on immutable value: 'sub' is a 'let' constant}}
sub.mutableProperty = Foo(foo: 0) // expected-error{{cannot assign to property}}
sub.mutableProperty.foo = 0 // expected-error{{cannot assign to property}}
sub.nonmutatingProperty = Foo(foo: 0)
sub.nonmutatingProperty.foo = 0
sub.mutatingGetProperty = Foo(foo: 0) // expected-error{{cannot use mutating}}
sub.mutatingGetProperty.foo = 0 // expected-error{{cannot use mutating}}
_ = sub.mutableProperty
_ = sub.mutableProperty.foo
_ = sub.nonmutatingProperty
_ = sub.nonmutatingProperty.foo
_ = sub.mutatingGetProperty // expected-error{{cannot use mutating}}
_ = sub.mutatingGetProperty.foo // expected-error{{cannot use mutating}}
var mutableC = c
mutableC.mutatingMethod()
mutableC.mutableProperty = Foo(foo: 0)
mutableC.mutableProperty.foo = 0
mutableC.nonmutatingProperty = Foo(foo: 0)
mutableC.nonmutatingProperty.foo = 0
mutableC.mutatingGetProperty = Foo(foo: 0)
mutableC.mutatingGetProperty.foo = 0
_ = mutableC.mutableProperty
_ = mutableC.mutableProperty.foo
_ = mutableC.nonmutatingProperty
_ = mutableC.nonmutatingProperty.foo
_ = mutableC.mutatingGetProperty
_ = mutableC.mutatingGetProperty.foo
var mutableSub = sub
mutableSub.mutatingMethod()
mutableSub.mutableProperty = Foo(foo: 0)
mutableSub.mutableProperty.foo = 0
mutableSub.nonmutatingProperty = Foo(foo: 0)
mutableSub.nonmutatingProperty.foo = 0
_ = mutableSub.mutableProperty
_ = mutableSub.mutableProperty.foo
_ = mutableSub.nonmutatingProperty
_ = mutableSub.nonmutatingProperty.foo
_ = mutableSub.mutatingGetProperty
_ = mutableSub.mutatingGetProperty.foo
}
// <rdar://problem/18879585> QoI: error message for attempted access to instance properties in static methods are bad.
enum LedModules: Int {
case WS2811_1x_5V
}
extension LedModules {
static var watts: Double {
return [0.30][self.rawValue] // expected-error {{instance member 'rawValue' cannot be used on type 'LedModules'}}
}
}
// <rdar://problem/15117741> QoI: calling a static function on an instance produces a non-helpful diagnostic
class r15117741S {
static func g() {}
}
func test15117741(_ s: r15117741S) {
s.g() // expected-error {{static member 'g' cannot be used on instance of type 'r15117741S'}}
}
// <rdar://problem/22491394> References to unavailable decls sometimes diagnosed as ambiguous
struct UnavailMember {
@available(*, unavailable)
static var XYZ : X { get {} } // expected-note {{'XYZ' has been explicitly marked unavailable here}}
}
let _ : [UnavailMember] = [.XYZ] // expected-error {{'XYZ' is unavailable}}
let _ : [UnavailMember] = [.ABC] // expected-error {{type 'UnavailMember' has no member 'ABC'}}
// <rdar://problem/22490787> QoI: Poor error message iterating over property with non-sequence type that defines an Iterator type alias
struct S22490787 {
typealias Iterator = AnyIterator<Int>
}
func f22490787() {
var path: S22490787 = S22490787()
for p in path { // expected-error {{type 'S22490787' does not conform to protocol 'Sequence'}}
}
}
// <rdar://problem/23942743> [QoI] Bad diagnostic when errors inside enum constructor
enum r23942743 {
case Tomato(cloud: String)
}
let _ = .Tomato(cloud: .none) // expected-error {{reference to member 'Tomato' cannot be resolved without a contextual type}}
// SR-650: REGRESSION: Assertion failed: (baseTy && "Couldn't find appropriate context"), function getMemberSubstitutions
enum SomeErrorType {
case StandaloneError
case UnderlyingError(String)
static func someErrorFromString(_ str: String) -> SomeErrorType? {
if str == "standalone" { return .StandaloneError }
if str == "underlying" { return .UnderlyingError } // expected-error {{contextual member 'UnderlyingError' expects argument of type 'String'}}
return nil
}
}
| apache-2.0 |
tensorflow/swift-models | Models/Text/WordSeg/SemiRing.swift | 1 | 4029 | // Copyright 2020 The TensorFlow Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import _Differentiation
#if os(iOS) || os(macOS) || os(tvOS) || os(watchOS)
import Darwin
#elseif os(Windows)
#if canImport(CRT)
import CRT
#else
import MSVCRT
#endif
#else
import Glibc
#endif
/// Returns a single tensor containing the log of the sum of the exponentials
/// in `x`.
///
/// Used for numerical stability when dealing with very small values.
@differentiable
public func logSumExp(_ x: [Float]) -> Float {
if x.count == 0 { return -Float.infinity}
let maxVal = x.max()!
let exps = x.map { exp($0 - maxVal) }
return maxVal + log(exps.reduce(into: 0, +=))
}
@derivative(of: logSumExp)
public func vjpLogSumExp(_ x: [Float]) -> (
value: Float,
pullback: (Float) -> (Array<Float>.TangentVector)
) {
func pb(v: Float) -> (Array<Float>.TangentVector) {
if x.count == 0 { return Array<Float>.TangentVector([]) }
let maxVal = x.max()!
let exps = x.map { exp($0 - maxVal) }
let sumExp = exps.reduce(into: 0, +=)
return Array<Float>.TangentVector(exps.map{ v * $0 / sumExp })
}
return (logSumExp(x), pb)
}
/// Returns a single tensor containing the log of the sum of the exponentials
/// in `lhs` and `rhs`.
///
/// Used for numerical stability when dealing with very small values.
@differentiable
public func logSumExp(_ lhs: Float, _ rhs: Float) -> Float {
return logSumExp([lhs, rhs])
}
/// A storage mechanism for scoring inside a lattice.
public struct SemiRing: Differentiable {
/// The log likelihood.
public var logp: Float
/// The regularization factor.
public var logr: Float
/// Creates an instance with log likelihood `logp` and regularization
/// factor `logr`.
@differentiable
public init(logp: Float, logr: Float) {
self.logp = logp
self.logr = logr
}
/// The baseline score of zero.
static var zero: SemiRing { SemiRing(logp: -Float.infinity, logr: -Float.infinity) }
/// The baseline score of one.
static var one: SemiRing { SemiRing(logp: 0.0, logr: -Float.infinity) }
}
/// Multiplies `lhs` by `rhs`.
///
/// Since scores are on a logarithmic scale, products become sums.
@differentiable
func * (_ lhs: SemiRing, _ rhs: SemiRing) -> SemiRing {
return SemiRing(
logp: lhs.logp + rhs.logp,
logr: logSumExp(lhs.logp + rhs.logr, rhs.logp + lhs.logr))
}
/// Sums `lhs` by `rhs`.
@differentiable
func + (_ lhs: SemiRing, _ rhs: SemiRing) -> SemiRing {
return SemiRing(
logp: logSumExp(lhs.logp, rhs.logp),
logr: logSumExp(lhs.logr, rhs.logr))
}
extension Array where Element == SemiRing {
/// Returns a sum of all scores in the collection.
@differentiable
func sum() -> SemiRing {
return SemiRing(
logp: logSumExp(differentiableMap { $0.logp }),
logr: logSumExp(differentiableMap { $0.logr }))
}
}
extension SemiRing {
/// The plain text description of this instance with score details.
var shortDescription: String {
"(\(logp), \(logr))"
}
}
extension SemiRing {
/// Returns true when `self` is within `tolerance` of `other`.
///
/// - Note: This behavior is modeled after SE-0259.
// TODO(abdulras) see if we can use ulp as a default tolerance
@inlinable
public func isAlmostEqual(to other: Self, tolerance: Float) -> Bool {
let diffP = abs(self.logp - other.logp)
let diffR = abs(self.logp - other.logp)
return (diffP <= tolerance || diffP.isNaN)
&& (diffR <= tolerance || diffR.isNaN)
}
}
| apache-2.0 |
Baichenghui/TestCode | 16-计步器OneHourWalker-master/OneHourWalker/TimerViewController.swift | 1 | 5128 | //
// TimerViewController.swift
// OneHourWalker
//
// Created by Matthew Maher on 2/18/16.
// Copyright © 2016 Matt Maher. All rights reserved.
//
import UIKit
import CoreLocation
import HealthKit
class TimerViewController: UIViewController, CLLocationManagerDelegate {
@IBOutlet weak var timerLabel: UILabel!
@IBOutlet weak var milesLabel: UILabel!
@IBOutlet weak var heightLabel: UILabel!
var zeroTime = NSTimeInterval()
var timer : NSTimer = NSTimer()
let locationManager = CLLocationManager()
var startLocation: CLLocation!
var lastLocation: CLLocation!
var distanceTraveled = 0.0
let healthManager:HealthKitManager = HealthKitManager()
var height: HKQuantitySample?
override func viewDidLoad() {
super.viewDidLoad()
locationManager.requestWhenInUseAuthorization()
if CLLocationManager.locationServicesEnabled(){
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
} else {
print("Need to Enable Location")
}
// We cannot access the user's HealthKit data without specific permission.
getHealthKitPermission()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func getHealthKitPermission() {
// Seek authorization in HealthKitManager.swift.
healthManager.authorizeHealthKit { (authorized, error) -> Void in
if authorized {
// Get and set the user's height.
self.setHeight()
} else {
if error != nil {
print(error)
}
print("Permission denied.")
}
}
}
@IBAction func startTimer(sender: AnyObject) {
timer = NSTimer.scheduledTimerWithTimeInterval(0.01, target: self, selector: Selector("updateTime"), userInfo: nil, repeats: true)
zeroTime = NSDate.timeIntervalSinceReferenceDate()
distanceTraveled = 0.0
startLocation = nil
lastLocation = nil
locationManager.startUpdatingLocation()
}
@IBAction func stopTimer(sender: AnyObject) {
timer.invalidate()
locationManager.stopUpdatingLocation()
}
func updateTime() {
let currentTime = NSDate.timeIntervalSinceReferenceDate()
var timePassed: NSTimeInterval = currentTime - zeroTime
let minutes = UInt8(timePassed / 60.0)
timePassed -= (NSTimeInterval(minutes) * 60)
let seconds = UInt8(timePassed)
timePassed -= NSTimeInterval(seconds)
let millisecsX10 = UInt8(timePassed * 100)
let strMinutes = String(format: "%02d", minutes)
let strSeconds = String(format: "%02d", seconds)
let strMSX10 = String(format: "%02d", millisecsX10)
timerLabel.text = "\(strMinutes):\(strSeconds):\(strMSX10)"
if timerLabel.text == "60:00:00" {
timer.invalidate()
locationManager.stopUpdatingLocation()
}
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if startLocation == nil {
startLocation = locations.first as CLLocation!
} else {
let lastDistance = lastLocation.distanceFromLocation(locations.last as CLLocation!)
distanceTraveled += lastDistance * 0.000621371
let trimmedDistance = String(format: "%.2f", distanceTraveled)
milesLabel.text = "\(trimmedDistance) Miles"
}
lastLocation = locations.last as CLLocation!
}
func setHeight() {
// Create the HKSample for Height.
let heightSample = HKSampleType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeight)
// Call HealthKitManager's getSample() method to get the user's height.
self.healthManager.getHeight(heightSample!, completion: { (userHeight, error) -> Void in
if( error != nil ) {
print("Error: \(error.localizedDescription)")
return
}
var heightString = ""
self.height = userHeight as? HKQuantitySample
// The height is formatted to the user's locale.
if let meters = self.height?.quantity.doubleValueForUnit(HKUnit.meterUnit()) {
let formatHeight = NSLengthFormatter()
formatHeight.forPersonHeightUse = true
heightString = formatHeight.stringFromMeters(meters)
}
// Set the label to reflect the user's height.
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.heightLabel.text = heightString
})
})
}
@IBAction func share(sender: AnyObject) {
healthManager.saveDistance(distanceTraveled, date: NSDate())
}
}
| mit |
Bartlebys/Bartleby | Bartleby.xOS/core/extensions/CollectionMetadatum+Proxy.swift | 1 | 357 | //
// CollectionMetadatum.swift
// Bartleby
//
// Created by Benoit Pereira da Silva on 03/11/2015.
// Copyright © 2015 https://pereira-da-silva.com for Chaosmos SAS
// All rights reserved you can ask for a license.
import Foundation
// Formal conformance to CollectionMetadatumProtocol
extension CollectionMetadatum:CollectionMetadatumProtocol {}
| apache-2.0 |
Raizlabs/RIGImageGallery | RIGImageGalleryTests/TestingExtensions.swift | 1 | 997 | //
// TestingExtensions.swift
// RIGImageGallery
//
// Created by Michael Skiba on 7/12/16.
// Copyright © 2016 Raizlabs. All rights reserved.
//
import UIKit
extension CGSize {
static let wide = CGSize(width: 1920, height: 1080)
static let tall = CGSize(width: 480, height: 720)
static let smallWide = CGSize(width: 480, height: 270)
static let smallTall = CGSize(width: 207, height: 368)
}
extension UIImage {
static var allGenerics: [UIImage] {
return [UIImage.genericImage(.wide), UIImage.genericImage(.tall), UIImage.genericImage(.smallWide), UIImage.genericImage(.smallTall)]
}
static func genericImage(_ size: CGSize) -> UIImage {
UIGraphicsBeginImageContextWithOptions(size, true, 0)
let fillPath = UIBezierPath(rect: CGRect(origin: CGPoint(), size: size))
fillPath.fill()
let genericImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return genericImage!
}
}
| mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.