repo_name
stringlengths
6
91
ref
stringlengths
12
59
path
stringlengths
7
936
license
stringclasses
15 values
copies
stringlengths
1
3
content
stringlengths
61
714k
hash
stringlengths
32
32
line_mean
float64
4.88
60.8
line_max
int64
12
421
alpha_frac
float64
0.1
0.92
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
Swinject/SwinjectMVVMExample
refs/heads/master
Carthage/Checkouts/ReactiveSwift/Sources/Event.swift
mit
2
// // Event.swift // ReactiveSwift // // Created by Justin Spahr-Summers on 2015-01-16. // Copyright (c) 2015 GitHub. All rights reserved. // /// Represents a signal event. /// /// Signals must conform to the grammar: /// `value* (failed | completed | interrupted)?` public enum Event<Value, Error: Swift.Error> { /// A value provided by the signal. case value(Value) /// The signal terminated because of an error. No further events will be /// received. case failed(Error) /// The signal successfully terminated. No further events will be received. case completed /// Event production on the signal has been interrupted. No further events /// will be received. /// /// - important: This event does not signify the successful or failed /// completion of the signal. case interrupted /// Whether this event indicates signal termination (i.e., that no further /// events will be received). public var isTerminating: Bool { switch self { case .value: return false case .failed, .completed, .interrupted: return true } } /// Lift the given closure over the event's value. /// /// - important: The closure is called only on `value` type events. /// /// - parameters: /// - f: A closure that accepts a value and returns a new value /// /// - returns: An event with function applied to a value in case `self` is a /// `value` type of event. public func map<U>(_ f: (Value) -> U) -> Event<U, Error> { switch self { case let .value(value): return .value(f(value)) case let .failed(error): return .failed(error) case .completed: return .completed case .interrupted: return .interrupted } } /// Lift the given closure over the event's error. /// /// - important: The closure is called only on failed type event. /// /// - parameters: /// - f: A closure that accepts an error object and returns /// a new error object /// /// - returns: An event with function applied to an error object in case /// `self` is a `.Failed` type of event. public func mapError<F>(_ f: (Error) -> F) -> Event<Value, F> { switch self { case let .value(value): return .value(value) case let .failed(error): return .failed(f(error)) case .completed: return .completed case .interrupted: return .interrupted } } /// Unwrap the contained `value` value. public var value: Value? { if case let .value(value) = self { return value } else { return nil } } /// Unwrap the contained `Error` value. public var error: Error? { if case let .failed(error) = self { return error } else { return nil } } } public func == <Value: Equatable, Error: Equatable> (lhs: Event<Value, Error>, rhs: Event<Value, Error>) -> Bool { switch (lhs, rhs) { case let (.value(left), .value(right)): return left == right case let (.failed(left), .failed(right)): return left == right case (.completed, .completed): return true case (.interrupted, .interrupted): return true default: return false } } extension Event: CustomStringConvertible { public var description: String { switch self { case let .value(value): return "VALUE \(value)" case let .failed(error): return "FAILED \(error)" case .completed: return "COMPLETED" case .interrupted: return "INTERRUPTED" } } } /// Event protocol for constraining signal extensions public protocol EventProtocol { /// The value type of an event. associatedtype Value /// The error type of an event. If errors aren't possible then `NoError` can /// be used. associatedtype Error: Swift.Error /// Extracts the event from the receiver. var event: Event<Value, Error> { get } } extension Event: EventProtocol { public var event: Event<Value, Error> { return self } }
67b45e8952b20714d5c552f14a818e0d
22.024242
114
0.659121
false
false
false
false
jpush/jchat-swift
refs/heads/master
JChat/Src/ContacterModule/View/JCSearchController.swift
mit
1
// // JCSearchView.swift // JChat // // Created by JIGUANG on 2017/3/22. // Copyright © 2017年 HXHG. All rights reserved. // import UIKit @objc public protocol JCSearchControllerDelegate: NSObjectProtocol { @objc optional func didEndEditing(_ searchBar: UISearchBar) @objc optional func didClickBarSearchButton(_ searchBar: UISearchBar) } class JCSearchController: UISearchController { weak var searchControllerDelegate: JCSearchControllerDelegate? override init(searchResultsController: UIViewController?) { super.init(searchResultsController: searchResultsController) _init() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) _init() } override func viewDidLoad() { super.viewDidLoad() } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) let frame = searchBar.frame if frame.origin.y > 0 && frame.origin.y < 20 { searchBar.frame = CGRect(x: frame.origin.x, y: 20, width: frame.size.width, height: 31) } else { searchBar.frame = CGRect(x: frame.origin.x, y: frame.origin.y, width: frame.size.width, height: 31) } } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() searchBar.layer.borderColor = UIColor.white.cgColor searchBar.layer.borderWidth = 1 searchBar.layer.masksToBounds = true let frame = searchBar.frame if frame.origin.y > 0 && frame.origin.y < 20 { searchBar.frame = CGRect(x: frame.origin.x, y: 20, width: frame.size.width, height: 31) } else { searchBar.frame = CGRect(x: frame.origin.x, y: frame.origin.y, width: frame.size.width, height: 31) } } private func _init() { automaticallyAdjustsScrollViewInsets = false dimsBackgroundDuringPresentation = false hidesNavigationBarDuringPresentation = true searchBar.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: 31) if #available(iOS 11.0, *) { searchBar.setPositionAdjustment(UIOffset(horizontal: 0, vertical: 3), for: .search) searchBar.searchTextPositionAdjustment = UIOffset(horizontal: 5, vertical: 3) } searchBar.barStyle = .default searchBar.backgroundColor = .white searchBar.barTintColor = .white searchBar.delegate = self searchBar.autocapitalizationType = .none searchBar.placeholder = "搜索" searchBar.layer.borderColor = UIColor.white.cgColor searchBar.layer.borderWidth = 1 searchBar.layer.masksToBounds = true searchBar.setSearchFieldBackgroundImage(UIImage.createImage(color: .white, size: CGSize(width: UIScreen.main.bounds.size.width, height: 31)), for: .normal) } } extension JCSearchController: UISearchBarDelegate { func searchBarSearchButtonClicked(_ searchBar: UISearchBar) { print("\(String(describing: searchBar.text))") searchControllerDelegate?.didClickBarSearchButton?(searchBar) } func searchBarTextDidEndEditing(_ searchBar: UISearchBar) { searchControllerDelegate?.didEndEditing?(searchBar) } func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) { searchBar.showsCancelButton = true for view in (searchBar.subviews.first?.subviews)! { if view is UIButton { let cancelButton = view as! UIButton cancelButton.setTitleColor(UIColor(netHex: 0x2dd0cf), for: .normal) if #available(iOS 11.0, *) { cancelButton.titleEdgeInsets = UIEdgeInsets.init(top: 8, left: 0, bottom: 0, right: 0) } break } } } }
506add9bcf0ea3cb8f7e612eb7083d61
35.342342
163
0.651215
false
false
false
false
hovansuit/FoodAndFitness
refs/heads/master
FoodAndFitness/Controllers/History/HistoryViewModel.swift
mit
1
// // HistoryViewModel.swift // FoodAndFitness // // Created by Mylo Ho on 4/26/17. // Copyright © 2017 SuHoVan. All rights reserved. // import UIKit import RealmS import RealmSwift import SwiftDate class HistoryViewModel { let breakfastFoods: [UserFood] let lunchFoods: [UserFood] let dinnerFoods: [UserFood] let userExercises: [UserExercise] let trackings: [Tracking] let date: Date fileprivate let userFoods: [UserFood] init(date: Date) { self.date = date let realm = RealmS() userFoods = realm.objects(UserFood.self).filter { (userFood) -> Bool in guard let me = User.me, let user = userFood.userHistory?.user else { return false } return me.id == user.id && userFood.createdAt.isInSameDayOf(date: date) } breakfastFoods = userFoods.filter({ (userFood) -> Bool in return userFood.meal == HomeViewController.AddActivity.breakfast.title }) lunchFoods = userFoods.filter({ (userFood) -> Bool in return userFood.meal == HomeViewController.AddActivity.lunch.title }) dinnerFoods = userFoods.filter({ (userFood) -> Bool in return userFood.meal == HomeViewController.AddActivity.dinner.title }) userExercises = realm.objects(UserExercise.self).filter({ (userExercise) -> Bool in guard let me = User.me, let user = userExercise.userHistory?.user else { return false } return me.id == user.id && userExercise.createdAt.isInSameDayOf(date: date) }) trackings = realm.objects(Tracking.self).filter { (tracking) -> Bool in guard let me = User.me, let user = tracking.userHistory?.user else { return false } return me.id == user.id && tracking.createdAt.isInSameDayOf(date: date) } } func dataForProgressCell() -> ProgressCell.Data? { guard let userHistory = RealmS().objects(UserHistory.self).filter({ (userHistory) -> Bool in let userHistoryDate = DateInRegion(absoluteDate: userHistory.createdAt).ffDate() let historyDate = DateInRegion(absoluteDate: self.date).ffDate() return userHistoryDate <= historyDate }).last else { return nil } var eaten = eatenToday() let burn = burnToday() let calories = userHistory.caloriesToday + Double(burn) if Int(calories) - eaten < 0 { eaten = Int(calories) } let carbsString = "\(carbsLeft(calories: calories))" + Strings.gLeft let proteinString = "\(proteinLeft(calories: calories))" + Strings.gLeft let fatString = "\(fatLeft(calories: calories))" + Strings.gLeft return ProgressCell.Data(calories: Int(calories), eaten: eaten, burn: burn, carbs: carbsString, protein: proteinString, fat: fatString) } private func eatenToday() -> Int { let eaten = userFoods.map { (userFood) -> Int in return userFood.calories }.reduce(0) { (result, calories) -> Int in return result + calories } return eaten } private func carbsLeft(calories: Double) -> Int { let carbsUserFoods = userFoods.map { (userFood) -> Int in return userFood.carbs }.reduce(0) { (result, carbs) -> Int in return result + carbs } let carbsLeft = carbs(calories: calories) - carbsUserFoods if carbsLeft < 0 { return 0 } else { return carbsLeft } } private func proteinLeft(calories: Double) -> Int { let proteinUserFoods = userFoods.map { (userFood) -> Int in return userFood.protein }.reduce(0) { (result, protein) -> Int in return result + protein } let proteinLeft = protein(calories: calories) - proteinUserFoods if proteinLeft < 0 { return 0 } else { return proteinLeft } } private func fatLeft(calories: Double) -> Int { let fatUserFoods = userFoods.map { (userFood) -> Int in return userFood.fat }.reduce(0) { (result, fat) -> Int in return result + fat } let fatLeft = fat(calories: calories) - fatUserFoods if fatLeft < 0 { return 0 } else { return fatLeft } } private func burnToday() -> Int { let exercisesBurn = userExercises.map { (userExercise) -> Int in return userExercise.calories }.reduce(0) { (result, calories) -> Int in return result + calories } let trackingsBurn = trackings.map { (tracking) -> Int in return tracking.caloriesBurn }.reduce(0) { (result, calories) -> Int in return result + calories } return exercisesBurn + trackingsBurn } }
83dab694fef37ece27a4622956caeb77
36.356061
143
0.594808
false
false
false
false
amraboelela/swift
refs/heads/master
stdlib/public/core/StringGraphemeBreaking.swift
apache-2.0
3
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// import SwiftShims /// CR and LF are common special cases in grapheme breaking logic private var _CR: UInt8 { return 0x0d } private var _LF: UInt8 { return 0x0a } private func _hasGraphemeBreakBetween( _ lhs: Unicode.Scalar, _ rhs: Unicode.Scalar ) -> Bool { // CR-LF is a special case: no break between these if lhs == Unicode.Scalar(_CR) && rhs == Unicode.Scalar(_LF) { return false } // Whether the given scalar, when it appears paired with another scalar // satisfying this property, has a grapheme break between it and the other // scalar. func hasBreakWhenPaired(_ x: Unicode.Scalar) -> Bool { // TODO: This doesn't generate optimal code, tune/re-write at a lower // level. // // NOTE: Order of case ranges affects codegen, and thus performance. All // things being equal, keep existing order below. switch x.value { // Unified CJK Han ideographs, common and some supplemental, amongst // others: // U+3400 ~ U+A4CF case 0x3400...0xa4cf: return true // Repeat sub-300 check, this is beneficial for common cases of Latin // characters embedded within non-Latin script (e.g. newlines, spaces, // proper nouns and/or jargon, punctuation). // // NOTE: CR-LF special case has already been checked. case 0x0000...0x02ff: return true // Non-combining kana: // U+3041 ~ U+3096 // U+30A1 ~ U+30FC case 0x3041...0x3096: return true case 0x30a1...0x30fc: return true // Non-combining modern (and some archaic) Cyrillic: // U+0400 ~ U+0482 (first half of Cyrillic block) case 0x0400...0x0482: return true // Modern Arabic, excluding extenders and prependers: // U+061D ~ U+064A case 0x061d...0x064a: return true // Precomposed Hangul syllables: // U+AC00 ~ U+D7AF case 0xac00...0xd7af: return true // Common general use punctuation, excluding extenders: // U+2010 ~ U+2029 case 0x2010...0x2029: return true // CJK punctuation characters, excluding extenders: // U+3000 ~ U+3029 case 0x3000...0x3029: return true // Full-width forms: // U+FF01 ~ U+FF9D case 0xFF01...0xFF9D: return true default: return false } } return hasBreakWhenPaired(lhs) && hasBreakWhenPaired(rhs) } @inline(never) // slow-path @_effects(releasenone) private func _measureCharacterStrideICU( of utf8: UnsafeBufferPointer<UInt8>, startingAt i: Int ) -> Int { let iterator = _ThreadLocalStorage.getUBreakIterator(utf8) let offset = __swift_stdlib_ubrk_following( iterator, Int32(truncatingIfNeeded: i)) // ubrk_following returns -1 (UBRK_DONE) when it hits the end of the buffer. if _fastPath(offset != -1) { // The offset into our buffer is the distance. _internalInvariant(offset > i, "zero-sized grapheme?") return Int(truncatingIfNeeded: offset) &- i } _internalInvariant(utf8.count > i) return utf8.count &- i } @inline(never) // slow-path @_effects(releasenone) private func _measureCharacterStrideICU( of utf16: UnsafeBufferPointer<UInt16>, startingAt i: Int ) -> Int { let iterator = _ThreadLocalStorage.getUBreakIterator(utf16) let offset = __swift_stdlib_ubrk_following( iterator, Int32(truncatingIfNeeded: i)) // ubrk_following returns -1 (UBRK_DONE) when it hits the end of the buffer. if _fastPath(offset != -1) { // The offset into our buffer is the distance. _internalInvariant(offset > i, "zero-sized grapheme?") return Int(truncatingIfNeeded: offset) &- i } return utf16.count &- i } @inline(never) // slow-path @_effects(releasenone) private func _measureCharacterStrideICU( of utf8: UnsafeBufferPointer<UInt8>, endingAt i: Int ) -> Int { let iterator = _ThreadLocalStorage.getUBreakIterator(utf8) let offset = __swift_stdlib_ubrk_preceding( iterator, Int32(truncatingIfNeeded: i)) // ubrk_following returns -1 (UBRK_DONE) when it hits the end of the buffer. if _fastPath(offset != -1) { // The offset into our buffer is the distance. _internalInvariant(offset < i, "zero-sized grapheme?") return i &- Int(truncatingIfNeeded: offset) } return i &- utf8.count } @inline(never) // slow-path @_effects(releasenone) private func _measureCharacterStrideICU( of utf16: UnsafeBufferPointer<UInt16>, endingAt i: Int ) -> Int { let iterator = _ThreadLocalStorage.getUBreakIterator(utf16) let offset = __swift_stdlib_ubrk_preceding( iterator, Int32(truncatingIfNeeded: i)) // ubrk_following returns -1 (UBRK_DONE) when it hits the end of the buffer. if _fastPath(offset != -1) { // The offset into our buffer is the distance. _internalInvariant(offset < i, "zero-sized grapheme?") return i &- Int(truncatingIfNeeded: offset) } return i &- utf16.count } extension _StringGuts { @usableFromInline @inline(never) @_effects(releasenone) internal func isOnGraphemeClusterBoundary(_ i: String.Index) -> Bool { guard i.transcodedOffset == 0 else { return false } let offset = i.encodedOffset if offset == 0 || offset == self.count { return true } guard isOnUnicodeScalarBoundary(i) else { return false } let str = String(self) return i == str.index(before: str.index(after: i)) } @usableFromInline @inline(never) @_effects(releasenone) internal func _opaqueCharacterStride(startingAt i: Int) -> Int { if _slowPath(isForeign) { return _foreignOpaqueCharacterStride(startingAt: i) } return self.withFastUTF8 { utf8 in let (sc1, len) = _decodeScalar(utf8, startingAt: i) if i &+ len == utf8.endIndex { // Last scalar is last grapheme return len } let (sc2, _) = _decodeScalar(utf8, startingAt: i &+ len) if _fastPath(_hasGraphemeBreakBetween(sc1, sc2)) { return len } return _measureCharacterStrideICU(of: utf8, startingAt: i) } } @inline(never) @_effects(releasenone) private func _foreignOpaqueCharacterStride(startingAt i: Int) -> Int { #if _runtime(_ObjC) _internalInvariant(isForeign) // TODO(String performance): Faster to do it from a pointer directly let count = _object.largeCount let cocoa = _object.cocoaObject let startIdx = String.Index(encodedOffset: i) let (sc1, len) = foreignErrorCorrectedScalar(startingAt: startIdx) if i &+ len == count { // Last scalar is last grapheme return len } let (sc2, _) = foreignErrorCorrectedScalar( startingAt: startIdx.encoded(offsetBy: len)) if _fastPath(_hasGraphemeBreakBetween(sc1, sc2)) { return len } if let utf16Ptr = _stdlib_binary_CFStringGetCharactersPtr(cocoa) { let utf16 = UnsafeBufferPointer(start: utf16Ptr, count: count) return _measureCharacterStrideICU(of: utf16, startingAt: i) } // TODO(String performance): Local small stack first, before making large // array. Also, make a smaller initial array and grow over time. var codeUnits = Array<UInt16>(repeating: 0, count: count) codeUnits.withUnsafeMutableBufferPointer { _cocoaStringCopyCharacters( from: cocoa, range: 0..<count, into: $0.baseAddress._unsafelyUnwrappedUnchecked) } return codeUnits.withUnsafeBufferPointer { _measureCharacterStrideICU(of: $0, startingAt: i) } #else fatalError("No foreign strings on Linux in this version of Swift") #endif } @usableFromInline @inline(never) @_effects(releasenone) internal func _opaqueCharacterStride(endingAt i: Int) -> Int { if _slowPath(isForeign) { return _foreignOpaqueCharacterStride(endingAt: i) } return self.withFastUTF8 { utf8 in let (sc2, len) = _decodeScalar(utf8, endingAt: i) if i &- len == utf8.startIndex { // First scalar is first grapheme return len } let (sc1, _) = _decodeScalar(utf8, endingAt: i &- len) if _fastPath(_hasGraphemeBreakBetween(sc1, sc2)) { return len } return _measureCharacterStrideICU(of: utf8, endingAt: i) } } @inline(never) @_effects(releasenone) private func _foreignOpaqueCharacterStride(endingAt i: Int) -> Int { #if _runtime(_ObjC) _internalInvariant(isForeign) // TODO(String performance): Faster to do it from a pointer directly let count = _object.largeCount let cocoa = _object.cocoaObject let endIdx = String.Index(encodedOffset: i) let (sc2, len) = foreignErrorCorrectedScalar(endingAt: endIdx) if i &- len == 0 { // First scalar is first grapheme return len } let (sc1, _) = foreignErrorCorrectedScalar( endingAt: endIdx.encoded(offsetBy: -len)) if _fastPath(_hasGraphemeBreakBetween(sc1, sc2)) { return len } if let utf16Ptr = _stdlib_binary_CFStringGetCharactersPtr(cocoa) { let utf16 = UnsafeBufferPointer(start: utf16Ptr, count: count) return _measureCharacterStrideICU(of: utf16, endingAt: i) } // TODO(String performance): Local small stack first, before making large // array. Also, make a smaller initial array and grow over time. var codeUnits = Array<UInt16>(repeating: 0, count: count) codeUnits.withUnsafeMutableBufferPointer { _cocoaStringCopyCharacters( from: cocoa, range: 0..<count, into: $0.baseAddress._unsafelyUnwrappedUnchecked) } return codeUnits.withUnsafeBufferPointer { _measureCharacterStrideICU(of: $0, endingAt: i) } #else fatalError("No foreign strings on Linux in this version of Swift") #endif } }
3e6072b5bd99775419d812725a38a767
32.348837
80
0.670452
false
false
false
false
akisute/ReactiveCocoaSwift
refs/heads/master
ReactiveCocoaSwift/Views/ListViewController.swift
mit
1
// // ListViewController.swift // ReactiveCocoaSwift // // Created by Ono Masashi on 2015/01/14. // Copyright (c) 2015年 akisute. All rights reserved. // import UIKit import ReactiveCocoa class ListViewController: UITableViewController { var presentation: ListViewControllerPresentation! // MARK: - UIViewController override func viewDidLoad() { self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Add, target: nil, action: nil) self.navigationItem.rightBarButtonItem?.rac_command = RACCommand(signalBlock: { (sender: AnyObject!) -> RACSignal! in self.presentation.addNote() return RACSignal.empty() }) self.presentation.documentUpdatedSignal.subscribeNext { (notesValue: AnyObject!) -> Void in self.tableView.reloadData() } } // MARK: - UITableViewDelegate override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return self.presentation.numberOfSections } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.presentation.numberOfRowsInSection(section) } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let CellIdentifier = "Cell" let cell: UITableViewCell = tableView.dequeueReusableCellWithIdentifier(CellIdentifier, forIndexPath: indexPath) as UITableViewCell let note = self.presentation.noteForRowAtIndexPath(indexPath) cell.textLabel?.text = note.text cell.detailTextLabel?.text = note.timestamp return cell } }
68fbe88608315f08882dd275afc64098
34.875
139
0.698026
false
false
false
false
HarukaMa/iina
refs/heads/master
iina/MPVProperty.swift
gpl-3.0
1
import Foundation struct MPVProperty { /** audio-speed-correction */ static let audioSpeedCorrection = "audio-speed-correction" /** video-speed-correction */ static let videoSpeedCorrection = "video-speed-correction" /** display-sync-active */ static let displaySyncActive = "display-sync-active" /** filename */ static let filename = "filename" /** filename/no-ext */ static let filenameNoExt = "filename/no-ext" /** file-size */ static let fileSize = "file-size" /** estimated-frame-count */ static let estimatedFrameCount = "estimated-frame-count" /** estimated-frame-number */ static let estimatedFrameNumber = "estimated-frame-number" /** path */ static let path = "path" /** media-title */ static let mediaTitle = "media-title" /** file-format */ static let fileFormat = "file-format" /** current-demuxer */ static let currentDemuxer = "current-demuxer" /** stream-path */ static let streamPath = "stream-path" /** stream-pos */ static let streamPos = "stream-pos" /** stream-end */ static let streamEnd = "stream-end" /** duration */ static let duration = "duration" /** avsync */ static let avsync = "avsync" /** total-avsync-change */ static let totalAvsyncChange = "total-avsync-change" /** decoder-frame-drop-count */ static let decoderFrameDropCount = "decoder-frame-drop-count" /** frame-drop-count */ static let frameDropCount = "frame-drop-count" /** mistimed-frame-count */ static let mistimedFrameCount = "mistimed-frame-count" /** vsync-ratio */ static let vsyncRatio = "vsync-ratio" /** vo-delayed-frame-count */ static let voDelayedFrameCount = "vo-delayed-frame-count" /** percent-pos */ static let percentPos = "percent-pos" /** time-pos */ static let timePos = "time-pos" /** time-start */ static let timeStart = "time-start" /** time-remaining */ static let timeRemaining = "time-remaining" /** audio-pts */ static let audioPts = "audio-pts" /** playtime-remaining */ static let playtimeRemaining = "playtime-remaining" /** playback-time */ static let playbackTime = "playback-time" /** chapter */ static let chapter = "chapter" /** edition */ static let edition = "edition" /** disc-titles */ static let discTitles = "disc-titles" /** disc-titles/count */ static let discTitlesCount = "disc-titles/count" /** disc-titles/id */ static let discTitlesId = "disc-titles/id" /** disc-titles/length */ static let discTitlesLength = "disc-titles/length" /** disc-title-list */ static let discTitleList = "disc-title-list" /** disc-title */ static let discTitle = "disc-title" /** chapters */ static let chapters = "chapters" /** editions */ static let editions = "editions" /** edition-list */ static let editionList = "edition-list" /** edition-list/count */ static let editionListCount = "edition-list/count" /** edition-list/N/id */ static func editionListNId(_ n: Int) -> String { return "edition-list/\(n)/id" } /** edition-list/N/default */ static func editionListNDefault(_ n: Int) -> String { return "edition-list/\(n)/default" } /** edition-list/N/title */ static func editionListNTitle(_ n: Int) -> String { return "edition-list/\(n)/title" } /** angle */ static let angle = "angle" /** metadata */ static let metadata = "metadata" /** metadata/list/count */ static let metadataListCount = "metadata/list/count" /** metadata/list/N/key */ static func metadataListNKey(_ n: Int) -> String { return "metadata/list/\(n)/key" } /** metadata/list/N/value */ static func metadataListNValue(_ n: Int) -> String { return "metadata/list/\(n)/value" } /** filtered-metadata */ static let filteredMetadata = "filtered-metadata" /** chapter-metadata */ static let chapterMetadata = "chapter-metadata" /** idle-active */ static let idleActive = "idle-active" /** core-idle */ static let coreIdle = "core-idle" /** cache */ static let cache = "cache" /** cache-size */ static let cacheSize = "cache-size" /** cache-free */ static let cacheFree = "cache-free" /** cache-used */ static let cacheUsed = "cache-used" /** cache-speed */ static let cacheSpeed = "cache-speed" /** cache-idle */ static let cacheIdle = "cache-idle" /** demuxer-cache-duration */ static let demuxerCacheDuration = "demuxer-cache-duration" /** demuxer-cache-time */ static let demuxerCacheTime = "demuxer-cache-time" /** demuxer-cache-idle */ static let demuxerCacheIdle = "demuxer-cache-idle" /** paused-for-cache */ static let pausedForCache = "paused-for-cache" /** cache-buffering-state */ static let cacheBufferingState = "cache-buffering-state" /** eof-reached */ static let eofReached = "eof-reached" /** seeking */ static let seeking = "seeking" /** mixer-active */ static let mixerActive = "mixer-active" /** ao-volume */ static let aoVolume = "ao-volume" /** ao-mute */ static let aoMute = "ao-mute" /** audio-codec */ static let audioCodec = "audio-codec" /** audio-codec-name */ static let audioCodecName = "audio-codec-name" /** audio-params */ static let audioParams = "audio-params" /** audio-params/format */ static let audioParamsFormat = "audio-params/format" /** audio-params/samplerate */ static let audioParamsSamplerate = "audio-params/samplerate" /** audio-params/channels */ static let audioParamsChannels = "audio-params/channels" /** audio-params/hr-channels */ static let audioParamsHrChannels = "audio-params/hr-channels" /** audio-params/channel-count */ static let audioParamsChannelCount = "audio-params/channel-count" /** audio-out-params */ static let audioOutParams = "audio-out-params" /** colormatrix */ static let colormatrix = "colormatrix" /** colormatrix-input-range */ static let colormatrixInputRange = "colormatrix-input-range" /** colormatrix-primaries */ static let colormatrixPrimaries = "colormatrix-primaries" /** hwdec */ static let hwdec = "hwdec" /** hwdec-current */ static let hwdecCurrent = "hwdec-current" /** hwdec-interop */ static let hwdecInterop = "hwdec-interop" /** video-format */ static let videoFormat = "video-format" /** video-codec */ static let videoCodec = "video-codec" /** width */ static let width = "width" /** height */ static let height = "height" /** video-params */ static let videoParams = "video-params" /** video-params/pixelformat */ static let videoParamsPixelformat = "video-params/pixelformat" /** video-params/average-bpp */ static let videoParamsAverageBpp = "video-params/average-bpp" /** video-params/plane-depth */ static let videoParamsPlaneDepth = "video-params/plane-depth" /** video-params/w */ static let videoParamsW = "video-params/w" /** video-params/h */ static let videoParamsH = "video-params/h" /** video-params/dw */ static let videoParamsDw = "video-params/dw" /** video-params/dh */ static let videoParamsDh = "video-params/dh" /** video-params/aspect */ static let videoParamsAspect = "video-params/aspect" /** video-params/par */ static let videoParamsPar = "video-params/par" /** video-params/colormatrix */ static let videoParamsColormatrix = "video-params/colormatrix" /** video-params/colorlevels */ static let videoParamsColorlevels = "video-params/colorlevels" /** video-params/primaries */ static let videoParamsPrimaries = "video-params/primaries" /** video-params/gamma */ static let videoParamsGamma = "video-params/gamma" /** video-params/nom-peak */ static let videoParamsNomPeak = "video-params/nom-peak" /** video-params/sig-peak */ static let videoParamsSigPeak = "video-params/sig-peak" /** video-params/chroma-location */ static let videoParamsChromaLocation = "video-params/chroma-location" /** video-params/rotate */ static let videoParamsRotate = "video-params/rotate" /** video-params/stereo-in */ static let videoParamsStereoIn = "video-params/stereo-in" /** dwidth */ static let dwidth = "dwidth" /** dheight */ static let dheight = "dheight" /** video-dec-params */ static let videoDecParams = "video-dec-params" /** video-out-params */ static let videoOutParams = "video-out-params" /** video-frame-info */ static let videoFrameInfo = "video-frame-info" /** container-fps */ static let containerFps = "container-fps" /** estimated-vf-fps */ static let estimatedVfFps = "estimated-vf-fps" /** window-scale */ static let windowScale = "window-scale" /** window-minimized */ static let windowMinimized = "window-minimized" /** display-names */ static let displayNames = "display-names" /** display-fps */ static let displayFps = "display-fps" /** estimated-display-fps */ static let estimatedDisplayFps = "estimated-display-fps" /** vsync-jitter */ static let vsyncJitter = "vsync-jitter" /** video-aspect */ static let videoAspect = "video-aspect" /** osd-width */ static let osdWidth = "osd-width" /** osd-height */ static let osdHeight = "osd-height" /** osd-par */ static let osdPar = "osd-par" /** program */ static let program = "program" /** dvb-channel */ static let dvbChannel = "dvb-channel" /** dvb-channel-name */ static let dvbChannelName = "dvb-channel-name" /** sub-text */ static let subText = "sub-text" /** tv-brightness */ static let tvBrightness = "tv-brightness" /** tv-contrast */ static let tvContrast = "tv-contrast" /** tv-saturation */ static let tvSaturation = "tv-saturation" /** tv-hue */ static let tvHue = "tv-hue" /** playlist-pos */ static let playlistPos = "playlist-pos" /** playlist-pos-1 */ static let playlistPos1 = "playlist-pos-1" /** playlist-count */ static let playlistCount = "playlist-count" /** playlist */ static let playlist = "playlist" /** playlist/count */ static let playlistCount2 = "playlist/count" /** playlist/N/filename */ static func playlistNFilename(_ n: Int) -> String { return "playlist/\(n)/filename" } /** playlist/N/current */ static func playlistNCurrent(_ n: Int) -> String { return "playlist/\(n)/current" } /** playlist/N/playing */ static func playlistNPlaying(_ n: Int) -> String { return "playlist/\(n)/playing" } /** playlist/N/title */ static func playlistNTitle(_ n: Int) -> String { return "playlist/\(n)/title" } /** track-list */ static let trackList = "track-list" /** track-list/count */ static let trackListCount = "track-list/count" /** track-list/N/id */ static func trackListNId(_ n: Int) -> String { return "track-list/\(n)/id" } /** track-list/N/type */ static func trackListNType(_ n: Int) -> String { return "track-list/\(n)/type" } /** track-list/N/src-id */ static func trackListNSrcId(_ n: Int) -> String { return "track-list/\(n)/src-id" } /** track-list/N/title */ static func trackListNTitle(_ n: Int) -> String { return "track-list/\(n)/title" } /** track-list/N/lang */ static func trackListNLang(_ n: Int) -> String { return "track-list/\(n)/lang" } /** track-list/N/albumart */ static func trackListNAlbumart(_ n: Int) -> String { return "track-list/\(n)/albumart" } /** track-list/N/default */ static func trackListNDefault(_ n: Int) -> String { return "track-list/\(n)/default" } /** track-list/N/forced */ static func trackListNForced(_ n: Int) -> String { return "track-list/\(n)/forced" } /** track-list/N/codec */ static func trackListNCodec(_ n: Int) -> String { return "track-list/\(n)/codec" } /** track-list/N/external */ static func trackListNExternal(_ n: Int) -> String { return "track-list/\(n)/external" } /** track-list/N/external-filename */ static func trackListNExternalFilename(_ n: Int) -> String { return "track-list/\(n)/external-filename" } /** track-list/N/selected */ static func trackListNSelected(_ n: Int) -> String { return "track-list/\(n)/selected" } /** track-list/N/ff-index */ static func trackListNFfIndex(_ n: Int) -> String { return "track-list/\(n)/ff-index" } /** track-list/N/decoder-desc */ static func trackListNDecoderDesc(_ n: Int) -> String { return "track-list/\(n)/decoder-desc" } /** track-list/N/demux-w */ static func trackListNDemuxW(_ n: Int) -> String { return "track-list/\(n)/demux-w" } /** track-list/N/demux-h */ static func trackListNDemuxH(_ n: Int) -> String { return "track-list/\(n)/demux-h" } /** track-list/N/demux-channel-count */ static func trackListNDemuxChannelCount(_ n: Int) -> String { return "track-list/\(n)/demux-channel-count" } /** track-list/N/demux-channels */ static func trackListNDemuxChannels(_ n: Int) -> String { return "track-list/\(n)/demux-channels" } /** track-list/N/demux-samplerate */ static func trackListNDemuxSamplerate(_ n: Int) -> String { return "track-list/\(n)/demux-samplerate" } /** track-list/N/demux-fps */ static func trackListNDemuxFps(_ n: Int) -> String { return "track-list/\(n)/demux-fps" } /** track-list/N/audio-channels */ static func trackListNAudioChannels(_ n: Int) -> String { return "track-list/\(n)/audio-channels" } /** track-list/N/replaygain-track-peak */ static func trackListNReplaygainTrackPeak(_ n: Int) -> String { return "track-list/\(n)/replaygain-track-peak" } /** track-list/N/replaygain-track-gain */ static func trackListNReplaygainTrackGain(_ n: Int) -> String { return "track-list/\(n)/replaygain-track-gain" } /** track-list/N/replaygain-album-peak */ static func trackListNReplaygainAlbumPeak(_ n: Int) -> String { return "track-list/\(n)/replaygain-album-peak" } /** track-list/N/replaygain-album-gain */ static func trackListNReplaygainAlbumGain(_ n: Int) -> String { return "track-list/\(n)/replaygain-album-gain" } /** chapter-list */ static let chapterList = "chapter-list" /** chapter-list/count */ static let chapterListCount = "chapter-list/count" /** chapter-list/N/title */ static func chapterListNTitle(_ n: Int) -> String { return "chapter-list/\(n)/title" } /** chapter-list/N/time */ static func chapterListNTime(_ n: Int) -> String { return "chapter-list/\(n)/time" } /** af */ static let af = "af" /** vf */ static let vf = "vf" /** seekable */ static let seekable = "seekable" /** partially-seekable */ static let partiallySeekable = "partially-seekable" /** playback-abort */ static let playbackAbort = "playback-abort" /** cursor-autohide */ static let cursorAutohide = "cursor-autohide" /** osd-sym-cc */ static let osdSymCc = "osd-sym-cc" /** osd-ass-cc */ static let osdAssCc = "osd-ass-cc" /** vo-configured */ static let voConfigured = "vo-configured" /** vo-performance */ static let voPerformance = "vo-performance" /** upload */ static let upload = "upload" /** render */ static let render = "render" /** present */ static let present = "present" /** last */ static let last = "last" /** avg */ static let avg = "avg" /** peak */ static let peak = "peak" /** video-bitrate */ static let videoBitrate = "video-bitrate" /** audio-bitrate */ static let audioBitrate = "audio-bitrate" /** sub-bitrate */ static let subBitrate = "sub-bitrate" /** packet-video-bitrate */ static let packetVideoBitrate = "packet-video-bitrate" /** packet-audio-bitrate */ static let packetAudioBitrate = "packet-audio-bitrate" /** packet-sub-bitrate */ static let packetSubBitrate = "packet-sub-bitrate" /** audio-device-list */ static let audioDeviceList = "audio-device-list" /** audio-device */ static let audioDevice = "audio-device" /** current-vo */ static let currentVo = "current-vo" /** current-ao */ static let currentAo = "current-ao" /** audio-out-detected-device */ static let audioOutDetectedDevice = "audio-out-detected-device" /** working-directory */ static let workingDirectory = "working-directory" /** protocol-list */ static let protocolList = "protocol-list" /** decoder-list */ static let decoderList = "decoder-list" /** family */ static let family = "family" /** codec */ static let codec = "codec" /** driver */ static let driver = "driver" /** description */ static let description = "description" /** encoder-list */ static let encoderList = "encoder-list" /** mpv-version */ static let mpvVersion = "mpv-version" /** mpv-configuration */ static let mpvConfiguration = "mpv-configuration" /** ffmpeg-version */ static let ffmpegVersion = "ffmpeg-version" /** options/<name> */ static func options(_ name: String) -> String { return "options/\(name)" } /** file-local-options/<name> */ static func fileLocalOptions(_ name: String) -> String { return "file-local-options/\(name)" } /** option-info/<name> */ static func optionInfo(_ name: String) -> String { return "option-info/\(name)" } /** option-info/<name>/name */ static func optionInfoName(_ name: String) -> String { return "option-info/\(name)/name" } /** option-info/<name>/type */ static func optionInfoType(_ name: String) -> String { return "option-info/\(name)/type" } /** option-info/<name>/set-from-commandline */ static func optionInfoSetFromCommandline(_ name: String) -> String { return "option-info/\(name)/set-from-commandline" } /** option-info/<name>/set-locally */ static func optionInfoSetLocally(_ name: String) -> String { return "option-info/\(name)/set-locally" } /** option-info/<name>/default-value */ static func optionInfoDefaultValue(_ name: String) -> String { return "option-info/\(name)/default-value" } /** option-info/<name>/min */ static func optionInfoMin(_ name: String) -> String { return "option-info/\(name)/min" } /** option-info/<name>/max */ static func optionInfoMax(_ name: String) -> String { return "option-info/\(name)/max" } /** option-info/<name>/choices */ static func optionInfoChoices(_ name: String) -> String { return "option-info/\(name)/choices" } /** property-list */ static let propertyList = "property-list" /** profile-list */ static let profileList = "profile-list" }
619eca086f4e84291f87bd1db652893d
32.602564
71
0.656674
false
false
false
false
dulingkang/Capture
refs/heads/master
Capture/Capture/Util/CustumPhotoAlbum.swift
mit
1
// // CustumPhotoAlbum.swift // Capture // // Created by dulingkang on 15/11/15. // Copyright © 2015 ShawnDu. All rights reserved. // import UIKit import Photos class CustomPhotoAlbum { var assetCollection: PHAssetCollection! var albumFound : Bool = false var photosAsset: PHFetchResult! var collection: PHAssetCollection! var assetCollectionPlaceholder: PHObjectPlaceholder! static let albumName = "爱拍美图" class var sharedInstance: CustomPhotoAlbum { struct Singleton { static let instance = CustomPhotoAlbum() } return Singleton.instance } init() { self.createAlbum() } private func createAlbum() { let fetchOptions = PHFetchOptions() fetchOptions.predicate = NSPredicate(format: "title = %@", CustomPhotoAlbum.albumName) let collection : PHFetchResult = PHAssetCollection.fetchAssetCollectionsWithType(.Album, subtype: .Any, options: fetchOptions) if let _: AnyObject = collection.firstObject { self.albumFound = true assetCollection = collection.firstObject as! PHAssetCollection } else { PHPhotoLibrary.sharedPhotoLibrary().performChanges({ let createAlbumRequest : PHAssetCollectionChangeRequest = PHAssetCollectionChangeRequest.creationRequestForAssetCollectionWithTitle(CustomPhotoAlbum.albumName) self.assetCollectionPlaceholder = createAlbumRequest.placeholderForCreatedAssetCollection }, completionHandler: { success, error in self.albumFound = (success ? true: false) if (success) { let collectionFetchResult = PHAssetCollection.fetchAssetCollectionsWithLocalIdentifiers([self.assetCollectionPlaceholder.localIdentifier], options: nil) print(collectionFetchResult) self.assetCollection = collectionFetchResult.firstObject as! PHAssetCollection } }) } } // performChanges(changeBlock: dispatch_block_t, completionHandler: ((Bool, NSError?) -> Void)?) func saveImage(image: UIImage) { if self.assetCollection != nil { PHPhotoLibrary.sharedPhotoLibrary().performChanges({ let assetChangeRequest = PHAssetChangeRequest.creationRequestForAssetFromImage(image) let assetPlaceholder = assetChangeRequest.placeholderForCreatedAsset let albumChangeRequest = PHAssetCollectionChangeRequest(forAssetCollection: self.assetCollection) albumChangeRequest?.addAssets([assetPlaceholder!]) }, completionHandler: { success, error in if error != nil { print(error) } else { } }) } } }
50e4975bc20fab80d1bf9f032b30dfa7
39.506849
176
0.628678
false
false
false
false
jxxcarlson/exploring_swift
refs/heads/master
heatFlow.playground/Contents.swift
mit
1
import Cocoa typealias vector = [Double] typealias matrix = [vector] func next_state(x: vector, k: Double) -> vector { var y = vector(count: x.count, repeatedValue:0.0) let lastIndex = x.count - 1 // Boundary conditions: y[0] = x[0] y[lastIndex] = x[lastIndex] for (var i = 1; i < lastIndex; i++) { let u = (k/2)*(x[i-1] + x[i + 1]) let v = (1-k)*x[i] y[i] = u + v } return y } func run(initial_state:vector, n: Int) -> matrix { var sa:matrix = [initial_state] for(var i = 1; i < n; i++) { sa = sa + [next_state(sa[i-1], k: 0.8)] } return sa } var c1: vector = [1.0, 0, 0, 0, 0, 0.3, 0.9, 0.3, 0, 0] var result = run(c1, n: 10) for state in result { print(state) } print(result[0]) result.count result[0].count class Thermograph { var state = vector() init( data: vector ) { state = data } func draw(frame: NSRect) { let width = frame.width let height = frame.height let n = state.count var x = CGFloat(0.0) let dx = CGFloat(width/CGFloat(n)) for (var i = 0; i < n; i++) { let currentRect = NSMakeRect(x, 0, dx, height) x = x + dx let temperature = CGFloat(state[i]) let currentColor = NSColor(red: temperature, green: 0.0, blue: 0.0, alpha: 1.0) currentColor.set() NSRectFill(currentRect) } } } class Thermograph2D { var state = matrix() init( data: matrix ) { state = data } func draw(frame: NSRect) { let width = frame.width let height = frame.height let n_rows = state.count let n_cols = (state[0]).count var x = CGFloat(0.0) var y = CGFloat(0.0) let dx = CGFloat(width/CGFloat(n_cols)) let dy = CGFloat(height/CGFloat(n_rows)) for (var row = 0; row < n_rows; row++) { x = CGFloat(0.0) for (var col = 0; col < n_cols; col++ ) { let currentRect = NSMakeRect(x, y, dx, dy) x = x + dx let temperature = CGFloat(state[row][col]) print("t[\(row),\(col)] = \(temperature)") let currentColor = NSColor(red: temperature, green: 0.0, blue: 0.0, alpha: 1.0) currentColor.set() NSRectFill(currentRect) } y = y + dy } } } let k = 3 let tg = Thermograph(data:result[k]) // let tg = Thermograph(data:[1, 0.8, 0.6, 0.4, 0.2, 0.0, 0.2, 0.4, 0.6, 0.8, 1.0]) print(tg.state) class GView: NSView { override func drawRect(dirtyRect: NSRect) { tg.draw(frame) } } let view = GView(frame: NSRect(x: 0, y: 0, width: 500, height: 20)) let tg2d = Thermograph2D(data: result) class GView2D: NSView { override func drawRect(dirtyRect: NSRect) { tg2d.draw(frame) } } let view2D = GView2D(frame: NSRect(x: 0, y: 0, width: 500, height: 500))
5596f6832377fc9fadce2b51395daf51
20.085526
83
0.489236
false
false
false
false
TENDIGI/Obsidian-UI-iOS
refs/heads/master
src/CharacterTextView.swift
mit
1
// // CharacterTextView.swift // Alfredo // // Created by Eric Kunz on 10/26/15. // Copyright © 2015 TENDIGI, LLC. All rights reserved. // import Foundation import UIKit import QuartzCore import CoreText class CharacterTextView: UITextView, NSLayoutManagerDelegate { var oldCharacterTextLayers: [CALayer] = [] var characterTextLayers: [CALayer] = [] override var text: String! { get { return super.text } set { self.attributedText = NSAttributedString(string: newValue) } } override var attributedText: NSAttributedString! { get { return super.attributedText } set { cleanOutOldCharacterTextLayers() oldCharacterTextLayers = Array<CALayer>(characterTextLayers) let newAttributedText = NSMutableAttributedString(attributedString: newValue) newAttributedText.addAttribute(NSAttributedStringKey.foregroundColor, value:UIColor.clear, range: NSRange(location: 0, length: newValue.length)) super.attributedText = newAttributedText } } override init(frame: CGRect, textContainer: NSTextContainer!) { super.init(frame: frame, textContainer: textContainer) setupLayoutManager() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setupLayoutManager() } override func awakeFromNib() { super.awakeFromNib() setupLayoutManager() } func setupLayoutManager() { layoutManager.delegate = self } func layoutManager(_ layoutManager: NSLayoutManager, didCompleteLayoutFor textContainer: NSTextContainer?, atEnd layoutFinishedFlag: Bool) { calculateTextLayers() } func calculateTextLayers() { let wordRange = NSRange(location: 0, length: attributedText.length) let attributedString = self.internalAttributedText() // for var index = wordRange.location; index < wordRange.length+wordRange.location; index += 0 { // let glyphRange = NSRange(location: index, length: 1) // let characterRange = layoutManager.characterRange(forGlyphRange: glyphRange, actualGlyphRange:nil) // let textContainer = layoutManager.textContainer(forGlyphAt: index, effectiveRange: nil) // var glyphRect = layoutManager.boundingRect(forGlyphRange: glyphRange, in: textContainer!) // let location = layoutManager.location(forGlyphAt: index) // let kerningRange = layoutManager.range(ofNominallySpacedGlyphsContaining: index) // // if kerningRange.length > 1 && kerningRange.location == index { // let previousLayer = self.characterTextLayers[self.characterTextLayers.endIndex] // var frame = previousLayer.frame // frame.size.width += (glyphRect.maxX+location.x)-frame.maxX // previousLayer.frame = frame // } // // // glyphRect.origin.y += location.y-(glyphRect.height/2) // let textLayer = CATextLayer(frame: glyphRect, string: (attributedString?.attributedSubstring(from: characterRange))!) // // layer.addSublayer(textLayer) // characterTextLayers.append(textLayer) // // let stepGlyphRange = layoutManager.glyphRange(forCharacterRange: characterRange, actualCharacterRange:nil) // index += stepGlyphRange.length // } } func internalAttributedText() -> NSMutableAttributedString! { let wordRange = NSRange(location: 0, length: self.attributedText.length) let attributedText = NSMutableAttributedString(string: text) attributedText.addAttribute(NSAttributedStringKey.foregroundColor, value: textColor!.cgColor, range: wordRange) attributedText.addAttribute(NSAttributedStringKey.font, value: font!, range: wordRange) return attributedText } func cleanOutOldCharacterTextLayers() { //Remove all text layers from the superview for textLayer in oldCharacterTextLayers { textLayer.removeFromSuperlayer() } //clean out the text layer characterTextLayers.removeAll(keepingCapacity: false) } }
f7614c5a4e9d6fd2631dc6590fbf7663
35.594828
156
0.669022
false
false
false
false
RobinFalko/Ubergang
refs/heads/master
Examples/TweenApp/Pods/Ubergang/Ubergang/Core/UTweenSetup.swift
apache-2.0
1
// // UTweenSetup.swift // Ubergang // // Created by RF on 11/07/16. // Copyright © 2016 Robin Falko. All rights reserved. // import Foundation open class UTweenSetup { open static let instance = UTweenSetup() fileprivate var isLoggingEnabled = false internal lazy var logger: UTweenLoggable? = { guard UTweenSetup.instance.isLoggingEnabled else { return nil } return UTweenLogger() }() fileprivate init() {} open func enableLogging(_ enabled: Bool) { isLoggingEnabled = enabled } open func enableLogging(_ enabled: Bool, withLogger logger: UTweenLoggable) { enableLogging(enabled) self.logger = logger } }
9c28a138c661bd7af9ad34f934e37809
22.032258
81
0.644258
false
false
false
false
Coderian/SwiftedGPX
refs/heads/master
SwiftedGPX/Elements/Satellites.swift
mit
1
// // Sat.swift // SwiftedGPX // // Created by 佐々木 均 on 2016/02/16. // Copyright © 2016年 S-Parts. All rights reserved. // import Foundation /// GPX Satellites /// /// [GPX 1.1 schema](http://www.topografix.com/GPX/1/1/gpx.xsd) /// /// <xsd:element name="sat" type="xsd:nonNegativeInteger" minOccurs="0"> /// <xsd:annotation> /// <xsd:documentation> /// Number of satellites used to calculate the GPX fix. /// </xsd:documentation> /// </xsd:annotation> /// </xsd:element> public class Satellites : SPXMLElement, HasXMLElementValue, HasXMLElementSimpleValue { public static var elementName: String = "sat" public override var parent:SPXMLElement! { didSet { // 複数回呼ばれたて同じものがある場合は追加しない if self.parent.childs.contains(self) == false { self.parent.childs.insert(self) switch parent { case let v as WayPoint: v.value.sat = self case let v as TrackPoint: v.value.sat = self case let v as RoutePoint: v.value.sat = self default: break } } } } public var value: UInt! public func makeRelation(contents:String, parent:SPXMLElement) -> SPXMLElement{ self.value = UInt(contents) self.parent = parent return parent } public required init(attributes:[String:String]){ super.init(attributes: attributes) } }
08f3c3907e08084d0053687bb00735c3
30.404255
86
0.589153
false
false
false
false
izotx/iTenWired-Swift
refs/heads/master
Conference App/MapViewController.swift
bsd-2-clause
1
// Copyright (c) 2016, Izotx // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of Izotx nor the names of its contributors may be used to // endorse or promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // MapViewController.swift // Conference App // // Created by Julian L on 4/8/16. import UIKit import MapKit import CoreLocation class MapViewController: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate { // Outlets for Map, and Segment Result @IBOutlet weak var segmentResult: UISegmentedControl! @IBOutlet weak var mainMap: MKMapView! @IBOutlet weak var segmentStyle: UISegmentedControl! /// CLLocation Manager var locationManager: CLLocationManager = CLLocationManager() /// The Start Location var startLocation: CLLocation! /// The destination location var destination: MKMapItem? // Pulls Map Data var mapController: MapData = MapData() var locArray: [ConferenceLocation] = [] var annotationArray: [AddAnnotation] = [] // Coordinates for Center Location var latSum:Double = 0.00 var longSum:Double = 0.00 // Fallback in case JSON does not load var mainLatitude: CLLocationDegrees = 30.331991 // Need to get from JSON var mainLongitude: CLLocationDegrees = -87.136002 // Need to get from JSON var locationStatus : NSString = "Not Started" @IBAction func openDirections(sender: AnyObject) { // Segmented Control on the Bottom of Screen (iTenWired, My Location, & Directions) switch sender.selectedSegmentIndex { case 0: // Show All Map Annotations let newCoords = CLLocationCoordinate2D(latitude: CLLocationDegrees(latSum), longitude: CLLocationDegrees(longSum)) let span = MKCoordinateSpan(latitudeDelta: 0.5, longitudeDelta: 0.5) let newRegion:MKCoordinateRegion = MKCoordinateRegion(center:newCoords, span:span ) self.mainMap.setRegion(newRegion, animated: true) case 1: // Show User's Location on the Map self.mainMap.showsUserLocation = true; let latDelta:CLLocationDegrees = 0.04 let lonDelta:CLLocationDegrees = 0.04 // If lat & long are available, center map on location if let latitude:CLLocationDegrees = locationManager.location?.coordinate.latitude { if let longitude:CLLocationDegrees = locationManager.location?.coordinate.longitude { let userLocation: CLLocationCoordinate2D = CLLocationCoordinate2DMake(latitude, longitude) let span:MKCoordinateSpan = MKCoordinateSpanMake(latDelta, lonDelta) let region:MKCoordinateRegion = MKCoordinateRegionMake(userLocation, span) mainMap.setRegion(region, animated: false) } } default: break; } } @IBAction func menuButtonAction(sender: AnyObject) { if let splitController = self.splitViewController{ if !splitController.collapsed { splitController.toggleMasterView() } } } override func viewDidLoad() { super.viewDidLoad() segmentStyle.layer.cornerRadius = 5 // Setup the Map and Location Manager self.locationManager.requestWhenInUseAuthorization() locationManager.desiredAccuracy = kCLLocationAccuracyBest locationManager.delegate = self self.mainMap.delegate = self startLocation = nil // Retrieves locations from MapData and loaded into locArray for locs in mapController.conferenceLocations { locArray.append(locs) } if (annotationArray.count == 0) { addNotations() } if let splitController = self.splitViewController{ splitController.toggleMasterView() } } // Adds the Info Button to all of the Annotations func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? { let identifier = "LocationAnnotation" if annotation.isKindOfClass(AddAnnotation.self) { if let annotationView = mapView.dequeueReusableAnnotationViewWithIdentifier(identifier) { annotationView.annotation = annotation return annotationView } else { let annotationView = MKPinAnnotationView(annotation:annotation, reuseIdentifier:identifier) annotationView.enabled = true annotationView.canShowCallout = true let btn = UIButton(type: .DetailDisclosure) annotationView.rightCalloutAccessoryView = btn return annotationView } } return nil } // Object that Selected Map Annotation will be Stored In var selectedAnnotation: AddAnnotation! // Called when Annotation Info Button is Selected func mapView(mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) { if control == view.rightCalloutAccessoryView { if let tempName = view.annotation?.title, let tempLat = view.annotation?.coordinate.latitude, let tempLong = view.annotation?.coordinate.longitude, let tempSub = view.annotation?.subtitle { let tempCoord = CLLocationCoordinate2D(latitude: tempLat, longitude: tempLong) selectedAnnotation = AddAnnotation(title: tempName!, coordinate: tempCoord, info: tempSub!) } //selectedAnnotation = view.annotation as? MKPointAnnotation // Launches AnnotationDetailViewController performSegueWithIdentifier("NextScene", sender: self) } } // Preparing to segue to AnnotationDetailViewController and sending the selected annotation data with it override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if let destination = segue.destinationViewController as? AnnotationDetailViewController { destination.receivedAnnotation = selectedAnnotation } } // This is called when viewDidLoad() and sets up all of the annotations on the map func addNotations() { // Centers Map on Main Location (Called on Launch) var count = 0.00 // All locations "loc" are stored in this array and converted into annotations for locs in locArray { if let tempLat = CLLocationDegrees(locs.latitude), let tempLong = CLLocationDegrees(locs.longitude), let tempName:String = locs.name, let tempDesc:String = locs.description { let tempCoord = CLLocationCoordinate2D(latitude: CLLocationDegrees(tempLat), longitude: CLLocationDegrees(tempLong)) latSum += Double(tempLat) longSum += Double(tempLong) let tempAnnotation = AddAnnotation(title: tempName, coordinate: tempCoord, info: tempDesc) annotationArray.append(tempAnnotation) count += 1 } } // Add annotations to the map if !(annotationArray.isEmpty) { self.mainMap.addAnnotations(annotationArray) // Gets the average coordinates to center the map region on latSum = latSum/count longSum = longSum/count // Centers the map based on average of locations let newCoords = CLLocationCoordinate2D(latitude: CLLocationDegrees(latSum), longitude: CLLocationDegrees(longSum)) let span = MKCoordinateSpan(latitudeDelta: 0.5, longitudeDelta: 0.5) let newRegion:MKCoordinateRegion = MKCoordinateRegion(center:newCoords, span:span ) self.mainMap.setRegion(newRegion, animated: true) self.mainMap.showsUserLocation = true; } else { // // Presents an error message saying "No Internet Connection" // let noInternet = UIAlertController(title: "Internet Connection", message: "Map cannot be loaded because there is no internet connection.", preferredStyle: UIAlertControllerStyle.Alert) // // noInternet.addAction(UIAlertAction(title: "Dismiss", style: .Default, handler: { (action: UIAlertAction!) in // print("Handle Ok logic here") // })) // // presentViewController(noInternet, animated: true, completion: nil) latSum = mainLatitude longSum = mainLongitude let newCoords = CLLocationCoordinate2D(latitude: CLLocationDegrees(latSum), longitude: CLLocationDegrees(longSum)) let span = MKCoordinateSpan(latitudeDelta: 0.5, longitudeDelta: 0.5) let newRegion:MKCoordinateRegion = MKCoordinateRegion(center:newCoords, span:span ) self.mainMap.setRegion(newRegion, animated: true) } } func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) { var shouldIAllow = false switch status { case CLAuthorizationStatus.Restricted: locationStatus = "Restricted Access to location" case CLAuthorizationStatus.Denied: locationStatus = "User denied access to location" case CLAuthorizationStatus.NotDetermined: locationStatus = "Status not determined" default: locationStatus = "Allowed to location Access" shouldIAllow = true } NSNotificationCenter.defaultCenter().postNotificationName("LabelHasbeenUpdated", object: nil) if (shouldIAllow == true) { NSLog("Location to Allowed") // Start location services locationManager.startUpdatingLocation() } else { NSLog("Denied access: \(locationStatus)") } } @IBAction func showMenu(sender: AnyObject) { if let splitController = self.splitViewController{ if !splitController.collapsed { splitController.toggleMasterView() } else{ let rightNavController = splitViewController!.viewControllers.first as! UINavigationController rightNavController.popToRootViewControllerAnimated(true) } } } }
7b4900d3f088818231f9297f0330fa07
41.248276
201
0.639732
false
false
false
false
lijianwei-jj/OOSegmentViewController
refs/heads/master
OOSegmentViewController/OOCursorMoveEffect.swift
mit
1
// // OOCursorMoveEffect.swift // OOSegmentViewController // // Created by lee on 16/7/6. // Copyright © 2016年 clearlove. All rights reserved. // import UIKit @objc public protocol CursorMoveEffect { @objc optional func scroll(_ scrollView:UIScrollView,navBar:OOSegmentNavigationBar,cursor:UIView,newItem:UIButton,oldItem:UIButton); @objc optional func scroll(_ scrollView:UIScrollView,navBar:OOSegmentNavigationBar,cursor:UIView,fullWidth:CGFloat,xScale:CGFloat,correctXScale:CGFloat,computeWidth:CGFloat,leftXOffset:CGFloat,centerXOffset:CGFloat,finished:Bool); } open class OOCursorMoveEffect: CursorMoveEffect { // @objc public func scroll(scrollView: UIScrollView, navBar: OOSegmentNavigationBar, cursor: UIView, newItem: UIButton, oldItem: UIButton) { // let fullWidth = CGRectGetWidth(scrollView.frame) // let button = newItem , oldButton = oldItem // // let xScale = scrollView.contentOffset.x % fullWidth / fullWidth // // let indicatorWidth = button.frame.size.width // titleWidthAtFont(titleFont, index: index) // let oldWidth = oldButton.frame.size.width // titleWidthAtFont(titleFont, index: oldIndex) // let f = CGFloat(newItem.tag - oldItem.tag) // var s = (f > 0 ? 1.0 - (xScale == 0 ? 1.0 : xScale) : xScale) // == 1.0 ? xScale : 0 // s = s < 0.01 || s > 0.99 ? round(s) : s // let w = (oldWidth - indicatorWidth) * s + indicatorWidth // let xOffset = (oldButton.center.x - button.center.x) * s // let x = xOffset + button.center.x // // print(xOffset) // // print("nx:\(button.center.x) ox:\(oldButton.center.x) x:\(x) f:\(f) s:\(s) xs:\(xScale)") // // // cursor.frame.size.width = w // cursor.center.x = x // if navBar.contentSize.width > fullWidth { // UIView.animateWithDuration(0.3) { // if CGRectGetMaxX(navBar.bounds) < CGRectGetMaxX(button.frame) + 2 { // navBar.contentOffset.x += (CGRectGetMaxX(button.frame) - CGRectGetMaxX(navBar.bounds) + 2) + navBar.itemOffset // } else if CGRectGetMinX(navBar.bounds) > CGRectGetMinX(button.frame) - 2 { // navBar.contentOffset.x = CGRectGetMinX(button.frame) - 2 - navBar.itemOffset // } // } // } // } @objc open func scroll(_ scrollView: UIScrollView, navBar: OOSegmentNavigationBar, cursor: UIView, fullWidth: CGFloat, xScale: CGFloat, correctXScale: CGFloat, computeWidth: CGFloat, leftXOffset: CGFloat, centerXOffset: CGFloat, finished: Bool) { // let maxMargin = fullWidth - computeWidth - navBar.itemMargin - navBar.itemOffset // let effect = OOCursorLeftDockMoveEffect(leftMargin: leftXOffset >= maxMargin ? maxMargin : leftXOffset ) // effect.scroll(scrollView, navBar: navBar, cursor: cursor, fullWidth: fullWidth, xScale: xScale, correctXScale: correctXScale, computeWidth: computeWidth, leftXOffset: leftXOffset, centerXOffset: centerXOffset, finished: finished) cursor.frame.size.width = computeWidth cursor.center.x = centerXOffset let minOffset = leftXOffset - navBar.itemOffset, maxOffset = leftXOffset + computeWidth + navBar.itemOffset if navBar.bounds.maxX < maxOffset { navBar.contentOffset.x += maxOffset - navBar.bounds.maxX } else if navBar.contentOffset.x > minOffset { navBar.contentOffset.x = minOffset } } } open class OOCursorCenterMoveEffect : CursorMoveEffect { // // @objc public func scroll(scrollView: UIScrollView, navBar: OOSegmentNavigationBar, cursor: UIView, newItem: UIButton, oldItem: UIButton) { // let fullWidth = CGRectGetWidth(scrollView.frame) // let button = newItem , oldButton = oldItem // // let xScale = scrollView.contentOffset.x % fullWidth / fullWidth // // let indicatorWidth = button.frame.size.width // titleWidthAtFont(titleFont, index: index) // let oldWidth = oldButton.frame.size.width // titleWidthAtFont(titleFont, index: oldIndex) // let f = CGFloat(newItem.tag - oldItem.tag) // var s = (f > 0 ? 1.0 - (xScale == 0 ? 1.0 : xScale) : xScale) // == 1.0 ? xScale : 0 // s = s < 0.01 || s > 0.99 ? round(s) : s // let w = (oldWidth - indicatorWidth) * s + indicatorWidth // let xOffset = (oldButton.center.x - button.center.x) * s // let x = xOffset + button.center.x // // print(xOffset) // // print("nx:\(button.center.x) ox:\(oldButton.center.x) x:\(x) f:\(f) s:\(s) xs:\(xScale)") // // // cursor.frame.size.width = w // cursor.center.x = x // if navBar.contentSize.width > fullWidth { // var offset = CGFloat(0) // if button.center.x < fullWidth / 2.0 || button.center.x > navBar.contentSize.width - fullWidth / 2.0 { // offset = button.center.x < fullWidth / 2.0 ? fullWidth / 2.0 - button.center.x : navBar.contentSize.width - fullWidth / 2.0 - button.center.x // } // UIView.animateWithDuration(0.3) { // navBar.contentOffset.x = button.center.x - fullWidth / 2.0 + offset // } // } // } @objc open func scroll(_ scrollView: UIScrollView, navBar: OOSegmentNavigationBar, cursor: UIView, fullWidth: CGFloat, xScale: CGFloat, correctXScale: CGFloat, computeWidth: CGFloat, leftXOffset: CGFloat, centerXOffset: CGFloat, finished: Bool) { let effect = OOCursorLeftDockMoveEffect(leftMargin: (fullWidth - computeWidth) / 2.0) effect.scroll(scrollView, navBar: navBar, cursor: cursor, fullWidth: fullWidth, xScale: xScale, correctXScale: correctXScale, computeWidth: computeWidth, leftXOffset: centerXOffset - computeWidth / 2.0, centerXOffset: centerXOffset, finished: finished) } } open class OOCursorLeftDockMoveEffect : CursorMoveEffect { open var leftMargin : CGFloat public init(leftMargin:CGFloat = 40) { self.leftMargin = leftMargin } // @objc public func scroll(scrollView: UIScrollView, navBar: OOSegmentNavigationBar, cursor: UIView, newItem: UIButton, oldItem: UIButton) { // let fullWidth = CGRectGetWidth(scrollView.frame) // let button = newItem , oldButton = oldItem // // let xScale = scrollView.contentOffset.x % fullWidth / fullWidth // // let indicatorWidth = button.frame.size.width // titleWidthAtFont(titleFont, index: index) // let oldWidth = oldButton.frame.size.width // titleWidthAtFont(titleFont, index: oldIndex) // let f = CGFloat(newItem.tag - oldItem.tag) // var s = (f > 0 ? 1.0 - (xScale == 0 ? 1.0 : xScale) : xScale) // == 1.0 ? xScale : 0 // s = s < 0.01 || s > 0.99 ? round(s) : s // let w = round((oldWidth - indicatorWidth) * s + indicatorWidth) // let xOffset = round((oldButton.frame.origin.x - button.frame.origin.x) * s) // let x = xOffset + button.frame.origin.x // // cursor.frame.size.width = w // cursor.frame.origin.x = x // if navBar.contentSize.width > fullWidth { // let targetX = x - navBar.itemMargin - leftMargin // if targetX <= navBar.contentSize.width - fullWidth && targetX >= 0 { // navBar.contentOffset.x = targetX // } // } // // } @objc open func scroll(_ scrollView: UIScrollView, navBar: OOSegmentNavigationBar, cursor: UIView, fullWidth: CGFloat, xScale: CGFloat, correctXScale: CGFloat, computeWidth: CGFloat, leftXOffset: CGFloat, centerXOffset: CGFloat, finished: Bool) { cursor.frame.size.width = computeWidth cursor.frame.origin.x = leftXOffset if navBar.contentSize.width > fullWidth { let targetX = leftXOffset - leftMargin guard targetX >= 0 else { return } let maxOffset = navBar.contentSize.width - fullWidth if targetX <= maxOffset { navBar.contentOffset.x = targetX } else if navBar.contentOffset.x < maxOffset { navBar.contentOffset.x = maxOffset } } } }
7e528edd45eff832fbefe9ae2ad6b6e0
51.708861
260
0.62512
false
false
false
false
fletcher89/SwiftyRC
refs/heads/master
Sources/SwiftyRC/Types/Message.swift
mit
1
// // Message.swift // SwiftyRC // // Created by Christian on 22.07.17. // import Foundation // MARK: Internal internal extension IRC { /// Represents a message /// /// - ping: A `PING` message /// - serverReply: A numeric code reply /// - event: A event /// - unknown: I have no idea enum Message { case ping(ping: IRC.Ping) case serverReply(reply: IRC.Reply) case event(event: IRC.Event) case unknown(rawMessage: IRC.RawMessage) } } // MARK: Internal Message API internal extension IRC.Message { /// Returns an `IRC.Message` case from a raw message /// /// - Parameter message: The raw message /// - Returns: - static func from(rawMessage message: IRC.RawMessage) -> IRC.Message { var prefix = "" var messageSplitBySpaces = message.split(separator: " ") if messageSplitBySpaces.count >= 3 && message.characters[message.characters.startIndex] == ":" { // If we have three or more elements and the first one is a colon... we found ourselves an event or server reply code! // First, extract the prefix prefix = String(messageSplitBySpaces[0]) prefix = String(prefix[prefix.index(after: prefix.startIndex)...]) // Check if we're having an event or a code reply by trying to convert the second element in the message to Int if let code = Int(String(messageSplitBySpaces[1])) { // We have a code reply return .serverReply(reply: IRC.Reply( type: IRC.ReplyType(rawValue: code) ?? IRC.ReplyType.unknownReplyType, rawMessage: message ) ) } else { // Or an event... // Remove the prefix from the split message array messageSplitBySpaces.remove(at: 0) // The next item in the list is the event // Try to extract an `IRC.EventType` from this, if we don't get anything, just return .notImplemented // Finally, convert the messages array into an array of strings (from substrings) let rawEvent = String(messageSplitBySpaces.remove(at: 0)) let eventType = IRC.EventType(rawValue: rawEvent) ?? IRC.EventType.notImplemented let arguments = messageSplitBySpaces.map { String($0) } guard let user = IRC.User(with: prefix) else { return .unknown(rawMessage: message) } // And return the event enum case return .event(event: IRC.Event( user: user, type: eventType, arguments: arguments, rawMessage: message ) ) } } else if message.hasPrefix("PING") { // Was it a PING instead? return .ping(ping: IRC.Ping( payload: String(message[message.index(message.startIndex, offsetBy: 5)...]), rawMessage: message ) ) } // Well... gotta catch this! return .unknown(rawMessage: message) } }
f701267d0221fea73945bc21e02ee02f
36.182796
130
0.520243
false
false
false
false
SusanDoggie/Doggie
refs/heads/main
Sources/DoggieGeometry/Bezier/LineSegment.swift
mit
1
// // LineSegment.swift // // The MIT License // Copyright (c) 2015 - 2022 Susan Cheng. 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. // @frozen public struct LineSegment<Element: ScalarMultiplicative>: BezierProtocol where Element.Scalar == Double { public var p0: Element public var p1: Element @inlinable @inline(__always) public init() { self.p0 = .zero self.p1 = .zero } @inlinable @inline(__always) public init(_ p0: Element, _ p1: Element) { self.p0 = p0 self.p1 = p1 } } extension Bezier { @inlinable @inline(__always) public init(_ bezier: LineSegment<Element>) { self.init(bezier.p0, bezier.p1) } } extension LineSegment: Hashable where Element: Hashable { } extension LineSegment: Decodable where Element: Decodable { @inlinable @inline(__always) public init(from decoder: Decoder) throws { var container = try decoder.unkeyedContainer() self.init(try container.decode(Element.self), try container.decode(Element.self)) } } extension LineSegment: Encodable where Element: Encodable { @inlinable @inline(__always) public func encode(to encoder: Encoder) throws { var container = encoder.unkeyedContainer() try container.encode(p0) try container.encode(p1) } } @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) extension LineSegment: Sendable where Element: Sendable { } extension LineSegment { @inlinable @inline(__always) public func map(_ transform: (Element) -> Element) -> LineSegment { return LineSegment(transform(p0), transform(p1)) } @inlinable @inline(__always) public func reduce<Result>(into initialResult: Result, _ updateAccumulatingResult: (inout Result, Element) -> Void) -> Result { var accumulator = initialResult updateAccumulatingResult(&accumulator, p0) updateAccumulatingResult(&accumulator, p1) return accumulator } @inlinable @inline(__always) public func combined(_ other: LineSegment, _ transform: (Element, Element) -> Element) -> LineSegment { return LineSegment(transform(p0, other.p0), transform(p1, other.p1)) } } extension LineSegment { public typealias Indices = Range<Int> @inlinable @inline(__always) public var startIndex: Int { return 0 } @inlinable @inline(__always) public var endIndex: Int { return 2 } @inlinable @inline(__always) public subscript(position: Int) -> Element { get { return withUnsafeTypePunnedPointer(of: self, to: Element.self) { $0[position] } } set { withUnsafeMutableTypePunnedPointer(of: &self, to: Element.self) { $0[position] = newValue } } } } extension LineSegment { @inlinable @inline(__always) public var start: Element { return p0 } @inlinable @inline(__always) public var end: Element { return p1 } @inlinable @inline(__always) public func eval(_ t: Double) -> Element { return p0 + t * (p1 - p0) } @inlinable @inline(__always) public func split(_ t: Double) -> (LineSegment, LineSegment) { let q0 = p0 + t * (p1 - p0) return (LineSegment(p0, q0), LineSegment(q0, p1)) } @inlinable @inline(__always) public func elevated() -> QuadBezier<Element> { return QuadBezier(p0, eval(0.5), p1) } @inlinable @inline(__always) public func derivative() -> LineSegment { let q = p1 - p0 return LineSegment(q, q) } } extension LineSegment where Element == Double { @inlinable @inline(__always) public var polynomial: Polynomial { let a = p0 let b = p1 - p0 return [a, b] } } extension LineSegment where Element == Point { @inlinable @inline(__always) public func _closest(_ point: Point) -> Double { let a = p0 - point let b = p1 - p0 let c = b.x * a.x + b.y * a.y let d = b.x * b.x + b.y * b.y return -c / d } @inlinable @inline(__always) public func distance(from point: Point) -> Double { let d = p1 - p0 let m = p0.y * p1.x - p0.x * p1.y return abs(d.y * point.x - d.x * point.y + m) / d.magnitude } } extension LineSegment where Element == Point { @inlinable @inline(__always) public func closest(_ point: Point, in range: ClosedRange<Double> = -.infinity ... .infinity) -> [Double] { let a = p0 - point let b = p1 - p0 return Polynomial(b.x * a.x + b.y * a.y, b.x * b.x + b.y * b.y).roots(in: range) } } extension LineSegment where Element == Point { @inlinable @inline(__always) public var area: Double { return 0.5 * (p0.x * p1.y - p0.y * p1.x) } } extension LineSegment where Element: Tensor { @inlinable @inline(__always) public func length(_ t: Double = 1) -> Double { return p0.distance(to: eval(t)) } @inlinable @inline(__always) public func inverseLength(_ length: Double) -> Double { return length / p0.distance(to: p1) } } extension LineSegment where Element == Point { @inlinable @inline(__always) public var boundary: Rect { let minX = Swift.min(p0.x, p1.x) let minY = Swift.min(p0.y, p1.y) let maxX = Swift.max(p0.x, p1.x) let maxY = Swift.max(p0.y, p1.y) return Rect(x: minX, y: minY, width: maxX - minX, height: maxY - minY) } } extension LineSegment where Element == Point { @inlinable @inline(__always) public func intersect(_ other: LineSegment) -> Point? { let q0 = p0 - p1 let q1 = other.p0 - other.p1 let d = q0.x * q1.y - q0.y * q1.x if d.almostZero() { return nil } let a = (p0.x * p1.y - p0.y * p1.x) / d let b = (other.p0.x * other.p1.y - other.p0.y * other.p1.x) / d return Point(x: q1.x * a - q0.x * b, y: q1.y * a - q0.y * b) } }
37c6491c3f43d3ab83427ce5267e5c49
25.893382
131
0.600137
false
false
false
false
karivalkama/Agricola-Scripture-Editor
refs/heads/master
TranslationEditor/UserCell.swift
mit
1
// // UserCell.swift // TranslationEditor // // Created by Mikko Hilpinen on 6.6.2017. // Copyright © 2017 SIL. All rights reserved. // import UIKit class UserCell: UITableViewCell { // OUTLETS --------------------- @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var createdLabel: UILabel! @IBOutlet weak var isAdminSwitch: UISwitch! @IBOutlet weak var clearPasswordButton: BasicButton! @IBOutlet weak var deleteButton: BasicButton! // ATTRIBUTES ----------------- static let identifier = "UserCell" private var setAdminAction: ((UITableViewCell, Bool) -> ())? private var passwordAction: ((UITableViewCell) -> ())? private var deleteAction: ((UITableViewCell) -> ())? // ACTIONS --------------------- @IBAction func adminValueChanged(_ sender: Any) { setAdminAction?(self, isAdminSwitch.isOn) } @IBAction func clearPasswordPressed(_ sender: Any) { passwordAction?(self) } @IBAction func deletePressed(_ sender: Any) { deleteAction?(self) } // OTHER METHODS ------------- func configure(name: String, created: Date, isAdmin: Bool, hasPassword: Bool, deleteEnabled: Bool, setAdminAction: @escaping (UITableViewCell, Bool) -> (), clearPasswordAction: @escaping (UITableViewCell) -> (), deleteAction: @escaping (UITableViewCell) -> ()) { self.passwordAction = clearPasswordAction self.deleteAction = deleteAction self.setAdminAction = setAdminAction nameLabel.text = name isAdminSwitch.isOn = isAdmin clearPasswordButton.isEnabled = hasPassword deleteButton.isEnabled = deleteEnabled let formatter = DateFormatter() formatter.dateStyle = .medium createdLabel.text = formatter.string(from: created) } }
04a547506bc62422c3748b0e97ff3bfc
24.343284
261
0.693168
false
false
false
false
ahayman/RxStream
refs/heads/master
RxStream/Streams/Cold.swift
mit
1
// // Cold.swift // RxStream // // Created by Aaron Hayman on 3/15/17. // Copyright © 2017 Aaron Hayman. All rights reserved. // import Foundation /** A Cold stream is a kind of stream that only produces values when it is asked to. A cold stream can be asked to produce a value by making a `request` anywhere down stream. It differs from other types of stream in that a cold stream will only produce one value per request. Moreover, the result of a request will _only_ be passed back down the chain that originally requested it. This prevents other branches from receiving requests they did not ask for. */ public class Cold<Request, Response> : Stream<Response> { public typealias ColdTask = (_ state: Observable<StreamState>, _ request: Request, _ response: (Result<Response>) -> Void) -> Void typealias ParentProcessor = (Request, EventPath) -> Void override var streamType: StreamType { return .cold } /// The processor responsible for filling a request. It can either be a ColdTask or a ParentProcessor (a Parent stream that can handle fill the request). private var requestProcessor: Either<ColdTask, ParentProcessor> /// The promise needed to pass into the promise task. lazy private var stateObservable: ObservableInput<StreamState> = ObservableInput(self.state) /// Override and observe didSet to update the observable override public var state: StreamState { didSet { stateObservable.set(state) } } func newSubStream<U>(_ op: String) -> Cold<Request, U> { return Cold<Request, U>(op: op) { [weak self] (request, key) in self?.process(request: request, withKey: key) } } func newMappedRequestStream<U>(mapper: @escaping (U) -> Request) -> Cold<U, Response> { return Cold<U, Response>(op: "mapRequest<\(String(describing: Request.self))>"){ [weak self] (request: U, key: EventPath) in self?.process(request: mapper(request), withKey: key) } } /** A cold stream must be initialized with a Task that takes a request and returns a response. A task should return only 1 response for each request. All other responses will be ignored. */ public init(task: @escaping ColdTask) { self.requestProcessor = Either(task) super.init(op: "Task") } init(op: String, processor: @escaping ParentProcessor) { self.requestProcessor = Either(processor) super.init(op: op) } private func make(request: Request, withKey key: EventPath, withTask task: @escaping ColdTask) { let work = { var key: EventPath? = key task(self.stateObservable, request) { guard let requestKey = key else { return } key = nil $0 .onFailure { self.process(event: .error($0), withKey: requestKey) } .onSuccess { self.process(event: .next($0), withKey: requestKey) } } } if let dispatch = self.dispatch { dispatch.execute(work) } else { work() } } private func process(request: Request, withKey key: EventPath) { guard isActive else { return } let key: EventPath = .key(id, next: key) requestProcessor .onLeft{ self.make(request: request, withKey: key, withTask: $0) } .onRight{ $0(request, key) } } /** Make a request from this stream. The response will be passed back once the task has completed. - parameters: - request: The request object to submit to the stream's task - share: **default:** false: If false, then the response will end here. If true, then the response will be passed to all attached streams. */ public func request(_ request: Request, share: Bool = false) { process(request: request, withKey: share ? .share : .end) } /** Make a request from this stream. The response will be passed back once the task has completed. - parameter request: The request object to submit to the stream's task */ public func request(_ request: Request) { process(request: request, withKey: .end) } /// Terminate the Cold Stream with a reason. public func terminate(withReason reason: Termination) { self.process(event: .terminate(reason: reason), withKey: .share) } deinit { if self.isActive { self.process(event: .terminate(reason: .completed)) } } }
cf0dd189f59d340b85d94b87b49723b1
34.380165
156
0.678813
false
false
false
false
kfarst/alarm
refs/heads/master
alarm/TimePresenter.swift
mit
1
// // TimePresenter.swift // alarm // // Created by Michael Lewis on 3/8/15. // Copyright (c) 2015 Kevin Farst. All rights reserved. // import Foundation class TimePresenter: Comparable { // Support time-based, or sunrise/sunset based let type: AlarmEntity.AlarmType let time: RawTime? // Time type is required, and a raw time is optional init(type: AlarmEntity.AlarmType, time: RawTime? = nil) { self.type = type self.time = time // If we're dealing with an AlarmType of .Time, ensure // that we have a valid `time`. if type == .Time { assert(time != nil) } } // Allow creation by raw hours/minutes convenience init(hour24: Int, minute: Int) { self.init(type: .Time, time: RawTime(hour24: hour24, minute: minute)) } // Create a TimePresenter, using an AlarmEntity as the base convenience init(alarmEntity: AlarmEntity) { switch alarmEntity.alarmTypeEnum { case .Time: self.init( hour24: Int(alarmEntity.hour), minute: Int(alarmEntity.minute) ) default: self.init(type: alarmEntity.alarmTypeEnum) } } // This presenter supports static times as well as sun-based times // This function will return a raw time representing what the // true time is, no matter how this presenter was constructed. func calculatedTime() -> RawTime? { switch self.type { case .Time: return time! case .Sunrise: return SunriseHelper.singleton.sunrise() case .Sunset: return SunriseHelper.singleton.sunset() } } // Don't include the am/pm portion in the main wheel func stringForWheelDisplay() -> String { // Precalculate the time let time = calculatedTime() switch self.type { case .Time: // Special formatting for special times if time!.hour24 == 0 && time!.minute == 0 { return "midnight" } else if time!.hour24 == 12 && time!.minute == 0 { return "noon" } else { return String(format: "%2d : %02d", time!.hour12, time!.minute) } case .Sunrise: // If we can't comput the time, just return "sunrise" if (time == nil) { return "sunrise" } else { return String(format: "sunrise (%2d:%02d)", time!.hour12, time!.minute) } case .Sunset: // If we can't comput the time, just return "sunrise" if (time == nil) { return "sunset" } else { return String(format: "sunset (%2d:%02d)", time!.hour12, time!.minute) } } } // The table display view doesn't need times for sunrise/sunset func stringForTableDisplay() -> String { switch self.type { case .Time: // Special formatting for special times if time!.hour24 == 0 && time!.minute == 0 { return "midnight" } else if time!.hour24 == 12 && time!.minute == 0 { return "noon" } else { return String(format: "%2d:%02d %@", time!.hour12, time!.minute, TimePresenter.amPmToString(time!.amOrPm)) } case .Sunrise: return "Sunrise" case .Sunset: return "Sunset" } } func stringForAmPm() -> String { if let time = calculatedTime() { return TimePresenter.amPmToString(time.amOrPm) } else { return "error" } } func primaryStringForTwoPartDisplay() -> String { switch self.type { case .Time: // Special formatting for special times if time!.hour24 == 0 && time!.minute == 0 { return "midnight" } else if time!.hour24 == 12 && time!.minute == 0 { return "noon" } else { return String(format: "%2d:%02d %@", time!.hour12, time!.minute, TimePresenter.amPmToString(time!.amOrPm)) } case .Sunrise: return "Sunrise" case .Sunset: return "Sunset" } } func secondaryStringForTwoPartDisplay() -> String { switch self.type { case .Time: return "" case .Sunrise, .Sunset: let time = calculatedTime() // Special formatting for special times if time!.hour24 == 0 && time!.minute == 0 { return "midnight" } else if time!.hour24 == 12 && time!.minute == 0 { return "noon" } else { return String(format: "%2d:%02d %@", time!.hour12, time!.minute, TimePresenter.amPmToString(time!.amOrPm)) } } } // Generate all of the time elements that we will allow. // This includes sunset and sunrise. class func generateAllElements() -> Array<TimePresenter> { // Start by generating the static times var times = (0...23).map { hour in [0, 15, 30, 45].map { minute in TimePresenter(hour24: hour, minute: minute) } }.reduce([], combine: +) // Add in sunrise and sunset. // Skip them if they can't be calculated let sunrise = TimePresenter(type: AlarmEntity.AlarmType.Sunrise) if sunrise.calculatedTime() != nil { times.append(sunrise) } let sunset = TimePresenter(type: AlarmEntity.AlarmType.Sunset) if sunset.calculatedTime() != nil { times.append(sunset) } // Sort the entire array, based upon calculated time return times.sorted { $0 < $1 } } class func amPmToString(amPm: RawTime.AmPm) -> String { switch amPm { case .AM: return "am" case .PM: return "pm" } } /* Private */ } // Comparison operators for TimePresenter func <(left: TimePresenter, right: TimePresenter) -> Bool { return left.calculatedTime() < right.calculatedTime() } func ==(left: TimePresenter, right: TimePresenter) -> Bool { // They have to share the same type to be equal if left.type == right.type { switch left.type { case .Time: // If it's static time, make sure it's the same return left.time == right.time default: // If it's sunrise/sunset, type alone is enough return true } } else { // If type is different, they're inequal return false } }
e567657151e94d339c86600d1d23be6d
26.882629
114
0.61054
false
false
false
false
faimin/ZDOpenSourceDemo
refs/heads/master
ZDOpenSourceSwiftDemo/Pods/lottie-ios/lottie-swift/src/Private/Utility/Extensions/AnimationKeypathExtension.swift
mit
1
// // KeypathSearchableExtension.swift // lottie-swift // // Created by Brandon Withrow on 2/4/19. // import Foundation import QuartzCore extension KeypathSearchable { func animatorNodes(for keyPath: AnimationKeypath) -> [AnimatorNode]? { // Make sure there is a current key path. guard let currentKey = keyPath.currentKey else { return nil } // Now try popping the keypath for wildcard / child search guard let nextKeypath = keyPath.popKey(keypathName) else { // We may be on the final keypath. Check for match. if let node = self as? AnimatorNode, currentKey.equalsKeypath(keypathName) { // This is the final keypath and matches self. Return.s return [node] } /// Nope. Stop Search return nil } var results: [AnimatorNode] = [] if let node = self as? AnimatorNode, nextKeypath.currentKey == nil { // Keypath matched self and was the final keypath. results.append(node) } for childNode in childKeypaths { // Check if the child has any nodes matching the next keypath. if let foundNodes = childNode.animatorNodes(for: nextKeypath) { results.append(contentsOf: foundNodes) } // In this case the current key is fuzzy, and both child and self match the next keyname. Keep digging! if currentKey.keyPathType == .fuzzyWildcard, let nextKeypath = keyPath.nextKeypath, nextKeypath.equalsKeypath(childNode.keypathName), let foundNodes = childNode.animatorNodes(for: keyPath) { results.append(contentsOf: foundNodes) } } guard results.count > 0 else { return nil } return results } func nodeProperties(for keyPath: AnimationKeypath) -> [AnyNodeProperty]? { guard let nextKeypath = keyPath.popKey(keypathName) else { /// Nope. Stop Search return nil } /// Keypath matches in some way. Continue the search. var results: [AnyNodeProperty] = [] /// Check if we have a property keypath yet if let propertyKey = nextKeypath.propertyKey, let property = keypathProperties[propertyKey] { /// We found a property! results.append(property) } if nextKeypath.nextKeypath != nil { /// Now check child keypaths. for child in childKeypaths { if let childProperties = child.nodeProperties(for: nextKeypath) { results.append(contentsOf: childProperties) } } } guard results.count > 0 else { return nil } return results } func layer(for keyPath: AnimationKeypath) -> CALayer? { if keyPath.nextKeypath == nil, let layerKey = keyPath.currentKey, layerKey.equalsKeypath(keypathName) { /// We found our layer! return keypathLayer } guard let nextKeypath = keyPath.popKey(keypathName) else { /// Nope. Stop Search return nil } if nextKeypath.nextKeypath != nil { /// Now check child keypaths. for child in childKeypaths { if let layer = child.layer(for: keyPath) { return layer } } } return nil } func logKeypaths(for keyPath: AnimationKeypath?) { let newKeypath: AnimationKeypath if let previousKeypath = keyPath { newKeypath = previousKeypath.appendingKey(keypathName) } else { newKeypath = AnimationKeypath(keys: [keypathName]) } print(newKeypath.fullPath) for key in keypathProperties.keys { print(newKeypath.appendingKey(key).fullPath) } for child in childKeypaths { child.logKeypaths(for: newKeypath) } } } extension AnimationKeypath { var currentKey: String? { return keys.first } var nextKeypath: String? { guard keys.count > 1 else { return nil } return keys[1] } var propertyKey: String? { if nextKeypath == nil { /// There are no more keypaths. This is a property key. return currentKey } if keys.count == 2, currentKey?.keyPathType == .fuzzyWildcard { /// The next keypath is the last and the current is a fuzzy key. return nextKeypath } return nil } // Pops the top keypath from the stack if the keyname matches. func popKey(_ keyname: String) -> AnimationKeypath? { guard let currentKey = currentKey, currentKey.equalsKeypath(keyname), keys.count > 1 else { // Current key either doesnt match or we are on the last key. return nil } // Pop the keypath from the stack and return the new stack. let newKeys: [String] if currentKey.keyPathType == .fuzzyWildcard { /// Dont remove if current key is a fuzzy wildcard, and if the next keypath doesnt equal keypathname if let nextKeypath = nextKeypath, nextKeypath.equalsKeypath(keyname) { /// Remove next two keypaths. This keypath breaks the wildcard. var oldKeys = keys oldKeys.remove(at: 0) oldKeys.remove(at: 0) newKeys = oldKeys } else { newKeys = keys } } else { var oldKeys = keys oldKeys.remove(at: 0) newKeys = oldKeys } return AnimationKeypath(keys: newKeys) } var fullPath: String { return keys.joined(separator: ".") } func appendingKey(_ key: String) -> AnimationKeypath { var newKeys = keys newKeys.append(key) return AnimationKeypath(keys: newKeys) } } extension String { var keyPathType: KeyType { switch self { case "*": return .wildcard case "**": return .fuzzyWildcard default: return .specific } } func equalsKeypath(_ keyname: String) -> Bool { if keyPathType == .wildcard || keyPathType == .fuzzyWildcard { return true } if self == keyname { return true } if let index = self.firstIndex(of: "*") { // Wildcard search. let prefix = self.prefix(upTo: index) let suffix = self.suffix(from: self.index(after: index)) if prefix.count > 0 { // Match prefix. if keyname.count < prefix.count { return false } let testPrefix = keyname.prefix(upTo: keyname.index(keyname.startIndex, offsetBy: prefix.count)) if testPrefix != prefix { // Prefix doesnt match return false } } if suffix.count > 0 { // Match suffix. if keyname.count < suffix.count { // Suffix doesnt match return false } let index = keyname.index(keyname.endIndex, offsetBy: -suffix.count) let testSuffix = keyname.suffix(from: index) if testSuffix != suffix { return false } } return true } return false } } enum KeyType { case specific case wildcard case fuzzyWildcard }
51dcf1f1ba573ffbdaa58fc5d941228f
25.875
109
0.620203
false
false
false
false
LYM-mg/DemoTest
refs/heads/master
Floral/Pods/HandyJSON/Source/ExtendCustomModelType.swift
apache-2.0
6
// // ExtendCustomType.swift // HandyJSON // // Created by zhouzhuo on 16/07/2017. // Copyright © 2017 aliyun. All rights reserved. // import Foundation public protocol _ExtendCustomModelType: _Transformable { init() mutating func willStartMapping() mutating func mapping(mapper: HelpingMapper) mutating func didFinishMapping() } extension _ExtendCustomModelType { public mutating func willStartMapping() {} public mutating func mapping(mapper: HelpingMapper) {} public mutating func didFinishMapping() {} } fileprivate func convertKeyIfNeeded(dict: [String: Any]) -> [String: Any] { if HandyJSONConfiguration.deserializeOptions.contains(.caseInsensitive) { var newDict = [String: Any]() dict.forEach({ (kvPair) in let (key, value) = kvPair newDict[key.lowercased()] = value }) return newDict } return dict } fileprivate func getRawValueFrom(dict: [String: Any], property: PropertyInfo, mapper: HelpingMapper) -> Any? { let address = Int(bitPattern: property.address) if let mappingHandler = mapper.getMappingHandler(key: address) { if let mappingPaths = mappingHandler.mappingPaths, mappingPaths.count > 0 { for mappingPath in mappingPaths { if let _value = dict.findValueBy(path: mappingPath) { return _value } } return nil } } if HandyJSONConfiguration.deserializeOptions.contains(.caseInsensitive) { return dict[property.key.lowercased()] } return dict[property.key] } fileprivate func convertValue(rawValue: Any, property: PropertyInfo, mapper: HelpingMapper) -> Any? { if rawValue is NSNull { return nil } if let mappingHandler = mapper.getMappingHandler(key: Int(bitPattern: property.address)), let transformer = mappingHandler.assignmentClosure { return transformer(rawValue) } if let transformableType = property.type as? _Transformable.Type { return transformableType.transform(from: rawValue) } else { return extensions(of: property.type).takeValue(from: rawValue) } } fileprivate func assignProperty(convertedValue: Any, instance: _ExtendCustomModelType, property: PropertyInfo) { if property.bridged { (instance as! NSObject).setValue(convertedValue, forKey: property.key) } else { extensions(of: property.type).write(convertedValue, to: property.address) } } fileprivate func readAllChildrenFrom(mirror: Mirror) -> [(String, Any)] { var children = [(label: String?, value: Any)]() let mirrorChildrenCollection = AnyRandomAccessCollection(mirror.children)! children += mirrorChildrenCollection var currentMirror = mirror while let superclassChildren = currentMirror.superclassMirror?.children { let randomCollection = AnyRandomAccessCollection(superclassChildren)! children += randomCollection currentMirror = currentMirror.superclassMirror! } var result = [(String, Any)]() children.forEach { (child) in if let _label = child.label { result.append((_label, child.value)) } } return result } fileprivate func merge(children: [(String, Any)], propertyInfos: [PropertyInfo]) -> [String: (Any, PropertyInfo?)] { var infoDict = [String: PropertyInfo]() propertyInfos.forEach { (info) in infoDict[info.key] = info } var result = [String: (Any, PropertyInfo?)]() children.forEach { (child) in result[child.0] = (child.1, infoDict[child.0]) } return result } // this's a workaround before https://bugs.swift.org/browse/SR-5223 fixed extension NSObject { static func createInstance() -> NSObject { return self.init() } } extension _ExtendCustomModelType { static func _transform(from object: Any) -> Self? { if let dict = object as? [String: Any] { // nested object, transform recursively return self._transform(dict: dict) as? Self } return nil } static func _transform(dict: [String: Any]) -> _ExtendCustomModelType? { var instance: Self if let _nsType = Self.self as? NSObject.Type { instance = _nsType.createInstance() as! Self } else { instance = Self.init() } instance.willStartMapping() _transform(dict: dict, to: &instance) instance.didFinishMapping() return instance } static func _transform(dict: [String: Any], to instance: inout Self) { guard let properties = getProperties(forType: Self.self) else { InternalLogger.logDebug("Failed when try to get properties from type: \(type(of: Self.self))") return } // do user-specified mapping first let mapper = HelpingMapper() instance.mapping(mapper: mapper) // get head addr let rawPointer = instance.headPointer() InternalLogger.logVerbose("instance start at: ", Int(bitPattern: rawPointer)) // process dictionary let _dict = convertKeyIfNeeded(dict: dict) let instanceIsNsObject = instance.isNSObjectType() let bridgedPropertyList = instance.getBridgedPropertyList() for property in properties { let isBridgedProperty = instanceIsNsObject && bridgedPropertyList.contains(property.key) let propAddr = rawPointer.advanced(by: property.offset) InternalLogger.logVerbose(property.key, "address at: ", Int(bitPattern: propAddr)) if mapper.propertyExcluded(key: Int(bitPattern: propAddr)) { InternalLogger.logDebug("Exclude property: \(property.key)") continue } let propertyDetail = PropertyInfo(key: property.key, type: property.type, address: propAddr, bridged: isBridgedProperty) InternalLogger.logVerbose("field: ", property.key, " offset: ", property.offset, " isBridgeProperty: ", isBridgedProperty) if let rawValue = getRawValueFrom(dict: _dict, property: propertyDetail, mapper: mapper) { if let convertedValue = convertValue(rawValue: rawValue, property: propertyDetail, mapper: mapper) { assignProperty(convertedValue: convertedValue, instance: instance, property: propertyDetail) continue } } InternalLogger.logDebug("Property: \(property.key) hasn't been written in") } } } extension _ExtendCustomModelType { func _plainValue() -> Any? { return Self._serializeAny(object: self) } static func _serializeAny(object: _Transformable) -> Any? { let mirror = Mirror(reflecting: object) guard let displayStyle = mirror.displayStyle else { return object.plainValue() } // after filtered by protocols above, now we expect the type is pure struct/class switch displayStyle { case .class, .struct: let mapper = HelpingMapper() // do user-specified mapping first if !(object is _ExtendCustomModelType) { InternalLogger.logDebug("This model of type: \(type(of: object)) is not mappable but is class/struct type") return object } let children = readAllChildrenFrom(mirror: mirror) guard let properties = getProperties(forType: type(of: object)) else { InternalLogger.logError("Can not get properties info for type: \(type(of: object))") return nil } var mutableObject = object as! _ExtendCustomModelType let instanceIsNsObject = mutableObject.isNSObjectType() let head = mutableObject.headPointer() let bridgedProperty = mutableObject.getBridgedPropertyList() let propertyInfos = properties.map({ (desc) -> PropertyInfo in return PropertyInfo(key: desc.key, type: desc.type, address: head.advanced(by: desc.offset), bridged: instanceIsNsObject && bridgedProperty.contains(desc.key)) }) mutableObject.mapping(mapper: mapper) let requiredInfo = merge(children: children, propertyInfos: propertyInfos) return _serializeModelObject(instance: mutableObject, properties: requiredInfo, mapper: mapper) as Any default: return object.plainValue() } } static func _serializeModelObject(instance: _ExtendCustomModelType, properties: [String: (Any, PropertyInfo?)], mapper: HelpingMapper) -> [String: Any] { var dict = [String: Any]() for (key, property) in properties { var realKey = key var realValue = property.0 if let info = property.1 { if info.bridged, let _value = (instance as! NSObject).value(forKey: key) { realValue = _value } if mapper.propertyExcluded(key: Int(bitPattern: info.address)) { continue } if let mappingHandler = mapper.getMappingHandler(key: Int(bitPattern: info.address)) { // if specific key is set, replace the label if let mappingPaths = mappingHandler.mappingPaths, mappingPaths.count > 0 { // take the first path, last segment if more than one realKey = mappingPaths[0].segments.last! } if let transformer = mappingHandler.takeValueClosure { if let _transformedValue = transformer(realValue) { dict[realKey] = _transformedValue } continue } } } if let typedValue = realValue as? _Transformable { if let result = self._serializeAny(object: typedValue) { dict[realKey] = result continue } } InternalLogger.logDebug("The value for key: \(key) is not transformable type") } return dict } }
b65e9049cd2349f514c2d8193de991e5
36.184116
157
0.618447
false
false
false
false
MadArkitekt/Swift_Tutorials_And_Demos
refs/heads/master
CustomViewTransitions/CustomViewTransitions/ViewController.swift
gpl-2.0
1
// // ViewController.swift // CustomViewTransitions // // Created by Edward Salter on 9/6/14. // Copyright (c) 2014 Edward Salter. All rights reserved. // import UIKit class ViewController: UIViewController { let transitionManager = TransAnimateManager() 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. } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { let toViewController = segue.destinationViewController as UIViewController toViewController.transitioningDelegate = self.transitionManager } @IBAction func unwindToViewController(segue: UIStoryboardSegue) { } override func preferredStatusBarStyle() -> UIStatusBarStyle { return self.presentingViewController == nil ? UIStatusBarStyle.Default : UIStatusBarStyle.LightContent } }
921adac0bacbe060c7a4d7e862107b44
26.825
110
0.697215
false
false
false
false
tamaracha/libsane
refs/heads/master
Sources/Device.swift
mit
1
import Clibsane /// Represents a SANE device. public class Device { //MARK: Types /// Device-specific errors public enum DeviceError: Error { /// Currently, the device has no open handle case noHandle } /// Possible states of a device public enum State { /// The physical device is inaccessible case disconnected /// The physical device is accessible. This is the default state case connected /// The device is open and can execute different operations case open } /** An additional information bitset which is returned after setting a device option. It is implemented as a OptionSet for better swift integration. - seealso: http://sane.alioth.debian.org/html/doc012.html */ struct Info: OptionSet { let rawValue: Int32 /// The given value couldn't be set exactly, but the nearest aproximate value is used static let inexact = Info(rawValue: SANE_INFO_INEXACT) /// The option descriptors may have changed static let reloadOptions = Info(rawValue: SANE_INFO_RELOAD_OPTIONS) /// the device parameters may have changed. static let reloadParams = Info(rawValue: SANE_INFO_RELOAD_PARAMS) } /// This constant is used as maximal buffer size when reading image data static private let bufferSize = 1024*1024 //MARK: Properties /// Properties which describe a SANE device public let name, model, vendor, type: String /// The current device state public private(set) var state: State = .connected /// The options of the device public private(set) var options = [String: BaseOption]() private var handle: SANE_Handle? { didSet { state = handle == nil ? .connected : .open } } //MARK: Lifecycle Hooks init(_ name: String, model: String, vendor: String, type: String) { self.name = name self.vendor = vendor self.model = model self.type = type } convenience init(_ name: String) { self.init(name, model: "unknown", vendor: "Noname", type: "virtual device") } init(from device: SANE_Device) { name = String(cString: device.name) model = String(cString: device.model) vendor = String(cString: device.vendor) type = String(cString: device.type) } deinit { close() } //MARK: Methods /// Open the device for configuration and image taking public func open() throws { var handle: SANE_Handle? let status = sane_open(name, &handle) guard status == SANE_STATUS_GOOD else { throw Status(rawValue: status)! } self.handle = handle if state == .open { try getOptions() } } /// Terminate the interaction with the device public func close() { if let handle = handle { sane_close(handle) } handle = nil options.removeAll() } /// Load the options of the device func getOptions() throws { guard case .open = state else { return } guard let handle = handle else { throw DeviceError.noHandle } var count: SANE_Int = 1 let status = sane_control_option(handle, 0, SANE_ACTION_GET_VALUE, &count, nil) guard status == SANE_STATUS_GOOD else { throw Status(rawValue: status)! } guard count > 1 else { return } for index in 1 ... count-1 { let descriptor = sane_get_option_descriptor(handle, index).pointee var option: BaseOption switch descriptor.type { case SANE_TYPE_BOOL: option = SwitchOption(from: descriptor, at: index, of: self) case SANE_TYPE_INT: option = IntOption(from: descriptor, at: index, of: self) case SANE_TYPE_FIXED: option = NumericOption(from: descriptor, at: index, of: self) case SANE_TYPE_STRING: option = TextOption(from: descriptor, at: index, of: self) case SANE_TYPE_BUTTON: option = ButtonOption(from: descriptor, at: index, of: self) case SANE_TYPE_GROUP: continue default: continue } options[option.name] = option } } /// Reload the options of the device func reloadOptions() throws { guard case .open = state else { return } guard let handle = handle else { throw DeviceError.noHandle } for (_, option) in options { let descriptor = sane_get_option_descriptor(handle, option.index).pointee option.update(descriptor) } } /// Set an option to its default value func setAuto(at index: SANE_Int) throws { guard case .open = state else { return } guard let handle = handle else { throw DeviceError.noHandle } let status = sane_control_option(handle, index, SANE_ACTION_SET_AUTO, nil, nil) guard status == SANE_STATUS_GOOD else { throw Status(rawValue: status)! } } /// Get the value of an option func getValue(at index: SANE_Int, to ptr: UnsafeMutableRawPointer) throws { guard case .open = state else { return } guard let handle = handle else { throw DeviceError.noHandle } let status = sane_control_option(handle, index, SANE_ACTION_GET_VALUE, ptr, nil) guard status == SANE_STATUS_GOOD else { throw Status(rawValue: status)! } } /// Change the value of an option func setValue(at index: SANE_Int, to ptr: UnsafeMutableRawPointer) throws { guard case .open = state else { return } guard let handle = handle else { throw DeviceError.noHandle } var saneInfo: SANE_Int = 0 let status = sane_control_option(handle, index, SANE_ACTION_SET_VALUE, ptr, &saneInfo) guard status == SANE_STATUS_GOOD else { throw Status(rawValue: status)! } let info = Info(rawValue: saneInfo) if info.contains(.reloadOptions) { try reloadOptions() } } /// Get the scan parameters of the device public func getParameters() throws -> Parameters { guard let handle = handle else { throw DeviceError.noHandle } var params = SANE_Parameters() let status = sane_get_parameters(handle, &params) guard status == SANE_STATUS_GOOD else { throw Status(rawValue: status)! } return Parameters(params) } private func start() throws { guard case .open = state else { return } guard let handle = handle else { throw DeviceError.noHandle } let status = sane_start(handle) guard status == SANE_STATUS_GOOD else { throw Status(rawValue: status)! } } private func setAsync() throws -> Bool { guard let handle = handle else { throw DeviceError.noHandle } let status = sane_set_io_mode(handle, SANE_TRUE) if status == SANE_STATUS_GOOD { return true } else if status == SANE_STATUS_UNSUPPORTED { return false } else { throw Status(rawValue: status)! } } private func read(frameSize: Int? = nil, maxLen: Int = Device.bufferSize) throws -> [SANE_Byte] { guard let handle = handle else { throw DeviceError.noHandle } var data = [SANE_Byte]() var buf = [SANE_Byte](repeating: 0, count: maxLen) var status: SANE_Status var n: SANE_Int = 0 if let frameSize = frameSize { repeat { status = sane_read(handle, &buf, SANE_Int(maxLen), &n) data += buf.prefix(Int(n)) } while status == SANE_STATUS_GOOD && data.count < frameSize } else { repeat { status = sane_read(handle, &buf, SANE_Int(maxLen), &n) data += buf.prefix(Int(n)) } while status == SANE_STATUS_GOOD } guard status == SANE_STATUS_EOF || status == SANE_STATUS_GOOD else { throw Status(rawValue: status)! } return data } /// Cancel a currently pending physical operation public func cancel() { guard case .open = state else { return } if let handle = handle { sane_cancel(handle) } } /// Scan an image public func scan() throws -> (data: [SANE_Byte], params: Parameters) { try start() let params = try getParameters() let data = try read(frameSize: params.bytesTotal) cancel() return (data: data, params: params) } } //MARK: Extensions extension Device: CustomStringConvertible { /// use the device name as description public var description: String { return name } } extension Device: Hashable { /// use the device name as hash value public var hashValue: Int { return name.hashValue } } extension Device: Comparable { /// Devices can be equated by their hash value static public func ==(lhs: Device, rhs: Device) -> Bool { return lhs.hashValue == rhs.hashValue } static public func <(lhs: Device, rhs: Device) -> Bool { return lhs.hashValue < rhs.hashValue } }
6738ef9382a7553b3874435f8062748c
27.169935
147
0.644316
false
false
false
false
WalletOne/P2P
refs/heads/master
P2PExample/Controllers/Employer/EmployerViewController.swift
mit
1
// // EmployerViewController.swift // P2P_iOS // // Created by Vitaliy Kuzmenko on 02/08/2017. // Copyright © 2017 Wallet One. All rights reserved. // import UIKit import P2PCore import P2PUI class EmployerViewController: UITableViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. let employer = Employer() employer.id = "vitaliykuzmenko" // NSUUID().uuidString employer.title = "Vitaliy Kuzmenko" employer.phoneNumber = "79281234567" DataStorage.default.employer = employer P2PCore.setPayer(id: employer.id, title: employer.title, phoneNumber: employer.phoneNumber) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { super.prepare(for: segue, sender: sender) switch segue.identifier! { case "DealsViewController": let vc = segue.destination as! DealsViewController vc.userTypeId = .employer default:break } } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let paymentToolsIndexPath = IndexPath(row: 0, section: 1) let refundsIndexPath = IndexPath(row: 1, section: 1) switch indexPath { case paymentToolsIndexPath: presentPaymentTools() case refundsIndexPath: presentRefunds() default: break } } func presentPaymentTools() { let vc = PaymentToolsViewController(owner: .payer, delegate: nil) navigationController?.pushViewController(vc, animated: true) } func presentRefunds() { let vc = RefundsViewController(dealId: nil) navigationController?.pushViewController(vc, animated: true) } }
54c6d2e80c21e6c41b60ae64d7d7fafb
28.492063
99
0.64155
false
false
false
false
noppoMan/SwiftKnex
refs/heads/master
Sources/SwiftKnex/Clauses/Join.swift
mit
1
// // Join.swift // SwiftKnex // // Created by Yuki Takei on 2017/01/12. // // class Join: Buildable { let table: String let type: JoinType var conditions = [ConditionalFilter]() init(table: String, type: JoinType){ self.table = table self.type = type } public func build() throws -> String { var conds = [String]() for cond in conditions { let prefix: String if conds.count == 0 { prefix = "ON" } else { prefix = "AND" } try conds.append(prefix + " " + cond.toQuery(secure: false)) } return try "\(type.build()) \(table) \(conds.joined(separator: " "))" } } enum JoinType { case left case right case inner case `default` } extension JoinType { public func build() throws -> String { switch self { case .left: return "LEFT JOIN" case .right: return "RIGHT JOIN" case .inner: return "INNER JOIN" case .default: //`\(table)` ON \(filter.toQuery(secure: false))" return "JOIN" } } } extension Collection where Self.Iterator.Element == Join { func build() throws -> String { let clauses: [String] = try self.map { try $0.build() } return clauses.joined(separator: " ") } }
7b027a5647cd38baa9d787a176eeae37
21.121212
77
0.49726
false
false
false
false
casd82/powerup-iOS
refs/heads/develop
Powerup/Accessory.swift
gpl-2.0
2
/** Data model for accessories (i.e. Eyes, Hair, etc) */ import UIKit // The types of the accessories. enum AccessoryType: String { case face = "Face" case eyes = "Eyes" case hair = "Hair" case clothes = "Clothes" case necklace = "Necklace" case handbag = "Handbag" case hat = "Hat" case glasses = "Glasses" case unknown = "" } struct Accessory { // The type of the accessory. var type: AccessoryType // Each accessory has a unique ID. var id: Int // The image of the accessory. var image: UIImage? // The image shown in Shop Scene boxes. var displayImage: UIImage? // The price to buy the accessory. var points: Int // Whether the accessory is purchased yet. var purchased: Bool init(type: AccessoryType, id: Int, imageName: String, points: Int, purchased: Bool) { self.type = type self.id = id self.image = UIImage(named: imageName) self.points = points self.purchased = purchased // Set display image. Avatar image is prefixed with "avatar_", display image is prefixed with "display_", so we have to substring from '_' and prefix it with "display". let fromIndex = imageName.count >= 6 ? imageName.index(imageName.startIndex, offsetBy: 6) : imageName.startIndex let displayName = "display" + String(imageName[fromIndex...]) self.displayImage = UIImage(named: displayName) } init(type: AccessoryType) { do { self = try DatabaseAccessor.sharedInstance.getAccessory(accessoryType: type, accessoryIndex: 1) } catch _ { self.type = .unknown self.id = 0 self.image = nil self.displayImage = nil self.points = 0 self.purchased = false } } }
fc44f50e3e21c564608e7bae24f2821c
28.483871
176
0.615974
false
false
false
false
Eonil/ClangWrapper.Swift
refs/heads/master
ClangWrapper/Cursor+Equatable.swift
mit
2
// // Cursor+Equatable.swift // ClangWrapper // // Created by Hoon H. on 2015/01/21. // Copyright (c) 2015 Eonil. All rights reserved. // extension Cursor: Equatable { } public func == (left:Cursor, right:Cursor) -> Bool { let r = clang_equalCursors(left.raw, right.raw) return r != 0 } public func != (left:Cursor, right:Cursor) -> Bool { return !(left == right) } extension Cursor: Hashable { public var hashValue:Int { get { return Int(bitPattern: UInt(clang_hashCursor(raw))) } } }
be3d4f22a19e7579e638147a459a0929
10.413043
54
0.634286
false
false
false
false
harlanhaskins/trill
refs/heads/master
Sources/Diagnostics/StreamConsumer.swift
mit
2
/// /// StreamConsumer.swift /// /// Copyright 2016-2017 the Trill project authors. /// Licensed under the MIT License. /// /// Full license text available at https://github.com/trill-lang/trill /// import Source import Foundation public class StreamConsumer<StreamType: ColoredStream>: DiagnosticConsumer { var stream: StreamType public init(stream: inout StreamType) { self.stream = stream } func highlightString(forDiag diag: Diagnostic) -> String { guard let loc = diag.loc, loc.line > 0 && loc.column > 0 else { return "" } var s = [Character]() let ranges = diag.highlights .filter { $0.start.line == loc.line && $0.end.line == loc.line } .sorted { $0.start.charOffset < $1.start.charOffset } if !ranges.isEmpty { s = [Character](repeating: " ", count: ranges.last!.end.column) for r in ranges { let range = (r.start.column - 1)..<(r.end.column - 1) let tildes = [Character](repeating: "~", count: range.count) s.replaceSubrange(range, with: tildes) } } let index = loc.column - 1 if index >= s.endIndex { s += [Character](repeating: " ", count: s.endIndex.distance(to: index)) s.append("^") } else { s[index] = "^" as Character } return String(s) } func sourceFile(for diag: Diagnostic) -> SourceFile? { return diag.loc?.file } public func consume(_ diagnostic: Diagnostic) { let file = sourceFile(for: diagnostic) stream.write("\(diagnostic.diagnosticType): ", with: [.bold, diagnostic.diagnosticType.color]) stream.write("\(diagnostic.message)\n", with: [.bold]) if let loc = diagnostic.loc, let line = file?.lines[loc.line - 1], loc.line > 0 { stream.write(" --> ", with: [.bold, .cyan]) let filename = file?.path.basename ?? "<unknown>" stream.write("\(filename)") if let sourceLoc = diagnostic.loc { stream.write(":\(sourceLoc.line):\(sourceLoc.column)", with: [.bold]) } stream.write("\n") let lineStr = "\(loc.line)" let indentation = "\(indent(lineStr.count))" stream.write(" \(indentation)|\n", with: [.cyan]) if let prior = file?.lines[safe: loc.line - 2] { stream.write(" \(indentation)| ", with: [.cyan]) stream.write("\(prior)\n") } stream.write(" \(lineStr)| ", with: [.cyan]) stream.write("\(line)\n") stream.write(" \(indentation)| ", with: [.cyan]) stream.write(highlightString(forDiag: diagnostic), with: [.bold, .green]) stream.write("\n") if let next = file?.lines[safe: loc.line] { stream.write(" \(indentation)| ", with: [.cyan]) stream.write("\(next)\n") } stream.write("\n") } } } func indent(_ n: Int) -> String { return String(repeating: " ", count: n) }
96c2f5a20d4a51a90fe018bd10fda93e
34.876404
83
0.526464
false
false
false
false
blockchain/My-Wallet-V3-iOS
refs/heads/master
Modules/Platform/Sources/PlatformUIKit/Components/AssetPieChartView/LoadingState+AssetPieChart.swift
lgpl-3.0
1
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import Charts import ComposableArchitectureExtensions import PlatformKit extension LoadingState where Content == PieChartData { /// Initializer that receives the interaction state and /// maps it to `self` init(with state: LoadingState<[AssetPieChart.Value.Interaction]>) { switch state { case .loading: self = .loading case .loaded(let values): let data: PieChartData if values.allSatisfy(\.percentage.isZero) { data = .empty } else { data = PieChartData(with: values) } self = .loaded(next: data) } } }
ae83fbcc3e491053a8fa9ed768e5b8e5
27.92
71
0.598893
false
false
false
false
openHPI/xikolo-ios
refs/heads/dev
Common/Branding/Brand.swift
gpl-3.0
1
// // Created for xikolo-ios under GPL-3.0 license. // Copyright © HPI. All rights reserved. // import Foundation import UIKit public struct Brand: Decodable { private enum CodingKeys: CodingKey { case host case imprintURL case privacyURL case faqURL case singleSignOn case copyrightName case poweredByText case colors case courseDateLabelStyle case showCurrentCoursesInSelfPacedSection case features case courseClassifierSearchFilters case additionalLearningMaterial case testAccountUserId } public static let `default`: Brand = { let data = NSDataAsset(name: "BrandConfiguration")?.data let decoder = PropertyListDecoder() return try! decoder.decode(Brand.self, from: data!) // swiftlint:disable:this force_try }() private let copyrightName: String public let host: String let imprintURL: URL let privacyURL: URL let faqURL: URL public let colors: BrandColors public let singleSignOn: SingleSignOnConfiguration? public let poweredByText: String? public let courseDateLabelStyle: CourseDateLabelStyle public let showCurrentCoursesInSelfPacedSection: Bool public let features: BrandFeatures public let courseClassifierSearchFilters: CourseClassifierSearchFilters? public let additionalLearningMaterial: [AdditionalLearningMaterial] public let testAccountUserId: String? public var copyrightText: String { let currentYear = Calendar.current.component(.year, from: Date()) return "Copyright © \(currentYear) \(self.copyrightName). All rights reserved." } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) self.host = try container.decode(String.self, forKey: .host) self.imprintURL = try container.decodeURL(forKey: .imprintURL) self.privacyURL = try container.decodeURL(forKey: .privacyURL) self.faqURL = try container.decodeURL(forKey: .faqURL) self.singleSignOn = try? container.decode(SingleSignOnConfiguration.self, forKey: .singleSignOn) self.copyrightName = try container.decode(String.self, forKey: .copyrightName) self.poweredByText = try container.decodeIfPresent(String.self, forKey: .poweredByText) self.colors = try container.decode(BrandColors.self, forKey: .colors) self.courseDateLabelStyle = try container.decodeCourseDateLabelStyle(forKey: .courseDateLabelStyle) self.showCurrentCoursesInSelfPacedSection = try container.decodeIfPresent(Bool.self, forKey: .showCurrentCoursesInSelfPacedSection) ?? false self.features = try container.decode(BrandFeatures.self, forKey: .features) self.courseClassifierSearchFilters = try? container.decode(CourseClassifierSearchFilters.self, forKey: .courseClassifierSearchFilters) self.additionalLearningMaterial = try container.decodeIfPresent([AdditionalLearningMaterial].self, forKey: .additionalLearningMaterial) ?? [] self.testAccountUserId = try? container.decode(String.self, forKey: .testAccountUserId) } } private extension KeyedDecodingContainer { func decodeURL(forKey key: K) throws -> URL { let value = try self.decode(String.self, forKey: key) return URL(string: value)! } func decodeCourseDateLabelStyle(forKey key: K) throws -> CourseDateLabelStyle { let defaultValue = CourseDateLabelStyle.normal guard let value = try self.decodeIfPresent(String.self, forKey: key) else { return defaultValue } return CourseDateLabelStyle(rawValue: value) ?? defaultValue } }
ee735f14f4de90173c28d22e37334024
40.764045
149
0.724778
false
false
false
false
NobodyNada/FireAlarm
refs/heads/master
Sources/Frontend/RowEncoder.swift
mit
3
// // RowEncoder.swift // FireAlarm // // Created by NobodyNada on 7/14/17. // import Foundation import SwiftChatSE internal func nestedObject() -> Never { fatalError("Arrays and nested dictionaries may not be encoded into database rows") } public class RowEncoder { public init() {} public func encode(_ value: Codable) throws -> Row { let encoder = _RowEncoder() try value.encode(to: encoder) var columns = [DatabaseNativeType?]() var columnIndices = [String:Int]() for (key, value) in encoder.storage { columnIndices[key] = columns.count columns.append(value?.asNative) } return Row(columns: columns, columnNames: columnIndices) } } private class _RowEncoder: Encoder { var codingPath: [CodingKey] = [] var userInfo: [CodingUserInfoKey : Any] = [:] var storage: [String:DatabaseType?] = [:] func container<Key>(keyedBy type: Key.Type) -> KeyedEncodingContainer<Key> where Key : CodingKey { return KeyedEncodingContainer(_KeyedEncoder<Key>(encoder: self, codingPath: codingPath)) } func unkeyedContainer() -> UnkeyedEncodingContainer { nestedObject() } func singleValueContainer() -> SingleValueEncodingContainer { guard !codingPath.isEmpty else { fatalError("Root object for a database row must be a dictionary") } return _SingleValueContainer(encoder: self, key: codingPath.last!, codingPath: codingPath) } } private class _KeyedEncoder<K: CodingKey>: KeyedEncodingContainerProtocol { typealias Key = K let encoder: _RowEncoder let codingPath: [CodingKey] init(encoder: _RowEncoder, codingPath: [CodingKey]) { self.encoder = encoder self.codingPath = codingPath } func encodeNil(forKey key: K) throws { encoder.storage[key.stringValue] = nil as DatabaseType? } func encode(_ value: DatabaseType, forKey key: K) throws { encoder.storage[key.stringValue] = value } func encode<T>(_ value: T, forKey key: K) throws where T : Encodable { if let v = value as? DatabaseType { try encode(v, forKey: key) return } encoder.codingPath.append(key) try value.encode(to: encoder) encoder.codingPath.removeLast() } func nestedContainer<NestedKey: CodingKey>(keyedBy keyType: NestedKey.Type, forKey key: K) -> KeyedEncodingContainer<NestedKey> { nestedObject() } func nestedUnkeyedContainer(forKey key: K) -> UnkeyedEncodingContainer { nestedObject() } func superEncoder() -> Encoder { nestedObject() } func superEncoder(forKey key: K) -> Encoder { nestedObject() } } private class _SingleValueContainer: SingleValueEncodingContainer { let encoder: _RowEncoder let key: CodingKey let codingPath: [CodingKey] init(encoder: _RowEncoder, key: CodingKey, codingPath: [CodingKey]) { self.encoder = encoder self.key = key self.codingPath = codingPath } func encodeNil() throws { try encode(nil as DatabaseType?) } func encode(_ value: DatabaseType?) throws { encoder.storage[key.stringValue] = value } func encode<T>(_ value: T) throws where T : Encodable { fatalError("Single-value containers may only encode DatabaseTypes") } }
2870f4d213d0873fd4db8eb806f1e44a
26.585938
133
0.626735
false
false
false
false
DonMag/ScratchPad
refs/heads/master
Swift3/scratchy/XC8.playground/Pages/TableView.xcplaygroundpage/Contents.swift
mit
1
//: [Previous](@previous) import Foundation import UIKit import PlaygroundSupport class rndCell: UITableViewCell { var myLabel1: UILabel! var myLabel2: UILabel! var myBKGView: UIView! required init(coder aDecoder: NSCoder) { fatalError("init(coder:)") } override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) let gap : CGFloat = 10 let labelHeight: CGFloat = 30 let labelWidth: CGFloat = 150 let lineGap : CGFloat = 5 let label2Y : CGFloat = gap + labelHeight + lineGap let v = UIView(frame: CGRect.zero) v.backgroundColor = UIColor.red v.translatesAutoresizingMaskIntoConstraints = false contentView.addSubview(v) v.leadingAnchor.constraint(equalTo: contentView.leadingAnchor).isActive = true v.trailingAnchor.constraint(equalTo: contentView.trailingAnchor).isActive = true v.topAnchor.constraint(equalTo: contentView.topAnchor).isActive = true v.bottomAnchor.constraint(equalTo: contentView.bottomAnchor).isActive = true myBKGView = v myLabel1 = UILabel() myLabel1.frame = CGRect(x: gap, y: gap, width: labelWidth, height: labelHeight) // CGRectMake(gap, gap, labelWidth, labelHeight) myLabel1.textColor = UIColor.black contentView.addSubview(myLabel1) myLabel2 = UILabel() myLabel2.frame = CGRect(x: gap, y: label2Y, width: labelWidth, height: labelHeight) //CGRectMake(gap, label2Y, labelWidth, labelHeight) myLabel2.textColor = UIColor.blue contentView.addSubview(myLabel2) } override func layoutSubviews() { super.layoutSubviews() myBKGView.layer.cornerRadius = myBKGView.frame.height / 2 } } class TableViewController: UITableViewController { override func viewDidLoad() { // tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell") tableView.register(rndCell.self, forCellReuseIdentifier: "Cell") tableView.contentInset.top = 76.0 tableView.backgroundColor = UIColor.clear } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) var r = tableView.bounds let wImg = UIImage(named: "wtran") let bImg = UIImage(named: "bt") let imgLayer = CALayer() imgLayer.contents = bImg?.cgImage r.size = (bImg?.size)! imgLayer.frame = r tableView.superview?.layer.mask = imgLayer // let theLayer = CAShapeLayer() //// theLayer.backgroundColor = UIColor.orange.cgColor // // theLayer.frame = r // // r.size.height = 260 // r.origin.x = 40 // r.size.width -= 80 // //// let pth = UIBezierPath() //// pth.move(to: CGPoint(x: 0, y: 0)) //// pth.addLine(to: CGPoint(x: 200, y: 0)) //// pth.addLine(to: CGPoint(x: 200, y: 100)) //// pth.addLine(to: CGPoint(x: 0, y: 100)) //// pth.close() // // let pth = CGPath(rect: r, transform: nil) // // theLayer.path = pth // theLayer.fillColor = UIColor.gray.cgColor //// theLayer.fillRule = kCAFillRuleNonZero // // tableView.layer.mask = theLayer // tableView.superview?.layer.mask = theLayer // let theLayer = CALayer() // var r = tableView.frame //// r.size.height = 176 // theLayer.frame = r // CGRect(x: 0, y: 0, width: tableView.frame.width, height: 76) //CGRectMake(0, 0, self.tableView.frame.width, 76) // var clr = UIColor(white: 0.0, alpha: 0.5) // UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 0.5) // theLayer.backgroundColor = clr.cgColor // // r.size.height = 100 // // var pth = CGPath(rect: r, transform: nil) // // // // tableView.superview?.layer.mask = theLayer // tableView.superview?.layer.addSublayer(theLayer) // r.origin.y = 76 // // let theGradLayer = CAGradientLayer() // theGradLayer.frame = r // // var trC = UIColor.darkGray.cgColor // var opC = UIColor.clear.cgColor // // theGradLayer.colors = [trC, trC, opC, opC] // theGradLayer.locations = [0.0, 0.31, 0.31, 1] // // tableView.superview?.layer.mask = theGradLayer // tableView.superview?.layer.addSublayer(theGradLayer) // CAGradientLayer *gradientLayer = [CAGradientLayer layer]; // gradientLayer.frame = self.tableView.frame; // id transparent = (id)[UIColor clearColor].CGColor; // id opaque = (id)[UIColor blackColor].CGColor; // gradientLayer.colors = @[transparent, opaque, opaque]; // gradientLayer.locations = @[@0.1, @0.11, @1]; // self.tableView.superview.layer.mask = gradientLayer; } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 15 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath as IndexPath) as! rndCell cell.myLabel1.text = "Sec: \(indexPath.section)" cell.myLabel2.text = "Row: \(indexPath.row)" // cell.textLabel?.text = "Row: \(indexPath.row)" return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let next = TableViewController() next.title = "Row: \(indexPath.row)" navigationController?.pushViewController(next, animated: true) print(navigationController?.viewControllers.count ?? "Hö?") } } let tableViewController = TableViewController() tableViewController.title = "start" let navigationController = UINavigationController(rootViewController: tableViewController) navigationController.view.frame.size = CGSize(width: 320, height: 400) navigationController.navigationBar.barTintColor = UIColor.white navigationController.view.backgroundColor = UIColor.green // PlaygroundPage.current.liveView = navigationController.view PlaygroundPage.current.needsIndefiniteExecution = true
cc522d45de16afee2b15fbdafb41376e
26.760976
137
0.708311
false
false
false
false
abellono/IssueReporter
refs/heads/master
IssueReporter/Core/Image.swift
mit
1
// // Image.swift // IssueReporter // // Created by Hakon Hanesand on 10/6/16. // Copyright © 2017 abello. All rights reserved. // // import Foundation internal class Image { let image: UIImage let identifier: String = UUID().uuidString let compressionRatio: Double = 0.5 var localImageURL: URL? = nil var cloudImageURL: URL? = nil var state: State = .initial var compressionCompletionBlock: (Image) -> () = { _ in } init(image: UIImage) { self.image = image.applyRotationToImageData() DispatchQueue.global(qos: .userInitiated).async { [weak self] in guard let strongSelf = self else { return } strongSelf.imageData = strongSelf.image.jpegData(compressionQuality: CGFloat(strongSelf.compressionRatio)) } } var imageData: Data? { didSet { DispatchQueue.main.async { self.compressionCompletionBlock(self) } } } } extension Image: Equatable { public static func ==(lhs: Image, rhs: Image) -> Bool { return lhs.identifier == rhs.identifier } }
4cddae13dea3413000838425b1430ac7
23.145833
118
0.599655
false
false
false
false
xocialize/Kiosk
refs/heads/master
kiosk/DataManager.swift
mit
1
// // DataManager.swift // kiosk // // Created by Dustin Nielson on 5/1/15. // Copyright (c) 2015 Dustin Nielson. All rights reserved. // import Foundation import UIKit import CoreData class DataManager: NSObject, NSFileManagerDelegate { var appDel:AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate // *** Mark Core Data Functions *** func getSettings() -> Dictionary<String,AnyObject> { var context:NSManagedObjectContext = appDel.managedObjectContext! var request = NSFetchRequest(entityName: "Settings") request.returnsObjectsAsFaults = false var results = context.executeFetchRequest(request, error: nil) if results!.count > 0 { for result: AnyObject in results! { var xset = result.valueForKey("settingsData") as? NSData let settings:Dictionary<String,AnyObject> = NSKeyedUnarchiver.unarchiveObjectWithData(xset!)! as! Dictionary return settings } } return Dictionary<String,AnyObject>() } func checkForIndex() -> Bool{ var folderPath = NSSearchPathForDirectoriesInDomains(.LibraryDirectory, .UserDomainMask, true)[0] as! String let fileManager = NSFileManager.defaultManager() var filePath: String = "kiosk_index.html" folderPath = folderPath + "/webFiles/" + filePath if NSFileManager.defaultManager().fileExistsAtPath(folderPath){ return true } return false } func saveSettings(dict: Dictionary<String,AnyObject> ){ var settings:Dictionary<String,AnyObject> = dict var context:NSManagedObjectContext = appDel.managedObjectContext! var request = NSFetchRequest(entityName: "Settings") request.returnsObjectsAsFaults = false var results = context.executeFetchRequest(request, error: nil) if results!.count > 0 { let data : NSData = NSKeyedArchiver.archivedDataWithRootObject(settings) let settingsTest:Dictionary<String,AnyObject> = NSKeyedUnarchiver.unarchiveObjectWithData(data)! as! Dictionary for result: AnyObject in results! { result.setValue(data, forKey: "settingsData") } } else { var uuid = NSUUID().UUIDString var uuidString = uuid as String settings["systemUUID"] = uuidString let data : NSData = NSKeyedArchiver.archivedDataWithRootObject(settings) var newPref = NSEntityDescription.insertNewObjectForEntityForName("Settings", inManagedObjectContext: context) as! NSManagedObject newPref.setValue(data, forKey: "settingsData") } context.save(nil) } // *** Mark File Directory Functions *** func showLibraryFiles(){ var folderPath = NSSearchPathForDirectoriesInDomains(.LibraryDirectory, .UserDomainMask, true)[0] as! String let fileManager = NSFileManager.defaultManager() let enumerator:NSDirectoryEnumerator = fileManager.enumeratorAtPath(folderPath)! while let element = enumerator.nextObject() as? String { if element != "" { let filePath = folderPath + "/" + element println(filePath) } } } func clearLibraryDirectory(){ var folderPath = NSSearchPathForDirectoriesInDomains(.LibraryDirectory, .UserDomainMask, true)[0] as! String let fileManager = NSFileManager.defaultManager() folderPath = folderPath + "/webFiles" if NSFileManager.defaultManager().fileExistsAtPath(folderPath){ fileManager.removeItemAtPath(folderPath, error: nil) } } func saveToLibrary(file:NSData, path:String){ let newPath = path.stringByReplacingOccurrencesOfString("/", withString: "_") FileSave.saveData(file, directory:NSSearchPathDirectory.LibraryDirectory, path: newPath, subdirectory: "webFiles") var paths = NSSearchPathForDirectoriesInDomains(.LibraryDirectory, .UserDomainMask, true)[0] as! String // Don't backup these files to iCloud var localUrl:NSURL = NSURL.fileURLWithPath(paths + "/webFiles/" + newPath)! var num:NSNumber = 1 if localUrl.setResourceValue(num, forKey: "NSURLIsExcludedFromBackupKey", error: nil) { println("Backup Disabled") } else { println("Backup Enabled") } } }
83b81babd7911cbbfad9a074c17acc5a
28.519774
142
0.564976
false
false
false
false
Longhanks/qlift
refs/heads/master
Sources/Qlift/QGroupBox.swift
mit
1
import CQlift open class QGroupBox: QWidget { public var alignment: Qt.Alignment = .AlignLeft { didSet { QGroupBox_setAlignment(self.ptr, alignment.rawValue) } } public var title: String = "" { didSet { QGroupBox_setTitle(self.ptr, title) } } public init(title: String = "", parent: QWidget? = nil) { self.title = title super.init(ptr: QGroupBox_new(title, parent?.ptr), parent: parent) } override init(ptr: UnsafeMutableRawPointer, parent: QWidget? = nil) { super.init(ptr: ptr, parent: parent) } deinit { if self.ptr != nil { if QObject_parent(self.ptr) == nil { QGroupBox_delete(self.ptr) } self.ptr = nil } } }
315e2f7748a1566f9b1e8e088b96e9e6
22.142857
74
0.540741
false
false
false
false
karstengresch/rw_studies
refs/heads/master
Apprentice/Checklists09/Checklists/ItemDetailViewController.swift
unlicense
1
// // ItemDetailViewController.swift // Checklists // // Created by Karsten Gresch on 02.12.15. // Copyright © 2015 Closure One. All rights reserved. // import Foundation import UIKit protocol ItemDetailViewControllerDelegate: class { func itemDetailViewControllerDidCancel(_ controller: ItemDetailViewController) func itemDetailViewController(_ controller: ItemDetailViewController, didFinishAddingItem checklistItem: ChecklistItem) func itemDetailViewController(_ controller: ItemDetailViewController, didFinishEditingItem checklistItem: ChecklistItem) } class ItemDetailViewController: UITableViewController, UITextFieldDelegate { var checklistItemToEdit: ChecklistItem? var dueDate = Date() var datePickerVisible = false @IBOutlet weak var addItemTextField: UITextField? @IBOutlet weak var doneBarButton: UIBarButtonItem? @IBOutlet weak var shouldRemindSwitch: UISwitch? @IBOutlet weak var dueDateLabel: UILabel? @IBOutlet weak var datePickerCell: UITableViewCell? @IBOutlet weak var datePicker: UIDatePicker? weak var delegate: ItemDetailViewControllerDelegate? // MARK: View related override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) addItemTextField?.becomeFirstResponder() } override func viewDidLoad() { super.viewDidLoad() if let itemToEdit = checklistItemToEdit { title = "Edit item" addItemTextField?.text = itemToEdit.text doneBarButton?.isEnabled = true shouldRemindSwitch?.isOn = itemToEdit.shouldRemind dueDate = itemToEdit.dueDate as Date } updateDueDateLabel() } func updateDueDateLabel() { print("updateDueDateLabel") let formatter = DateFormatter() formatter.dateStyle = .medium formatter.timeStyle = .short dueDateLabel?.text = formatter.string(from: dueDate) } // MARK: Table specific // MARK: Action handlers @IBAction func cancel() { // dismissViewControllerAnimated(true, completion: nil) delegate?.itemDetailViewControllerDidCancel(self); } @IBAction func done() { print("done()") if let checklistItem = checklistItemToEdit { print("done() - checklistItem exists") checklistItem.text = (addItemTextField?.text)! checklistItem.shouldRemind = (shouldRemindSwitch?.isOn)! checklistItem.dueDate = dueDate delegate?.itemDetailViewController(self, didFinishEditingItem: checklistItem) } else { print("done() - checklistItem does not exist") let checklistItem = ChecklistItem() checklistItem.text = (addItemTextField?.text)! checklistItem.checked = false checklistItem.shouldRemind = (shouldRemindSwitch?.isOn)! checklistItem.dueDate = dueDate delegate?.itemDetailViewController(self, didFinishAddingItem: checklistItem) } } // MARK: Text field specific func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { if let oldText: NSString = textField.text as NSString? { let newText: NSString = oldText.replacingCharacters(in: range, with: string) as NSString doneBarButton?.isEnabled = (newText.length > 0) } return true } func showDatePicker() { print("showDatePicker()") datePickerVisible = true let indexPathDatePicker = IndexPath(row: 2, section: 1) tableView.insertRows(at: [indexPathDatePicker], with: .fade) } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { print("cellForRowAtIndexPath() indexPath.section: \((indexPath as NSIndexPath).section) - indexPath.row: \((indexPath as NSIndexPath).row)") if (indexPath as NSIndexPath).section == 1 && (indexPath as NSIndexPath).row == 2 { // dangerous return datePickerCell! } else { return super.tableView(tableView, cellForRowAt: indexPath) } } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if section == 1 && datePickerVisible { print("numberOfRowsInSection(): section 1 AND datePickerVisible") return 3 } else { print("numberOfRowsInSection(): section 1 ?XOR datePickerVisible") return super.tableView(tableView, numberOfRowsInSection: section) } } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { if (indexPath as NSIndexPath).section == 1 && (indexPath as NSIndexPath).row == 2 { return 217 } else { return super.tableView(tableView, heightForRowAt: indexPath) } } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { print("didSelectRowAtIndexPath: \((indexPath as NSIndexPath).row) - didSelectRowAtIndexPath: \((indexPath as NSIndexPath).section)") tableView.deselectRow(at: indexPath, animated: true) addItemTextField?.resignFirstResponder() if (indexPath as NSIndexPath).section == 1 && (indexPath as NSIndexPath).row == 1 { print("Trying to show date picker") showDatePicker() } } override func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? { if (indexPath as NSIndexPath).section == 1 && (indexPath as NSIndexPath).row == 1 { return indexPath } else { return nil } } override func tableView(_ tableView: UITableView, indentationLevelForRowAt indexPath: IndexPath) -> Int { var indexPath = indexPath if (indexPath as NSIndexPath).section == 1 && (indexPath as NSIndexPath).row == 2 { indexPath = IndexPath(row: 0, section: (indexPath as NSIndexPath).section) } return super.tableView(tableView, indentationLevelForRowAt: indexPath) } }
faee776e6f436649487b824c43e26416
31.672222
144
0.706342
false
false
false
false
iAugux/SlideMenu-Swift
refs/heads/master
SlideMenu/AppDelegate.swift
mit
2
// // AppDelegate.swift // SlideMenu // // Created by Augus on 4/27/15. // Copyright (c) 2015 Augus. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? var storyboard = UIStoryboard(name: "Main", bundle: nil) func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. application.statusBarStyle = .LightContent let titleDict: NSDictionary = [NSForegroundColorAttributeName: UIColor.whiteColor()] UINavigationBar.appearance().titleTextAttributes = titleDict as? [String : AnyObject] UINavigationBar.appearance().tintColor = UIColor.whiteColor() let containerViewController = ContainerViewController() let homeNav = storyboard.instantiateViewControllerWithIdentifier("homeNav") as! UINavigationController homeNav.viewControllers[0] = containerViewController homeNav.setNavigationBarHidden(true, animated: false) window?.rootViewController = homeNav 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:. } }
e8883dbaeff2698ae774be63a29ad0e3
45.887097
285
0.73581
false
false
false
false
christiankm/FinanceKit
refs/heads/master
Sources/FinanceKit/ComparableToZero.swift
mit
1
// // FinanceKit // Copyright © 2022 Christian Mitteldorf. All rights reserved. // MIT license, see LICENSE file for details. // import Foundation /// Conforming to this protocol requires the conformer to provide methods comparing a numeric value against zero. /// The protocol provides methods to check if a number is zero, positive, negative or greater than zero. public protocol ComparableToZero { /// - returns: True if the amount is exactly zero. var isZero: Bool { get } /// - returns: True if the rounded amount is positive, i.e. zero or more. var isPositive: Bool { get } /// - returns: True if the rounded amount is less than zero, or false if the amount is zero or more. var isNegative: Bool { get } /// - returns: True if the rounded amount is greater than zero, or false if the amount is zero or less. var isGreaterThanZero: Bool { get } } extension Int: ComparableToZero { /// - returns: True if the amount is exactly zero. public var isZero: Bool { self == 0 } /// - returns: True if the rounded amount is positive, i.e. zero or more. public var isPositive: Bool { isZero || isGreaterThanZero } /// - returns: True if the rounded amount is less than zero, or false if the amount is zero or more. public var isNegative: Bool { self < Self(0) } /// - returns: True if the rounded amount is greater than zero, or false if the amount is zero or less. public var isGreaterThanZero: Bool { self > Self(0) } } extension Decimal: ComparableToZero { /// - returns: True if the amount is exactly zero. public var isZero: Bool { self == 0 } /// - returns: True if the rounded amount is positive, i.e. zero or more. public var isPositive: Bool { isZero || isGreaterThanZero } /// - returns: True if the rounded amount is less than zero, or false if the amount is zero or more. public var isNegative: Bool { self < Self(0) } /// - returns: True if the rounded amount is greater than zero, or false if the amount is zero or less. public var isGreaterThanZero: Bool { self > Self(0) } } extension FloatingPoint { /// - returns: True if the amount is exactly zero. public var isZero: Bool { self == Self(0) } /// - returns: True if the rounded amount is positive, i.e. zero or more. public var isPositive: Bool { isZero || isGreaterThanZero } /// - returns: True if the rounded amount is less than zero, or false if the amount is zero or more. public var isNegative: Bool { self < Self(0) } /// - returns: True if the rounded amount is greater than zero, or false if the amount is zero or less. public var isGreaterThanZero: Bool { self > Self(0) } }
45c35b8d5b34e3de5ddfe4fcada7cbf4
29.591398
113
0.648506
false
false
false
false
Drakken-Engine/GameEngine
refs/heads/master
DrakkenEngine/dSimpleSceneRender.swift
gpl-3.0
1
// // dSimpleSceneRender.swift // DrakkenEngine // // Created by Allison Lindner on 26/08/16. // Copyright © 2016 Drakken Studio. All rights reserved. // import simd import Metal import MetalKit import Foundation internal class dMaterialMeshBind { fileprivate var material: dMaterialData! fileprivate var mesh: dMeshData! fileprivate var instanceTransforms: [dTransform] = [] fileprivate var instanceTexCoordIDs: [Int32] = [] fileprivate var transformsBuffer: dBuffer<float4x4>! fileprivate var texCoordIDsBuffer: dBuffer<Int32>! fileprivate func addTransform(_ t: dTransform) { instanceTransforms.append(t) t.materialMeshBind = self t.materialMeshBindTransformID = instanceTransforms.index(of: t) } fileprivate func addTexCoordID(_ s: dSprite, _ frame: Int32) { instanceTexCoordIDs.append(frame) s.materialMeshBindTexCoordID = instanceTexCoordIDs.index(of: frame) } internal func remove(_ t: dTransform) { if t.materialMeshBindTransformID != nil { instanceTransforms.remove(at: t.materialMeshBindTransformID!) } if t.sprite != nil { if t.sprite!.materialMeshBindTexCoordID != nil { instanceTexCoordIDs.remove(at: t.sprite!.materialMeshBindTexCoordID!) } } } } internal class dSimpleSceneRender { private var renderGraph: [String : [String : dMaterialMeshBind]] = [:] private var _animatorToBeUpdated: [(materialMeshBind: dMaterialMeshBind, index: Int, animator: dAnimator)] = [] private var _jsScriptToBeUpdated: [dJSScript] = [] private var ids: [Int] = [] private var _scene: dScene! private var uCameraBuffer: dBuffer<dCameraUniform>! private var messagesToSend: [NSString] = [] internal init() { } internal func load(scene: dScene) { DrakkenEngine.Setup() self._scene = scene self._scene.simpleRender = self process() } internal func process() { self.renderGraph.removeAll() self._jsScriptToBeUpdated.removeAll() self._animatorToBeUpdated.removeAll() self.ids.removeAll() self.process(transforms: _scene.root.childrenTransforms) } private func process(transforms: [Int: dTransform]) { for transform in transforms { self.process(components: transform.value.components) self.process(transforms: transform.value.childrenTransforms) } } private func process(components: [dComponent]) { var materialMeshBind: dMaterialMeshBind? = nil var animatorToBeProcess: dAnimator? = nil var spriteToBeProcess: dSprite? = nil var hasSprite: Bool = false var hasAnimator: Bool = false for component in components { switch component.self { case is dMeshRender: //##################################################################################### //####################################################################### MESH RENDER let meshRender = component as! dMeshRender if meshRender.material != nil { if meshRender.mesh != nil { materialMeshBind = process(mesh: meshRender.mesh!, with: meshRender.material!, transform: meshRender.parentTransform!) } } //##################################################################### //################################################################### break case is dSprite: //##################################################################################### //############################################################################ SPRITE hasSprite = true spriteToBeProcess = component as? dSprite //##################################################################### //################################################################### break case is dAnimator: //##################################################################################### //########################################################################## ANIMATOR hasAnimator = true let animator = component as! dAnimator if materialMeshBind == nil { animatorToBeProcess = animator } else { self.process(animator: animator, materialMeshBind: materialMeshBind!) animatorToBeProcess = nil } //##################################################################### //################################################################### break case is dJSScript: //##################################################################################### //############################################################################ SCRIPT let script = component as! dJSScript _jsScriptToBeUpdated.append(script) //##################################################################### //################################################################### break default: break } if component is dAnimator { if materialMeshBind != nil && animatorToBeProcess != nil { self.process(animator: component as! dAnimator, materialMeshBind: materialMeshBind!) } } } if hasSprite && !hasAnimator { if materialMeshBind != nil && spriteToBeProcess != nil { self.process(sprite: spriteToBeProcess!, materialMeshBind: materialMeshBind!) } } } private func process(mesh: String, with material: String, transform: dTransform) -> dMaterialMeshBind { if renderGraph[material] != nil { if let materialMeshBind = renderGraph[material]![mesh] { materialMeshBind.addTransform(transform) return materialMeshBind } else { let materialMeshBind = dMaterialMeshBind() materialMeshBind.material = dCore.instance.mtManager.get(material: material) materialMeshBind.mesh = dCore.instance.mshManager.get(mesh: mesh) materialMeshBind.addTransform(transform) renderGraph[material]![mesh] = materialMeshBind return materialMeshBind } } else { renderGraph[material] = [:] let materialMeshBind = dMaterialMeshBind() materialMeshBind.material = dCore.instance.mtManager.get(material: material) materialMeshBind.mesh = dCore.instance.mshManager.get(mesh: mesh) materialMeshBind.addTransform(transform) renderGraph[material]![mesh] = materialMeshBind return materialMeshBind } } private func generateBufferOf(materialMeshBind: dMaterialMeshBind) { var matrixArray: [float4x4] = [] for transform in materialMeshBind.instanceTransforms { var matrix = transform.worldMatrix4x4 if transform._transformData.meshScale != nil { matrix = matrix * dMath.newScale(transform._transformData.meshScale!.Get().x, y: transform._transformData.meshScale!.Get().y, z: 1.0) } matrixArray.append(matrix) } if materialMeshBind.transformsBuffer == nil || materialMeshBind.transformsBuffer.count != materialMeshBind.instanceTransforms.count { materialMeshBind.transformsBuffer = dBuffer<float4x4>(data: matrixArray, index: 1) } else { materialMeshBind.transformsBuffer.change(matrixArray) } if materialMeshBind.texCoordIDsBuffer == nil || materialMeshBind.texCoordIDsBuffer.count != materialMeshBind.instanceTexCoordIDs.count { materialMeshBind.texCoordIDsBuffer = dBuffer<Int32>(data: materialMeshBind.instanceTexCoordIDs, index: 6) } else { materialMeshBind.texCoordIDsBuffer.change(materialMeshBind.instanceTexCoordIDs) } } private func generateCameraBuffer() { let projectionMatrix = dMath.newOrtho( -_scene.size.x/2.0, right: _scene.size.x/2.0, bottom: -_scene.size.y/2.0, top: _scene.size.y/2.0, near: -1000, far: 1000) let viewMatrix = dMath.newTranslation(float3(0.0, 0.0, -500.0)) * dMath.newScale(_scene.scale) let uCamera = dCameraUniform(viewMatrix: viewMatrix, projectionMatrix: projectionMatrix) if uCameraBuffer == nil { uCameraBuffer = dBuffer(data: uCamera, index: 0) } else { uCameraBuffer.change([uCamera]) } } private func process(animator: dAnimator, materialMeshBind: dMaterialMeshBind) { let index = materialMeshBind.instanceTexCoordIDs.count materialMeshBind.addTexCoordID(animator.sprite, animator.frame) _animatorToBeUpdated.append((materialMeshBind: materialMeshBind, index: index, animator: animator)) } private func process(sprite: dSprite, materialMeshBind: dMaterialMeshBind) { materialMeshBind.addTexCoordID(sprite, sprite.frame) } internal func update(deltaTime: Float) { for value in _animatorToBeUpdated { #if os(iOS) if #available(iOS 10, *) { let thread = Thread(block: { value.animator.update(deltaTime: deltaTime) return }) thread.start() } else { value.animator.update(deltaTime: deltaTime) } #endif #if os(tvOS) if #available(tvOS 10, *) { let thread = Thread(block: { value.animator.update(deltaTime: deltaTime) return }) thread.start() } else { value.animator.update(deltaTime: deltaTime) } #endif #if os(OSX) if #available(OSX 10.12, *) { let thread = Thread(block: { value.animator.update(deltaTime: deltaTime) return }) thread.start() } else { value.animator.update(deltaTime: deltaTime) } #endif value.materialMeshBind.instanceTexCoordIDs[value.index] = value.animator.frame } for script in _jsScriptToBeUpdated { for message in messagesToSend { script.receiveMessage(message) } messagesToSend.removeAll() script.run(function: "Update") } } internal func draw(drawable: CAMetalDrawable) { let id = dCore.instance.renderer.startFrame(drawable.texture) self.ids.append(id) let renderer = dCore.instance.renderer generateCameraBuffer() renderer?.bind(uCameraBuffer, encoderID: id) for m in renderGraph { for materialMeshBind in m.value { if materialMeshBind.value.material != nil && materialMeshBind.value.mesh != nil { generateBufferOf(materialMeshBind: materialMeshBind.value) renderer?.bind(materialMeshBind.value.material, encoderID: id) renderer?.bind(materialMeshBind.value.texCoordIDsBuffer, encoderID: id) renderer?.draw(materialMeshBind.value.mesh, encoderID: id, modelMatrixBuffer: materialMeshBind.value.transformsBuffer!) } } } renderer?.endFrame(id) renderer?.present(drawable) } internal func start() { for script in _jsScriptToBeUpdated { script.start() } } internal func rightClick(_ x: Float, _ y: Float) { for script in _jsScriptToBeUpdated { script.rightClick(x, y) } } internal func leftClick(_ x: Float, _ y: Float) { for script in _jsScriptToBeUpdated { script.leftClick(x, y) } } internal func touch(_ x: Float, _ y: Float) { for script in _jsScriptToBeUpdated { script.touch(x, y) } } internal func keyDown(_ keyCode: UInt16, _ modifier: UInt16? = nil) { for script in _jsScriptToBeUpdated { script.keyDown(keyCode, modifier) } } internal func keyUp(_ keyCode: UInt16, _ modifier: UInt16? = nil) { for script in _jsScriptToBeUpdated { script.keyUp(keyCode, modifier) } } internal func sendMessage(_ message: NSString) { messagesToSend.append(message) } }
4f2b5d29e6f77c6acc4a3e09077944a4
34.22905
144
0.549635
false
false
false
false
hernanc/swift-1
refs/heads/master
Pitch Perfect/recordSoundsViewController.swift
mit
1
// // recordSoundsViewController.swift // Pitch Perfect // // Created by HernanGCalabrese on 4/6/15. // Copyright (c) 2015 Ouiea. All rights reserved. // import UIKit import AVFoundation class recordSoundsViewController: UIViewController, AVAudioRecorderDelegate { @IBOutlet weak var labelStatus: UILabel! @IBOutlet weak var stopButton: UIButton! @IBOutlet weak var recordButton: UIButton! var audioRecorder:AVAudioRecorder! var recordedAudio:RecordedAudio! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func viewWillAppear(animated: Bool) { stopButton.hidden = true } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func recordAudio(sender: UIButton) { stopButton.hidden = false labelStatus.text = "Recording in Progress" recordButton.enabled = false let dirPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as! String var currentDateTime = NSDate() var formatter = NSDateFormatter() formatter.dateFormat = "ddMMyyyy-HHmmss" var recordingName = formatter.stringFromDate(currentDateTime)+".wav" var pathArray = [dirPath, recordingName] let filePath = NSURL.fileURLWithPathComponents(pathArray) println(filePath) // Setup Audio session var session = AVAudioSession.sharedInstance() session.setCategory(AVAudioSessionCategoryPlayAndRecord, error: nil) // Initialize and prepare the recorder audioRecorder = AVAudioRecorder(URL: filePath, settings: nil, error:nil) audioRecorder.delegate = self audioRecorder.meteringEnabled = true audioRecorder.prepareToRecord() audioRecorder.record() } func audioRecorderDidFinishRecording(recorder: AVAudioRecorder!, successfully flag: Bool) { if(flag){ recordedAudio = RecordedAudio(title: recorder.url.lastPathComponent!, filePathURL: recorder.url) self.performSegueWithIdentifier("stopRecording", sender: recordedAudio) }else{ println("Error recording") recordButton.enabled = true stopButton.hidden = true } } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if(segue.identifier == "stopRecording"){ let playSoundsVC:PlaySoundsViewController = segue.destinationViewController as! PlaySoundsViewController let data = sender as! RecordedAudio playSoundsVC.receivedAudio = data } } @IBAction func stopAudio(sender: UIButton) { labelStatus.text = "Tap to Record" stopButton.hidden = true recordButton.enabled = true audioRecorder.stop() var audioSession = AVAudioSession.sharedInstance() audioSession.setActive(false, error: nil) } }
5c3a3814b6bce90a6e805a4b9f942115
31.09901
116
0.652684
false
false
false
false
bourdakos1/Visual-Recognition-Tool
refs/heads/master
iOS/Visual Recognition/FaceResult.swift
mit
1
// // FaceResult.swift // Visual Recognition // // Created by Nicholas Bourdakos on 7/19/17. // Copyright © 2017 Nicholas Bourdakos. All rights reserved. // import UIKit struct FaceResult { let age: Age let location: Location let gender: Gender struct Age { let max: Int let min: Int let score: CGFloat } struct Location { let height: CGFloat let left: CGFloat let top: CGFloat let width: CGFloat } struct Gender { enum Sex: String { case male, female } let sex: Sex let score: CGFloat } } extension FaceResult { init?(json: Any) { guard let json = json as? [String: Any], let age = json["age"] as? [String: Any], let location = json["face_location"] as? [String: Any], let gender = json["gender"] as? [String: Any], let ageScore = age["score"] as? CGFloat, let height = location["height"] as? CGFloat, let left = location["left"] as? CGFloat, let top = location["top"] as? CGFloat, let width = location["width"] as? CGFloat, let genderSex = gender["gender"] as? String, let genderScore = gender["score"] as? CGFloat else { return nil } // The age max or min might be empty let maxAge: Int = age["max"] as? Int ?? 0 let minAge: Int = age["min"] as? Int ?? 0 self.age = Age(max: maxAge, min: minAge, score: ageScore) self.location = Location(height: height, left: left, top: top, width: width) self.gender = Gender(sex: Gender.Sex(rawValue: genderSex.lowercased())!, score: genderScore) } }
9ffa332ecc13f701ccfc3f1c38077ab4
25.867647
100
0.532567
false
false
false
false
withcopper/CopperKit
refs/heads/master
CopperKit/JWTDecode.swift
mit
1
// JWTDecode.swift // // Copyright (c) 2015 Auth0 (http://auth0.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation /** Decodes a JWT token into an object that holds the decoded body (along with token header and signature parts). If the token cannot be decoded a `NSError` will be thrown. :param: jwt string value to decode :returns: a decoded token as an instance of JWT */ public func decodeJWT(jwt: String) throws -> JWT { return try DecodedJWT(jwt: jwt) } struct DecodedJWT: JWT { let header: [String: AnyObject] let body: [String: AnyObject] let signature: String? init(jwt: String) throws { let parts = jwt.componentsSeparatedByString(".") guard parts.count == 3 else { throw invalidPartCountInJWT(jwt, parts: parts.count) } self.header = try decodeJWTPart(parts[0]) self.body = try decodeJWTPart(parts[1]) self.signature = parts[2] } var expiresAt: NSDate? { return claim("exp") } var issuer: String? { return claim("iss") } var subject: String? { return claim("sub") } var audience: [String]? { guard let aud: String = claim("aud") else { return claim("aud") } return [aud] } var issuedAt: NSDate? { return claim("iat") } var notBefore: NSDate? { return claim("nbf") } var identifier: String? { return claim("jti") } private func claim(name: String) -> NSDate? { guard let timestamp:Double = claim(name) else { return nil } return NSDate(timeIntervalSince1970: timestamp) } var expired: Bool { guard let date = self.expiresAt else { return false } return date.compare(NSDate()) != NSComparisonResult.OrderedDescending } } private func base64UrlDecode(value: String) -> NSData? { var base64 = value .stringByReplacingOccurrencesOfString("-", withString: "+") .stringByReplacingOccurrencesOfString("_", withString: "/") let length = Double(base64.lengthOfBytesUsingEncoding(NSUTF8StringEncoding)) let requiredLength = 4 * ceil(length / 4.0) let paddingLength = requiredLength - length if paddingLength > 0 { let padding = "".stringByPaddingToLength(Int(paddingLength), withString: "=", startingAtIndex: 0) base64 = base64.stringByAppendingString(padding) } return NSData(base64EncodedString: base64, options: .IgnoreUnknownCharacters) } private func decodeJWTPart(value: String) throws -> [String: AnyObject] { guard let bodyData = base64UrlDecode(value) else { throw invalidBase64UrlValue(value) } do { guard let json = try NSJSONSerialization.JSONObjectWithData(bodyData, options: NSJSONReadingOptions()) as? [String: AnyObject] else { throw invalidJSONValue(value) } return json } catch { throw invalidJSONValue(value) } }
7d31ecda1af91f217bc83e3430c4e91f
35.366972
141
0.682311
false
false
false
false
yonaskolb/XcodeGen
refs/heads/master
Sources/XcodeGenKit/GraphVizGenerator.swift
mit
1
import DOT import Foundation import GraphViz import ProjectSpec extension Dependency { var graphVizName: String { switch self.type { case .bundle, .package, .sdk, .framework, .carthage: return "[\(self.type)]\\n\(reference)" case .target: return reference } } } extension Dependency.DependencyType: CustomStringConvertible { public var description: String { switch self { case .bundle: return "bundle" case .package: return "package" case .framework: return "framework" case .carthage: return "carthage" case .sdk: return "sdk" case .target: return "target" } } } extension Node { init(target: Target) { self.init(target.name) self.shape = .box } init(dependency: Dependency) { self.init(dependency.reference) self.shape = .box self.label = dependency.graphVizName } } public class GraphVizGenerator { public init() {} public func generateModuleGraphViz(targets: [Target]) -> String { return DOTEncoder().encode(generateGraph(targets: targets)) } func generateGraph(targets: [Target]) -> Graph { var graph = Graph(directed: true) targets.forEach { target in target.dependencies.forEach { dependency in let from = Node(target: target) graph.append(from) let to = Node(dependency: dependency) graph.append(to) var edge = Edge(from: from, to: to) edge.style = .dashed graph.append(edge) } } return graph } }
477d25d7dd1386eca4dd6fcb2e8ccd30
24.772727
69
0.576132
false
false
false
false
totocaster/JSONFeed
refs/heads/master
Classes/JSONFeedAttachment.swift
mit
1
// // JSONFeedAttachment.swift // JSONFeed // // Created by Toto Tvalavadze on 2017/05/18. // Copyright © 2017 Toto Tvalavadze. All rights reserved. // import Foundation public struct JSONFeedAttachment { /// Specifies the location of the attachment. public let url: URL /// Specifies the type of the attachment, such as `audio/mpeg`. public let mimeType: String /// name for the attachment. /// - important: if there are multiple attachments, and two or more have the exact same title (when title is present), then they are considered as alternate representations of the same thing. In this way a podcaster, for instance, might provide an audio recording in different formats. public let title: String? /// Specifies how large the file is in *bytes*. public let size: UInt64? /// Specifies how long the attachment takes to listen to or watch in *seconds*. public let duration: UInt? // MARK: - Parsing internal init?(json: JsonDictionary) { let keys = JSONFeedSpecV1Keys.Attachment.self guard let url = URL(for: keys.url, inJson: json), let mimeType = json[keys.mimeType] as? String else { return nil } // items without id will be discarded, per spec self.url = url self.mimeType = mimeType self.title = json[keys.title] as? String self.duration = json[keys.durationSeconds] as? UInt self.size = json[keys.sizeBytes] as? UInt64 } }
0b4f0f4f32a9918529f250f9f04ba081
30.938776
289
0.641534
false
false
false
false
sonnygauran/trailer
refs/heads/master
Trailer/PullRequestCell.swift
mit
1
final class PullRequestCell: TrailerCell { init(pullRequest: PullRequest) { super.init(frame: NSZeroRect) dataItemId = pullRequest.objectID detailFont = NSFont.menuFontOfSize(10.0) titleFont = NSFont.menuFontOfSize(13.0) unselectedTitleColor = goneDark ? NSColor.controlHighlightColor() : NSColor.controlTextColor() var _commentsNew = 0 let _commentsTotal = pullRequest.totalComments?.integerValue ?? 0 let sectionIndex = pullRequest.sectionIndex?.integerValue ?? 0 if sectionIndex==PullRequestSection.Mine.rawValue || sectionIndex==PullRequestSection.Participated.rawValue || Settings.showCommentsEverywhere { _commentsNew = pullRequest.unreadComments?.integerValue ?? 0 } let _title = pullRequest.titleWithFont(titleFont, labelFont: detailFont, titleColor: unselectedTitleColor) let _subtitle = pullRequest.subtitleWithFont(detailFont, lightColor: NSColor.grayColor(), darkColor: NSColor.darkGrayColor()) var W = MENU_WIDTH-LEFTPADDING-app.scrollBarWidth let showUnpin = (pullRequest.condition?.integerValue != PullRequestCondition.Open.rawValue) || pullRequest.markUnmergeable() if showUnpin { W -= REMOVE_BUTTON_WIDTH } else { W -= 4.0 } let showAvatar = !(pullRequest.userAvatarUrl ?? "").isEmpty && !Settings.hideAvatars if showAvatar { W -= AVATAR_SIZE+AVATAR_PADDING } else { W += 4.0 } let titleHeight = ceil(_title.boundingRectWithSize(CGSizeMake(W-4.0, CGFloat.max), options: stringDrawingOptions).size.height) let subtitleHeight = ceil(_subtitle.boundingRectWithSize(CGSizeMake(W-4.0, CGFloat.max), options: stringDrawingOptions).size.height+4.0) var statusRects = [NSValue]() var statuses: [PRStatus]? = nil var bottom: CGFloat, CELL_PADDING: CGFloat var statusBottom = CGFloat(0) let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.headIndent = 92.0 var statusAttributes = [String : AnyObject]() statusAttributes[NSFontAttributeName] = NSFont(name: "Monaco", size: 9) statusAttributes[NSParagraphStyleAttributeName] = paragraphStyle if Settings.showStatusItems { CELL_PADDING = 10 bottom = ceil(CELL_PADDING * 0.5) statuses = pullRequest.displayedStatuses() for s in statuses! { let H = ceil(s.displayText().boundingRectWithSize(CGSizeMake(W, CGFloat.max), options: stringDrawingOptions, attributes: statusAttributes).size.height) statusRects.append(NSValue(rect: NSMakeRect(LEFTPADDING, bottom+statusBottom, W, H))) statusBottom += H } } else { CELL_PADDING = 6.0 bottom = ceil(CELL_PADDING * 0.5) } frame = NSMakeRect(0, 0, MENU_WIDTH, titleHeight+subtitleHeight+statusBottom+CELL_PADDING) addCounts(_commentsTotal, _commentsNew) var titleRect = NSMakeRect(LEFTPADDING, subtitleHeight+bottom+statusBottom, W, titleHeight) var dateRect = NSMakeRect(LEFTPADDING, statusBottom+bottom, W, subtitleHeight) var pinRect = NSMakeRect(LEFTPADDING+W, floor((bounds.size.height-24)*0.5), REMOVE_BUTTON_WIDTH-10, 24) var shift: CGFloat = -4 if showAvatar { let userImage = AvatarView( frame: NSMakeRect(LEFTPADDING, bounds.size.height-AVATAR_SIZE-7.0, AVATAR_SIZE, AVATAR_SIZE), url: pullRequest.userAvatarUrl ?? "") addSubview(userImage) shift = AVATAR_PADDING+AVATAR_SIZE } pinRect = NSOffsetRect(pinRect, shift, 0) dateRect = NSOffsetRect(dateRect, shift, 0) titleRect = NSOffsetRect(titleRect, shift, 0) var replacementRects = [NSValue]() for rv in statusRects { replacementRects.append(NSValue(rect: CGRectOffset(rv.rectValue, shift, 0))) } statusRects = replacementRects if showUnpin { if (pullRequest.condition?.integerValue ?? 0)==PullRequestCondition.Open.rawValue { let unmergeableLabel = CenterTextField(frame: pinRect) unmergeableLabel.textColor = NSColor.redColor() unmergeableLabel.font = NSFont(name: "Monaco", size: 8.0) unmergeableLabel.alignment = NSTextAlignment.Center unmergeableLabel.stringValue = "Cannot be merged" addSubview(unmergeableLabel) } else { let unpin = NSButton(frame: pinRect) unpin.title = "Remove" unpin.target = self unpin.action = Selector("unPinSelected") unpin.setButtonType(NSButtonType.MomentaryLightButton) unpin.bezelStyle = NSBezelStyle.RoundRectBezelStyle unpin.font = NSFont.systemFontOfSize(10.0) addSubview(unpin) } } title = CenterTextField(frame: titleRect) title.attributedStringValue = _title addSubview(title) let subtitle = CenterTextField(frame: dateRect) subtitle.attributedStringValue = _subtitle addSubview(subtitle) if let s = statuses { for count in 0 ..< statusRects.count { let frame = statusRects[statusRects.count-count-1].rectValue let statusLabel = LinkField(frame: frame) let status = s[count] statusLabel.targetUrl = status.targetUrl statusLabel.needsCommand = !Settings.makeStatusItemsSelectable statusLabel.attributedStringValue = NSAttributedString(string: status.displayText(), attributes: statusAttributes) statusLabel.textColor = status.colorForDisplay() addSubview(statusLabel) } } if let n = pullRequest.number { addMenuWithTitle("PR #\(n)") } else { addMenuWithTitle("PR Options") } } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
1b8f3367100381ac0c078e71e60beab4
36.58156
146
0.742593
false
false
false
false
timbodeit/RegexNamedCaptureGroups
refs/heads/master
RegexNamedCaptureGroups/Classes/GroupnameResolver.swift
mit
1
import unicode import Regex /** Resolves a capture group's name to its index for a given regex. To do this, GroupnameResolver calls into the ICU regex library, that NSRegularExpression is based on. */ class GroupnameResolver { private let uregex: COpaquePointer init?(regex: NSRegularExpression) { let cPattern = (regex.pattern as NSString).UTF8String let flag = regex.options.uregexFlag var errorCode = U_ZERO_ERROR uregex = uregex_openC(cPattern, flag, nil, &errorCode) if errorCode.isFailure { return nil } } func numberForCaptureGroupWithName(name: String) -> Int? { let cName = (name as NSString).UTF8String let nullTerminatedStringFlag: Int32 = -1 var errorCode = U_ZERO_ERROR let groupNumber = uregex_groupNumberFromCName(uregex, cName, nullTerminatedStringFlag, &errorCode) if errorCode.isSuccess { return Int(groupNumber) } else { return nil } } deinit { uregex_close(uregex) } } private extension UErrorCode { var isSuccess: Bool { return self.rawValue <= U_ZERO_ERROR.rawValue } var isFailure: Bool { return self.rawValue > U_ZERO_ERROR.rawValue } } private extension NSRegularExpressionOptions { var uregexFlag: UInt32 { var flag = 0 as UInt32 if self.contains(.CaseInsensitive) { flag |= UREGEX_CASE_INSENSITIVE.rawValue } if self.contains(.AllowCommentsAndWhitespace) { flag |= UREGEX_COMMENTS.rawValue } if self.contains(.DotMatchesLineSeparators) { flag |= UREGEX_DOTALL.rawValue } if self.contains(.AnchorsMatchLines) { flag |= UREGEX_MULTILINE.rawValue } if self.contains(.UseUnixLineSeparators) { flag |= UREGEX_UNIX_LINES.rawValue } if self.contains(.UseUnicodeWordBoundaries) { flag |= UREGEX_UWORD.rawValue } return flag } }
bdffb1b486a1dd9f3d4a05104f25f1ff
23.307692
102
0.676688
false
false
false
false
FraDeliro/ISaMaterialLogIn
refs/heads/master
Example/Pods/Material/Sources/iOS/Icon.swift
mit
1
/* * Copyright (C) 2015 - 2016, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.com>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of CosmicMind nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import UIKit public struct Icon { /// An internal reference to the icons bundle. private static var internalBundle: Bundle? /** A public reference to the icons bundle, that aims to detect the correct bundle to use. */ public static var bundle: Bundle { if nil == Icon.internalBundle { Icon.internalBundle = Bundle(for: View.self) let url = Icon.internalBundle!.resourceURL! let b = Bundle(url: url.appendingPathComponent("io.cosmicmind.material.icons.bundle")) if let v = b { Icon.internalBundle = v } } return Icon.internalBundle! } /// Get the icon by the file name. public static func icon(_ name: String) -> UIImage? { return UIImage(named: name, in: bundle, compatibleWith: nil)?.withRenderingMode(.alwaysTemplate) } /// Google icons. public static let add = Icon.icon("ic_add_white") public static let addCircle = Icon.icon("ic_add_circle_white") public static let addCircleOutline = Icon.icon("ic_add_circle_outline_white") public static let arrowBack = Icon.icon("ic_arrow_back_white") public static let arrowDownward = Icon.icon("ic_arrow_downward_white") public static let audio = Icon.icon("ic_audiotrack_white") public static let bell = Icon.icon("cm_bell_white") public static let cameraFront = Icon.icon("ic_camera_front_white") public static let cameraRear = Icon.icon("ic_camera_rear_white") public static let check = Icon.icon("ic_check_white") public static let clear = Icon.icon("ic_close_white") public static let close = Icon.icon("ic_close_white") public static let edit = Icon.icon("ic_edit_white") public static let email = Icon.icon("ic_email_white") public static let favorite = Icon.icon("ic_favorite_white") public static let favoriteBorder = Icon.icon("ic_favorite_border_white") public static let flashAuto = Icon.icon("ic_flash_auto_white") public static let flashOff = Icon.icon("ic_flash_off_white") public static let flashOn = Icon.icon("ic_flash_on_white") public static let history = Icon.icon("ic_history_white") public static let home = Icon.icon("ic_home_white") public static let image = Icon.icon("ic_image_white") public static let menu = Icon.icon("ic_menu_white") public static let moreHorizontal = Icon.icon("ic_more_horiz_white") public static let moreVertical = Icon.icon("ic_more_vert_white") public static let movie = Icon.icon("ic_movie_white") public static let pen = Icon.icon("ic_edit_white") public static let place = Icon.icon("ic_place_white") public static let phone = Icon.icon("ic_phone_white") public static let photoCamera = Icon.icon("ic_photo_camera_white") public static let photoLibrary = Icon.icon("ic_photo_library_white") public static let search = Icon.icon("ic_search_white") public static let settings = Icon.icon("ic_settings_white") public static let share = Icon.icon("ic_share_white") public static let star = Icon.icon("ic_star_white") public static let starBorder = Icon.icon("ic_star_border_white") public static let starHalf = Icon.icon("ic_star_half_white") public static let videocam = Icon.icon("ic_videocam_white") public static let visibility = Icon.icon("ic_visibility_white") /// CosmicMind icons. public struct cm { public static let add = Icon.icon("cm_add_white") public static let arrowBack = Icon.icon("cm_arrow_back_white") public static let arrowDownward = Icon.icon("cm_arrow_downward_white") public static let audio = Icon.icon("cm_audio_white") public static let audioLibrary = Icon.icon("cm_audio_library_white") public static let bell = Icon.icon("cm_bell_white") public static let check = Icon.icon("cm_check_white") public static let clear = Icon.icon("cm_close_white") public static let close = Icon.icon("cm_close_white") public static let edit = Icon.icon("cm_pen_white") public static let image = Icon.icon("cm_image_white") public static let menu = Icon.icon("cm_menu_white") public static let microphone = Icon.icon("cm_microphone_white") public static let moreHorizontal = Icon.icon("cm_more_horiz_white") public static let moreVertical = Icon.icon("cm_more_vert_white") public static let movie = Icon.icon("cm_movie_white") public static let pause = Icon.icon("cm_pause_white") public static let pen = Icon.icon("cm_pen_white") public static let photoCamera = Icon.icon("cm_photo_camera_white") public static let photoLibrary = Icon.icon("cm_photo_library_white") public static let play = Icon.icon("cm_play_white") public static let search = Icon.icon("cm_search_white") public static let settings = Icon.icon("cm_settings_white") public static let share = Icon.icon("cm_share_white") public static let shuffle = Icon.icon("cm_shuffle_white") public static let skipBackward = Icon.icon("cm_skip_backward_white") public static let skipForward = Icon.icon("cm_skip_forward_white") public static let star = Icon.icon("cm_star_white") public static let videocam = Icon.icon("cm_videocam_white") public static let volumeHigh = Icon.icon("cm_volume_high_white") public static let volumeMedium = Icon.icon("cm_volume_medium_white") public static let volumeOff = Icon.icon("cm_volume_off_white") } }
5c6a14363015fc0da342cee3921f2388
51.134328
104
0.717864
false
false
false
false
wavecos/curso_ios_3
refs/heads/master
Playgrounds/Arrays.playground/section-1.swift
apache-2.0
1
// Playground - Arrays import UIKit // Declaracion de un Arrays usando Literals let diasEnMes = [31,28,31,30,31,30,31,31,30,31,30,31] var opcionesColor = ["Negro", "Azul", "Verde"] var sabores : [String] sabores = ["Vainilla", "Chocolate", "Mora"] println("El segundo sabor es \(sabores[1])") sabores[0] = "Limon" sabores // Adicionando un Item al array sabores.append("Durazno") sabores // Otra forma de adicionar un Item sabores += ["Tamarindo"] sabores // Insertar un Item en una posicion especifica sabores.insert("Papaya", atIndex: 1) sabores // Removiendo Elementos de un Array let saborEliminado = sabores.removeAtIndex(3) sabores sabores.removeLast() sabores // Para saber el numero de elementos de un Array println("Tenemos actualmente \(sabores.count) sabores") if diasEnMes.isEmpty { println("El array esta vacio") } else { println("Tenemos \(diasEnMes.count) meses en el año") } // iterar un Array for mes in diasEnMes { println(mes) }
835a06bc99bdcc0c77744fff2003ed51
13.924242
55
0.707614
false
false
false
false
silt-lang/silt
refs/heads/master
Sources/Seismography/Value.swift
mit
1
/// Value.swift /// /// Copyright 2017-2018, The Silt Language Project. /// /// This project is released under the MIT license, a copy of which is /// available in the repository. import Foundation import Moho public class Value: Hashable, ManglingEntity { public enum Category { case object case address } public private(set) var type: Value public let category: Value.Category init(type: Value, category: Value.Category) { self.type = type self.category = category } /// Query the type information of a GIR type to determine whether it is /// "trivial". /// /// Values of trivial type requires no further work to copy, move, or destroy. /// /// - Parameter module: The module in which the type resides. /// - Returns: `true` if the lowered type is trivial, else `false`. public func isTrivial(_ module: GIRModule) -> Bool { return module.typeConverter.lowerType(self).trivial } /// All values are equatable and hashable using reference equality and /// the hash of their ObjectIdentifiers. public static func == (lhs: Value, rhs: Value) -> Bool { return lhs.equals(rhs) } public func equals(_ other: Value) -> Bool { return self === other } public func hash(into hasher: inout Hasher) { "\(ObjectIdentifier(self).hashValue)".hash(into: &hasher) } fileprivate var firstUse: Operand? public var hasUsers: Bool { return self.firstUse != nil } public var users: AnySequence<Operand> { guard let first = self.firstUse else { return AnySequence<Operand>([]) } return AnySequence<Operand>(sequence(first: first) { use in return use.nextUse }) } public func replaceAllUsesWith(_ RHS: Value) { precondition(self !== RHS, "Cannot RAUW a value with itself") for user in self.users { user.value = RHS } } public func mangle<M: Mangler>(into mangler: inout M) { fatalError("Generic Value may not be mangled; this must be overriden") } } public class NominalValue: Value { public let name: QualifiedName public init(name: QualifiedName, type: Value, category: Value.Category) { self.name = name super.init(type: type, category: category) } public var baseName: String { return self.name.name.description } } public enum Ownership { case trivial case unowned case owned } public class Parameter: Value { unowned public let parent: Continuation public let index: Int public let ownership: Ownership = .owned init(parent: Continuation, index: Int, type: Value) { self.parent = parent self.index = index super.init(type: type, category: type.category) } public override func mangle<M: Mangler>(into mangler: inout M) { self.type.mangle(into: &mangler) } } public enum Copy { case trivial case malloc case custom(Continuation) } public enum Destructor { case trivial case free case custom(Continuation) } /// A formal reference to a value, suitable for use as a stored operand. public final class Operand: Hashable { /// The next operand in the use-chain. Note that the chain holds /// every use of the current ValueBase, not just those of the /// designated result. var nextUse: Operand? /// A back-pointer in the use-chain, required for fast patching /// of use-chains. weak var back: Operand? /// The owner of this operand. /// FIXME: this could be space-compressed. weak var owningOp: PrimOp? init(owner: PrimOp, value: Value) { self.value = value self.owningOp = owner self.insertIntoCurrent() } deinit { self.removeFromCurrent() } public static func == (lhs: Operand, rhs: Operand) -> Bool { return lhs.value == rhs.value } public func hash(into hasher: inout Hasher) { self.value.hash(into: &hasher) } /// The value used as this operand. public var value: Value { willSet { self.removeFromCurrent() } didSet { self.insertIntoCurrent() } } /// Remove this use of the operand. public func drop() { self.removeFromCurrent() self.nextUse = nil self.back = nil self.owningOp = nil } /// Return the user that owns this use. public var user: PrimOp { return self.owningOp! } private func removeFromCurrent() { guard let backPtr = self.back else { return } self.back = self.nextUse if let next = self.nextUse { next.back = backPtr } } private func insertIntoCurrent() { self.back = self.value.firstUse self.nextUse = self.value.firstUse if let next = self.nextUse { next.back = self.nextUse } self.value.firstUse = self } }
2cd131af7359d307e33389335673c562
22.275
80
0.667884
false
false
false
false
donmichael41/helloVapor
refs/heads/master
Sources/App/Controllers/PostController.swift
mit
1
import Vapor import HTTP import Foundation import VaporPostgreSQL final class PostController { func addRoutes(drop: Droplet) { drop.group("posts") { group in group.post("create", handler: create) group.get(handler: index) group.post("update", Post.self, handler: update) group.post("show", Post.self, handler: show) group.post("delete", Post.self, handler: delete) group.post("deleteAll", handler: deleteAll) } } func create(request: Request) throws -> ResponseRepresentable { guard let content = request.parameters["content"]?.string else { throw Abort.badRequest } var mediaurl = "" var post = Post(createdon: Date().stringForDate(), content: content, mediaurl: mediaurl) try post.save() return Response(redirect: "/posts") } func index(request: Request) throws -> ResponseRepresentable { var parametes = [String: Node]() if let db = drop.database?.driver as? PostgreSQLDriver { let query = try db.raw("Select * from posts order by createdon desc") parametes = ["posts": query] } return try drop.view.make("manage", parametes) } func show(request: Request, post: Post) throws -> ResponseRepresentable { return post } func update(request: Request, post: Post) throws -> ResponseRepresentable { let new = try request.post() var post = post post.createdon = new.createdon post.content = new.content post.mediaurl = new.mediaurl try post.save() return post } func delete(request: Request, post: Post) throws -> ResponseRepresentable { try post.delete() return Response(redirect: "/posts") } func deleteAll(request: Request) throws -> ResponseRepresentable { let posts = try Post.all() try posts.forEach { (post) in try post.delete() } return "Delete all" } } extension Request { func post() throws -> Post { guard let json = json else { throw Abort.badRequest } return try Post(node: json) } } extension Date { func stringForDate() -> String { let formatter = DateFormatter() formatter.dateFormat = "EEEE, MMM d, yyyy 'at' hh:mm" return formatter.string(from: self) } }
5d61b2c8ecb176cc276b1795fb6fb630
27.51087
81
0.556233
false
false
false
false
jjuster/JSSAlertView
refs/heads/master
Example/Pods/PhoneNumberKit/PhoneNumberKit/TextField.swift
apache-2.0
2
// // TextField.swift // PhoneNumberKit // // Created by Roy Marmelstein on 07/11/2015. // Copyright © 2015 Roy Marmelstein. All rights reserved. // import Foundation import UIKit /// Custom text field that formats phone numbers public class PhoneNumberTextField: UITextField, UITextFieldDelegate { /// Override region to set a custom region. Automatically uses the default region code. public var defaultRegion = PhoneNumberKit().defaultRegionCode() { didSet { partialFormatter.defaultRegion = defaultRegion } } public var withPrefix: Bool = true { didSet { partialFormatter.withPrefix = withPrefix if withPrefix == false { self.keyboardType = UIKeyboardType.NumberPad } else { self.keyboardType = UIKeyboardType.PhonePad } } } var partialFormatter = PartialFormatter() let nonNumericSet: NSCharacterSet = { var mutableSet = NSCharacterSet.decimalDigitCharacterSet().invertedSet.mutableCopy() as! NSMutableCharacterSet mutableSet.removeCharactersInString(PhoneNumberConstants.plusChars) return mutableSet }() weak private var _delegate: UITextFieldDelegate? override public var delegate: UITextFieldDelegate? { get { return _delegate } set { self._delegate = newValue } } //MARK: Status public var currentRegion: String { get { return partialFormatter.currentRegion } } public var isValidNumber: Bool { get { let rawNumber = self.text ?? String() do { let phoneNumber = try PhoneNumber(rawNumber: rawNumber) return phoneNumber.isValidNumber } catch { return false } } } //MARK: Lifecycle /** Init with frame - parameter frame: UITextfield F - returns: UITextfield */ override public init(frame:CGRect) { super.init(frame:frame) self.setup() } /** Init with coder - parameter aDecoder: decoder - returns: UITextfield */ required public init(coder aDecoder: NSCoder) { super.init(coder: aDecoder)! self.setup() } func setup(){ self.autocorrectionType = .No self.keyboardType = UIKeyboardType.PhonePad super.delegate = self } // MARK: Phone number formatting /** * To keep the cursor position, we find the character immediately after the cursor and count the number of times it repeats in the remaining string as this will remain constant in every kind of editing. */ internal struct CursorPosition { let numberAfterCursor: String let repetitionCountFromEnd: Int } internal func extractCursorPosition() -> CursorPosition? { var repetitionCountFromEnd = 0 // Check that there is text in the UITextField guard let text = text, let selectedTextRange = selectedTextRange else { return nil } let textAsNSString = text as NSString let cursorEnd = offsetFromPosition(beginningOfDocument, toPosition: selectedTextRange.end) // Look for the next valid number after the cursor, when found return a CursorPosition struct for i in cursorEnd ..< textAsNSString.length { let cursorRange = NSMakeRange(i, 1) let candidateNumberAfterCursor: NSString = textAsNSString.substringWithRange(cursorRange) if (candidateNumberAfterCursor.rangeOfCharacterFromSet(nonNumericSet).location == NSNotFound) { for j in cursorRange.location ..< textAsNSString.length { let candidateCharacter = textAsNSString.substringWithRange(NSMakeRange(j, 1)) if candidateCharacter == candidateNumberAfterCursor { repetitionCountFromEnd += 1 } } return CursorPosition(numberAfterCursor: candidateNumberAfterCursor as String, repetitionCountFromEnd: repetitionCountFromEnd) } } return nil } // Finds position of previous cursor in new formatted text internal func selectionRangeForNumberReplacement(textField: UITextField, formattedText: String) -> NSRange? { let textAsNSString = formattedText as NSString var countFromEnd = 0 guard let cursorPosition = extractCursorPosition() else { return nil } for i in (textAsNSString.length - 1).stride(through: 0, by: -1) { let candidateRange = NSMakeRange(i, 1) let candidateCharacter = textAsNSString.substringWithRange(candidateRange) if candidateCharacter == cursorPosition.numberAfterCursor { countFromEnd += 1 if countFromEnd == cursorPosition.repetitionCountFromEnd { return candidateRange } } } return nil } public func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool { guard let text = text else { return false } // allow delegate to intervene guard _delegate?.textField?(textField, shouldChangeCharactersInRange: range, replacementString: string) ?? true else { return false } let textAsNSString = text as NSString let changedRange = textAsNSString.substringWithRange(range) as NSString let modifiedTextField = textAsNSString.stringByReplacingCharactersInRange(range, withString: string) let formattedNationalNumber = partialFormatter.formatPartial(modifiedTextField as String) var selectedTextRange: NSRange? let nonNumericRange = (changedRange.rangeOfCharacterFromSet(nonNumericSet).location != NSNotFound) if (range.length == 1 && string.isEmpty && nonNumericRange) { selectedTextRange = selectionRangeForNumberReplacement(textField, formattedText: modifiedTextField) textField.text = modifiedTextField } else { selectedTextRange = selectionRangeForNumberReplacement(textField, formattedText: formattedNationalNumber) textField.text = formattedNationalNumber } sendActionsForControlEvents(.EditingChanged) if let selectedTextRange = selectedTextRange, let selectionRangePosition = textField.positionFromPosition(beginningOfDocument, offset: selectedTextRange.location) { let selectionRange = textField.textRangeFromPosition(selectionRangePosition, toPosition: selectionRangePosition) textField.selectedTextRange = selectionRange } return false } //MARK: UITextfield Delegate public func textFieldShouldBeginEditing(textField: UITextField) -> Bool { return _delegate?.textFieldShouldBeginEditing?(textField) ?? true } public func textFieldDidBeginEditing(textField: UITextField) { _delegate?.textFieldDidBeginEditing?(textField) } public func textFieldShouldEndEditing(textField: UITextField) -> Bool { return _delegate?.textFieldShouldEndEditing?(textField) ?? true } public func textFieldDidEndEditing(textField: UITextField) { _delegate?.textFieldDidEndEditing?(textField) } public func textFieldShouldClear(textField: UITextField) -> Bool { return _delegate?.textFieldShouldClear?(textField) ?? true } public func textFieldShouldReturn(textField: UITextField) -> Bool { return _delegate?.textFieldShouldReturn?(textField) ?? true } }
c07fcbc603020e4c8f4218fe3379566b
34.231111
206
0.64484
false
false
false
false
Hansoncoder/SpriteDemo
refs/heads/master
SpriteKitDemo/SpriteKitDemo/MyGameScene.swift
apache-2.0
1
// // MyGameScene.swift // SpriteKitDemo // // Created by Hanson on 16/5/10. // Copyright © 2016年 Hanson. All rights reserved. // import SpriteKit import AVFoundation let playerName = "player" class MyGameScene: SKScene { // 敌人 var monsters = [SKSpriteNode]() // 飞镖 var projectiles = [SKSpriteNode]() // 音效 lazy var projectileSoundEffectAction = SKAction.playSoundFileNamed("pew-pew-lei", waitForCompletion: false) // 击退敌人 var monstersDestroyed = 0 var bgmPlayer: AVAudioPlayer? = { let bgmPath = NSBundle.mainBundle().pathForResource("background-music-aac", ofType: "caf") let bgmPlayer = try! AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: bgmPath!)) bgmPlayer.numberOfLoops = -1 return bgmPlayer }() override init(size: CGSize) { super.init(size: size) // 添加英雄 backgroundColor = SKColor(colorLiteralRed: 1.0, green: 1.0, blue: 1.0, alpha: 1.0) let player = SKSpriteNode(imageNamed: "player") player.name = playerName player.position = CGPointMake(player.size.width * 0.5, frame.size.height * 0.5) addChild(player) // 添加敌人 let actionAddMonster = SKAction.runBlock { [unowned self] in self.addMonster() } let actionWaitNextMonster = SKAction.waitForDuration(1.0) runAction(SKAction.repeatActionForever(SKAction.sequence([actionAddMonster,actionWaitNextMonster]))) // 播放背景音乐 bgmPlayer?.play() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // 添加敌人 func addMonster() { let monster = SKSpriteNode(imageNamed: "monster") let winSize = size let minY = monster.size.height * 0.5 let maxY = winSize.height - monster.size.height * 0.5 let rangeY = maxY - minY let actualY = (CGFloat(arc4random()) % rangeY) + minY // 显示敌人 monster.position = CGPointMake(winSize.width - monster.size.width * 0.5, actualY) addChild(monster) monsters.append(monster) // 计算敌人移动参数 let minDuration = 2.00 let maxDuration = 4.00 let rangeDuration = maxDuration - minDuration let actualDuration = (Double(arc4random()) % rangeDuration) + minDuration let actionMove = SKAction.moveTo(CGPointMake(-monster.size.width * 0.5, actualY), duration: actualDuration) let actionMoveDone = SKAction.runBlock { [unowned self] in self.monsters.removeAtIndex(self.monsters.indexOf(monster)!) monster.removeFromParent() // 敌人移动到屏幕边缘,跳转场景(输) self.changeToResultSceneWithWon(false) } monster.runAction(SKAction.sequence([actionMove,actionMoveDone])) } // 点击屏幕发射飞镖 override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { for touch in touches { let winSize = size // 取出英雄 guard let player = childNodeWithName(playerName) else { return } // 当前点击的点 let touchPoint = touch.locationInNode(self) let offSet = CGPointMake(touchPoint.x - player.position.x, touchPoint.y - player.position.y) // 点击英雄左边无效 if offSet.x <= 0 { return } // 创建飞镖 let projectile = SKSpriteNode(imageNamed: "projectile.png") projectile.position = player.position addChild(projectile) projectiles.append(projectile) // 计算偏移量 let realX = winSize.width - projectile.size.width * 0.5 let ratio = offSet.y / offSet.x let realY = (realX * ratio) + projectile.position.y let realDest = CGPointMake(realX, realY) // 计算飞镖移动时间 let offRealX = realX - projectile.position.x let offRealY = realY - projectile.position.y let length = sqrtf(Float((offRealX * offRealX) + (offRealY * offRealY))) let velocity = self.size.width let realMoveDuration = CGFloat(length) / velocity // 执行飞镖移动操作,移动结束将移除飞镖 let moveAction = SKAction.moveTo(realDest, duration: Double(realMoveDuration)) let projectileCastAction = SKAction.group([moveAction, projectileSoundEffectAction]) projectile.runAction(projectileCastAction){ [unowned self] in self.projectiles.removeAtIndex(self.projectiles.indexOf(projectile)!) projectile.removeFromParent() } } } // 检测飞镖和敌人是否碰撞,碰撞即移除飞镖和敌人 override func update(currentTime: NSTimeInterval) { var projectilesToDelete = [SKSpriteNode]() for projectile in projectiles { // 标记中飞镖的敌人monster var monstersToDelete = [SKSpriteNode]() for monster in monsters { if CGRectIntersectsRect(projectile.frame, monster.frame) { monstersToDelete.append(monster) // 击中敌人,统计数量 monstersDestroyed += 1 if monstersDestroyed >= 30 { // 击中人数达到30人,跳转场景(赢) changeToResultSceneWithWon(true) } } } // 将中飞镖的敌人移除 for monster in monstersToDelete { monsters.removeAtIndex(monsters.indexOf(monster)!) monster.removeFromParent() } // 若该飞镖击中敌人,标记飞镖 if monstersToDelete.count > 0 { projectilesToDelete.append(projectile) } } // 移除击中敌人的飞镖 for projectile in projectilesToDelete { projectiles.removeAtIndex(projectiles.indexOf(projectile)!) projectile.removeFromParent() } } func changeToResultSceneWithWon(won: Bool) { bgmPlayer?.stop() bgmPlayer = nil let resultScene = MyGameResultScene(size: self.size, won: won) let reveal = SKTransition.revealWithDirection(SKTransitionDirection.Up, duration: 1.0) self.scene?.view?.presentScene(resultScene, transition: reveal) } }
f8b138d842b49b885d9441e814a8348f
33.13089
115
0.573401
false
false
false
false
HabitRPG/habitrpg-ios
refs/heads/develop
fastlane/SnapshotHelper.swift
gpl-3.0
1
// // SnapshotHelper.swift // Example // // Created by Felix Krause on 10/8/15. // // ----------------------------------------------------- // IMPORTANT: When modifying this file, make sure to // increment the version number at the very // bottom of the file to notify users about // the new SnapshotHelper.swift // ----------------------------------------------------- import Foundation import XCTest var deviceLanguage = "" var locale = "" func setupSnapshot(_ app: XCUIApplication, waitForAnimations: Bool = true) { Snapshot.setupSnapshot(app, waitForAnimations: waitForAnimations) } func snapshot(_ name: String, waitForLoadingIndicator: Bool) { if waitForLoadingIndicator { Snapshot.snapshot(name) } else { Snapshot.snapshot(name, timeWaitingForIdle: 0) } } /// - Parameters: /// - name: The name of the snapshot /// - timeout: Amount of seconds to wait until the network loading indicator disappears. Pass `0` if you don't want to wait. func snapshot(_ name: String, timeWaitingForIdle timeout: TimeInterval = 20) { Snapshot.snapshot(name, timeWaitingForIdle: timeout) } enum SnapshotError: Error, CustomDebugStringConvertible { case cannotDetectUser case cannotFindHomeDirectory case cannotFindSimulatorHomeDirectory case cannotAccessSimulatorHomeDirectory(String) case cannotRunOnPhysicalDevice var debugDescription: String { switch self { case .cannotDetectUser: return "Couldn't find Snapshot configuration files - can't detect current user " case .cannotFindHomeDirectory: return "Couldn't find Snapshot configuration files - can't detect `Users` dir" case .cannotFindSimulatorHomeDirectory: return "Couldn't find simulator home location. Please, check SIMULATOR_HOST_HOME env variable." case .cannotAccessSimulatorHomeDirectory(let simulatorHostHome): return "Can't prepare environment. Simulator home location is inaccessible. Does \(simulatorHostHome) exist?" case .cannotRunOnPhysicalDevice: return "Can't use Snapshot on a physical device." } } } @objcMembers open class Snapshot: NSObject { static var app: XCUIApplication? static var waitForAnimations = true static var cacheDirectory: URL? static var screenshotsDirectory: URL? { return cacheDirectory?.appendingPathComponent("screenshots", isDirectory: true) } open class func setupSnapshot(_ app: XCUIApplication, waitForAnimations: Bool = true) { Snapshot.app = app Snapshot.waitForAnimations = waitForAnimations do { let cacheDir = try pathPrefix() Snapshot.cacheDirectory = cacheDir setLanguage(app) setLocale(app) setLaunchArguments(app) } catch let error { print(error) } } class func setLanguage(_ app: XCUIApplication) { guard let cacheDirectory = cacheDirectory else { print("CacheDirectory is not set - probably running on a physical device?") return } let path = cacheDirectory.appendingPathComponent("language.txt") do { let trimCharacterSet = CharacterSet.whitespacesAndNewlines deviceLanguage = try String(contentsOf: path, encoding: .utf8).trimmingCharacters(in: trimCharacterSet) app.launchArguments += ["-AppleLanguages", "(\(deviceLanguage))"] } catch { print("Couldn't detect/set language...") } } class func setLocale(_ app: XCUIApplication) { guard let cacheDirectory = cacheDirectory else { print("CacheDirectory is not set - probably running on a physical device?") return } let path = cacheDirectory.appendingPathComponent("locale.txt") do { let trimCharacterSet = CharacterSet.whitespacesAndNewlines locale = try String(contentsOf: path, encoding: .utf8).trimmingCharacters(in: trimCharacterSet) } catch { print("Couldn't detect/set locale...") } if locale.isEmpty && !deviceLanguage.isEmpty { locale = Locale(identifier: deviceLanguage).identifier } if !locale.isEmpty { app.launchArguments += ["-AppleLocale", "\"\(locale)\""] } } class func setLaunchArguments(_ app: XCUIApplication) { guard let cacheDirectory = cacheDirectory else { print("CacheDirectory is not set - probably running on a physical device?") return } let path = cacheDirectory.appendingPathComponent("snapshot-launch_arguments.txt") app.launchArguments += ["-FASTLANE_SNAPSHOT", "YES", "-ui_testing"] do { let launchArguments = try String(contentsOf: path, encoding: String.Encoding.utf8) let regex = try NSRegularExpression(pattern: "(\\\".+?\\\"|\\S+)", options: []) let matches = regex.matches(in: launchArguments, options: [], range: NSRange(location: 0, length: launchArguments.count)) let results = matches.map { result -> String in (launchArguments as NSString).substring(with: result.range) } app.launchArguments += results } catch { print("Couldn't detect/set launch_arguments...") } } open class func snapshot(_ name: String, timeWaitingForIdle timeout: TimeInterval = 20) { if timeout > 0 { waitForLoadingIndicatorToDisappear(within: timeout) } print("snapshot: \(name)") // more information about this, check out https://docs.fastlane.tools/actions/snapshot/#how-does-it-work if Snapshot.waitForAnimations { sleep(1) // Waiting for the animation to be finished (kind of) } #if os(OSX) guard let app = app else { print("XCUIApplication is not set. Please call setupSnapshot(app) before snapshot().") return } app.typeKey(XCUIKeyboardKeySecondaryFn, modifierFlags: []) #else guard let app = app else { print("XCUIApplication is not set. Please call setupSnapshot(app) before snapshot().") return } let window = app.windows.firstMatch let screenshot = window.screenshot() guard let simulator = ProcessInfo().environment["SIMULATOR_DEVICE_NAME"], let screenshotsDir = screenshotsDirectory else { return } let path = screenshotsDir.appendingPathComponent("\(simulator)-\(name).png") do { try screenshot.pngRepresentation.write(to: path) } catch let error { print("Problem writing screenshot: \(name) to \(path)") print(error) } #endif } class func waitForLoadingIndicatorToDisappear(within timeout: TimeInterval) { #if os(tvOS) return #endif guard let app = app else { print("XCUIApplication is not set. Please call setupSnapshot(app) before snapshot().") return } let networkLoadingIndicator = app.otherElements.deviceStatusBars.networkLoadingIndicators.element let networkLoadingIndicatorDisappeared = XCTNSPredicateExpectation(predicate: NSPredicate(format: "exists == false"), object: networkLoadingIndicator) _ = XCTWaiter.wait(for: [networkLoadingIndicatorDisappeared], timeout: timeout) } class func pathPrefix() throws -> URL? { let homeDir: URL // on OSX config is stored in /Users/<username>/Library // and on iOS/tvOS/WatchOS it's in simulator's home dir #if os(OSX) guard let user = ProcessInfo().environment["USER"] else { throw SnapshotError.cannotDetectUser } guard let usersDir = FileManager.default.urls(for: .userDirectory, in: .localDomainMask).first else { throw SnapshotError.cannotFindHomeDirectory } homeDir = usersDir.appendingPathComponent(user) #else #if arch(i386) || arch(x86_64) guard let simulatorHostHome = ProcessInfo().environment["SIMULATOR_HOST_HOME"] else { throw SnapshotError.cannotFindSimulatorHomeDirectory } guard let homeDirUrl = URL(string: simulatorHostHome) else { throw SnapshotError.cannotAccessSimulatorHomeDirectory(simulatorHostHome) } homeDir = URL(fileURLWithPath: homeDirUrl.path) #else throw SnapshotError.cannotRunOnPhysicalDevice #endif #endif return homeDir.appendingPathComponent("Library/Caches/tools.fastlane") } } private extension XCUIElementAttributes { var isNetworkLoadingIndicator: Bool { if hasWhiteListedIdentifier { return false } let hasOldLoadingIndicatorSize = frame.size == CGSize(width: 10, height: 20) let hasNewLoadingIndicatorSize = frame.size.width.isBetween(46, and: 47) && frame.size.height.isBetween(2, and: 3) return hasOldLoadingIndicatorSize || hasNewLoadingIndicatorSize } var hasWhiteListedIdentifier: Bool { let whiteListedIdentifiers = ["GeofenceLocationTrackingOn", "StandardLocationTrackingOn"] return whiteListedIdentifiers.contains(identifier) } func isStatusBar(_ deviceWidth: CGFloat) -> Bool { if elementType == .statusBar { return true } guard frame.origin == .zero else { return false } let oldStatusBarSize = CGSize(width: deviceWidth, height: 20) let newStatusBarSize = CGSize(width: deviceWidth, height: 44) return [oldStatusBarSize, newStatusBarSize].contains(frame.size) } } private extension XCUIElementQuery { var networkLoadingIndicators: XCUIElementQuery { let isNetworkLoadingIndicator = NSPredicate { (evaluatedObject, _) in guard let element = evaluatedObject as? XCUIElementAttributes else { return false } return element.isNetworkLoadingIndicator } return containing(isNetworkLoadingIndicator) } var deviceStatusBars: XCUIElementQuery { guard let app = Snapshot.app else { fatalError("XCUIApplication is not set. Please call setupSnapshot(app) before snapshot().") } let deviceWidth = app.windows.firstMatch.frame.width let isStatusBar = NSPredicate { (evaluatedObject, _) in guard let element = evaluatedObject as? XCUIElementAttributes else { return false } return element.isStatusBar(deviceWidth) } return containing(isStatusBar) } } private extension CGFloat { func isBetween(_ numberA: CGFloat, and numberB: CGFloat) -> Bool { return numberA...numberB ~= self } } // Please don't remove the lines below // They are used to detect outdated configuration files // SnapshotHelperVersion [1.15]
6de1ce637e8ffb87b5c659e97255d86f
36.647651
158
0.635083
false
false
false
false
CodaFi/swift
refs/heads/master
test/decl/protocol/req/associated_type_inference_fixed_type.swift
apache-2.0
2
// RUN: %target-typecheck-verify-swift protocol P1 where A == Never { associatedtype A } struct S1: P1 {} // OK, A := Never protocol P2a { associatedtype A } protocol P2b: P2a where A == Never {} protocol P2c: P2b {} struct S2a: P2b {} // OK, A := Never struct S2b: P2c {} // OK, A := Never // Fixed type witnesses can reference dependent members. protocol P3a { associatedtype A associatedtype B } protocol P3b: P3a where A == [B] {} struct S3: P3b { // OK, A := [Never], B := Never typealias B = Never } protocol P4 {} extension P4 { typealias B = Self } struct S4: P4, P3b {} // OK, A := [S4], B := S4 // Self is a valid fixed type witness. protocol P5a { associatedtype A } protocol P5b: P5a where A == Self {} struct S5<X>: P5b {} // OK, A := S5<X> protocol P6 where A == Never { // expected-error {{same-type constraint type 'Never' does not conform to required protocol 'P6'}} // expected-error@+2 {{same-type constraint type 'Never' does not conform to required protocol 'P6'}} // expected-note@+1 {{protocol requires nested type 'A}} associatedtype A: P6 } struct S6: P6 {} // expected-error {{type 'S6' does not conform to protocol 'P6'}} protocol P7a where A == Never { associatedtype A } // expected-error@+2 {{'Self.A' cannot be equal to both 'Bool' and 'Never'}} // expected-note@+1 {{same-type constraint 'Self.A' == 'Never' implied here}} protocol P7b: P7a where A == Bool {} struct S7: P7b {} protocol P8 where A == Bool { associatedtype A } // expected-error@+2 {{'P7a' requires the types 'S8.A' (aka 'Bool') and 'Never' be equivalent}} // expected-note@+1 {{requirement specified as 'Self.A' == 'Never' [with Self = S8]}} struct S8: P8, P7a {} protocol P9a where A == Never { associatedtype A } protocol P9b: P9a { associatedtype A } struct S9a: P9b {} // OK, A := Never // expected-error@+2 {{'P9a' requires the types 'S9b.A' (aka 'Bool') and 'Never' be equivalent}} // expected-note@+1 {{requirement specified as 'Self.A' == 'Never' [with Self = S9b]}} struct S9b: P9b { typealias A = Bool } struct S9c: P9b { // OK, S9c.A does not contradict Self.A == Never. typealias Sugar = Never typealias A = Sugar } protocol P10 {} extension P10 { typealias A = Bool } // FIXME: 'P10 extension.A' should not be considered a viable type witness; // instead, the compiler should infer A := Never and synthesize S10.A. // expected-error@+2 {{'P9a' requires the types 'S10.A' (aka 'Bool') and 'Never' be equivalent}} // expected-note@+1 {{requirement specified as 'Self.A' == 'Never' [with Self = S10]}} struct S10: P10, P9a {} protocol P11a { associatedtype A } protocol P11b: P11a where A == Never {} protocol Q11 { associatedtype A // expected-note {{protocol requires nested type 'A'}} } // FIXME: Unrelated protocols with a matching associated type should // also be considered when computing a fixed type witness. // expected-error@+3 {{type 'S11' does not conform to protocol 'Q11'}} // expected-error@+2 {{type 'S11' does not conform to protocol 'P11a'}} // expected-error@+1 {{type 'S11' does not conform to protocol 'P11b'}} struct S11: Q11, P11b {}
fb8d9a3438d4018b79d8c6a61eb00742
29.90099
129
0.668055
false
false
false
false
jcleblanc/box-examples
refs/heads/master
swift/JWTSampleApp/JWTSampleApp/ViewController.swift
mit
1
// // ViewController.swift // JWTSampleApp-carthage // // Created by Martina Stremenova on 28/06/2019. // Copyright © 2019 Box. All rights reserved. // import BoxSDK import UIKit class ViewController: UITableViewController { private var sdk: BoxSDK! private var client: BoxClient! private var folderItems: [FolderItem] = [] private lazy var dateFormatter: DateFormatter = { let formatter = DateFormatter() formatter.dateFormat = "MMM dd,yyyy at HH:mm a" return formatter }() override func viewDidLoad() { super.viewDidLoad() setUpBoxSDK() setUpUI() } // MARK: - Actions @objc private func loginButtonPressed() { authorizeWithJWClient() } @objc private func loadItemsButtonPressed() { getRootFolderItems() } // MARK: - Set up private func setUpBoxSDK() { sdk = BoxSDK( clientId: Constants.clientID, clientSecret: Constants.clientSecret ) } private func setUpUI() { title = "JWT Example" navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Login", style: .plain, target: self, action: #selector(loginButtonPressed)) tableView.tableFooterView = UIView() } } // MARK: - TableView extension ViewController { override func numberOfSections(in _: UITableView) -> Int { return 1 } override func tableView(_: UITableView, numberOfRowsInSection _: Int) -> Int { return folderItems.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let item = folderItems[indexPath.row] let cell = tableView.dequeueReusableCell(withIdentifier: "ItemCell", for: indexPath) cell.textLabel?.numberOfLines = 0 switch item.itemValue { case let .file(file): cell.textLabel?.text = file.name cell.detailTextLabel?.text = String(format: "Date Modified %@", dateFormatter.string(from: file.modifiedAt ?? Date())) cell.accessoryType = .none case let .folder(folder): cell.textLabel?.text = folder.name cell.detailTextLabel?.text = String(format: "Date Modified %@", dateFormatter.string(from: folder.modifiedAt ?? Date())) cell.accessoryType = .disclosureIndicator cell.imageView?.image = UIImage(named: "folder") default: break } return cell } } // MARK: - Loading items private extension ViewController { func getRootFolderItems() { let iterator: PaginationIterator<FolderItem> = client.folders.getFolderItems( folderId: "0", usemarker: true, fields: ["modified_at", "name"] ) iterator.nextItems { [weak self] result in switch result { case let .failure(error): print(error) case let .success(items): self?.folderItems = items DispatchQueue.main.async { self?.tableView.reloadData() self?.navigationItem.rightBarButtonItem?.title = "Refresh" } } } } } // MARK: - JWT Helpers private extension ViewController { func authorizeWithJWClient() { #warning("Get uniqueID from your server. It's a way for your server to identify the app it's generating JWT token for.") sdk.getDelegatedAuthClient(authClosure: obtainJWTTokenFromExternalSources(), uniqueID: "dummyID") { [weak self] result in switch result { case let .success(client): guard let self = self else { return } self.client = client self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Load items", style: .plain, target: self, action: #selector(self.loadItemsButtonPressed)) case let .failure(error): print(error) } } } func obtainJWTTokenFromExternalSources() -> DelegatedAuthClosure { return { uniqueID, completion in // The code below is an example implementation of the delegate function — please provide your own // implementation let session = URLSession(configuration: .default) //REPLACE WITH YOUR HEROKU APPLICATION LINK let tokenUrl = "https://myapp.herokuapp.com/" let urlRequest = URLRequest(url: URL(string: tokenUrl)!) let task = session.dataTask(with: urlRequest) { data, response, error in if let unwrappedError = error { print(error.debugDescription) completion(.failure(unwrappedError)) return } if let body = data, let token = String(data: body, encoding: .utf8) { print("\nFetched new token: \(token)\n") completion(.success((accessToken: token, expiresIn: 999))) } else { completion(.failure(BoxError.tokenRetrieval)) } } task.resume() } } }
10df630c4ee661e533fd2a83aef64f69
31.8875
170
0.58875
false
false
false
false
SerjKultenko/Calculator3
refs/heads/master
Calculator/GraphicViewController.swift
mit
1
// // GraphicViewController.swift // Calculator // // Created by Sergei Kultenko on 05/09/2017. // Copyright © 2017 Sergey Kultenko. All rights reserved. // import UIKit class GraphicViewController: UIViewController, UIScrollViewDelegate { let kGraphicSettingsKey = "GraphicSettingsKey" @IBOutlet weak var scrollView: UIScrollView! { didSet { scrollView.delegate = self } } private var lastScrollViewContentOffset: CGPoint = CGPoint.zero @IBOutlet weak var graphicView: GraphicView! public var graphDataSource: GraphDataSource? { didSet { graphicView?.graphDataSource = graphDataSource navigationItem.title = graphDataSource?.description } } var settingsLoaded = false override func viewDidLoad() { super.viewDidLoad() automaticallyAdjustsScrollViewInsets = false graphicView?.graphDataSource = graphDataSource NotificationCenter.default.addObserver(self, selector: #selector(deviceOrientationDidChange), name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil) } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() if !settingsLoaded { _ = loadSettings() settingsLoaded = true } if graphicView.scale <= 1 { graphicView.frame = scrollView.bounds scrollView.contentSize = graphicView.frame.size scrollView.contentOffset = CGPoint.zero graphicView.setNeedsDisplay() } } @IBAction func scaleChangeAction(_ sender: UIPinchGestureRecognizer) { if sender.state == .began { sender.scale = graphicView.scale } else { if sender.scale < 4 && sender.scale > 0.1 { if sender.scale < 1 { graphicView.frame = scrollView.bounds scrollView.contentSize = graphicView.frame.size scrollView.contentOffset = CGPoint.zero } else { let graphicNewWidth = view.frame.width * sender.scale let graphicNewHeight = view.frame.height * sender.scale graphicView.frame = CGRect(x: 0, y: 0, width: graphicNewWidth, height: graphicNewHeight) scrollView.contentSize = CGSize(width: graphicNewWidth, height: graphicNewHeight) scrollView.contentOffset = CGPoint(x: graphicNewWidth/2 - scrollView.frame.width/2 , y: graphicNewHeight/2 - scrollView.frame.height/2) } graphicView.setNeedsDisplay() graphicView.scale = sender.scale } } saveSettings() } @IBAction func doubleTapAction(_ sender: UITapGestureRecognizer) { let centerPoint = sender.location(in: view) scrollView.contentOffset = CGPoint(x: graphicView.frame.width/2 - centerPoint.x , y: graphicView.frame.height/2 - centerPoint.y) saveSettings() } func scrollViewDidScroll(_ scrollView: UIScrollView) { lastScrollViewContentOffset = scrollView.contentOffset saveSettings() } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) // if UIDevice.current.orientation.isLandscape { // print("Landscape \(size)") // } else { // print("Portrait \(size)") // } } @objc func deviceOrientationDidChange() { // switch UIDevice.current.orientation { // case .faceDown: // print("Face down") // case .faceUp: // print("Face up") // case .unknown: // print("Unknown") // case .landscapeLeft: // print("Landscape left") // case .landscapeRight: // print("Landscape right") // case .portrait: // print("Portrait") // case .portraitUpsideDown: // print("Portrait upside down") // } } func saveSettings() { guard settingsLoaded else { return } let graphicSettings = GraphicSettings(graphicViewFrame: graphicView.frame, scrollViewContentSize: scrollView.contentSize, scrollViewContentOffset: scrollView.contentOffset, scale: graphicView.scale) //print("saved \(graphicSettings)") UserDefaults.standard.set(graphicSettings.encode(), forKey: kGraphicSettingsKey) UserDefaults.standard.synchronize() } func loadSettings()->Bool { guard let graphicSettingsData = UserDefaults.standard.object(forKey: kGraphicSettingsKey) as? Data, let graphicSettings = GraphicSettings(data:graphicSettingsData) else { return false } graphicView.frame = graphicSettings.graphicViewFrame scrollView.contentSize = graphicSettings.scrollViewContentSize scrollView.contentOffset = graphicSettings.scrollViewContentOffset graphicView.scale = graphicSettings.scale return true } deinit { NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil) } } struct GraphicSettings: Codable { let graphicViewFrame: CGRect let scrollViewContentSize: CGSize let scrollViewContentOffset: CGPoint let scale: CGFloat init(graphicViewFrame: CGRect, scrollViewContentSize: CGSize, scrollViewContentOffset: CGPoint, scale: CGFloat) { self.graphicViewFrame = graphicViewFrame self.scrollViewContentSize = scrollViewContentSize self.scrollViewContentOffset = scrollViewContentOffset self.scale = scale } init?(data: Data) { let decoder = JSONDecoder() if let decoded = try? decoder.decode(GraphicSettings.self, from: data) { self = decoded } else { return nil } } func encode() -> Data? { let encoder = JSONEncoder() return try? encoder.encode(self) } } //extension GraphicSettings { // init?(data: Data) { // if let coding = NSKeyedUnarchiver.unarchiveObject(with: data) as? GraphicSettingsEncoding { // graphicViewFrame = coding.graphicViewFrame as CGRect // scrollViewContentSize = coding.scrollViewContentSize as CGSize // scrollViewContentOffset = coding.scrollViewContentOffset as CGPoint // scale = coding.scale as CGFloat // } else { // return nil // } // } // // func encode() -> Data { // return NSKeyedArchiver.archivedData(withRootObject: GraphicSettingsEncoding(self)) // } // // private class GraphicSettingsEncoding: NSObject, NSCoding { // let graphicViewFrame: CGRect // let scrollViewContentSize: CGSize // let scrollViewContentOffset: CGPoint // let scale: CGFloat // // init(_ graphicSettings: GraphicSettings) { // graphicViewFrame = graphicSettings.graphicViewFrame // scrollViewContentSize = graphicSettings.scrollViewContentSize // scrollViewContentOffset = graphicSettings.scrollViewContentOffset // scale = graphicSettings.scale // } // // required init?(coder aDecoder: NSCoder) { // graphicViewFrame = aDecoder.decodeCGRect(forKey: "graphicViewFrame") // scrollViewContentSize = aDecoder.decodeCGSize(forKey: "scrollViewContentSize") // scrollViewContentOffset = aDecoder.decodeCGPoint(forKey: "scrollViewContentOffset") // scale = CGFloat(aDecoder.decodeFloat(forKey: "scale")) // } // // public func encode(with aCoder: NSCoder) { // aCoder.encode(graphicViewFrame, forKey: "graphicViewFrame") // aCoder.encode(scrollViewContentSize, forKey: "scrollViewContentSize") // aCoder.encode(scrollViewContentOffset, forKey: "scrollViewContentOffset") // aCoder.encode(Float(scale), forKey: "scale") // } // } //}
c0022b2d59fa92a4aa657d258ba09154
36.026667
170
0.622974
false
false
false
false
jigneshsheth/Datastructures
refs/heads/master
DataStructure/DataStructure/FindMedianSortedArray.swift
mit
1
// // FindMedianSortedArray.swift // DataStructure // // Created by Jigs Sheth on 11/2/21. // Copyright © 2021 jigneshsheth.com. All rights reserved. // import Foundation class FindMedianSortedArray { public static func findMedianSortedArrays(_ nums1: [Int], _ nums2: [Int]) -> Double { let arr = mergeSortedArrays(nums1, nums2) if arr.count % 2 == 1{ return Double(arr[Int((arr.count + 1) / 2) - 1]) }else{ let midIndex = arr.count/2 return Double(arr[midIndex-1] + arr[midIndex]) / 2 } } public static func mergeSortedArrays(_ arr1:[Int],_ arr2:[Int]) -> [Int] { var arr = arr1 for i in arr2 { arr.append(i) } return arr.sorted() } }
ac717a5034a20eae662d0e6a8a31a36c
19.470588
86
0.632184
false
false
false
false
wireapp/wire-ios
refs/heads/develop
Wire-iOS/Sources/Helpers/syncengine/ProfileImageFetchable.swift
gpl-3.0
1
// // Wire // Copyright (C) 2018 Wire Swiss GmbH // // 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/. // import Foundation import WireSyncEngine extension CIContext { static var shared: CIContext = CIContext(options: nil) } typealias ProfileImageFetchableUser = UserType & ProfileImageFetchable protocol ProfileImageFetchable { func fetchProfileImage(session: ZMUserSessionInterface, cache: ImageCache<UIImage>, sizeLimit: Int?, desaturate: Bool, completion: @escaping (_ image: UIImage?, _ cacheHit: Bool) -> Void) } extension ProfileImageFetchable where Self: UserType { private func cacheKey(for size: ProfileImageSize, sizeLimit: Int?, desaturate: Bool) -> String? { guard let baseKey = (size == .preview ? smallProfileImageCacheKey : mediumProfileImageCacheKey) else { return nil } var derivedKey = baseKey if desaturate { derivedKey = "\(derivedKey)_desaturated" } if let sizeLimit = sizeLimit { derivedKey = "\(derivedKey)_\(sizeLimit)" } return derivedKey } func fetchProfileImage(session: ZMUserSessionInterface, cache: ImageCache<UIImage> = UIImage.defaultUserImageCache, sizeLimit: Int? = nil, desaturate: Bool = false, completion: @escaping (_ image: UIImage?, _ cacheHit: Bool) -> Void) { let screenScale = UIScreen.main.scale let previewSizeLimit: CGFloat = 280 let size: ProfileImageSize if let sizeLimit = sizeLimit { size = CGFloat(sizeLimit) * screenScale < previewSizeLimit ? .preview : .complete } else { size = .complete } guard let cacheKey = cacheKey(for: size, sizeLimit: sizeLimit, desaturate: desaturate) as NSString? else { return completion(nil, false) } if let image = cache.cache.object(forKey: cacheKey) { return completion(image, true) } switch size { case .preview: self.requestPreviewProfileImage() default: self.requestCompleteProfileImage() } imageData(for: size, queue: cache.processingQueue) { (imageData) in guard let imageData = imageData else { return DispatchQueue.main.async { completion(nil, false) } } var image: UIImage? if let sizeLimit = sizeLimit { image = UIImage(from: imageData, withMaxSize: CGFloat(sizeLimit) * screenScale) } else { image = UIImage(data: imageData)?.decoded } if desaturate { image = image?.desaturatedImage(with: CIContext.shared) } if let image = image { cache.cache.setObject(image, forKey: cacheKey) } DispatchQueue.main.async { completion(image, false) } } } } extension ZMUser: ProfileImageFetchable {} extension ZMSearchUser: ProfileImageFetchable {}
48c52690ff4ff8096db66cb577bf6f77
31.711864
114
0.598964
false
false
false
false
whatme/BSImagePicker
refs/heads/master
Pod/Classes/Controller/PhotosViewController.swift
mit
1
// The MIT License (MIT) // // Copyright (c) 2015 Joakim Gyllström // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import UIKit import Photos final class PhotosViewController : UICollectionViewController, UIPopoverPresentationControllerDelegate, UITableViewDelegate, UINavigationControllerDelegate, SelectableDataDelegate { var selectionClosure: ((asset: PHAsset) -> Void)? var deselectionClosure: ((asset: PHAsset) -> Void)? var cancelClosure: ((assets: [PHAsset]) -> Void)? var finishClosure: ((assets: [PHAsset]) -> Void)? var doneBarButton: UIBarButtonItem? var cancelBarButton: UIBarButtonItem? var albumTitleView: AlbumTitleView? private let expandAnimator = ZoomAnimator() private let shrinkAnimator = ZoomAnimator() private var photosDataSource: CollectionViewDataSource? private var albumsDataSource: TableViewDataSource private let photoCellFactory = PhotoCellFactory() private let albumCellFactory = AlbumCellFactory() private let settings: BSImagePickerSettings private var doneBarButtonTitle: String? private lazy var albumsViewController: AlbumsViewController? = { let storyboard = UIStoryboard(name: "Albums", bundle: BSImagePickerViewController.bundle) let vc = storyboard.instantiateInitialViewController() as? AlbumsViewController vc?.modalPresentationStyle = .Popover vc?.preferredContentSize = CGSize(width: 320, height: 300) vc?.tableView.dataSource = self.albumsDataSource vc?.tableView.delegate = self return vc }() private lazy var previewViewContoller: PreviewViewController? = { return PreviewViewController(nibName: nil, bundle: nil) }() required init(dataSource: SelectableDataSource, settings aSettings: BSImagePickerSettings, selections: [PHAsset] = []) { albumsDataSource = TableViewDataSource(dataSource: dataSource, cellFactory: albumCellFactory) settings = aSettings super.init(collectionViewLayout: UICollectionViewFlowLayout()) photoCellFactory.settings = settings albumsDataSource.data.delegate = self // Default is to have first album selected albumsDataSource.data.selectObjectAtIndexPath(NSIndexPath(forRow: 0, inSection: 0)) if let album = albumsDataSource.data.selections.first as? PHAssetCollection { initializePhotosDataSource(album) photosDataSource?.data.selections = selections } } required init?(coder aDecoder: NSCoder) { albumsDataSource = TableViewDataSource(dataSource: FetchResultsDataSource(fetchResults: []), cellFactory: albumCellFactory) albumsDataSource.data.allowsMultipleSelection = false settings = Settings() super.init(coder: aDecoder) } override func loadView() { super.loadView() // Setup collection view // TODO: Settings collectionView?.backgroundColor = UIColor.whiteColor() photoCellFactory.registerCellIdentifiersForCollectionView(collectionView) // Set an empty title to get < back button title = " " // Set button actions and add them to navigation item doneBarButton?.target = self doneBarButton?.action = Selector("doneButtonPressed:") cancelBarButton?.target = self cancelBarButton?.action = Selector("cancelButtonPressed:") albumTitleView?.albumButton.addTarget(self, action: Selector("albumButtonPressed:"), forControlEvents: .TouchUpInside) navigationItem.leftBarButtonItem = cancelBarButton navigationItem.rightBarButtonItem = doneBarButton navigationItem.titleView = albumTitleView if let album = albumsDataSource.data.selections.first as? PHAssetCollection { updateAlbumTitle(album) synchronizeCollectionView() } // Add long press recognizer let longPressRecognizer = UILongPressGestureRecognizer(target: self, action: "collectionViewLongPressed:") longPressRecognizer.minimumPressDuration = 0.5 collectionView?.addGestureRecognizer(longPressRecognizer) // Set navigation controller delegate navigationController?.delegate = self } // MARK: Appear/Disappear override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) updateDoneButton() } // MARK: Button actions func cancelButtonPressed(sender: UIBarButtonItem) { if let closure = cancelClosure, let assets = photosDataSource?.data.selections as? [PHAsset] { dispatch_async(dispatch_get_global_queue(0, 0), { () -> Void in closure(assets: assets) }) } dismissViewControllerAnimated(true, completion: nil) } func doneButtonPressed(sender: UIBarButtonItem) { if let closure = finishClosure, let assets = photosDataSource?.data.selections as? [PHAsset] { dispatch_async(dispatch_get_global_queue(0, 0), { () -> Void in closure(assets: assets) }) } dismissViewControllerAnimated(true, completion: nil) } func albumButtonPressed(sender: UIButton) { if let albumsViewController = albumsViewController, let popVC = albumsViewController.popoverPresentationController { popVC.permittedArrowDirections = .Up popVC.sourceView = sender let senderRect = sender.convertRect(sender.frame, fromView: sender.superview) let sourceRect = CGRect(x: senderRect.origin.x, y: senderRect.origin.y + (sender.frame.size.height / 2), width: senderRect.size.width, height: senderRect.size.height) popVC.sourceRect = sourceRect popVC.delegate = self albumsViewController.tableView.reloadData() presentViewController(albumsViewController, animated: true, completion: nil) } } func collectionViewLongPressed(sender: UIGestureRecognizer) { if sender.state == .Began { // Disable recognizer while we are figuring out location and pushing preview sender.enabled = false collectionView?.userInteractionEnabled = false // Calculate which index path long press came from let location = sender.locationInView(collectionView) let indexPath = collectionView?.indexPathForItemAtPoint(location) if let vc = previewViewContoller, let indexPath = indexPath, let cell = collectionView?.cellForItemAtIndexPath(indexPath) as? PhotoCell, let asset = cell.asset { // Setup fetch options to be synchronous let options = PHImageRequestOptions() options.synchronous = true // Load image for preview if let imageView = vc.imageView { PHCachingImageManager.defaultManager().requestImageForAsset(asset, targetSize:imageView.frame.size, contentMode: .AspectFit, options: options) { (result, _) in imageView.image = result } } // Setup animation expandAnimator.sourceImageView = cell.imageView expandAnimator.destinationImageView = vc.imageView shrinkAnimator.sourceImageView = vc.imageView shrinkAnimator.destinationImageView = cell.imageView navigationController?.pushViewController(vc, animated: true) } // Re-enable recognizer sender.enabled = true collectionView?.userInteractionEnabled = true } } // MARK: Traits override func traitCollectionDidChange(previousTraitCollection: UITraitCollection?) { super.traitCollectionDidChange(previousTraitCollection) if let collectionViewFlowLayout = collectionViewLayout as? UICollectionViewFlowLayout, let collectionViewWidth = collectionView?.bounds.size.width { let itemSpacing: CGFloat = 1.0 let cellsPerRow = settings.cellsPerRow(verticalSize: traitCollection.verticalSizeClass, horizontalSize: traitCollection.horizontalSizeClass) collectionViewFlowLayout.minimumInteritemSpacing = itemSpacing collectionViewFlowLayout.minimumLineSpacing = itemSpacing let width = (collectionViewWidth / CGFloat(cellsPerRow)) - itemSpacing let itemSize = CGSize(width: width, height: width) collectionViewFlowLayout.itemSize = itemSize photoCellFactory.imageSize = itemSize } } // MARK: UIPopoverPresentationControllerDelegate func adaptivePresentationStyleForPresentationController(controller: UIPresentationController) -> UIModalPresentationStyle { return .None } func popoverPresentationControllerShouldDismissPopover(popoverPresentationController: UIPopoverPresentationController) -> Bool { return true } // MARK: UITableViewDelegate func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { // Update selected album albumsDataSource.data.selectObjectAtIndexPath(indexPath) // Notify photos data source if let album = albumsDataSource.data.selections.first as? PHAssetCollection { initializePhotosDataSource(album) updateAlbumTitle(album) synchronizeCollectionView() } // Dismiss album selection albumsViewController?.dismissViewControllerAnimated(true, completion: nil) } // MARK: UICollectionViewDelegate override func collectionView(collectionView: UICollectionView, shouldSelectItemAtIndexPath indexPath: NSIndexPath) -> Bool { return photosDataSource?.data.selections.count < settings.maxNumberOfSelections } override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { // Select asset) photosDataSource?.data.selectObjectAtIndexPath(indexPath) // Set selection number if let cell = collectionView.cellForItemAtIndexPath(indexPath) as? PhotoCell, let count = photosDataSource?.data.selections.count { if let selectionCharacter = settings.selectionCharacter { cell.selectionString = String(selectionCharacter) } else { cell.selectionString = String(count) } } // Update done button updateDoneButton() // Call selection closure if let closure = selectionClosure, let asset = photosDataSource?.data.objectAtIndexPath(indexPath) as? PHAsset { dispatch_async(dispatch_get_global_queue(0, 0), { () -> Void in closure(asset: asset) }) } } override func collectionView(collectionView: UICollectionView, didDeselectItemAtIndexPath indexPath: NSIndexPath) { // Deselect asset photosDataSource?.data.deselectObjectAtIndexPath(indexPath) // Update done button updateDoneButton() // Reload selected cells to update their selection number if let photosDataSource = photosDataSource { UIView.setAnimationsEnabled(false) collectionView.reloadItemsAtIndexPaths(photosDataSource.data.selectedIndexPaths) syncSelectionInDataSource(photosDataSource.data, withCollectionView: collectionView) UIView.setAnimationsEnabled(true) } // Call deselection closure if let closure = deselectionClosure, let asset = photosDataSource?.data.objectAtIndexPath(indexPath) as? PHAsset { dispatch_async(dispatch_get_global_queue(0, 0), { () -> Void in closure(asset: asset) }) } } // MARK: Selectable data delegate func didUpdateData(sender: SelectableDataSource, incrementalChange: Bool, insertions insert: [NSIndexPath], deletions delete: [NSIndexPath], changes change: [NSIndexPath]) { // May come on a background thread, so dispatch to main dispatch_async(dispatch_get_main_queue(), { () -> Void in // Reload table view or collection view? if sender.isEqual(self.photosDataSource?.data) { if let collectionView = self.collectionView { if incrementalChange { // Update collectionView.deleteItemsAtIndexPaths(delete) collectionView.insertItemsAtIndexPaths(insert) collectionView.reloadItemsAtIndexPaths(change) } else { // Reload & scroll to top if significant change collectionView.reloadData() collectionView.scrollToItemAtIndexPath(NSIndexPath(forItem: 0, inSection: 0), atScrollPosition: .None, animated: false) } // Sync selection if let photosDataSource = self.photosDataSource { self.syncSelectionInDataSource(photosDataSource.data, withCollectionView: collectionView) } } } else if sender.isEqual(self.albumsDataSource.data) { if incrementalChange { // Update self.albumsViewController?.tableView?.deleteRowsAtIndexPaths(delete, withRowAnimation: .Automatic) self.albumsViewController?.tableView?.insertRowsAtIndexPaths(insert, withRowAnimation: .Automatic) self.albumsViewController?.tableView?.reloadRowsAtIndexPaths(change, withRowAnimation: .Automatic) } else { // Reload self.albumsViewController?.tableView?.reloadData() } } }) } // MARK: Private helper methods func updateDoneButton() { // Get selection count if let numberOfSelectedAssets = photosDataSource?.data.selections.count { // Find right button if let subViews = navigationController?.navigationBar.subviews { for view in subViews { if let btn = view as? UIButton where checkIfRightButtonItem(btn) { // Store original title if we havn't got it if doneBarButtonTitle == nil { doneBarButtonTitle = btn.titleForState(.Normal) } if let doneBarButtonTitle = doneBarButtonTitle { // Update title if numberOfSelectedAssets > 0 { btn.bs_setTitleWithoutAnimation("\(doneBarButtonTitle) (\(numberOfSelectedAssets))", forState: .Normal) } else { btn.bs_setTitleWithoutAnimation(doneBarButtonTitle, forState: .Normal) } } // Stop loop break } } } // Enabled if numberOfSelectedAssets > 0 { doneBarButton?.enabled = true } else { doneBarButton?.enabled = false } } } // Check if a give UIButton is the right UIBarButtonItem in the navigation bar // Somewhere along the road, our UIBarButtonItem gets transformed to an UINavigationButton func checkIfRightButtonItem(btn: UIButton) -> Bool { var isRightButton = false if let rightButton = navigationItem.rightBarButtonItem { // Store previous values let wasRightEnabled = rightButton.enabled let wasButtonEnabled = btn.enabled // Set a known state for both buttons rightButton.enabled = false btn.enabled = false // Change one and see if other also changes rightButton.enabled = true isRightButton = btn.enabled // Reset rightButton.enabled = wasRightEnabled btn.enabled = wasButtonEnabled } return isRightButton } func syncSelectionInDataSource(dataSource: SelectableDataSource, withCollectionView collectionView: UICollectionView) { // Get indexpaths of selected assets let indexPaths = dataSource.selectedIndexPaths // Loop through them and set them as selected in the collection view for indexPath in indexPaths { collectionView.selectItemAtIndexPath(indexPath, animated: false, scrollPosition: .None) } } private func updateAlbumTitle(album: PHAssetCollection) { if let title = album.localizedTitle { // Update album title albumTitleView?.albumTitle = title } } private func initializePhotosDataSource(album: PHAssetCollection) { // Set up a photo data source with album let fetchOptions = PHFetchOptions() fetchOptions.sortDescriptors = [ NSSortDescriptor(key: "creationDate", ascending: false) ] fetchOptions.predicate = NSPredicate(format: "mediaType = %d", PHAssetMediaType.Image.rawValue) let dataSource = FetchResultsDataSource(fetchResult: PHAsset.fetchAssetsInAssetCollection(album, options: fetchOptions)) let newDataSource = CollectionViewDataSource(dataSource: dataSource, cellFactory: photoCellFactory) // Keep selection if let photosDataSource = photosDataSource { newDataSource.data.selections = photosDataSource.data.selections } photosDataSource = newDataSource } func synchronizeCollectionView() { // Hook up data source collectionView?.dataSource = photosDataSource collectionView?.delegate = self photosDataSource?.data.delegate = self // Enable multiple selection photosDataSource?.data.allowsMultipleSelection = true collectionView?.allowsMultipleSelection = true // Reload and sync selections collectionView?.reloadData() syncSelectionInDataSource(photosDataSource!.data, withCollectionView: collectionView!) } // MARK: UINavigationControllerDelegate func navigationController(navigationController: UINavigationController, animationControllerForOperation operation: UINavigationControllerOperation, fromViewController fromVC: UIViewController, toViewController toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? { if operation == .Push { return expandAnimator } else { return shrinkAnimator } } }
0c18179682cc97ef1cdcaa7156139b77
43.367391
281
0.641384
false
false
false
false
testpress/ios-app
refs/heads/master
ios-app/Model/Course.swift
mit
1
// // Course.swift // ios-app // // Copyright © 2017 Testpress. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import ObjectMapper import Realm import RealmSwift class Course: DBModel { @objc dynamic var url: String = "" @objc dynamic var id = 0 @objc dynamic var title: String = "" @objc dynamic var image: String = "" @objc dynamic var modified: String = "" @objc dynamic var modifiedDate: Double = 0 @objc dynamic var contentsUrl: String = "" @objc dynamic var chaptersUrl: String = "" @objc dynamic var slug: String = "" @objc dynamic var trophiesCount = 0 @objc dynamic var chaptersCount = 0 @objc dynamic var contentsCount = 0 @objc dynamic var order = 0 @objc dynamic var active = true @objc dynamic var external_content_link: String = "" @objc dynamic var external_link_label: String = "" var tags = List<String>() public override func mapping(map: Map) { url <- map["url"] id <- map["id"] title <- map["title"] image <- map["image"] modified <- map["modified"] modifiedDate = FormatDate.getDate(from: modified)?.timeIntervalSince1970 ?? 0 contentsUrl <- map["contents_url"] chaptersUrl <- map["chapters_url"] slug <- map["slug"] trophiesCount <- map["trophies_count"] chaptersCount <- map["chapters_count"] contentsCount <- map["contents_count"] order <- map["order"] active <- map["active"] external_content_link <- map["external_content_link"] external_link_label <- map["external_link_label"] tags <- (map["tags"], StringArrayTransform()) } override public static func primaryKey() -> String? { return "id" } }
116a624dde3e429188811b1b0cb6cca6
37.821918
85
0.667255
false
false
false
false
reproto/reproto
refs/heads/main
it/versions/structures/simple/swift/Foo/V4.swift
apache-2.0
1
public struct Foo_V4_Thing { let name: String? let other: Bar_V1_Other? let other2: Bar_V20_Other? let other21: Bar_V21_Other? } public extension Foo_V4_Thing { static func decode(json: Any) throws -> Foo_V4_Thing { let json = try decode_value(json as? [String: Any]) var name: String? = Optional.none if let value = json["name"] { name = Optional.some(try decode_name(unbox(value, as: String.self), name: "name")) } var other: Bar_V1_Other? = Optional.none if let value = json["other"] { other = Optional.some(try Bar_V1_Other.decode(json: value)) } var other2: Bar_V20_Other? = Optional.none if let value = json["other2"] { other2 = Optional.some(try Bar_V20_Other.decode(json: value)) } var other21: Bar_V21_Other? = Optional.none if let value = json["other21"] { other21 = Optional.some(try Bar_V21_Other.decode(json: value)) } return Foo_V4_Thing(name: name, other: other, other2: other2, other21: other21) } func encode() throws -> [String: Any] { var json = [String: Any]() if let value = self.name { json["name"] = value } if let value = self.other { json["other"] = try value.encode() } if let value = self.other2 { json["other2"] = try value.encode() } if let value = self.other21 { json["other21"] = try value.encode() } return json } }
c47507a9e33092ff05af8062d29b2a4b
23.929825
88
0.608726
false
false
false
false
frootloops/swift
refs/heads/master
tools/SwiftSyntax/Trivia.swift
apache-2.0
1
//===------------------- Trivia.swift - Source Trivia Enum ----------------===// // // 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 // //===----------------------------------------------------------------------===// import Foundation /// A contiguous stretch of a single kind of trivia. The constituent part of /// a `Trivia` collection. /// /// For example, four spaces would be represented by /// `.spaces(4)` /// /// In general, you should deal with the actual Trivia collection instead /// of individual pieces whenever possible. public enum TriviaPiece: Codable { enum CodingKeys: CodingKey { case kind, value } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) let kind = try container.decode(String.self, forKey: .kind) switch kind { case "Space": let value = try container.decode(Int.self, forKey: .value) self = .spaces(value) case "Tab": let value = try container.decode(Int.self, forKey: .value) self = .tabs(value) case "VerticalTab": let value = try container.decode(Int.self, forKey: .value) self = .verticalTabs(value) case "Formfeed": let value = try container.decode(Int.self, forKey: .value) self = .formfeeds(value) case "Newline": let value = try container.decode(Int.self, forKey: .value) self = .newlines(value) case "Backtick": let value = try container.decode(Int.self, forKey: .value) self = .backticks(value) case "LineComment": let value = try container.decode(String.self, forKey: .value) self = .lineComment(value) case "BlockComment": let value = try container.decode(String.self, forKey: .value) self = .blockComment(value) case "DocLineComment": let value = try container.decode(String.self, forKey: .value) self = .docLineComment(value) case "DocBlockComment": let value = try container.decode(String.self, forKey: .value) self = .docLineComment(value) case "GarbageText": let value = try container.decode(String.self, forKey: .value) self = .garbageText(value) default: let context = DecodingError.Context(codingPath: [CodingKeys.kind], debugDescription: "invalid TriviaPiece kind \(kind)") throw DecodingError.valueNotFound(String.self, context) } } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) switch self { case .blockComment(let comment): try container.encode("BlockComment", forKey: .kind) try container.encode(comment, forKey: .value) case .docBlockComment(let comment): try container.encode("DocBlockComment", forKey: .kind) try container.encode(comment, forKey: .value) case .docLineComment(let comment): try container.encode("DocLineComment", forKey: .kind) try container.encode(comment, forKey: .value) case .lineComment(let comment): try container.encode("LineComment", forKey: .kind) try container.encode(comment, forKey: .value) case .garbageText(let text): try container.encode("GarbageText", forKey: .kind) try container.encode(text, forKey: .value) case .formfeeds(let count): try container.encode("Formfeed", forKey: .kind) try container.encode(count, forKey: .value) case .backticks(let count): try container.encode("Backtick", forKey: .kind) try container.encode(count, forKey: .value) case .newlines(let count): try container.encode("Newline", forKey: .kind) try container.encode(count, forKey: .value) case .spaces(let count): try container.encode("Space", forKey: .kind) try container.encode(count, forKey: .value) case .tabs(let count): try container.encode("Tab", forKey: .kind) try container.encode(count, forKey: .value) case .verticalTabs(let count): try container.encode("VerticalTab", forKey: .kind) try container.encode(count, forKey: .value) } } /// A space ' ' character. case spaces(Int) /// A tab '\t' character. case tabs(Int) /// A vertical tab '\v' character. case verticalTabs(Int) /// A form-feed '\f' character. case formfeeds(Int) /// A newline '\n' character. case newlines(Int) /// A backtick '`' character, used to escape identifiers. case backticks(Int) /// A developer line comment, starting with '//' case lineComment(String) /// A developer block comment, starting with '/*' and ending with '*/'. case blockComment(String) /// A documentation line comment, starting with '///'. case docLineComment(String) /// A documentation block comment, starting with '/**' and ending with '*/. case docBlockComment(String) /// Any skipped text. case garbageText(String) } extension TriviaPiece: TextOutputStreamable { /// Prints the provided trivia as they would be written in a source file. /// /// - Parameter stream: The stream to which to print the trivia. public func write<Target>(to target: inout Target) where Target: TextOutputStream { func printRepeated(_ character: String, count: Int) { for _ in 0..<count { target.write(character) } } switch self { case let .spaces(count): printRepeated(" ", count: count) case let .tabs(count): printRepeated("\t", count: count) case let .verticalTabs(count): printRepeated("\u{2B7F}", count: count) case let .formfeeds(count): printRepeated("\u{240C}", count: count) case let .newlines(count): printRepeated("\n", count: count) case let .backticks(count): printRepeated("`", count: count) case let .lineComment(text), let .blockComment(text), let .docLineComment(text), let .docBlockComment(text), let .garbageText(text): target.write(text) } } /// Computes the information from this trivia to inform the source locations /// of the associated tokens. /// Specifically, walks through the trivia and keeps track of every newline /// to give a number of how many newlines and UTF8 characters appear in the /// trivia, along with the UTF8 offset of the last column. func characterSizes() -> (lines: Int, lastColumn: Int, utf8Length: Int) { switch self { case .spaces(let n), .tabs(let n), .verticalTabs(let n), .formfeeds(let n), .backticks(let n): return (lines: 0, lastColumn: n, utf8Length: n) case .newlines(let n): return (lines: n, lastColumn: 0, utf8Length: n) case .lineComment(let text), .docLineComment(let text): let length = text.utf8.count return (lines: 0, lastColumn: length, utf8Length: length) case .blockComment(let text), .docBlockComment(let text), .garbageText(let text): var lines = 0 var col = 0 var total = 0 for char in text.utf8 { total += 1 if char == 10 /* ASCII newline */ { col = 0 lines += 1 } else { col += 1 } } return (lines: lines, lastColumn: col, utf8Length: total) } } } /// A collection of leading or trailing trivia. This is the main data structure /// for thinking about trivia. public struct Trivia: Codable { let pieces: [TriviaPiece] /// Creates Trivia with the provided underlying pieces. public init(pieces: [TriviaPiece]) { self.pieces = pieces } public init(from decoder: Decoder) throws { var container = try decoder.unkeyedContainer() var pieces = [TriviaPiece]() while let piece = try container.decodeIfPresent(TriviaPiece.self) { pieces.append(piece) } self.pieces = pieces } public func encode(to encoder: Encoder) throws { var container = encoder.unkeyedContainer() for piece in pieces { try container.encode(piece) } } /// Creates Trivia with no pieces. public static var zero: Trivia { return Trivia(pieces: []) } /// Creates a new `Trivia` by appending the provided `TriviaPiece` to the end. public func appending(_ piece: TriviaPiece) -> Trivia { var copy = pieces copy.append(piece) return Trivia(pieces: copy) } /// Return a piece of trivia for some number of space characters in a row. public static func spaces(_ count: Int) -> Trivia { return [.spaces(count)] } /// Return a piece of trivia for some number of tab characters in a row. public static func tabs(_ count: Int) -> Trivia { return [.tabs(count)] } /// A vertical tab '\v' character. public static func verticalTabs(_ count: Int) -> Trivia { return [.verticalTabs(count)] } /// A form-feed '\f' character. public static func formfeeds(_ count: Int) -> Trivia { return [.formfeeds(count)] } /// Return a piece of trivia for some number of newline characters /// in a row. public static func newlines(_ count: Int) -> Trivia { return [.newlines(count)] } /// Return a piece of trivia for some number of backtick '`' characters /// in a row. public static func backticks(_ count: Int) -> Trivia { return [.backticks(count)] } /// Return a piece of trivia for a single line of ('//') developer comment. public static func lineComment(_ text: String) -> Trivia { return [.lineComment(text)] } /// Return a piece of trivia for a block comment ('/* ... */') public static func blockComment(_ text: String) -> Trivia { return [.blockComment(text)] } /// Return a piece of trivia for a single line of ('///') doc comment. public static func docLineComment(_ text: String) -> Trivia { return [.docLineComment(text)] } /// Return a piece of trivia for a documentation block comment ('/** ... */') public static func docBlockComment(_ text: String) -> Trivia { return [.docBlockComment(text)] } /// Return a piece of trivia for any garbage text. public static func garbageText(_ text: String) -> Trivia { return [.garbageText(text)] } /// Computes the total sizes and offsets of all pieces in this Trivia. func characterSizes() -> (lines: Int, lastColumn: Int, utf8Length: Int) { var lines = 0 var lastColumn = 0 var length = 0 for piece in pieces { let (ln, col, len) = piece.characterSizes() lines += ln lastColumn = col length += len } return (lines: lines, lastColumn: lastColumn, utf8Length: length) } } /// Conformance for Trivia to the Collection protocol. extension Trivia: Collection { public var startIndex: Int { return pieces.startIndex } public var endIndex: Int { return pieces.endIndex } public func index(after i: Int) -> Int { return pieces.index(after: i) } public subscript(_ index: Int) -> TriviaPiece { return pieces[index] } } extension Trivia: ExpressibleByArrayLiteral { /// Creates Trivia from the provided pieces. public init(arrayLiteral elements: TriviaPiece...) { self.pieces = elements } } /// Concatenates two collections of `Trivia` into one collection. public func +(lhs: Trivia, rhs: Trivia) -> Trivia { return Trivia(pieces: lhs.pieces + rhs.pieces) }
ae1c23ca1dcaa129cac791e3816d03bb
31.88
83
0.650852
false
false
false
false
18775134221/SwiftBase
refs/heads/develop
10-combining-operators-in-practice/final/OurPlanet/Pods/RxCocoa/RxCocoa/Common/ControlTarget.swift
apache-2.0
37
// // ControlTarget.swift // RxCocoa // // Created by Krunoslav Zaher on 2/21/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // #if os(iOS) || os(tvOS) || os(macOS) import Foundation #if !RX_NO_MODULE import RxSwift #endif #if os(iOS) || os(tvOS) import UIKit typealias Control = UIKit.UIControl typealias ControlEvents = UIKit.UIControlEvents #elseif os(macOS) import Cocoa typealias Control = Cocoa.NSControl #endif // This should be only used from `MainScheduler` class ControlTarget: RxTarget { typealias Callback = (Control) -> Void let selector: Selector = #selector(ControlTarget.eventHandler(_:)) weak var control: Control? #if os(iOS) || os(tvOS) let controlEvents: UIControlEvents #endif var callback: Callback? #if os(iOS) || os(tvOS) init(control: Control, controlEvents: UIControlEvents, callback: @escaping Callback) { MainScheduler.ensureExecutingOnScheduler() self.control = control self.controlEvents = controlEvents self.callback = callback super.init() control.addTarget(self, action: selector, for: controlEvents) let method = self.method(for: selector) if method == nil { rxFatalError("Can't find method") } } #elseif os(macOS) init(control: Control, callback: @escaping Callback) { MainScheduler.ensureExecutingOnScheduler() self.control = control self.callback = callback super.init() control.target = self control.action = selector let method = self.method(for: selector) if method == nil { rxFatalError("Can't find method") } } #endif func eventHandler(_ sender: Control!) { if let callback = self.callback, let control = self.control { callback(control) } } override func dispose() { super.dispose() #if os(iOS) || os(tvOS) self.control?.removeTarget(self, action: self.selector, for: self.controlEvents) #elseif os(macOS) self.control?.target = nil self.control?.action = nil #endif self.callback = nil } } #endif
175128315143f32805222ec6e0657ea8
22.815217
90
0.637152
false
false
false
false
JGiola/swift
refs/heads/main
test/IDE/complete_rdar80489548.swift
apache-2.0
6
// RUN: %empty-directory(%t.ccp) // RUN: %target-swift-ide-test -batch-code-completion -source-filename %s -filecheck %raw-FileCheck -completion-output-dir %t // KW_IN: Keyword[in]/None: in{{; name=.+$}} // KW_NO_IN-NOT: Keyword[in] func test(value: [Int]) { value.map { #^NOIN_IMMEDIATE?check=KW_IN^# } value.map { value#^NOIN_AFTER_EXPR_NOSPCACE?check=KW_NO_IN^# } value.map { value #^NOIN_AFTER_EXPR?check=KW_IN^# } value.map { value #^NOIN_NEWLINE?check=KW_IN^# } value.map { value in #^IN_AFTER_IN?check=KW_NO_IN^# } value.map { value in #^IN_NEWLINE?check=KW_NO_IN^# } #^FUNCBODY_STMT?check=KW_NO_IN^# value #^FUNCBODY_POSTFIX?check=KW_NO_IN^# } #^GLOBAL_STMT?check=KW_NO_IN^# value #^GLOBAL_POSTFIX?check=KW_NO_IN^#
47ea08d330f14ed05b6ba04a05c7745f
28.115385
125
0.648613
false
true
false
false
itsaboutcode/WordPress-iOS
refs/heads/develop
WordPress/Classes/ViewRelated/Jetpack/Jetpack Restore/Restore Status/BaseRestoreStatusViewController.swift
gpl-2.0
2
import Foundation import CocoaLumberjack import WordPressShared struct JetpackRestoreStatusConfiguration { let title: String let iconImage: UIImage let messageTitle: String let messageDescription: String let hint: String let primaryButtonTitle: String let placeholderProgressTitle: String? let progressDescription: String? } class BaseRestoreStatusViewController: UIViewController { // MARK: - Public Properties lazy var statusView: RestoreStatusView = { let statusView = RestoreStatusView.loadFromNib() statusView.translatesAutoresizingMaskIntoConstraints = false return statusView }() // MARK: - Private Properties private(set) var site: JetpackSiteRef private(set) var activity: Activity private(set) var configuration: JetpackRestoreStatusConfiguration private lazy var dateFormatter: DateFormatter = { return ActivityDateFormatting.mediumDateFormatterWithTime(for: site) }() // MARK: - Initialization init(site: JetpackSiteRef, activity: Activity) { fatalError("A configuration struct needs to be provided") } init(site: JetpackSiteRef, activity: Activity, configuration: JetpackRestoreStatusConfiguration) { self.site = site self.activity = activity self.configuration = configuration super.init(nibName: nil, bundle: nil) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - View Lifecycle override func viewDidLoad() { super.viewDidLoad() configureTitle() configureNavigation() configureRestoreStatusView() } // MARK: - Public func primaryButtonTapped() { fatalError("Must override in subclass") } // MARK: - Configure private func configureTitle() { title = configuration.title } private func configureNavigation() { navigationItem.hidesBackButton = true navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(doneTapped)) } private func configureRestoreStatusView() { let publishedDate = dateFormatter.string(from: activity.published) statusView.configure( iconImage: configuration.iconImage, title: configuration.messageTitle, description: String(format: configuration.messageDescription, publishedDate), hint: configuration.hint ) statusView.update(progress: 0, progressTitle: configuration.placeholderProgressTitle, progressDescription: nil) view.addSubview(statusView) view.pinSubviewToAllEdges(statusView) } @objc private func doneTapped() { primaryButtonTapped() } }
9d8b16d09a0c2f0fd977fb3b388157bc
27.921569
119
0.660678
false
true
false
false
nicktoumpelis/HiBeacons
refs/heads/swift
HiBeacons/NATMonitoringOperation.swift
mit
1
// // NATMonitoringOperation.swift // HiBeacons // // Created by Nick Toumpelis on 2015-07-26. // Copyright © 2015 Nick Toumpelis. 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 import CoreLocation /// Lists the methods that a monitoring delegate should implement to be notified for all monitoring operation events. protocol NATMonitoringOperationDelegate { /// Triggered when the monitoring operation has started successfully. func monitoringOperationDidStartSuccessfully() /// Triggered by the monitoring operation when it has stopped successfully. func monitoringOperationDidStopSuccessfully() /// Triggered when the monitoring operation has failed to start. func monitoringOperationDidFailToStart() /// Triggered when the monitoring operation has failed to start due to the last authorization denial. func monitoringOperationDidFailToStartDueToAuthorization() /** Triggered when the monitoring operation has detected entering the given region. :param: region The region that the monitoring operation detected. */ func monitoringOperationDidDetectEnteringRegion(_ region: CLBeaconRegion) } /** NATMonitoringOperation contains all the process logic required to successfully monitor for events related to detecting a specific beacon region. */ final class NATMonitoringOperation: NATOperation { /// The delegate for a monitoring operation. var delegate: NATMonitoringOperationDelegate? /// Starts the beacon region monitoring process. func startMonitoringForBeacons() { activateLocationManagerNotifications() print("Turning on monitoring...") if !CLLocationManager.locationServicesEnabled() { print("Couldn't turn on monitoring: Location services are not enabled.") delegate?.monitoringOperationDidFailToStart() return } if !(CLLocationManager.isMonitoringAvailable(for: CLBeaconRegion.self)) { print("Couldn't turn on region monitoring: Region monitoring is not available for CLBeaconRegion class.") delegate?.monitoringOperationDidFailToStart() return } switch CLLocationManager.authorizationStatus() { case .authorizedAlways: turnOnMonitoring() case .authorizedWhenInUse, .denied, .restricted: print("Couldn't turn on monitoring: Required Location Access (Always) missing.") delegate?.monitoringOperationDidFailToStartDueToAuthorization() case .notDetermined: locationManager.requestAlwaysAuthorization() } } /// Turns on monitoring (after all the checks have been passed). func turnOnMonitoring() { locationManager.startMonitoring(for: beaconRegion) print("Monitoring turned on for region: \(beaconRegion)") delegate?.monitoringOperationDidStartSuccessfully() } /// Stops the monitoring process. func stopMonitoringForBeacons() { locationManager.stopMonitoring(for: beaconRegion) print("Turned off monitoring") delegate?.monitoringOperationDidStopSuccessfully() } } // MARK: - Location manager delegate methods extension NATMonitoringOperation { /// This method is triggered when there is a change in the authorization status for the location manager. func locationManager(_ manager: CLLocationManager!, didChangeAuthorizationStatus status: CLAuthorizationStatus) { if status == .authorizedAlways { print("Location Access (Always) granted!") delegate?.monitoringOperationDidStartSuccessfully() turnOnMonitoring() } else if status == .authorizedWhenInUse || status == .denied || status == .restricted { print("Location Access (Always) denied!") delegate?.monitoringOperationDidFailToStart() } } /// Triggered when the location manager has detected entering a given region. func locationManager(_ manager: CLLocationManager!, didEnterRegion region: CLRegion!) { print("Entered region: \(region)") delegate?.monitoringOperationDidDetectEnteringRegion(region as! CLBeaconRegion) } /// Triggered when the location manager has detected exiting a given region. func locationManager(_ manager: CLLocationManager!, didExitRegion region: CLRegion!) { print("Exited region: \(region)") } /// Triggered when the state has been determined for a given region. func locationManager(_ manager: CLLocationManager!, didDetermineState state: CLRegionState, forRegion region: CLRegion!) { let stateString: String switch state { case .inside: stateString = "inside" case .outside: stateString = "outside" case .unknown: stateString = "unknown" } print("State changed to " + stateString + " for region \(region).") } }
eb63e29b5f0d3c9a8851a68ed97c7326
40.020408
126
0.714096
false
false
false
false
jmgc/swift
refs/heads/master
test/SILGen/hop_to_executor.swift
apache-2.0
1
// RUN: %target-swift-frontend -emit-silgen %s -module-name test -swift-version 5 -enable-experimental-concurrency | %FileCheck --enable-var-scope %s // REQUIRES: concurrency actor class MyActor { private var p: Int // CHECK-LABEL: sil hidden [ossa] @$s4test7MyActorC6calleeyySiYF : $@convention(method) @async (Int, @guaranteed MyActor) -> () { // CHECK-NOT: hop_to_executor // CHECK: } // end sil function '$s4test7MyActorC6calleeyySiYF' @actorIndependent func callee(_ x: Int) async { print(x) } // CHECK-LABEL: sil hidden [ossa] @$s4test7MyActorC14throwingCalleeyySiYKF : $@convention(method) @async (Int, @guaranteed MyActor) -> @error Error { // CHECK-NOT: hop_to_executor // CHECK: } // end sil function '$s4test7MyActorC14throwingCalleeyySiYKF' @actorIndependent func throwingCallee(_ x: Int) async throws { print(x) } // CHECK-LABEL: sil hidden [ossa] @$s4test7MyActorC0A13AsyncFunctionyyYKF : $@convention(method) @async (@guaranteed MyActor) -> @error Error { // CHECK: hop_to_executor %0 : $MyActor // CHECK: = apply {{.*}} : $@convention(method) @async (Int, @guaranteed MyActor) -> () // CHECK-NEXT: hop_to_executor %0 : $MyActor // CHECK: try_apply {{.*}}, normal bb1, error bb2 // CHECK: bb1({{.*}}): // CHECK-NEXT: hop_to_executor %0 : $MyActor // CHECK: bb2({{.*}}): // CHECK-NEXT: hop_to_executor %0 : $MyActor // CHECK: } // end sil function '$s4test7MyActorC0A13AsyncFunctionyyYKF' func testAsyncFunction() async throws { await callee(p) await try throwingCallee(p) } // CHECK-LABEL: sil hidden [ossa] @$s4test7MyActorC0A22ConsumingAsyncFunctionyyYF : $@convention(method) @async (@owned MyActor) -> () { // CHECK: [[BORROWED_SELF:%[0-9]+]] = begin_borrow %0 : $MyActor // CHECK: hop_to_executor [[BORROWED_SELF]] : $MyActor // CHECK: = apply {{.*}} : $@convention(method) @async (Int, @guaranteed MyActor) -> () // CHECK-NEXT: hop_to_executor [[BORROWED_SELF]] : $MyActor // CHECK: } // end sil function '$s4test7MyActorC0A22ConsumingAsyncFunctionyyYF' __consuming func testConsumingAsyncFunction() async { await callee(p) } // CHECK-LABEL: sil private [ossa] @$s4test7MyActorC0A7ClosureSiyYFSiyYXEfU_ : $@convention(thin) @async (@guaranteed MyActor) -> Int { // CHECK: [[COPIED_SELF:%[0-9]+]] = copy_value %0 : $MyActor // CHECK: [[BORROWED_SELF:%[0-9]+]] = begin_borrow [[COPIED_SELF]] : $MyActor // CHECK: hop_to_executor [[BORROWED_SELF]] : $MyActor // CHECK: = apply // CHECK: } // end sil function '$s4test7MyActorC0A7ClosureSiyYFSiyYXEfU_' func testClosure() async -> Int { return await { () async in p }() } // CHECK-LABEL: sil hidden [ossa] @$s4test7MyActorC13dontInsertHTESiyF : $@convention(method) (@guaranteed MyActor) -> Int { // CHECK-NOT: hop_to_executor // CHECK: } // end sil function '$s4test7MyActorC13dontInsertHTESiyF' func dontInsertHTE() -> Int { return p } init() { p = 27 } } @globalActor struct GlobalActor { static var shared: MyActor = MyActor() } // CHECK-LABEL: sil hidden [ossa] @$s4test0A11GlobalActoryyYF : $@convention(thin) @async () -> () { // CHECK: [[F:%[0-9]+]] = function_ref @$s4test11GlobalActorV6sharedAA02MyC0Cvau : $@convention(thin) () -> Builtin.RawPointer // CHECK: [[P:%[0-9]+]] = apply [[F]]() : $@convention(thin) () -> Builtin.RawPointer // CHECK: [[A:%[0-9]+]] = pointer_to_address %2 : $Builtin.RawPointer to [strict] $*MyActor // CHECK: [[ACC:%[0-9]+]] = begin_access [read] [dynamic] [[A]] : $*MyActor // CHECK: [[L:%[0-9]+]] = load [copy] [[ACC]] : $*MyActor // CHECK: [[B:%[0-9]+]] = begin_borrow [[L]] : $MyActor // CHECK: hop_to_executor [[B]] : $MyActor // CHECK: } // end sil function '$s4test0A11GlobalActoryyYF' @GlobalActor func testGlobalActor() async { } // CHECK-LABEL: sil private [ossa] @$s4test0A22GlobalActorWithClosureyyYFyyYXEfU_ : $@convention(thin) @async () -> () { // CHECK: [[F:%[0-9]+]] = function_ref @$s4test11GlobalActorV6sharedAA02MyC0Cvau : $@convention(thin) () -> Builtin.RawPointer // CHECK: [[P:%[0-9]+]] = apply [[F]]() : $@convention(thin) () -> Builtin.RawPointer // CHECK: [[A:%[0-9]+]] = pointer_to_address %2 : $Builtin.RawPointer to [strict] $*MyActor // CHECK: [[ACC:%[0-9]+]] = begin_access [read] [dynamic] [[A]] : $*MyActor // CHECK: [[L:%[0-9]+]] = load [copy] [[ACC]] : $*MyActor // CHECK: [[B:%[0-9]+]] = begin_borrow [[L]] : $MyActor // CHECK: hop_to_executor [[B]] : $MyActor // CHECK: } // end sil function '$s4test0A22GlobalActorWithClosureyyYFyyYXEfU_' @GlobalActor func testGlobalActorWithClosure() async { await { () async in }() } @globalActor struct GenericGlobalActorWithGetter<T> { static var shared: MyActor { return MyActor() } } // CHECK-LABEL: sil hidden [ossa] @$s4test0A28GenericGlobalActorWithGetteryyYF : $@convention(thin) @async () -> () { // CHECK: [[MT:%[0-9]+]] = metatype $@thin GenericGlobalActorWithGetter<Int>.Type // CHECK: [[F:%[0-9]+]] = function_ref @$s4test28GenericGlobalActorWithGetterV6sharedAA02MyD0CvgZ : $@convention(method) <τ_0_0> (@thin GenericGlobalActorWithGetter<τ_0_0>.Type) -> @owned MyActor // CHECK: [[A:%[0-9]+]] = apply [[F]]<Int>([[MT]]) : $@convention(method) <τ_0_0> (@thin GenericGlobalActorWithGetter<τ_0_0>.Type) -> @owned MyActor // CHECK: [[B:%[0-9]+]] = begin_borrow [[A]] : $MyActor // CHECK: hop_to_executor [[B]] : $MyActor // CHECK: } // end sil function '$s4test0A28GenericGlobalActorWithGetteryyYF' @GenericGlobalActorWithGetter<Int> func testGenericGlobalActorWithGetter() async { } actor class RedActorImpl { // CHECK-LABEL: sil hidden [ossa] @$s4test12RedActorImplC5helloyySiF : $@convention(method) (Int, @guaranteed RedActorImpl) -> () { // CHECK-NOT: hop_to_executor // CHECK: } // end sil function '$s4test12RedActorImplC5helloyySiF' func hello(_ x : Int) {} } actor class BlueActorImpl { // CHECK-LABEL: sil hidden [ossa] @$s4test13BlueActorImplC4poke6personyAA03RedcD0C_tYF : $@convention(method) @async (@guaranteed RedActorImpl, @guaranteed BlueActorImpl) -> () { // CHECK: bb0([[RED:%[0-9]+]] : @guaranteed $RedActorImpl, [[BLUE:%[0-9]+]] : @guaranteed $BlueActorImpl): // CHECK: hop_to_executor [[BLUE]] : $BlueActorImpl // CHECK-NOT: hop_to_executor // CHECK: [[INTARG:%[0-9]+]] = apply {{%[0-9]+}}({{%[0-9]+}}, {{%[0-9]+}}) : $@convention(method) (Builtin.IntLiteral, @thin Int.Type) -> Int // CHECK-NOT: hop_to_executor // CHECK: [[METH:%[0-9]+]] = class_method [[RED]] : $RedActorImpl, #RedActorImpl.hello : (RedActorImpl) -> (Int) -> (), $@convention(method) (Int, @guaranteed RedActorImpl) -> () // CHECK: hop_to_executor [[RED]] : $RedActorImpl // CHECK-NEXT: {{%[0-9]+}} = apply [[METH]]([[INTARG]], [[RED]]) : $@convention(method) (Int, @guaranteed RedActorImpl) -> () // CHECK-NEXT: hop_to_executor [[BLUE]] : $BlueActorImpl // CHECK-NOT: hop_to_executor // CHECK: } // end sil function '$s4test13BlueActorImplC4poke6personyAA03RedcD0C_tYF' func poke(person red : RedActorImpl) async { await red.hello(42) } // CHECK-LABEL: sil hidden [ossa] @$s4test13BlueActorImplC14createAndGreetyyYF : $@convention(method) @async (@guaranteed BlueActorImpl) -> () { // CHECK: bb0([[BLUE:%[0-9]+]] : @guaranteed $BlueActorImpl): // CHECK: hop_to_executor [[BLUE]] : $BlueActorImpl // CHECK: [[RED:%[0-9]+]] = apply {{%[0-9]+}}({{%[0-9]+}}) : $@convention(method) (@thick RedActorImpl.Type) -> @owned RedActorImpl // CHECK: [[REDBORROW:%[0-9]+]] = begin_borrow [[RED]] : $RedActorImpl // CHECK: [[INTARG:%[0-9]+]] = apply {{%[0-9]+}}({{%[0-9]+}}, {{%[0-9]+}}) : $@convention(method) (Builtin.IntLiteral, @thin Int.Type) -> Int // CHECK: [[METH:%[0-9]+]] = class_method [[REDBORROW]] : $RedActorImpl, #RedActorImpl.hello : (RedActorImpl) -> (Int) -> (), $@convention(method) (Int, @guaranteed RedActorImpl) -> () // CHECK: hop_to_executor [[REDBORROW]] : $RedActorImpl // CHECK-NEXT: = apply [[METH]]([[INTARG]], [[REDBORROW]]) : $@convention(method) (Int, @guaranteed RedActorImpl) -> () // CHECK-NEXT: hop_to_executor [[BLUE]] : $BlueActorImpl // CHECK: end_borrow [[REDBORROW]] : $RedActorImpl // CHECK: destroy_value [[RED]] : $RedActorImpl // CHECK: } // end sil function '$s4test13BlueActorImplC14createAndGreetyyYF' func createAndGreet() async { let red = RedActorImpl() // <- key difference from `poke` is local construction of the actor await red.hello(42) } } @globalActor struct RedActor { static var shared: RedActorImpl { RedActorImpl() } } @globalActor struct BlueActor { static var shared: BlueActorImpl { BlueActorImpl() } } // CHECK-LABEL: sil hidden [ossa] @$s4test5redFnyySiF : $@convention(thin) (Int) -> () { // CHECK-NOT: hop_to_executor // CHECK: } // end sil function '$s4test5redFnyySiF' @RedActor func redFn(_ x : Int) {} // CHECK-LABEL: sil hidden [ossa] @$s4test6blueFnyyYF : $@convention(thin) @async () -> () { // ---- switch to blue actor, since we're an async function ---- // CHECK: [[MT:%[0-9]+]] = metatype $@thin BlueActor.Type // CHECK: [[F:%[0-9]+]] = function_ref @$s4test9BlueActorV6sharedAA0bC4ImplCvgZ : $@convention(method) (@thin BlueActor.Type) -> @owned BlueActorImpl // CHECK: [[B:%[0-9]+]] = apply [[F]]([[MT]]) : $@convention(method) (@thin BlueActor.Type) -> @owned BlueActorImpl // CHECK: [[BLUEEXE:%[0-9]+]] = begin_borrow [[B]] : $BlueActorImpl // CHECK: hop_to_executor [[BLUEEXE]] : $BlueActorImpl // ---- evaluate the argument to redFn ---- // CHECK: [[LIT:%[0-9]+]] = integer_literal $Builtin.IntLiteral, 100 // CHECK: [[INTMT:%[0-9]+]] = metatype $@thin Int.Type // CHECK: [[CTOR:%[0-9]+]] = function_ref @$sSi22_builtinIntegerLiteralSiBI_tcfC : $@convention(method) (Builtin.IntLiteral, @thin Int.Type) -> Int // CHECK: [[ARG:%[0-9]+]] = apply [[CTOR]]([[LIT]], [[INTMT]]) : $@convention(method) (Builtin.IntLiteral, @thin Int.Type) -> Int // ---- prepare to invoke redFn ---- // CHECK: [[CALLEE:%[0-9]+]] = function_ref @$s4test5redFnyySiF : $@convention(thin) (Int) -> () // ---- obtain and hop to RedActor's executor ---- // CHECK: [[REDMT:%[0-9]+]] = metatype $@thin RedActor.Type // CHECK: [[GETTER:%[0-9]+]] = function_ref @$s4test8RedActorV6sharedAA0bC4ImplCvgZ : $@convention(method) (@thin RedActor.Type) -> @owned RedActorImpl // CHECK: [[R:%[0-9]+]] = apply [[GETTER]]([[REDMT]]) : $@convention(method) (@thin RedActor.Type) -> @owned RedActorImpl // CHECK: [[REDEXE:%[0-9]+]] = begin_borrow [[R]] : $RedActorImpl // CHECK: hop_to_executor [[REDEXE]] : $RedActorImpl // ---- now invoke redFn, hop back to Blue, and clean-up ---- // CHECK-NEXT: {{%[0-9]+}} = apply [[CALLEE]]([[ARG]]) : $@convention(thin) (Int) -> () // CHECK-NEXT: hop_to_executor [[BLUEEXE]] : $BlueActorImpl // CHECK: end_borrow [[REDEXE]] : $RedActorImpl // CHECK: destroy_value [[R]] : $RedActorImpl // CHECK: end_borrow [[BLUEEXE]] : $BlueActorImpl // CHECK: destroy_value [[B]] : $BlueActorImpl // CHECK-NOT: hop_to_executor // CHECK: } // end sil function '$s4test6blueFnyyYF' @BlueActor func blueFn() async { await redFn(100) } // CHECK-LABEL: sil hidden [ossa] @$s4test20unspecifiedAsyncFuncyyYF : $@convention(thin) @async () -> () { // CHECK-NOT: hop_to_executor // CHECK: [[BORROW:%[0-9]+]] = begin_borrow {{%[0-9]+}} : $RedActorImpl // CHECK-NEXT: hop_to_executor [[BORROW]] : $RedActorImpl // CHECK-NEXT: {{%[0-9]+}} = apply {{%[0-9]+}}({{%[0-9]+}}) : $@convention(thin) (Int) -> () // CHECK-NEXT: end_borrow [[BORROW]] : $RedActorImpl // CHECK-NOT: hop_to_executor // CHECK: } // end sil function '$s4test20unspecifiedAsyncFuncyyYF' func unspecifiedAsyncFunc() async { await redFn(200) } // CHECK-LABEL: sil hidden [ossa] @$s4test27anotherUnspecifiedAsyncFuncyyAA12RedActorImplCYF : $@convention(thin) @async (@guaranteed RedActorImpl) -> () { // CHECK: bb0([[RED:%[0-9]+]] : @guaranteed $RedActorImpl): // CHECK-NOT: hop_to_executor // CHECK: [[INTARG:%[0-9]+]] = apply {{%[0-9]+}}({{%[0-9]+}}, {{%[0-9]+}}) : $@convention(method) (Builtin.IntLiteral, @thin Int.Type) -> Int // CHECK-NOT: hop_to_executor // CHECK: [[METH:%[0-9]+]] = class_method [[RED]] : $RedActorImpl, #RedActorImpl.hello : (RedActorImpl) -> (Int) -> (), $@convention(method) (Int, @guaranteed RedActorImpl) -> () // CHECK-NEXT: hop_to_executor [[RED]] : $RedActorImpl // CHECK-NEXT: {{%[0-9]+}} = apply [[METH]]([[INTARG]], [[RED]]) : $@convention(method) (Int, @guaranteed RedActorImpl) -> () // CHECK-NOT: hop_to_executor // CHECK: } // end sil function '$s4test27anotherUnspecifiedAsyncFuncyyAA12RedActorImplCYF' func anotherUnspecifiedAsyncFunc(_ red : RedActorImpl) async { await red.hello(12); }
a49d6a85835573897b29fc14fb4b45f0
53.970464
199
0.626008
false
true
false
false
ahmadbaraka/SwiftLayoutConstraints
refs/heads/master
Example/Tests/RhsLayoutConstraintSpec.swift
mit
1
// // RhsLayoutConstraintSpec.swift // SwiftLayoutConstraints // // Created by Ahmad Baraka on 7/22/16. // Copyright © 2016 CocoaPods. All rights reserved. // import Nimble import Quick import SwiftLayoutConstraints class RhsLayoutConstraintSpec: QuickSpec { override func spec() { describe("inits") { var object: NSObject! var constraint: RhsLayoutConstraint<NSObject>! beforeEach { object = NSObject() } it("should init with all values") { let attribute = NSLayoutAttribute.Top constraint = RhsLayoutConstraint(object, attribute: attribute, constant: 10, multiplier: 0.5) expect(constraint.object) == object expect(constraint.attribute) == attribute expect(constraint.constant) == 10 expect(constraint.multiplier) == 0.5 } it("should init with constant") { constraint = RhsLayoutConstraint(constant: 10) expect(constraint.object).to(beNil()) expect(constraint.attribute) == NSLayoutAttribute.NotAnAttribute expect(constraint.constant) == 10 expect(constraint.multiplier) == 1 } it("should init with object and attribute") { let attribute = NSLayoutAttribute.Bottom constraint = RhsLayoutConstraint(object, attribute: attribute) expect(constraint.object) == object expect(constraint.attribute) == attribute expect(constraint.constant) == 0 expect(constraint.multiplier) == 1 } it("should init with object") { constraint = RhsLayoutConstraint(object) expect(constraint.object) == object expect(constraint.attribute) == NSLayoutAttribute.NotAnAttribute expect(constraint.constant) == 0 expect(constraint.multiplier) == 1 } it("should copy values from another constraint with other type") { let object2 = NSURL() let attribute = NSLayoutAttribute.Bottom let org = RhsLayoutConstraint(object2, attribute: attribute) constraint = RhsLayoutConstraint(object, constraint: org) expect(constraint.object) == object expect(constraint.attribute) == attribute expect(constraint.constant) == 0 expect(constraint.multiplier) == 1 } it("should copy values from another constraint") { let attribute = NSLayoutAttribute.Bottom let org = RhsLayoutConstraint(object, attribute: attribute, constant: 10, multiplier: 0.5) constraint = RhsLayoutConstraint(constraint: org) expect(constraint.object) == object expect(constraint.attribute) == attribute expect(constraint.constant) == 10 expect(constraint.multiplier) == 0.5 } it("should copy values from lhs constraint") { let attribute = NSLayoutAttribute.Bottom let org = LhsLayoutConstraint(object, attribute: attribute) constraint = RhsLayoutConstraint(constraint: org) expect(constraint.object) == object expect(constraint.attribute) == attribute expect(constraint.constant) == 0 expect(constraint.multiplier) == 1 } } } }
2fba858d9a350c263f51cf5b2db7afe5
37.90099
109
0.530415
false
false
false
false
hollarab/LearningSwiftWorkshop
refs/heads/master
DaVinciWeekendWorkshop.playground/Pages/Review.xcplaygroundpage/Contents.swift
mit
1
/*: [Previous](@previous) # Review ## Variables and Constants * Constants don't change * Variables can change * Both are *strongly typed* ## Types Swift is a *strongly-typed* language, this means the compiler must know what *type* an variable or constant is. We've been able to skip this, because Swift *implies* the type for you. Code examples were chosen to avoid this problem while some basics were learned. All our examples in Part 1 were one of the four types below. var anIntValue:Int = 1 var aFloatValue:Float = 1.3 var aBool:Bool = true var someWords:String = "a string" So when we wrote `var isReady = true` Swift knew it was really `var isReady:Bool = true`. ## Functions *Functions* are self-contained chunks of code that perform a specific task. You give a function a name that identifies what it does, and this name is used to "call" the function to perform its task when needed. Functions allow us to re-use code and make our code readable. Functions have a *name*, take zero to many *parameters* and have a *return type*. func printHi() -> Void { print("Hi") } printHi() // calls the printHi method. prints "Hi" func add(a:Int, b:Int) -> Int { return a + b; } add(1,2) // calls the add method, passing two parameters. returns 3 func addStrings(strOne:String, strTwo:String) -> String { return strOne + strTwo; } addStrings("Hi ", "there!) // calls addStrings, passing two Strings retuns "Hi there!" ## Casting *Casting* is when you change a type from one to another. function squareAFloat(floatValue:Float) -> Float { return floatValue * floatValue } var intValue:Int = 10 squareAFloat( Float(intValue) ) // cast to a Float to pass to the method ## Conditions, Comparison We use `if`, `if/else`, `if/elseif` statements (and others) to create conditional flows. Comparisons and functions that evaluate to `true` or `false` help. if this > that { // do a thing } else if this == that { // do another thing } else { // worst case } ## Logic && And || Or ! Not == Equals != Not Equals ## Loops, Ranges Support doing sequences of operations. for ii in 0..<10 { // count from 0 to 9 } ---- [Next](@next) on to Optionals */
576e578cc0711c753d060b71204ed542
23.540816
273
0.641164
false
false
false
false
CarlosMChica/swift-dojos
refs/heads/master
MarsRoverKata/MarsRoverKataTest/actions/TurnLeftActionShould.swift
apache-2.0
1
import XCTest class TurnLeftActionShould: XCTestCase { let action = TurnLeftAction() let position = PositionSpy() let invalidCommand = "invalidCommand" func testTurmLeft_whenExecute() throws { let command = givenAnyCommand() try action.execute(command) XCTAssertTrue(position.turnLeftCalled) } func testReturnCanExecuteCommandTrue_whenCommandInputIsValid() { let command = givenValidCommand() let canExecute = action.canExecute(command) XCTAssertTrue(canExecute) } func testReturnCanExecuteCommandFalse_whenCommandInputIsInvalid() { let command = givenInvalidCommand() let canExecute = action.canExecute(command) XCTAssertFalse(canExecute) } func givenAnyCommand() -> Command { return Command(position: position) } func givenValidCommand() -> Command { return Command(input: TurnLeftAction.commandInput, position: position) } func givenInvalidCommand() -> Command { return Command(input: invalidCommand, position: position) } }
4ae62c9a2996720cc3fa4d233719afbd
22.181818
74
0.739216
false
true
false
false
kevin-zqw/play-swift
refs/heads/master
swift-lang/06. Functions.playground/section-1.swift
apache-2.0
1
// ------------------------------------------------------------------------------------------------ // Things to know: // // * Like most other languages, functions contain units of code to perform a task, but there are // a few key featurs of functions in Swift. // // * Functions are types in Swift. This means that a function can receive another function as an // input parameter or return a function as a result. You can even declare variables that are // functions. // // * Functions can be nested, and the inner function can be returned by the outer function. To // enable this, the current state of any local variables (local to the outer function) that are // used by the inner function are "captured" for use by the inner function. Any time that inner // function is called, it uses this captured state. This is the case even when a nested function // is returned by the parent function. // ------------------------------------------------------------------------------------------------ // Here's a simple function that receives a Single string and returns a String // // Note that each parameter has a local name (for use within the function) and a standard type // annotation. The return value's type is at the end of the function, following the ->. func sayHello(personName: String) -> String { return "Hello, \(personName)" } func mySayHello(name: String) -> String { return "Hello, \(name)" } // If we call the function, we'll receive the greeting sayHello("Peter Parker") mySayHello("Kevin Zhang") // Multiple input parameters are separated by a comma func halfOpenRangeLength(start: Int, end: Int) -> Int { return end - start } func addTwoNumbs(a: Int, b: Int) -> Int { return a + b } addTwoNumbs(1, b: 2) // A function with no parameters simply has an empty set of parenthesis following the function // name: func sayHelloWorld() -> String { return "Hello, world" } // A funciton with no return value can be expressed in two different ways. The first is to replace // the return type with a set of empty parenthesis, which can be thought of as an empty Tuple. func sayGoodbye(name: String) -> () { "Goodbye, \(name)" } // We can also remove the return type (and the -> delimiter) alltogether: func sayGoodbyeToMyLittleFriend(name: String) { "Goodbye, \(name)" } // Functions can return Tuples, which enable them to return multiple values. // // The following function simply returns two hard-coded strings. func getApplicationNameAndVersion() -> (appName: String, version: String) { return ("Modaferator", "v1.0") } let nameVersion = getApplicationNameAndVersion() nameVersion.appName nameVersion.version // Since the return value is a Tuple, we can use the Tuple's naming feature to name the values // being returned: func getApplicationInfo() -> (name: String, version: String) { return ("Modaferator", "v1.0") } var appInfo = getApplicationInfo() appInfo.name appInfo.version func safeMinMax(array: [Int]) -> (min:Int, max: Int)? { if array.isEmpty { return nil } return (1, 2) } var aaa = safeMinMax([]) print(aaa.dynamicType) if let (mm, nn) = safeMinMax([]) { print(mm, nn) } // By default, the first parameter omits its external name, and the second and subsequent parameters use their local name as their external name. All parameters must have unique local names. Although it's possible for multiple parameters to have the same external name, unique external names help make your code more readable. func withExternalParameters(first f: String, second s: String, third t: String) { print(f, s, t) } withExternalParameters(first: "1", second: "2", third: "3") // use _ to omit external parameter names, the first parameter is no external name by default func noExternalParameters(f: String, _ s: String, _ t: String) { print(f, s, t) } noExternalParameters("1", "2", "3") // ------------------------------------------------------------------------------------------------ // External Parameter Names // // We can use Objective-C-like external parameter names so the caller must name the external // parameters when they call the function. The extenal name appears before the local name. func addSeventeen(toNumber value: Int) -> Int { return value + 17 } addSeventeen(toNumber: 42) // If your internal and external names are the same, you can use a shorthand #name syntax to create // both names at once. // // The following declaration creates an internal parameter named "action" as well as an external // parameter named "action": func kangaroosCan(action action: String) -> String { return "A Kangaroo can \(action)" } // We can now use the external name ("action") to make the call: kangaroosCan(action: "jump") kangaroosCan(action: "carry children in their pouches") // We can also have default parameter values. Default parameter values must be placed at the end // of the parameter list. // // In the addMul routine, we'll add two numbers and multiply the result by an optional multiplier // value. We will default the multiplier to 1 so that if the parameter is not specified, the // multiplication won't affect the result. func addMul(firstAdder: Int, secondAdder: Int, multiplier: Int = 1) -> Int { return (firstAdder + secondAdder) * multiplier } // We can call with just two parameters to add them together addMul(1, secondAdder: 2) // Default parameter values and external names // // Swift automatically creates external parameter names for those parameters that have default // values. Since our declaration of addMul did not specify an external name (either explicitly or // using the shorthand method), Swift created one for us based on the name of the internal // parameter name. This acts as if we had defined the third parameter using the "#" shorthand. // // Therefore, when calling the function and specifying a value for the defaulted parameter, we // must provide the default parameter's external name: addMul(1, secondAdder: 2, multiplier: 9) // We can opt out of the automatic external name for default parameter values by specify an // external name of "_" like so: func anotherAddMul(firstAdder: Int, secondAdder: Int, _ multiplier: Int = 1) -> Int { return (firstAdder + secondAdder) * multiplier } // Here, we call without the third parameter as before: anotherAddMul(1, secondAdder: 2) // And now we can call with an un-named third parameter: anotherAddMul(1, secondAdder: 2, 9) // ------------------------------------------------------------------------------------------------ // Variadic Parameters // // Variadic parameters allow you to call functions with zero or more values of a specified type. // // Variadic parameters appear within the receiving function as an array of the given type. // // A function may only have at most one variadic and it must appear as the last parameter. func arithmeticMean(numbers: Double...) -> Double { var total = 0.0 // The variadic, numbers, looks like an array to the internal function so we can just loop // through them for number in numbers { total += number } return numbers.count == 0 ? total : total / Double(numbers.count) } // Let's call it with a few parameter lengths. Note that we can call with no parameters, since that // meets the criteria of a variadic parameter (zero or more). arithmeticMean() arithmeticMean(1) arithmeticMean(1, 2) arithmeticMean(1, 2, 3) arithmeticMean(1, 2, 3, 4) arithmeticMean(1, 2, 3, 4, 5) arithmeticMean(1, 2, 3, 4, 5, 6) // If we want to use variadic parameters and default parameter values, we can do so by making sure // that the default parameters come before the variadic, at the end of the parameter list: func anotherArithmeticMean(initialTotal: Double = 0, numbers: Double...) -> Double { var total = initialTotal for number in numbers { total += number } return numbers.count == 0 ? total : total / Double(numbers.count) } // Here, we can still call with no parameters because of the default parameter anotherArithmeticMean() // Going forward, we must specify the default parameter's external name (because we didn't opt-out // of it.) Also, you can see why Swift attempts to enforce the use of external parameter names for // default parameter values. In this case, it helps us recognize where the defalt parameters leave // off and the variadic parameters begin: anotherArithmeticMean(1) anotherArithmeticMean(1, numbers: 2) anotherArithmeticMean(1, numbers: 2, 3) anotherArithmeticMean(1, numbers: 2, 3, 4) anotherArithmeticMean(3, numbers: 4, 5) anotherArithmeticMean(1, numbers: 2, 3, 4, 5, 6) // Variadic parameters with external parameter names only apply their external name to the first // variadic parameter specified in the function call (if present.) func yetAnotherArithmeticMean(initialTotal: Double = 0, values numbers: Double...) -> Double { var total = initialTotal for number in numbers { total += number } return numbers.count == 0 ? total : total / Double(numbers.count) } // And here we can see the impact on the function call of adding the external name "values" to the // variadic parameter: yetAnotherArithmeticMean() yetAnotherArithmeticMean(1) yetAnotherArithmeticMean(1, values: 2) yetAnotherArithmeticMean(1, values: 2, 3) yetAnotherArithmeticMean(1, values: 2, 3, 4) yetAnotherArithmeticMean(1, values: 2, 3, 4, 5) yetAnotherArithmeticMean(1, values: 2, 3, 4, 5, 6) // ------------------------------------------------------------------------------------------------ // Constant and variable parameters // // All function parameters are constant by default. To make them variable, add the var introducer: func padString(var str: String, pad: Character, count: Int) -> String { str = String(count: count, repeatedValue: pad) + str return str } var paddedString = "padded with dots" padString(paddedString, pad: ".", count: 10) // Note that the function does not modify the caller's copy of the string that was passed in // because the value is still passed by value: paddedString func testArrayInOut(inout array: [Int]) { array = [1, 1, 1, 1] } var myArray = [1, 2, 3] testArrayInOut(&myArray) myArray // ------------------------------------------------------------------------------------------------ // In-Out Parameters // // In-Out parameters allow us to force a parameter to be passed by reference so those changes can // persist after the function call. // // Note that inout parameters cannot be variadic or have default parameter values. // // We'll write a standard swap function to exercise this: func swap(inout a: Int, inout b: Int) { let tmp = a a = b b = tmp } // Let's call the swap function to see what happens. // // To ensure that the caller is aware that the parameter is an inout (and hence, can modify their // variable), we must prefix the parameter name with "&". // // Note that the variables that will be passed as references may not be defined as constants, // because it is expected that their values will change: var one = 1, two = 2 swap(&one, &two) // And we can see that 'one' contains a 2 and 'two' contains a 1: one two // ------------------------------------------------------------------------------------------------ // Function types // // The type of a function is comprised of the specific parameter list (the number of parameters as // well as their type) and the return value's type. // // The following two functions have the same type. // // It's important to note that their type is described as: (Int, Int) -> Int func add(a: Int, b: Int) -> Int {return a+b} func mul(a: Int, b: Int) -> Int {return a*b} // A function that has no parameters or return value would have the type: () -> () func nop() -> () { return } // The type of the function below is the same as the one above: () -> () // // It is written in a shorter form, eliminating the return type entirely, but this syntactic // simplification doesn't alter the way that the function's type is notated: func doNothing() { return } // Using what we know about funciton types, we can define variables that are the type of a function let doMul: (Int, Int) -> Int = mul // We can now use the variable to perform the function: doMul(4, 5) // We can also name our parameters when assigning them to a variable, as well as taking advantage // of un-named parameters ("_"). // // This additional syntactic decoration has a purpose, but it doesn't affect the underlying // function type, which remains: (Int, Int) -> Int let doAddMul: (a: Int, b: Int, Int) -> Int = addMul // Calling the function now requires external names for the first two parameters doAddMul(a: 4, b: 2, 55) // We can pass function types as parameters to funcions, too. // // Here, our first parameter named 'doMulFunc' has the type "(Int, Int) -> Int" followed by two // parameters, 'a' and 'b' that are used as parameters to the 'doMulFunc' function: func doDoMul(doMulFunc: (Int, Int) -> Int, a: Int, b: Int) -> Int { return doMulFunc(a, b) } // We can now pass the function (along with a couple parameters to call it with) to another // function: doDoMul(doMul, a: 5, b: 5) typealias MyFunction = () -> Void func ff() -> Void { } let af: MyFunction = ff // We can also return function types. // // The syntax looks a little wird because of the two sets of arrows. To read this, understand that // the first arrow specifies the return type, and the second arrow is simply part of the function // type being returned: func getDoMul() -> (Int, Int) -> Int { return doMul } let newDoMul = getDoMul() newDoMul(9, 5) // Or, an even shorter version that avoids the additional stored value: getDoMul()(5, 5) // Earlier we discussed how functions that do not return values still have a return type that // includes: -> () // // Here, we'll see this in action by returning a function that doesn't return a value: func getNop() -> () -> () { return nop } // And we'll call nop (note the second set of parenthesis to make the actual call to nop()) getNop()() // We can nest functions inside of other functions: func getFive() -> Int { func returnFive() -> Int { return 5 } // Call returnFive() and return the result of that function return returnFive() } // Calling getFive will return the Int value 5: getFive() // You can return nested functions, too: func getReturnFive() -> () -> Int { func returnFive() -> Int { return 5 } return returnFive } // Calling outerFunc2 will return a function capable of returning the Int value 5: let returnFive = getReturnFive() // Here we call the nested function: returnFive() // Nested function
ec7edfa1ff9beab596a5c53114d96649
32.320366
326
0.691642
false
false
false
false
bradleybernard/EjectBar
refs/heads/master
EjectBar/Extensions/NSWindow+.swift
mit
1
// // NSWindow+.swift // EjectBar // // Created by Bradley Bernard on 10/28/20. // Copyright © 2020 Bradley Bernard. All rights reserved. // import Foundation import AppKit extension NSWindow { private static let fadeDuration = 0.35 // Based on the window's: NSWindow.StyleMask // https://developer.apple.com/documentation/appkit/nswindow/stylemask private static let leftRightPadding: CGFloat = 2 private func makeActiveWindow() { makeKeyAndOrderFront(self) NSApp.activate(ignoringOtherApps: true) } func fadeIn(completion: (() -> Void)? = nil) { guard !isMainWindow else { makeActiveWindow() return } guard !isVisible else { makeActiveWindow() completion?() return } alphaValue = 0 makeActiveWindow() NSAnimationContext.runAnimationGroup { [weak self] context in context.duration = Self.fadeDuration self?.animator().alphaValue = 1 } completionHandler: { [weak self] in self?.makeActiveWindow() completion?() } } func fadeOut(completion: (() -> Void)? = nil) { NSAnimationContext.runAnimationGroup { [weak self] context in context.duration = Self.fadeDuration self?.animator().alphaValue = 0 } completionHandler: { [weak self] in guard let self = self else { return } self.contentViewController?.view.window?.orderOut(self) self.alphaValue = 1 completion?() } } func resizeToFitTableView(tableView: NSTableView?) { guard let tableView = tableView else { return } let widthDifference = frame.size.width - tableView.frame.size.width // A window with a tableView has a 1 pixel line on left and 1 pixel line on right, // so we don't want to shrink the window by 2 pixels each time we redraw the tableView. // If the difference in width's is 2, we don't change the frame guard widthDifference != Self.leftRightPadding else { return } var windowFrame = frame windowFrame.size.width = tableView.frame.size.width setFrame(windowFrame, display: true) } }
8e69eb572057d40f67a2fc5897372fce
26.694118
95
0.598131
false
false
false
false
hGhostD/SwiftLearning
refs/heads/master
Swift设计模式/Swift设计模式/17 观察者模式/17.playground/Contents.swift
apache-2.0
1
import Cocoa /*: > 使用观察者模式可以让一个独享在不对另一个对象产生依赖的情况下,注册并接受该对象发出的通知 */ //实现观察者模式 protocol Observer: class { func notify(user: String, success: Bool) } protocol Subject { func addObservers(observers: [Observer]) func removeObserver(oberver: Observer) } class SubjectBase: Subject { private var observers = [Observer]() private var collectionQueue = DispatchQueue(label: "colQ") func addObservers(observers: [Observer]) { collectionQueue.sync(flags: DispatchWorkItemFlags.barrier) { observers.forEach { self.observers.append($0) } } } func removeObserver(oberver: Observer) { collectionQueue.sync(flags: DispatchWorkItemFlags.barrier) { observers = observers.filter {_ in return true } } } func sendNotification(user: String, success: Bool) { collectionQueue.sync { observers.forEach { $0.notify(user: user, success: success) } } } } class ActivityLog: Observer { func logActivity(_ activitity: String) { print("Log: \(activitity)") } func notify(user: String, success: Bool) { print("Auth request for \(user). Success: \(success)") } } class FileCache: Observer { func loadFiles(user: String) { print("Load files for \(user)") } func notify(user: String, success: Bool) { if success { loadFiles(user: user) } } } class AttackMonitor: Observer { var monitorSuspiciousActivity: Bool = false { didSet { print("Monitoring for attack: \(monitorSuspiciousActivity)") } } func notify(user: String, success: Bool) { monitorSuspiciousActivity = !success } } class AuthenticationManager: SubjectBase { func authenticate(user: String, pass: String) -> Bool { var result = false if (user == "bob" && pass == "secret") { result = true print("User \(user) is authenticated") log.logActivity(user) }else { print("Failed authentication attempt") log.logActivity("Failed authentication : \(user)") } sendNotification(user: user, success: result) return result } } let log = ActivityLog() let cache = FileCache() let montitor = AttackMonitor() let authM = AuthenticationManager() authM.addObservers(observers: [log,cache,montitor]) authM.authenticate(user: "bob", pass: "secret") print("--------") authM.authenticate(user: "joe", pass: "shhh")
d4470dbde52c16ed8e20c4a88a6a70d8
23.867925
72
0.596358
false
false
false
false
kickstarter/ios-oss
refs/heads/main
Library/ViewModels/LoadingButtonViewModel.swift
apache-2.0
1
import Prelude import ReactiveSwift public protocol LoadingButtonViewModelInputs { func isLoading(_ isLoading: Bool) } public protocol LoadingButtonViewModelOutputs { var isUserInteractionEnabled: Signal<Bool, Never> { get } var startLoading: Signal<Void, Never> { get } var stopLoading: Signal<Void, Never> { get } } public protocol LoadingButtonViewModelType { var inputs: LoadingButtonViewModelInputs { get } var outputs: LoadingButtonViewModelOutputs { get } } public final class LoadingButtonViewModel: LoadingButtonViewModelType, LoadingButtonViewModelInputs, LoadingButtonViewModelOutputs { public init() { let isLoading = self.isLoadingProperty.signal .skipNil() self.isUserInteractionEnabled = isLoading .negate() self.startLoading = isLoading .filter(isTrue) .ignoreValues() self.stopLoading = isLoading .filter(isFalse) .ignoreValues() } private let isLoadingProperty = MutableProperty<Bool?>(nil) public func isLoading(_ isLoading: Bool) { self.isLoadingProperty.value = isLoading } public let isUserInteractionEnabled: Signal<Bool, Never> public let startLoading: Signal<Void, Never> public let stopLoading: Signal<Void, Never> public var inputs: LoadingButtonViewModelInputs { return self } public var outputs: LoadingButtonViewModelOutputs { return self } }
b586c56ef77f92686cf6132b7f7a52b6
26.54
67
0.75236
false
false
false
false
AlvinL33/TownHunt
refs/heads/master
TownHunt-1.1 (LoginScreen)/TownHunt/VCMapView.swift
apache-2.0
3
// // VCMapView.swift // TownHunt // // Created by iD Student on 7/27/16. // Copyright © 2016 LeeTech. All rights reserved. // import Foundation import MapKit extension ViewController: MKMapViewDelegate{ func mapView(mapView: MKMapView!, viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView! { if let annotation = annotation as? PinLocation { let identifier = "pin" var view: MKPinAnnotationView if let dequeuedView = mapView.dequeueReusableAnnotationViewWithIdentifier(identifier) as? MKPinAnnotationView { // 2 dequeuedView.annotation = annotation view = dequeuedView } else { // 3 view = MKPinAnnotationView(annotation: annotation, reuseIdentifier: identifier) view.canShowCallout = true view.calloutOffset = CGPoint(x: -5, y: 5) } return view } return nil } }
dcc0b3329913180b686d35229203442f
31.193548
105
0.604814
false
false
false
false
Haud/DateTime
refs/heads/master
Carthage/Checkouts/Swinject/Carthage/Checkouts/Nimble/Sources/Nimble/Matchers/MatcherProtocols.swift
apache-2.0
55
import Foundation /// Implement this protocol to implement a custom matcher for Swift public protocol Matcher { typealias ValueType func matches(actualExpression: Expression<ValueType>, failureMessage: FailureMessage) throws -> Bool func doesNotMatch(actualExpression: Expression<ValueType>, failureMessage: FailureMessage) throws -> Bool } #if _runtime(_ObjC) /// Objective-C interface to the Swift variant of Matcher. @objc public protocol NMBMatcher { func matches(actualBlock: () -> NSObject!, failureMessage: FailureMessage, location: SourceLocation) -> Bool func doesNotMatch(actualBlock: () -> NSObject!, failureMessage: FailureMessage, location: SourceLocation) -> Bool } #endif #if _runtime(_ObjC) /// Protocol for types that support contain() matcher. @objc public protocol NMBContainer { func containsObject(object: AnyObject!) -> Bool } extension NSHashTable : NMBContainer {} // Corelibs Foundation does not include this class yet #else public protocol NMBContainer { func containsObject(object: AnyObject) -> Bool } #endif extension NSArray : NMBContainer {} extension NSSet : NMBContainer {} #if _runtime(_ObjC) /// Protocol for types that support only beEmpty(), haveCount() matchers @objc public protocol NMBCollection { var count: Int { get } } extension NSHashTable : NMBCollection {} // Corelibs Foundation does not include these classes yet extension NSMapTable : NMBCollection {} #else public protocol NMBCollection { var count: Int { get } } #endif extension NSSet : NMBCollection {} extension NSDictionary : NMBCollection {} #if _runtime(_ObjC) /// Protocol for types that support beginWith(), endWith(), beEmpty() matchers @objc public protocol NMBOrderedCollection : NMBCollection { func indexOfObject(object: AnyObject!) -> Int } #else public protocol NMBOrderedCollection : NMBCollection { func indexOfObject(object: AnyObject) -> Int } #endif extension NSArray : NMBOrderedCollection {} #if _runtime(_ObjC) /// Protocol for types to support beCloseTo() matcher @objc public protocol NMBDoubleConvertible { var doubleValue: CDouble { get } } #else public protocol NMBDoubleConvertible { var doubleValue: CDouble { get } } extension Double : NMBDoubleConvertible { public var doubleValue: CDouble { get { return self } } } extension Float : NMBDoubleConvertible { public var doubleValue: CDouble { get { return CDouble(self) } } } #endif extension NSNumber : NMBDoubleConvertible { } private let dateFormatter: NSDateFormatter = { let formatter = NSDateFormatter() formatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SSSS" formatter.locale = NSLocale(localeIdentifier: "en_US_POSIX") return formatter }() #if _runtime(_ObjC) extension NSDate: NMBDoubleConvertible { public var doubleValue: CDouble { get { return self.timeIntervalSinceReferenceDate } } } #endif extension NMBDoubleConvertible { public var stringRepresentation: String { get { if let date = self as? NSDate { return dateFormatter.stringFromDate(date) } if let debugStringConvertible = self as? CustomDebugStringConvertible { return debugStringConvertible.debugDescription } if let stringConvertible = self as? CustomStringConvertible { return stringConvertible.description } return "" } } } /// Protocol for types to support beLessThan(), beLessThanOrEqualTo(), /// beGreaterThan(), beGreaterThanOrEqualTo(), and equal() matchers. /// /// Types that conform to Swift's Comparable protocol will work implicitly too #if _runtime(_ObjC) @objc public protocol NMBComparable { func NMB_compare(otherObject: NMBComparable!) -> NSComparisonResult } #else // This should become obsolete once Corelibs Foundation adds Comparable conformance to NSNumber public protocol NMBComparable { func NMB_compare(otherObject: NMBComparable!) -> NSComparisonResult } #endif extension NSNumber : NMBComparable { public func NMB_compare(otherObject: NMBComparable!) -> NSComparisonResult { return compare(otherObject as! NSNumber) } } extension NSString : NMBComparable { public func NMB_compare(otherObject: NMBComparable!) -> NSComparisonResult { return compare(otherObject as! String) } }
219f12a4b21bb60eda2549111db89570
27.585987
117
0.705214
false
false
false
false
SioJL13/tec_ios
refs/heads/master
velocimetro.playground/velocimetro.swift
gpl-2.0
1
//: HW2. Velocimetro para automovil import UIKit enum Velocidades: Int{ case Apagado = 0, VelocidadBaja = 20, VelocidadMedia = 50, VelocidadAlta = 120 init(velocidadInicial: Velocidades){ self = velocidadInicial } } class Auto{ var velocidad = Velocidades(velocidadInicial: .Apagado) init(velocidad: Velocidades){ self.velocidad = velocidad } func cambioDeVelocidad()->(actual: Int, velocidadEnCadena: String){ var actual: Int var velocidadEnCadena: String actual = velocidad.rawValue switch velocidad { case .Apagado: velocidad = Velocidades.VelocidadBaja velocidadEnCadena = "Apagado" case .VelocidadBaja: velocidad = Velocidades.VelocidadMedia velocidadEnCadena = "Velocidad Baja" case .VelocidadMedia: velocidad = Velocidades.VelocidadAlta velocidadEnCadena = "Velocidad Media" case .VelocidadAlta: velocidad = Velocidades.VelocidadMedia velocidadEnCadena = "Velocidad Alta" } return (actual, velocidadEnCadena) } } var auto = Auto(velocidad: .Apagado) for n in 1...20 { var resultado = auto.cambioDeVelocidad() println("\(n): \(resultado.actual), \(resultado.velocidadEnCadena)") }
f0b66fe34dd4ed5e0e309b0e8ca8b0aa
25.056604
82
0.619117
false
false
false
false
GDSys/SwiftXMPP
refs/heads/master
SwiftXMPP/BuddyListViewController.swift
mit
3
// // BuddyListViewController.swift // SwiftXMPP // // Created by Felix Grabowski on 10/06/14. // Copyright (c) 2014 Felix Grabowski. All rights reserved. // import UIKit class BuddyListViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, ChatDelegate { @IBOutlet var tView: UITableView? var onlineBuddies: NSMutableArray = [] // init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { // super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) // // Custom initialization // } override func viewDidLoad() { super.viewDidLoad() tView!.delegate = self tView!.dataSource = self var del = appDelegate() del.chatDelegate = self onlineBuddies = NSMutableArray() // JabberClientAppDelegate *del = [self appDelegate]; // del._chatDelegate = self; // onlineBuddies = [[NSMutableArray alloc ] init]; } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) var login : AnyObject! = NSUserDefaults.standardUserDefaults().objectForKey("userID") if (login != nil) { if appDelegate().connect() { //show buddy list } else { showLogin() } } } func showLogin() { let storyBoard = UIStoryboard(name: "Main", bundle: nil) let loginController : AnyObject! = storyBoard.instantiateViewControllerWithIdentifier("loginViewController") presentViewController(loginController as! UIViewController, animated: true, completion: nil) } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var s: NSString = onlineBuddies.objectAtIndex(indexPath.row) as! NSString let cellIdentifier = "UserCellIdentifier" var cell: UITableViewCell? = tableView.dequeueReusableCellWithIdentifier(cellIdentifier) as? UITableViewCell if !(cell != nil) { cell = UITableViewCell(style: .Default, reuseIdentifier: cellIdentifier) // println("cell : \(cell)") } if let c = cell { c.textLabel!.text = s as String c.accessoryType = .DisclosureIndicator } // cell!.textLabel.text = s // cell!.accessoryType = .DisclosureIndicator return cell!; } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return onlineBuddies.count } func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { println("didSelectRowAtIndexPath") var userName: String? = onlineBuddies.objectAtIndex(indexPath.row) as? String var storyBoard = UIStoryboard(name: "Main", bundle: nil) var chatController: ChatViewController! = storyBoard.instantiateViewControllerWithIdentifier("chatViewController") as! ChatViewController if let controller = chatController { controller.chatWithUser = userName! //presentModalViewController(controller, animated: true) //presentViewController(controller, animated: true, completion: nil) //[self presentViewController: controller animated:YES completion:nil]; } println(chatController) } func newBuddyOnLine(buddyName: String) { onlineBuddies.addObject(buddyName) println("new buddy online: \(buddyName)") tView!.reloadData() } func buddyWentOffline(buddyName: String) { onlineBuddies.removeObject(buddyName) tView!.reloadData() } func appDelegate() -> AppDelegate { return UIApplication.sharedApplication().delegate as! AppDelegate } func xmppStream () -> XMPPStream { return appDelegate().xmppStream! } func didDisconnect() { onlineBuddies.removeAllObjects() tView!.reloadData() } }
ffe60ed620c9c94689adcfbab9acedbf
29.627907
141
0.699747
false
false
false
false
stomp1128/TIY-Assignments
refs/heads/master
CollectEmAll-Sports/CollectEmAll-Sports/PlayerDetailViewController.swift
cc0-1.0
1
// // TeamDetailViewController.swift // CollectEmAll-Sports // // Created by Chris Stomp on 11/6/15. // Copyright © 2015 The Iron Yard. All rights reserved. // import UIKit class PlayerDetailViewController: UIViewController { @IBOutlet weak var name: UILabel! @IBOutlet weak var birthPlace: UILabel! @IBOutlet weak var highSchool: UILabel! @IBOutlet weak var height: UILabel! @IBOutlet weak var weight: UILabel! @IBOutlet weak var position: UILabel! @IBOutlet weak var jerseyNumber: UILabel! @IBOutlet weak var experience: UILabel! var player: Player? override func viewDidLoad() { super.viewDidLoad() name.text = "Name: \(player!.name)" birthPlace.text = "Born: \(player!.birthPlace)" highSchool.text = "High School: \(player!.highSchool)" let heightInFeet = (player!.height)/12 let inches = (player!.height) % 12 let heightString = "\(heightInFeet)\' \(inches)\"" height.text = "Height: \(heightString)" weight.text = "Weight: \(player!.weight) lbs" position.text = "Position: \(player!.position)" jerseyNumber.text = "Number: \(player!.jerseyNumber)" experience.text = "Experience: \(player!.experience)" } 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. } */ }
f3ca2b52f9cc3b3550628871654fbbf0
28
106
0.639009
false
false
false
false
wireapp/wire-ios-sync-engine
refs/heads/develop
Source/Calling/AVS/AVSWrapper+Handlers.swift
gpl-3.0
1
// // Wire // Copyright (C) 2018 Wire Swiss GmbH // // 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/. // import Foundation import avs extension AVSWrapper { enum Handler { typealias StringPtr = UnsafePointer<Int8>? typealias VoidPtr = UnsafeMutableRawPointer? typealias ContextRef = VoidPtr /// Callback used to inform user that call uses CBR (in both directions). /// /// typedef void (wcall_audio_cbr_change_h)(const char *userid, /// const char *clientid, /// int enabled, /// void *arg); typealias ConstantBitRateChange = @convention(c) (StringPtr, StringPtr, Int32, ContextRef) -> Void /// Callback used to inform user that received video has started or stopped. /// /// typedef void (wcall_video_state_change_h)(const char *convid, /// const char *userid, /// const char *clientid, /// int state, /// void *arg); typealias VideoStateChange = @convention(c) (StringPtr, StringPtr, StringPtr, Int32, ContextRef) -> Void /// Callback used to inform the user of an incoming call. /// /// typedef void (wcall_incoming_h)(const char *convid, /// uint32_t msg_time, /// const char *userid, /// const char *clientid, /// int video_call /*bool*/, /// int should_ring /*bool*/, /// int conv_type /*WCALL_CONV_TYPE...*/, /// void *arg); typealias IncomingCall = @convention(c) (StringPtr, UInt32, StringPtr, StringPtr, Int32, Int32, Int32, ContextRef) -> Void /// Callback used to inform the user of a missed call. /// /// typedef void (wcall_missed_h)(const char *convid, /// uint32_t msg_time, /// const char *userid, /// const char *clientid, /// int video_call /*bool*/, /// void *arg); typealias MissedCall = @convention(c) (StringPtr, UInt32, StringPtr, StringPtr, Int32, ContextRef) -> Void /// Callback used to inform user that a 1:1 call was answered. /// /// typedef void (wcall_answered_h)(const char *convid, void *arg); typealias AnsweredCall = @convention(c) (StringPtr, ContextRef) -> Void /// Callback used to inform the user that a data channel was established. /// /// typedef void (wcall_data_chan_estab_h)(const char *convid, /// const char *userid, /// const char *clientid, /// void *arg); typealias DataChannelEstablished = @convention(c) (StringPtr, StringPtr, StringPtr, ContextRef) -> Void /// Callback used to inform the user that a call was established (with media). /// /// typedef void (wcall_estab_h)(const char *convid, /// const char *userid, /// const char *clientid, /// void *arg); typealias CallEstablished = @convention(c) (StringPtr, StringPtr, StringPtr, ContextRef) -> Void /// Callback used to inform the user that a call was terminated. /// /// typedef void (wcall_close_h)(int reason, /// const char *convid, /// uint32_t msg_time, /// const char *userid, /// const char *clientid, /// void *arg); typealias CloseCall = @convention(c) (Int32, StringPtr, UInt32, StringPtr, StringPtr, ContextRef) -> Void /// Callback used to inform the user of call metrics. /// /// typedef void (wcall_metrics_h)(const char *convid, /// const char *metrics_json, /// void *arg); typealias CallMetrics = @convention(c) (StringPtr, StringPtr, ContextRef) -> Void /// Callback used to request a refresh of the call config. /// /// typedef int (wcall_config_req_h)(WUSER_HANDLE wuser, void *arg); typealias CallConfigRefresh = @convention(c) (UInt32, ContextRef) -> Int32 /// Callback used when the calling system is ready for calling. The version parameter specifies the call config /// version to use. /// /// typedef void (wcall_ready_h)(int version, void *arg); typealias CallReady = @convention(c) (Int32, ContextRef) -> Void /// Callback used to send an OTR call message. /// /// The `targets` argument contains a json payload listing the clients for which the message is targeted. /// They payload has the following structure: /// /// ``` /// { /// "clients": [ /// {"userid": "xxxx", "clientid" "xxxx"}, /// {"userid": "xxxx", "clientid" "xxxx"}, /// ... /// ] /// } /// ``` /// /// typedef int (wcall_send_h)(void *ctx, /// const char *convid, /// const char *userid_self, /// const char *clientid_self, /// const char *targets /*optional*/, /// const char *clientid_dest /*deprecated - always null*/, /// const uint8_t *data, /// size_t len, /// int transient /*bool*/, /// void *arg); typealias CallMessageSend = @convention(c) (VoidPtr, StringPtr, StringPtr, StringPtr, StringPtr, StringPtr, UnsafePointer<UInt8>?, Int, Int32, ContextRef) -> Int32 /// Callback used to inform the user when the list of participants in a call changes. /// /// typedef void (wcall_participant_changed_h)(const char *convid, /// const char *mjson, /// void *arg); typealias CallParticipantChange = @convention(c) (StringPtr, StringPtr, ContextRef) -> Void /// Callback used to inform the user that all media has stopped. /// /// typedef void (wcall_media_stopped_h)(const char *convid, void *arg); typealias MediaStoppedChange = @convention(c) (StringPtr, ContextRef) -> Void /// Callback used to inform the user of a change in network quality for a participant. /// /// typedef void (wcall_network_quality_h)(const char *convid, /// const char *userid, /// const char *clientid, /// int quality, /* WCALL_QUALITY_ */ /// int rtt, /* round trip time in ms */ /// int uploss, /* upstream pkt loss % */ /// int downloss, /* dnstream pkt loss % */ /// void *arg); typealias NetworkQualityChange = @convention(c) (StringPtr, StringPtr, StringPtr, Int32, Int32, Int32, Int32, ContextRef) -> Void /// Callback used to inform the user when the mute state changes. /// /// typedef void (wcall_mute_h)(int muted, void *arg); typealias MuteChange = @convention(c) (Int32, ContextRef) -> Void /// Callback used to request a the list of clients in a conversation. /// /// typedef void (wcall_req_clients_h)(WUSER_HANDLE wuser, const char *convid, void *arg); typealias RequestClients = @convention(c) (UInt32, StringPtr, ContextRef) -> Void /// Callback used to request SFT communication. /// /// typedef int (wcall_sft_req_h)(void *ctx, const char *url, const uint8_t *data, size_t len, void *arg); typealias SFTCallMessageSend = @convention(c) (VoidPtr, StringPtr, UnsafePointer<UInt8>?, Int, ContextRef) -> Int32 /// Callback used to inform the user of a change in the list of active speakers /// /// typedef void (wcall_active_speaker_h)(WUSER_HANDLE wuser, const char *convid, const char *json_levels, void *arg); typealias ActiveSpeakersChange = @convention(c) (UInt32, StringPtr, StringPtr, ContextRef) -> Void } }
aa605431c368dddc24b55e464a379819
46.668269
171
0.498336
false
false
false
false
neoneye/SwiftyFORM
refs/heads/master
Source/Cells/PickerViewCell.swift
mit
1
// MIT license. Copyright (c) 2021 SwiftyFORM. All rights reserved. import UIKit struct PickerViewCellConstants { struct CellExpanded { static let height: CGFloat = 216 } } public class PickerViewCellModel { var title: String = "" var expandCollapseWhenSelectingRow = true var selectionStyle = UITableViewCell.SelectionStyle.default var titleFont: UIFont = .preferredFont(forTextStyle: .body) var titleTextColor: UIColor = Colors.text var detailFont: UIFont = .preferredFont(forTextStyle: .body) var detailTextColor: UIColor = Colors.secondaryText var titles = [[String]]() var value = [Int]() var humanReadableValueSeparator: String? var valueDidChange: ([Int]) -> Void = { (selectedRows: [Int]) in SwiftyFormLog("selectedRows \(selectedRows)") } var humanReadableValue: String { var result = [String]() for (component, row) in value.enumerated() { let title = titles[component][row] result.append(title) } return result.joined(separator: humanReadableValueSeparator ?? ",") } } /** # Picker view toggle-cell ### Tap this row to toggle This causes the inline picker view to expand/collapse */ public class PickerViewToggleCell: UITableViewCell, SelectRowDelegate, DontCollapseWhenScrolling, AssignAppearance { weak var expandedCell: PickerViewExpandedCell? public let model: PickerViewCellModel public init(model: PickerViewCellModel) { self.model = model super.init(style: .value1, reuseIdentifier: nil) selectionStyle = model.selectionStyle textLabel?.text = model.title textLabel?.font = model.titleFont detailTextLabel?.font = model.detailFont updateValue() assignDefaultColors() } public required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } public func updateValue() { detailTextLabel?.text = model.humanReadableValue } func setValueWithoutSync(_ value: [Int], animated: Bool) { if value.count != model.titles.count { print("Expected the number of components to be the same") return } SwiftyFormLog("set value \(value), animated \(animated)") model.value = value updateValue() expandedCell?.pickerView.form_selectRows(value, animated: animated) } public func form_cellHeight(_ indexPath: IndexPath, tableView: UITableView) -> CGFloat { 60 } public func form_didSelectRow(indexPath: IndexPath, tableView: UITableView) { if model.expandCollapseWhenSelectingRow == false { //print("cell is always expanded") return } if isExpandedCellVisible { _ = resignFirstResponder() } else { _ = becomeFirstResponder() } form_deselectRow() } // MARK: UIResponder public override var canBecomeFirstResponder: Bool { if model.expandCollapseWhenSelectingRow == false { return false } return true } public override func becomeFirstResponder() -> Bool { if !super.becomeFirstResponder() { return false } expand() return true } public override func resignFirstResponder() -> Bool { collapse() return super.resignFirstResponder() } // MARK: Expand collapse var isExpandedCellVisible: Bool { guard let sectionArray = form_tableView()?.dataSource as? TableViewSectionArray else { return false } guard let expandedItem = sectionArray.findItem(expandedCell) else { return false } if expandedItem.hidden { return false } return true } func toggleExpandCollapse() { guard let tableView = form_tableView() else { return } guard let sectionArray = tableView.dataSource as? TableViewSectionArray else { return } guard let expandedCell = expandedCell else { return } ToggleExpandCollapse.execute( toggleCell: self, expandedCell: expandedCell, tableView: tableView, sectionArray: sectionArray ) } func expand() { if isExpandedCellVisible { assignTintColors() } else { toggleExpandCollapse() } } func collapse() { if isExpandedCellVisible { toggleExpandCollapse() } } // MARK: AssignAppearance public func assignDefaultColors() { textLabel?.textColor = model.titleTextColor detailTextLabel?.textColor = model.detailTextColor } public func assignTintColors() { textLabel?.textColor = tintColor detailTextLabel?.textColor = tintColor } } /** # Picker view expanded-cell Row containing only a `UIPickerView` */ public class PickerViewExpandedCell: UITableViewCell { weak var collapsedCell: PickerViewToggleCell? lazy var pickerView: UIPickerView = { let instance = UIPickerView() instance.dataSource = self instance.delegate = self return instance }() var titles = [[String]]() func configure(_ model: PickerViewCellModel) { titles = model.titles pickerView.reloadAllComponents() pickerView.setNeedsLayout() pickerView.form_selectRows(model.value, animated: false) } public func valueChanged() { guard let collapsedCell = collapsedCell else { return } let model = collapsedCell.model var selectedRows = [Int]() for (component, _) in titles.enumerated() { let row: Int = pickerView.selectedRow(inComponent: component) selectedRows.append(row) } //print("selected rows: \(selectedRows)") model.value = selectedRows collapsedCell.updateValue() model.valueDidChange(selectedRows) } public init() { super.init(style: .default, reuseIdentifier: nil) contentView.addSubview(pickerView) } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } fileprivate var componentWidth: CGFloat = 0 public override func layoutSubviews() { super.layoutSubviews() pickerView.frame = contentView.bounds // Ensures that all UIPickerView components stay within the left/right layoutMargins let rect = pickerView.frame.inset(by: layoutMargins) let numberOfComponents = titles.count if numberOfComponents >= 1 { componentWidth = rect.width / CGFloat(numberOfComponents) } else { componentWidth = rect.width } /* Workaround: UIPickerView gets messed up on orientation change This is a very old problem On iOS9, as of 29 aug 2016, it's still a problem. http://stackoverflow.com/questions/7576679/uipickerview-as-inputview-gets-messed-up-on-orientation-change http://stackoverflow.com/questions/9767234/why-wont-uipickerview-resize-the-first-time-i-change-device-orientation-on-its The following line solves the problem. */ pickerView.setNeedsLayout() } } extension PickerViewExpandedCell: UIPickerViewDataSource { public func numberOfComponents(in pickerView: UIPickerView) -> Int { titles.count } public func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { titles[component].count } } extension PickerViewExpandedCell: UIPickerViewDelegate { public func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { titles[component][row] } public func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { valueChanged() } public func pickerView(_ pickerView: UIPickerView, rowHeightForComponent component: Int) -> CGFloat { 44 } public func pickerView(_ pickerView: UIPickerView, widthForComponent component: Int) -> CGFloat { componentWidth } } extension PickerViewExpandedCell: CellHeightProvider { public func form_cellHeight(indexPath: IndexPath, tableView: UITableView) -> CGFloat { PickerViewCellConstants.CellExpanded.height } } extension PickerViewExpandedCell: WillDisplayCellDelegate { public func form_willDisplay(tableView: UITableView, forRowAtIndexPath indexPath: IndexPath) { if let model = collapsedCell?.model { configure(model) } } } extension PickerViewExpandedCell: ExpandedCell { public var toggleCell: UITableViewCell? { collapsedCell } public var isCollapsable: Bool { collapsedCell?.model.expandCollapseWhenSelectingRow ?? false } } extension UIPickerView { func form_selectRows(_ rows: [Int], animated: Bool) { for (component, row) in rows.enumerated() { selectRow(row, inComponent: component, animated: animated) } } }
169082c80307c0ec4aaf5e1762175e86
24.3625
123
0.737432
false
false
false
false
gaowanli/PinGo
refs/heads/master
PinGo/PinGo/Other/Tool/Urls.swift
mit
1
// // Urls.swift // PinGo // // Created by GaoWanli on 16/1/16. // Copyright © 2016年 GWL. All rights reserved. // import Foundation let kAPI_URL = "http://api.impingo.me" let kAPI_USERID = "userID=1404034" let kAPI_SESSION_ID = "sessionID=e5c8c1b3e8153e78ab" let kAPI_SESSION_TOKEN = "sessionToken=cce76093c4" let kAPI_KEY = "key=B57B690BD66AE7B4C7F17A5E60293B20" let kAPI_PEERID = "peerID=6EDEE890B4E5" let kAPI_PRODUCTID = "productID=com.joyodream.pingo" let kAPI_VERSION = "version=3.7" let kAPI_VERSION_CODE = "versionCode=15" let kAPI_SYSVERSION = "sysVersion=9.2.1" let kAPI_CHANNELID = "channelID=App%20Store" let kAPI_OS = "os=ios" /// 首页精选列表的地址 let kHOME_TOPIC_LIST_URL = kAPI_URL + "/topic/listSelectionBottleTopic" /// 首页关注列表的地址 let kHOME_FOLLOW_TOPIC_LIST_URL = kAPI_URL + "/topic/listOnlineBottleTopic" /// 话题首页banner列表的地址 let kDISCOVER_BANNER_LIST_URL = kAPI_URL + "/banner/listBanner" /// 话题首页推荐列表的地址 let kDISCOVER_SUBJECTINFO_LIST_URL = kAPI_URL + "/subject/listSubjectCategory" /// 获取话题信息的地址 let kGET_SUBJECTINFO_URL = kAPI_URL + "/subject/getSubject" /// 获取话题下Topic的地址 let kGET_LISTSUBJECTTOPIC_URL = kAPI_URL + "/subject/listSubjectTopic" /// 访客记录的地址 let kVISITOR_RECORD_URL = kAPI_URL + "/user/listVisitUser"
80b8d6dd7f88ed1a2a0ee1fb329d860c
40.361111
81
0.617608
false
false
false
false
starrpatty28/MJMusicApp
refs/heads/master
MJMusicApp/MJMusicApp/ThrillerAlbumVC.swift
mit
1
// // ThrillerAlbumVC.swift // MJMusicApp // // Created by Noi-Ariella Baht Israel on 3/22/17. // Copyright © 2017 Plant A Seed of Code. All rights reserved. // import UIKit import AVFoundation class ThrillerAlbumVC: UIViewController { var audioPlayer = AVAudioPlayer() override func viewDidLoad() { super.viewDidLoad() do { audioPlayer = try AVAudioPlayer(contentsOf: URL.init(fileURLWithPath: Bundle.main.path(forResource: "40 Thriller", ofType: "mp3")!)) audioPlayer.prepareToPlay() } catch{ print(error) } } @IBAction func youtubeClkd(_ sender: Any) { openURL(url: "https://www.youtube.com/watch?v=CZqM_PgQ7BM&list=PLDs_1K5H3Lco3c8l0IMj0ZpOARsaDuwj1") } func openURL(url:String!) { if let url = NSURL(string:url) { UIApplication.shared.openURL(url as URL) } } @IBAction func backBtnPressed(_ sender: Any) { dismiss(animated: true, completion: nil) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func playMusic(_ sender: Any) { audioPlayer.play() } }
a944e3bcfe9a193396cd90f2bfd818e1
23.54717
144
0.607225
false
false
false
false
Fenrikur/ef-app_ios
refs/heads/master
EurofurenceTests/Presenter Tests/Schedule/Presenter Tests/WhenSceneChangesSearchScopeToAllEvents_SchedulePresenterShould.swift
mit
1
@testable import Eurofurence import EurofurenceModel import XCTest class WhenSceneChangesSearchScopeToAllEvents_SchedulePresenterShould: XCTestCase { func testTellTheSearchViewModelToFilterToFavourites() { let searchViewModel = CapturingScheduleSearchViewModel() let interactor = FakeScheduleInteractor(searchViewModel: searchViewModel) let context = SchedulePresenterTestBuilder().with(interactor).build() context.simulateSceneDidLoad() context.scene.delegate?.scheduleSceneDidChangeSearchScopeToAllEvents() XCTAssertTrue(searchViewModel.didFilterToAllEvents) } func testTellTheSearchResultsToHide() { let context = SchedulePresenterTestBuilder().build() context.simulateSceneDidLoad() context.scene.delegate?.scheduleSceneDidChangeSearchScopeToAllEvents() XCTAssertTrue(context.scene.didHideSearchResults) } func testNotHideTheSearchResultsWhenQueryActive() { let context = SchedulePresenterTestBuilder().build() context.simulateSceneDidLoad() context.scene.delegate?.scheduleSceneDidUpdateSearchQuery("Something") context.scene.delegate?.scheduleSceneDidChangeSearchScopeToAllEvents() XCTAssertFalse(context.scene.didHideSearchResults) } func testNotTellTheSearchResultsToAppearWhenQueryChangesToEmptyString() { let context = SchedulePresenterTestBuilder().build() context.simulateSceneDidLoad() context.scene.delegate?.scheduleSceneDidChangeSearchScopeToFavouriteEvents() context.scene.delegate?.scheduleSceneDidChangeSearchScopeToAllEvents() context.scene.delegate?.scheduleSceneDidUpdateSearchQuery("") XCTAssertEqual(1, context.scene.didShowSearchResultsCount) } }
3b47f32137b5ee1318949070be18f3d8
39.5
84
0.771044
false
true
false
false
anhnc55/fantastic-swift-library
refs/heads/master
Example/Pods/Material/Sources/iOS/MaterialLayout.swift
mit
2
/* * Copyright (C) 2015 - 2016, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.io>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of Material nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import UIKit public struct MaterialLayout { /// Width public static func width(parent: UIView, child: UIView, width: CGFloat = 0, options: NSLayoutFormatOptions = []) { let metrics: Dictionary<String, AnyObject> = ["width" : width] let views: Dictionary<String, AnyObject> = ["child" : child] parent.addConstraints(constraint("H:[child(width)]", options: options, metrics: metrics, views: views)) } /// Height public static func height(parent: UIView, child: UIView, height: CGFloat = 0, options: NSLayoutFormatOptions = []) { let metrics: Dictionary<String, AnyObject> = ["height" : height] let views: Dictionary<String, AnyObject> = ["child" : child] parent.addConstraints(constraint("V:[child(height)]", options: options, metrics: metrics, views: views)) } /// Size public static func size(parent: UIView, child: UIView, width: CGFloat = 0, height: CGFloat = 0, options: NSLayoutFormatOptions = []) { MaterialLayout.width(parent, child: child, width: width) MaterialLayout.height(parent, child: child, height: height) } /// AlignToParentHorizontally public static func alignToParentHorizontally(parent: UIView, children: Array<UIView>, left: CGFloat = 0, right: CGFloat = 0, spacing: CGFloat = 0, options: NSLayoutFormatOptions = []) { if 0 < children.count { var format: String = "H:|-(left)-" var i: Int = 1 var views: Dictionary<String, UIView> = Dictionary<String, UIView>() for v in children { let k: String = "view\(i)" i += 1 views[k] = v format += i > children.count ? "[\(k)(==view1)]-(right)-|" : "[\(k)(==view1)]-(spacing)-" } parent.addConstraints(constraint(format, options: options, metrics: ["left" : left, "right": right, "spacing": spacing], views: views)) } } /// AlignToParentVertically public static func alignToParentVertically(parent: UIView, children: Array<UIView>, top: CGFloat = 0, bottom: CGFloat = 0, spacing: CGFloat = 0, options: NSLayoutFormatOptions = []) { if 0 < children.count { var format: String = "V:|-(top)-" var i: Int = 1 var views: Dictionary<String, UIView> = Dictionary<String, UIView>() for v in children { let k: String = "view\(i)" i += 1 views[k] = v format += i > children.count ? "[\(k)(==view1)]-(bottom)-|" : "[\(k)(==view1)]-(spacing)-" } parent.addConstraints(constraint(format, options: options, metrics: ["top" : top, "bottom": bottom, "spacing": spacing], views: views)) } } /// AlignToParentHorizontally public static func alignToParentHorizontally(parent: UIView, child: UIView, left: CGFloat = 0, right: CGFloat = 0, options: NSLayoutFormatOptions = []) { parent.addConstraints(constraint("H:|-(left)-[child]-(right)-|", options: options, metrics: ["left": left, "right": right], views: ["child" : child])) } /// AlignToParentVertically public static func alignToParentVertically(parent: UIView, child: UIView, top: CGFloat = 0, bottom: CGFloat = 0, options: NSLayoutFormatOptions = []) { parent.addConstraints(constraint("V:|-(top)-[child]-(bottom)-|", options: options, metrics: ["bottom": bottom, "top": top], views: ["child" : child])) } /// AlignToParent public static func alignToParent(parent: UIView, child: UIView, top: CGFloat = 0, left: CGFloat = 0, bottom: CGFloat = 0, right: CGFloat = 0, options: NSLayoutFormatOptions = []) { alignToParentHorizontally(parent, child: child, left: left, right: right) alignToParentVertically(parent, child: child, top: top, bottom: bottom) } /// AlignFromTopLeft public static func alignFromTopLeft(parent: UIView, child: UIView, top: CGFloat = 0, left: CGFloat = 0, options: NSLayoutFormatOptions = []) { alignFromTop(parent, child: child, top: top) alignFromLeft(parent, child: child, left: left) } /// AlignFromTopRight public static func alignFromTopRight(parent: UIView, child: UIView, top: CGFloat = 0, right: CGFloat = 0, options: NSLayoutFormatOptions = []) { alignFromTop(parent, child: child, top: top) alignFromRight(parent, child: child, right: right) } /// AlignFromBottomLeft public static func alignFromBottomLeft(parent: UIView, child: UIView, bottom: CGFloat = 0, left: CGFloat = 0, options: NSLayoutFormatOptions = []) { alignFromBottom(parent, child: child, bottom: bottom) alignFromLeft(parent, child: child, left: left) } /// AlignFromBottomRight public static func alignFromBottomRight(parent: UIView, child: UIView, bottom: CGFloat = 0, right: CGFloat = 0, options: NSLayoutFormatOptions = []) { alignFromBottom(parent, child: child, bottom: bottom) alignFromRight(parent, child: child, right: right) } /// AlignFromTop public static func alignFromTop(parent: UIView, child: UIView, top: CGFloat = 0, options: NSLayoutFormatOptions = []) { parent.addConstraints(constraint("V:|-(top)-[child]", options: options, metrics: ["top" : top], views: ["child" : child])) } /// AlignFromLeft public static func alignFromLeft(parent: UIView, child: UIView, left: CGFloat = 0, options: NSLayoutFormatOptions = []) { parent.addConstraints(constraint("H:|-(left)-[child]", options: options, metrics: ["left" : left], views: ["child" : child])) } /// AlignFromBottom public static func alignFromBottom(parent: UIView, child: UIView, bottom: CGFloat = 0, options: NSLayoutFormatOptions = []) { parent.addConstraints(constraint("V:[child]-(bottom)-|", options: options, metrics: ["bottom" : bottom], views: ["child" : child])) } /// AlignFromRight public static func alignFromRight(parent: UIView, child: UIView, right: CGFloat = 0, options: NSLayoutFormatOptions = []) { parent.addConstraints(constraint("H:[child]-(right)-|", options: options, metrics: ["right" : right], views: ["child" : child])) } /// Constraint public static func constraint(format: String, options: NSLayoutFormatOptions, metrics: Dictionary<String, AnyObject>?, views: Dictionary<String, AnyObject>) -> Array<NSLayoutConstraint> { for (_, a) in views { if let v: UIView = a as? UIView { v.translatesAutoresizingMaskIntoConstraints = false } } return NSLayoutConstraint.constraintsWithVisualFormat( format, options: options, metrics: metrics, views: views ) } }
efdf99f70c18a22d3e481989681f0dc8
47.575
188
0.711234
false
false
false
false
JGiola/swift
refs/heads/main
test/SILGen/function_conversion_se0110.swift
apache-2.0
9
// RUN: %target-swift-emit-silgen -module-name function_conversion -primary-file %s | %FileCheck %s // Check SILGen against various FunctionConversionExprs emitted by Sema. // SE-0110 allows 'tuple splat' in a few narrow cases. Make sure SILGen supports them. func takesTwo(_: ((Int, Int)) -> ()) {} func givesTwo(_ fn: (Any, Any) -> ()) { takesTwo(fn) } // reabstraction thunk helper from @callee_guaranteed (@in_guaranteed Any, @in_guaranteed Any) -> () to @escaping @callee_guaranteed (@unowned Swift.Int, @unowned Swift.Int) -> () // CHECK-LABEL: sil shared [transparent] [serialized] [reabstraction_thunk] [ossa] @$sypypIgnn_S2iIegyy_TR : $@convention(thin) (Int, Int, @noescape @callee_guaranteed (@in_guaranteed Any, @in_guaranteed Any) -> ()) -> () func takesTwoGeneric<T>(_: (T) -> ()) -> T {} func givesTwoGeneric(_ fn: (Int, Int) -> ()) { _ = takesTwoGeneric(fn) } // reabstraction thunk helper from @callee_guaranteed (@unowned Swift.Int, @unowned Swift.Int) -> () to @escaping @callee_guaranteed (@in_guaranteed (Swift.Int, Swift.Int)) -> () // CHECK-LABEL: sil shared [transparent] [serialized] [reabstraction_thunk] [ossa] @$sS2iIgyy_Si_SitIegn_TR : $@convention(thin) (@in_guaranteed (Int, Int), @noescape @callee_guaranteed (Int, Int) -> ()) -> () // Use a silly trick to bind T := (Int, Int) here func givesTwoGenericAny(_ fn: (Any, Any) -> ()) -> (Int, Int) { return takesTwoGeneric(fn) } func givesNoneGeneric(_ fn: () -> ()) { _ = takesTwoGeneric(fn) } // reabstraction thunk helper from @callee_guaranteed () -> () to @escaping @callee_guaranteed (@in_guaranteed ()) -> () // CHECK-LABEL: sil shared [transparent] [serialized] [reabstraction_thunk] [ossa] @$sIg_ytIegn_TR : $@convention(thin) (@in_guaranteed (), @noescape @callee_guaranteed () -> ()) -> () // "Tuple splat" still works if there are __owned parameters. // Make sure the memory management is correct also. // CHECK-LABEL: sil hidden [ossa] @$s19function_conversion17takesTwoAnyObjectyyyyXl_yXlt_tXEF : $@convention(thin) (@noescape @callee_guaranteed (@guaranteed AnyObject, @guaranteed AnyObject) -> ()) -> () func takesTwoAnyObject(_: ((AnyObject, AnyObject)) -> ()) {} // CHECK-LABEL: sil hidden [ossa] @$s19function_conversion22givesTwoAnyObjectOwnedyyyyXln_yXlntXEF : $@convention(thin) (@noescape @callee_guaranteed (@owned AnyObject, @owned AnyObject) -> ()) -> () func givesTwoAnyObjectOwned(_ fn: (__owned AnyObject, __owned AnyObject) -> ()) { takesTwoAnyObject(fn) } // CHECK-LABEL: sil shared [transparent] [serialized] [reabstraction_thunk] [ossa] @$syXlyXlIgxx_yXlyXlIeggg_TR : $@convention(thin) (@guaranteed AnyObject, @guaranteed AnyObject, @noescape @callee_guaranteed (@owned AnyObject, @owned AnyObject) -> ()) -> () { // CHECK: bb0(%0 : @guaranteed $AnyObject, %1 : @guaranteed $AnyObject, %2 : $@noescape @callee_guaranteed (@owned AnyObject, @owned AnyObject) -> ()): // CHECK-NEXT: [[FIRST:%.*]] = copy_value %0 // CHECK-NEXT: [[SECOND:%.*]] = copy_value %1 // CHECK-NEXT: apply %2([[FIRST]], [[SECOND]]) : $@noescape @callee_guaranteed (@owned AnyObject, @owned AnyObject) -> () // CHECK-NEXT: [[RESULT:%.*]] = tuple () // CHECK-NEXT: return [[RESULT]] : $() // CHECK-NEXT: }
dbd9a88907217133bb8a8e5d0b057809
53.542373
260
0.675264
false
false
false
false
moked/iuob
refs/heads/master
iUOB 2/Controllers/Schedule Builder/ScheduleDetailsVC.swift
mit
1
// // ScheduleDetailsVC.swift // iUOB 2 // // Created by Miqdad Altaitoon on 1/16/17. // Copyright © 2017 Miqdad Altaitoon. All rights reserved. // import UIKit /// details of the option + ability to share class ScheduleDetailsVC: UIViewController { var sections = [Section]() // user choosen sections @IBOutlet weak var detailsTextView: UITextView! var summaryText = "" // MARK: - Life Cycle override func viewDidLoad() { super.viewDidLoad() googleAnalytics() buildSummary() } func googleAnalytics() { if let tracker = GAI.sharedInstance().defaultTracker { tracker.set(kGAIScreenName, value: NSStringFromClass(type(of: self)).components(separatedBy: ".").last!) let builder: NSObject = GAIDictionaryBuilder.createScreenView().build() tracker.send(builder as! [NSObject : AnyObject]) } } func buildSummary() { for section in sections { summaryText += "Course: \(section.note)\nSection #: \(section.sectionNo)\nDoctor: \(section.doctor)\n" if let finalDate = section.finalExam.date { summaryText += "Final Exam: \(finalDate.formattedLong) @\(section.finalExam.startTime)-\(section.finalExam.endTime)\n" } else { summaryText += "Final Exam: No Exam\n" } summaryText += "Time: " for timing in section.timing { summaryText += "\(timing.day) [\(timing.timeFrom)-\(timing.timeTo)] in [\(timing.room)]\n" } summaryText += "-------------------------------\n" } self.detailsTextView.text = summaryText } @IBAction func actionShareButton(_ sender: Any) { // text to share let text = summaryText // set up activity view controller let textToShare = [ text ] let activityViewController = UIActivityViewController(activityItems: textToShare, applicationActivities: nil) activityViewController.popoverPresentationController?.sourceView = self.view // so that iPads won't crash // exclude some activity types from the list (optional) //activityViewController.excludedActivityTypes = [ UIActivityType.airDrop, UIActivityType.postToFacebook ] // present the view controller self.present(activityViewController, animated: true, completion: nil) } @IBAction func doneButton(_ sender: Any) { dismiss(animated: true, completion: nil) } }
cb5f676e0f43458180980663d3c8c52b
29.494382
134
0.582167
false
false
false
false
okkhoury/SafeNights_iOS
refs/heads/master
Pods/JSONHelper/JSONHelper/Extensions/Int.swift
mit
1
// // Copyright © 2016 Baris Sencan. All rights reserved. // import Foundation extension Int: Convertible { public static func convert<T>(fromValue value: T?) throws -> Int? { guard let value = value else { return nil } if let intValue = value as? Int { return intValue } else if let stringValue = value as? String { return Int(stringValue) } else if let floatValue = value as? Float { return Int(floatValue) } else if let doubleValue = value as? Double { return Int(doubleValue) } throw ConversionError.unsupportedType } }
5c9496640baae6fd9b2829dcd2237bc7
23.416667
69
0.66041
false
false
false
false
lyp1992/douyu-Swift
refs/heads/master
YPTV/YPTV/Classes/Tools/YPPageView/YPTitleView.swift
mit
1
// // HYTitleView.swift // HYContentPageView // // Created by xiaomage on 2016/10/27. // Copyright © 2016年 seemygo. All rights reserved. // import UIKit // MARK:- 定义协议 protocol YPTitleViewDelegate : class { func titleView(_ titleView : YPTitleView, selectedIndex index : Int) } class YPTitleView: UIView { // MARK: 对外属性 weak var delegate : YPTitleViewDelegate? // MARK: 定义属性 fileprivate var titles : [String]! fileprivate var style : YPPageStyle! fileprivate var currentIndex : Int = 0 // MARK: 存储属性 fileprivate lazy var titleLabels : [UILabel] = [UILabel]() // MARK: 控件属性 fileprivate lazy var scrollView : UIScrollView = { let scrollV = UIScrollView() scrollV.frame = self.bounds scrollV.showsHorizontalScrollIndicator = false scrollV.scrollsToTop = false return scrollV }() fileprivate lazy var splitLineView : UIView = { let splitView = UIView() splitView.backgroundColor = UIColor.lightGray let h : CGFloat = 0.5 splitView.frame = CGRect(x: 0, y: self.frame.height - h, width: self.frame.width, height: h) return splitView }() fileprivate lazy var bottomLine : UIView = { let bottomLine = UIView() bottomLine.backgroundColor = self.style.bottomLineColor return bottomLine }() fileprivate lazy var coverView : UIView = { let coverView = UIView() coverView.backgroundColor = self.style.coverBgColor coverView.alpha = 0.7 return coverView }() // MARK: 计算属性 fileprivate lazy var normalColorRGB : (r : CGFloat, g : CGFloat, b : CGFloat) = self.getRGBWithColor(self.style.normalColor) fileprivate lazy var selectedColorRGB : (r : CGFloat, g : CGFloat, b : CGFloat) = self.getRGBWithColor(self.style.selectColor) // MARK: 自定义构造函数 init(frame: CGRect, titles : [String], style : YPPageStyle) { super.init(frame: frame) self.titles = titles self.style = style setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } // MARK:- 设置UI界面内容 extension YPTitleView { fileprivate func setupUI() { // 1.添加Scrollview addSubview(scrollView) // 2.添加底部分割线 addSubview(splitLineView) // 3.设置所有的标题Label setupTitleLabels() // 4.设置Label的位置 setupTitleLabelsPosition() // 5.设置底部的滚动条 if style.isBottomLineShow { setupBottomLine() } // 6.设置遮盖的View if style.isShowCoverView { setupCoverView() } } fileprivate func setupTitleLabels() { for (index, title) in titles.enumerated() { let label = UILabel() label.tag = index label.text = title label.textColor = index == 0 ? style.selectColor : style.normalColor label.font = UIFont.systemFont(ofSize: style.fontSize) label.textAlignment = .center label.isUserInteractionEnabled = true let tapGes = UITapGestureRecognizer(target: self, action: #selector(titleLabelClick(_ :))) label.addGestureRecognizer(tapGes) titleLabels.append(label) scrollView.addSubview(label) } } fileprivate func setupTitleLabelsPosition() { var titleX: CGFloat = 0.0 var titleW: CGFloat = 0.0 let titleY: CGFloat = 0.0 let titleH : CGFloat = frame.height let count = titles.count for (index, label) in titleLabels.enumerated() { if style.isScrollEnable { let rect = (label.text! as NSString).boundingRect(with: CGSize(width: CGFloat(MAXFLOAT), height: 0.0), options: .usesLineFragmentOrigin, attributes: [NSAttributedStringKey.font : UIFont.systemFont(ofSize: style.fontSize)], context: nil) titleW = rect.width if index == 0 { titleX = style.titleMargin * 0.5 } else { let preLabel = titleLabels[index - 1] titleX = preLabel.frame.maxX + style.titleMargin } } else { titleW = frame.width / CGFloat(count) titleX = titleW * CGFloat(index) } label.frame = CGRect(x: titleX, y: titleY, width: titleW, height: titleH) // 放大的代码 if index == 0 { let scale = style.isScaleAble ? style.scale : 1.0 label.transform = CGAffineTransform(scaleX: scale, y: scale) } } if style.isScrollEnable { scrollView.contentSize = CGSize(width: titleLabels.last!.frame.maxX + style.titleMargin * 0.5, height: 0) } } fileprivate func setupBottomLine() { scrollView.addSubview(bottomLine) bottomLine.frame = titleLabels.first!.frame bottomLine.frame.size.height = style.bottomLineHeight bottomLine.frame.origin.y = bounds.height - style.bottomLineHeight } fileprivate func setupCoverView() { scrollView.insertSubview(coverView, at: 0) let firstLabel = titleLabels[0] var coverW = firstLabel.frame.width let coverH = style.coverHeight var coverX = firstLabel.frame.origin.x let coverY = (bounds.height - coverH) * 0.5 if style.isScrollEnable { coverX -= style.coverMargin coverW += style.coverMargin * 2 } coverView.frame = CGRect(x: coverX, y: coverY, width: coverW, height: coverH) coverView.layer.cornerRadius = style.coverRadius coverView.layer.masksToBounds = true } } // MARK:- 事件处理 extension YPTitleView { @objc fileprivate func titleLabelClick(_ tap : UITapGestureRecognizer) { // 0.获取当前Label guard let currentLabel = tap.view as? UILabel else { return } // 1.如果是重复点击同一个Title,那么直接返回 if currentLabel.tag == currentIndex { return } // 2.获取之前的Label let oldLabel = titleLabels[currentIndex] // 3.切换文字的颜色 currentLabel.textColor = style.selectColor oldLabel.textColor = style.normalColor // 4.保存最新Label的下标值 currentIndex = currentLabel.tag // 5.通知代理 delegate?.titleView(self, selectedIndex: currentIndex) // 6.居中显示 contentViewDidEndScroll() // 7.调整bottomLine if style.isBottomLineShow { UIView.animate(withDuration: 0.15, animations: { self.bottomLine.frame.origin.x = currentLabel.frame.origin.x self.bottomLine.frame.size.width = currentLabel.frame.size.width }) } // 8.调整比例 if style.isScaleAble { oldLabel.transform = CGAffineTransform.identity currentLabel.transform = CGAffineTransform(scaleX: style.scale, y: style.scale) } // 9.遮盖移动 if style.isShowCoverView { let coverX = style.isScrollEnable ? (currentLabel.frame.origin.x - style.coverMargin) : currentLabel.frame.origin.x let coverW = style.isScrollEnable ? (currentLabel.frame.width + style.coverMargin * 2) : currentLabel.frame.width UIView.animate(withDuration: 0.15, animations: { self.coverView.frame.origin.x = coverX self.coverView.frame.size.width = coverW }) } } } // MARK:- 获取RGB的值 extension YPTitleView { fileprivate func getRGBWithColor(_ color : UIColor) -> (CGFloat, CGFloat, CGFloat) { guard let components = color.cgColor.components else { fatalError("请使用RGB方式给Title赋值颜色") } return (components[0] * 255, components[1] * 255, components[2] * 255) } } // MARK:- 对外暴露的方法 extension YPTitleView { func setTitleWithProgress(_ progress : CGFloat, sourceIndex : Int, targetIndex : Int) { // 1.取出sourceLabel/targetLabel let sourceLabel = titleLabels[sourceIndex] let targetLabel = titleLabels[targetIndex] // 3.颜色的渐变(复杂) // 3.1.取出变化的范围 let colorDelta = (selectedColorRGB.0 - normalColorRGB.0, selectedColorRGB.1 - normalColorRGB.1, selectedColorRGB.2 - normalColorRGB.2) // 3.2.变化sourceLabel sourceLabel.textColor = UIColor(r: selectedColorRGB.0 - colorDelta.0 * progress, g: selectedColorRGB.1 - colorDelta.1 * progress, b: selectedColorRGB.2 - colorDelta.2 * progress) // 3.2.变化targetLabel targetLabel.textColor = UIColor(r: normalColorRGB.0 + colorDelta.0 * progress, g: normalColorRGB.1 + colorDelta.1 * progress, b: normalColorRGB.2 + colorDelta.2 * progress) // 4.记录最新的index currentIndex = targetIndex let moveTotalX = targetLabel.frame.origin.x - sourceLabel.frame.origin.x let moveTotalW = targetLabel.frame.width - sourceLabel.frame.width // 5.计算滚动的范围差值 if style.isBottomLineShow { bottomLine.frame.size.width = sourceLabel.frame.width + moveTotalW * progress bottomLine.frame.origin.x = sourceLabel.frame.origin.x + moveTotalX * progress } // 6.放大的比例 if style.isScaleAble { let scaleDelta = (style.scale - 1.0) * progress sourceLabel.transform = CGAffineTransform(scaleX: style.scale - scaleDelta, y: style.scale - scaleDelta) targetLabel.transform = CGAffineTransform(scaleX: 1.0 + scaleDelta, y: 1.0 + scaleDelta) } // 7.计算cover的滚动 if style.isShowCoverView { coverView.frame.size.width = style.isScrollEnable ? (sourceLabel.frame.width + 2 * style.coverMargin + moveTotalW * progress) : (sourceLabel.frame.width + moveTotalW * progress) coverView.frame.origin.x = style.isScrollEnable ? (sourceLabel.frame.origin.x - style.coverMargin + moveTotalX * progress) : (sourceLabel.frame.origin.x + moveTotalX * progress) } } func contentViewDidEndScroll() { // 0.如果是不需要滚动,则不需要调整中间位置 guard style.isScrollEnable else { return } // 1.获取获取目标的Label let targetLabel = titleLabels[currentIndex] // 2.计算和中间位置的偏移量 var offSetX = targetLabel.center.x - bounds.width * 0.5 if offSetX < 0 { offSetX = 0 } let maxOffset = scrollView.contentSize.width - bounds.width if offSetX > maxOffset { offSetX = maxOffset } // 3.滚动UIScrollView scrollView.setContentOffset(CGPoint(x: offSetX, y: 0), animated: true) } }
587fd91c1578cba420f3dd9e0754cf82
33.523511
252
0.595206
false
false
false
false
iOSWizards/AwesomeMedia
refs/heads/master
Example/Pods/AwesomeCore/AwesomeCore/Classes/ModelParser/CategoryTrainingsMP.swift
mit
1
// // CategoryTrainingsMP.swift // AwesomeCore // // Created by Leonardo Vinicius Kaminski Ferreira on 06/09/17. // import Foundation struct CategoryTrainingsMP { static func parseCategoryTrainingsFrom(_ categoryTrainingsJSON: [String: AnyObject]) -> CategoryTrainings { var subcategoriesArray: [String] = [] if let subcategories = categoryTrainingsJSON["sub_categories"] as? [String] { for subcategory in subcategories { subcategoriesArray.append(subcategory) } } var trainingsArray: [TrainingCard] = [] if let trainings = categoryTrainingsJSON["trainings"] as? [[String: AnyObject]] { for training in trainings { if let train = TrainingCardMP.parseTrainingCardFrom(training) { trainingsArray.append(train) } } } return CategoryTrainings(subcategories: subcategoriesArray, trainings: trainingsArray) } }
dd45202e94b6ad5c274fdcad1a0cfec0
30.176471
111
0.596226
false
false
false
false
MukeshKumarS/Swift
refs/heads/master
stdlib/public/core/StringCore.swift
apache-2.0
1
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// /// The core implementation of a highly-optimizable String that /// can store both ASCII and UTF-16, and can wrap native Swift /// _StringBuffer or NSString instances. /// /// Usage note: when elements are 8 bits wide, this code may /// dereference one past the end of the byte array that it owns, so /// make sure that storage is allocated! You want a null terminator /// anyway, so it shouldn't be a burden. // // Implementation note: We try hard to avoid branches in this code, so // for example we use integer math to avoid switching on the element // size with the ternary operator. This is also the cause of the // extra element requirement for 8 bit elements. See the // implementation of subscript(Int) -> UTF16.CodeUnit below for details. public struct _StringCore { //===--------------------------------------------------------------------===// // Internals public var _baseAddress: COpaquePointer var _countAndFlags: UInt public var _owner: AnyObject? /// (private) create the implementation of a string from its component parts. init( baseAddress: COpaquePointer, _countAndFlags: UInt, owner: AnyObject? ) { self._baseAddress = baseAddress self._countAndFlags = _countAndFlags self._owner = owner _invariantCheck() } func _invariantCheck() { // Note: this code is intentionally #if'ed out. It unconditionally // accesses lazily initialized globals, and thus it is a performance burden // in non-checked builds. #if INTERNAL_CHECKS_ENABLED _sanityCheck(count >= 0) if _baseAddress == nil { #if _runtime(_ObjC) _sanityCheck(hasCocoaBuffer, "Only opaque cocoa strings may have a null base pointer") #endif _sanityCheck(elementWidth == 2, "Opaque cocoa strings should have an elementWidth of 2") } else if _baseAddress == _emptyStringBase { _sanityCheck(!hasCocoaBuffer) _sanityCheck(count == 0, "Empty string storage with non-zero length") _sanityCheck(_owner == nil, "String pointing at empty storage has owner") } else if let buffer = nativeBuffer { _sanityCheck(!hasCocoaBuffer) _sanityCheck(elementWidth == buffer.elementWidth, "_StringCore elementWidth doesn't match its buffer's") _sanityCheck(UnsafeMutablePointer(_baseAddress) >= buffer.start) _sanityCheck(UnsafeMutablePointer(_baseAddress) <= buffer.usedEnd) _sanityCheck(UnsafeMutablePointer(_pointerToNth(count)) <= buffer.usedEnd) } #endif } /// Bitmask for the count part of `_countAndFlags`. var _countMask: UInt { return UInt.max >> 2 } /// Bitmask for the flags part of `_countAndFlags`. var _flagMask: UInt { return ~_countMask } /// Value by which to multiply a 2nd byte fetched in order to /// assemble a UTF-16 code unit from our contiguous storage. If we /// store ASCII, this will be zero. Otherwise, it will be 0x100. var _highByteMultiplier: UTF16.CodeUnit { return UTF16.CodeUnit(elementShift) << 8 } /// Return a pointer to the Nth element of contiguous /// storage. Caveats: The string must have contiguous storage; the /// element may be 1 or 2 bytes wide, depending on elementWidth; the /// result may be null if the string is empty. @warn_unused_result func _pointerToNth(n: Int) -> COpaquePointer { _sanityCheck(hasContiguousStorage && n >= 0 && n <= count) return COpaquePointer( UnsafeMutablePointer<RawByte>(_baseAddress) + (n << elementShift)) } static func _copyElements( srcStart: COpaquePointer, srcElementWidth: Int, dstStart: COpaquePointer, dstElementWidth: Int, count: Int ) { // Copy the old stuff into the new storage if _fastPath(srcElementWidth == dstElementWidth) { // No change in storage width; we can use memcpy _memcpy( dest: UnsafeMutablePointer(dstStart), src: UnsafeMutablePointer(srcStart), size: UInt(count << (srcElementWidth - 1))) } else if (srcElementWidth < dstElementWidth) { // Widening ASCII to UTF-16; we need to copy the bytes manually var dest = UnsafeMutablePointer<UTF16.CodeUnit>(dstStart) var src = UnsafeMutablePointer<UTF8.CodeUnit>(srcStart) let srcEnd = src + count while (src != srcEnd) { dest.memory = UTF16.CodeUnit(src.memory) dest += 1 src += 1 } } else { // Narrowing UTF-16 to ASCII; we need to copy the bytes manually var dest = UnsafeMutablePointer<UTF8.CodeUnit>(dstStart) var src = UnsafeMutablePointer<UTF16.CodeUnit>(srcStart) let srcEnd = src + count while (src != srcEnd) { dest.memory = UTF8.CodeUnit(src.memory) dest += 1 src += 1 } } } //===--------------------------------------------------------------------===// // Initialization public init( baseAddress: COpaquePointer, count: Int, elementShift: Int, hasCocoaBuffer: Bool, owner: AnyObject? ) { _sanityCheck(elementShift == 0 || elementShift == 1) self._baseAddress = baseAddress self._countAndFlags = (UInt(elementShift) << (UInt._sizeInBits - 1)) | ((hasCocoaBuffer ? 1 : 0) << (UInt._sizeInBits - 2)) | UInt(count) self._owner = owner _sanityCheck(UInt(count) & _flagMask == 0, "String too long to represent") _invariantCheck() } /// Create a _StringCore that covers the entire length of the _StringBuffer. init(_ buffer: _StringBuffer) { self = _StringCore( baseAddress: COpaquePointer(buffer.start), count: buffer.usedCount, elementShift: buffer.elementShift, hasCocoaBuffer: false, owner: buffer._anyObject ) } /// Create the implementation of an empty string. /// /// - Note: There is no null terminator in an empty string. public init() { self._baseAddress = _emptyStringBase self._countAndFlags = 0 self._owner = nil _invariantCheck() } //===--------------------------------------------------------------------===// // Properties /// The number of elements stored /// - Complexity: O(1). public var count: Int { get { return Int(_countAndFlags & _countMask) } set(newValue) { _sanityCheck(UInt(newValue) & _flagMask == 0) _countAndFlags = (_countAndFlags & _flagMask) | UInt(newValue) } } /// Left shift amount to apply to an offset N so that when /// added to a UnsafeMutablePointer<RawByte>, it traverses N elements. var elementShift: Int { return Int(_countAndFlags >> (UInt._sizeInBits - 1)) } /// The number of bytes per element. /// /// If the string does not have an ASCII buffer available (including the case /// when we don't have a utf16 buffer) then it equals 2. public var elementWidth: Int { return elementShift &+ 1 } public var hasContiguousStorage: Bool { #if _runtime(_ObjC) return _fastPath(_baseAddress != nil) #else return true #endif } /// Are we using an `NSString` for storage? public var hasCocoaBuffer: Bool { return Int((_countAndFlags << 1)._value) < 0 } public var startASCII: UnsafeMutablePointer<UTF8.CodeUnit> { _sanityCheck(elementWidth == 1, "String does not contain contiguous ASCII") return UnsafeMutablePointer(_baseAddress) } /// True iff a contiguous ASCII buffer available. public var isASCII: Bool { return elementWidth == 1 } public var startUTF16: UnsafeMutablePointer<UTF16.CodeUnit> { _sanityCheck( count == 0 || elementWidth == 2, "String does not contain contiguous UTF-16") return UnsafeMutablePointer(_baseAddress) } /// the native _StringBuffer, if any, or `nil`. public var nativeBuffer: _StringBuffer? { if !hasCocoaBuffer { return _owner.map { unsafeBitCast($0, _StringBuffer.self) } } return nil } #if _runtime(_ObjC) /// the Cocoa String buffer, if any, or `nil`. public var cocoaBuffer: _CocoaStringType? { if hasCocoaBuffer { return _owner.map { unsafeBitCast($0, _CocoaStringType.self) } } return nil } #endif //===--------------------------------------------------------------------===// // slicing /// Returns the given sub-`_StringCore`. public subscript(subRange: Range<Int>) -> _StringCore { _precondition( subRange.startIndex >= 0, "subscript: subRange start precedes String start") _precondition( subRange.endIndex <= count, "subscript: subRange extends past String end") let newCount = subRange.endIndex - subRange.startIndex _sanityCheck(UInt(newCount) & _flagMask == 0) if hasContiguousStorage { return _StringCore( baseAddress: _pointerToNth(subRange.startIndex), _countAndFlags: (_countAndFlags & _flagMask) | UInt(newCount), owner: _owner) } #if _runtime(_ObjC) return _cocoaStringSlice(self, subRange) #else _sanityCheckFailure("subscript: non-native string without objc runtime") #endif } /// Get the Nth UTF-16 Code Unit stored. @warn_unused_result func _nthContiguous(position: Int) -> UTF16.CodeUnit { let p = UnsafeMutablePointer<UInt8>(_pointerToNth(position)._rawValue) // Always dereference two bytes, but when elements are 8 bits we // multiply the high byte by 0. // FIXME(performance): use masking instead of multiplication. return UTF16.CodeUnit(p.memory) + UTF16.CodeUnit((p + 1).memory) * _highByteMultiplier } /// Get the Nth UTF-16 Code Unit stored. public subscript(position: Int) -> UTF16.CodeUnit { _precondition( position >= 0, "subscript: index precedes String start") _precondition( position <= count, "subscript: index points past String end") if _fastPath(_baseAddress != nil) { return _nthContiguous(position) } #if _runtime(_ObjC) return _cocoaStringSubscript(self, position) #else _sanityCheckFailure("subscript: non-native string without objc runtime") #endif } /// Write the string, in the given encoding, to output. func encode< Encoding: UnicodeCodecType >(encoding: Encoding.Type, output: (Encoding.CodeUnit) -> Void) { if _fastPath(_baseAddress != nil) { if _fastPath(elementWidth == 1) { for x in UnsafeBufferPointer( start: UnsafeMutablePointer<UTF8.CodeUnit>(_baseAddress), count: count ) { Encoding.encode(UnicodeScalar(UInt32(x)), output: output) } } else { let hadError = transcode(UTF16.self, encoding, UnsafeBufferPointer( start: UnsafeMutablePointer<UTF16.CodeUnit>(_baseAddress), count: count ).generate(), output, stopOnError: true ) _sanityCheck(!hadError, "Swift.String with native storage should not have unpaired surrogates") } } else if (hasCocoaBuffer) { #if _runtime(_ObjC) _StringCore( _cocoaStringToContiguous(cocoaBuffer!, 0..<count, minimumCapacity: 0) ).encode(encoding, output: output) #else _sanityCheckFailure("encode: non-native string without objc runtime") #endif } } /// Attempt to claim unused capacity in the String's existing /// native buffer, if any. Return zero and a pointer to the claimed /// storage if successful. Otherwise, returns a suggested new /// capacity and a null pointer. /// /// - Note: If successful, effectively appends garbage to the String /// until it has newSize UTF-16 code units; you must immediately copy /// valid UTF-16 into that storage. /// /// - Note: If unsuccessful because of insufficient space in an /// existing buffer, the suggested new capacity will at least double /// the existing buffer's storage. @warn_unused_result mutating func _claimCapacity( newSize: Int, minElementWidth: Int) -> (Int, COpaquePointer) { if _fastPath((nativeBuffer != nil) && elementWidth >= minElementWidth) { var buffer = nativeBuffer! // In order to grow the substring in place, this _StringCore should point // at the substring at the end of a _StringBuffer. Otherwise, some other // String is using parts of the buffer beyond our last byte. let usedStart = _pointerToNth(0) let usedEnd = _pointerToNth(count) // Attempt to claim unused capacity in the buffer if _fastPath( buffer.grow( UnsafePointer(usedStart)..<UnsafePointer(usedEnd), newUsedCount: newSize) ) { count = newSize return (0, usedEnd) } else if newSize > buffer.capacity { // Growth failed because of insufficient storage; double the size return (max(_growArrayCapacity(buffer.capacity), newSize), nil) } } return (newSize, nil) } /// Ensure that this String references a _StringBuffer having /// a capacity of at least newSize elements of at least the given width. /// Effectively appends garbage to the String until it has newSize /// UTF-16 code units. Returns a pointer to the garbage code units; /// you must immediately copy valid data into that storage. @warn_unused_result mutating func _growBuffer( newSize: Int, minElementWidth: Int ) -> COpaquePointer { let (newCapacity, existingStorage) = _claimCapacity(newSize, minElementWidth: minElementWidth) if _fastPath(existingStorage != nil) { return existingStorage } let oldCount = count _copyInPlace( newSize: newSize, newCapacity: newCapacity, minElementWidth: minElementWidth) return _pointerToNth(oldCount) } /// Replace the storage of self with a native _StringBuffer having a /// capacity of at least newCapacity elements of at least the given /// width. Effectively appends garbage to the String until it has /// newSize UTF-16 code units. mutating func _copyInPlace( newSize newSize: Int, newCapacity: Int, minElementWidth: Int ) { _sanityCheck(newCapacity >= newSize) let oldCount = count // Allocate storage. let newElementWidth = minElementWidth >= elementWidth ? minElementWidth : representableAsASCII() ? 1 : 2 let newStorage = _StringBuffer(capacity: newCapacity, initialSize: newSize, elementWidth: newElementWidth) if hasContiguousStorage { _StringCore._copyElements( _baseAddress, srcElementWidth: elementWidth, dstStart: COpaquePointer(newStorage.start), dstElementWidth: newElementWidth, count: oldCount) } else { #if _runtime(_ObjC) // Opaque cocoa buffers might not store ASCII, so assert that // we've allocated for 2-byte elements. // FIXME: can we get Cocoa to tell us quickly that an opaque // string is ASCII? Do we care much about that edge case? _sanityCheck(newStorage.elementShift == 1) _cocoaStringReadAll(cocoaBuffer!, UnsafeMutablePointer(newStorage.start)) #else _sanityCheckFailure("_copyInPlace: non-native string without objc runtime") #endif } self = _StringCore(newStorage) } /// Append `c` to `self`. /// /// - Complexity: O(1) when amortized over repeated appends of equal /// character values. mutating func append(c: UnicodeScalar) { let width = UTF16.width(c) append( width == 2 ? UTF16.leadSurrogate(c) : UTF16.CodeUnit(c.value), width == 2 ? UTF16.trailSurrogate(c) : nil ) } /// Append `u` to `self`. /// /// - Complexity: Amortized O(1). public mutating func append(u: UTF16.CodeUnit) { append(u, nil) } mutating func append(u0: UTF16.CodeUnit, _ u1: UTF16.CodeUnit?) { _invariantCheck() let minBytesPerCodeUnit = u0 <= 0x7f ? 1 : 2 let utf16Width = u1 == nil ? 1 : 2 let destination = _growBuffer( count + utf16Width, minElementWidth: minBytesPerCodeUnit) if _fastPath(elementWidth == 1) { _sanityCheck( _pointerToNth(count) == COpaquePointer(UnsafeMutablePointer<RawByte>(destination) + 1)) UnsafeMutablePointer<UTF8.CodeUnit>(destination)[0] = UTF8.CodeUnit(u0) } else { let destination16 = UnsafeMutablePointer<UTF16.CodeUnit>(destination._rawValue) destination16[0] = u0 if u1 != nil { destination16[1] = u1! } } _invariantCheck() } mutating func append(rhs: _StringCore) { _invariantCheck() let minElementWidth = elementWidth >= rhs.elementWidth ? elementWidth : rhs.representableAsASCII() ? 1 : 2 let destination = _growBuffer( count + rhs.count, minElementWidth: minElementWidth) if _fastPath(rhs.hasContiguousStorage) { _StringCore._copyElements( rhs._baseAddress, srcElementWidth: rhs.elementWidth, dstStart: destination, dstElementWidth:elementWidth, count: rhs.count) } else { #if _runtime(_ObjC) _sanityCheck(elementWidth == 2) _cocoaStringReadAll(rhs.cocoaBuffer!, UnsafeMutablePointer(destination)) #else _sanityCheckFailure("subscript: non-native string without objc runtime") #endif } _invariantCheck() } /// Return true iff the contents of this string can be /// represented as pure ASCII. /// /// - Complexity: O(N) in the worst case. @warn_unused_result func representableAsASCII() -> Bool { if _slowPath(!hasContiguousStorage) { return false } if _fastPath(elementWidth == 1) { return true } let unsafeBuffer = UnsafeBufferPointer( start: UnsafeMutablePointer<UTF16.CodeUnit>(_baseAddress), count: count) return !unsafeBuffer.contains { $0 > 0x7f } } } extension _StringCore : CollectionType { public // @testable var startIndex: Int { return 0 } public // @testable var endIndex: Int { return count } } extension _StringCore : RangeReplaceableCollectionType { /// Replace the given `subRange` of elements with `newElements`. /// /// - Complexity: O(`subRange.count`) if `subRange.endIndex /// == self.endIndex` and `newElements.isEmpty`, O(N) otherwise. public mutating func replaceRange< C: CollectionType where C.Generator.Element == UTF16.CodeUnit >( subRange: Range<Int>, with newElements: C ) { _precondition( subRange.startIndex >= 0, "replaceRange: subRange start precedes String start") _precondition( subRange.endIndex <= count, "replaceRange: subRange extends past String end") let width = elementWidth == 2 || newElements.contains { $0 > 0x7f } ? 2 : 1 let replacementCount = numericCast(newElements.count) as Int let replacedCount = subRange.count let tailCount = count - subRange.endIndex let growth = replacementCount - replacedCount let newCount = count + growth // Successfully claiming capacity only ensures that we can modify // the newly-claimed storage without observably mutating other // strings, i.e., when we're appending. Already-used characters // can only be mutated when we have a unique reference to the // buffer. let appending = subRange.startIndex == endIndex let existingStorage = !hasCocoaBuffer && ( appending || isUniquelyReferencedNonObjC(&_owner) ) ? _claimCapacity(newCount, minElementWidth: width).1 : nil if _fastPath(existingStorage != nil) { let rangeStart = UnsafeMutablePointer<UInt8>( _pointerToNth(subRange.startIndex)) let tailStart = rangeStart + (replacedCount << elementShift) if growth > 0 { (tailStart + (growth << elementShift)).assignBackwardFrom( tailStart, count: tailCount << elementShift) } if _fastPath(elementWidth == 1) { var dst = rangeStart for u in newElements { dst.memory = UInt8(u & 0xFF) dst += 1 } } else { var dst = UnsafeMutablePointer<UTF16.CodeUnit>(rangeStart) for u in newElements { dst.memory = u dst += 1 } } if growth < 0 { (tailStart + (growth << elementShift)).assignFrom( tailStart, count: tailCount << elementShift) } } else { var r = _StringCore( _StringBuffer( capacity: newCount, initialSize: 0, elementWidth: width == 1 ? 1 : representableAsASCII() && !newElements.contains { $0 > 0x7f } ? 1 : 2 )) r.appendContentsOf(self[0..<subRange.startIndex]) r.appendContentsOf(newElements) r.appendContentsOf(self[subRange.endIndex..<count]) self = r } } public mutating func reserveCapacity(n: Int) { if _fastPath(!hasCocoaBuffer) { if _fastPath(isUniquelyReferencedNonObjC(&_owner)) { let subRange: Range<UnsafePointer<RawByte>> = UnsafePointer(_pointerToNth(0))..<UnsafePointer(_pointerToNth(count)) if _fastPath(nativeBuffer!.hasCapacity(n, forSubRange: subRange)) { return } } } _copyInPlace(newSize: count, newCapacity: max(count, n), minElementWidth: 1) } public mutating func appendContentsOf< S : SequenceType where S.Generator.Element == UTF16.CodeUnit >(s: S) { var width = elementWidth if width == 1 { if let hasNonAscii = s._preprocessingPass({ s in s.contains { $0 > 0x7f } }) { width = hasNonAscii ? 2 : 1 } } let growth = s.underestimateCount() var g = s.generate() if _fastPath(growth > 0) { let newSize = count + growth let destination = _growBuffer(newSize, minElementWidth: width) if elementWidth == 1 { let destination8 = UnsafeMutablePointer<UTF8.CodeUnit>(destination) for i in 0..<growth { destination8[i] = UTF8.CodeUnit(g.next()!) } } else { let destination16 = UnsafeMutablePointer<UTF16.CodeUnit>(destination) for i in 0..<growth { destination16[i] = g.next()! } } } // Append any remaining elements for u in GeneratorSequence(g) { self.append(u) } } } // Used to support a tighter invariant: all strings with contiguous // storage have a non-NULL base address. var _emptyStringStorage: UInt32 = 0 var _emptyStringBase: COpaquePointer { return COpaquePointer( UnsafeMutablePointer<UInt16>(Builtin.addressof(&_emptyStringStorage))) }
fdbb855436ecc3cde90ee1475902b145
30.870833
103
0.641783
false
false
false
false
SuperAwesomeLTD/sa-mobile-sdk-ios-demo
refs/heads/master
AwesomeAdsDemo/Events.swift
apache-2.0
1
// // Events.swift // AwesomeAdsDemo // // Created by Gabriel Coman on 29/09/2017. // Copyright © 2017 Gabriel Coman. All rights reserved. // import UIKit import RxSwift import SuperAwesome enum Event { // jwt token + login case LoadingJwtToken case NoJwtToken case JwtTokenError case EditLoginDetails case GotJwtToken(token: String) // profile case GotUserProfile(profile: UserProfile) case UserProfileError // apps & placements case GotAppsForCompany(apps: [App]) case FilterApps(withSearchTerm: String?) case SelectPlacement(placementId: Int?) // companies case LoadingCompanies case GotCompanies(comps: [Company]) case FilterCompanies(withSearchTerm: String?) case SelectCompany(company: Company) // ads case GotAds(ads: [DemoAd]) case FilterAds(withSearchTerm: String?) case SelectAd(ad: DemoAd) // selected ad & response for settings case GotResponse(response: SAResponse?, format: AdFormat) } extension Event { static func checkIsUserLoggedIn () -> Observable<Event> { if let jwtToken = UserDefaults.standard.string(forKey: "jwtToken"), let metadata = UserMetadata.processMetadata(jwtToken: jwtToken), metadata.isValid { return Observable.just(Event.GotJwtToken(token: jwtToken)) } else { return Observable.just(Event.NoJwtToken) } } } extension Event { static func loginUser (withUsername username: String, andPassword password: String) -> Observable<Event> { let operation = NetworkOperation.login(forUsername: username, andPassword: password) let request = NetworkRequest(withOperation: operation) let task = NetworkTask() return task.execute(withInput: request) .flatMap { rawData -> Single<LogedUser> in return ParseTask<LogedUser>().execute(withInput: rawData) } .map { loggedUser -> String? in return loggedUser.token } .asObservable() .do(onNext: { token in if let token = token { UserDefaults.standard.set(token, forKey: "jwtToken") UserDefaults.standard.synchronize() } }) .flatMap{ (token: String?) -> Observable<Event> in guard let token = token else { return Observable.just(Event.JwtTokenError) } return Observable.just(Event.GotJwtToken(token: token)) } .catchError { error -> Observable<Event> in return Observable.just(Event.JwtTokenError) } } } extension Event { static func loadUser (withJwtToken jwtToken: String) -> Observable<Event> { let operation = NetworkOperation.getProfile(forJWTToken: jwtToken) let request = NetworkRequest(withOperation: operation) let task = NetworkTask() return task.execute(withInput: request) .flatMap { rawData -> Single<UserProfile> in return ParseTask<UserProfile>().execute(withInput: rawData) } .asObservable() .flatMap { (profile: UserProfile) -> Observable<Event> in return Observable.just(Event.GotUserProfile(profile: profile)) } .catchError { error -> Observable<Event> in return Observable.just(Event.UserProfileError) } } } extension Event { static func loadApps (forCompany company: Int, andJwtToken token: String) -> Observable<Event> { let operation = NetworkOperation.getApps(forCompany: company, andJWTToken: token) let request = NetworkRequest(withOperation: operation) let task = NetworkTask() return task.execute(withInput: request) .flatMap { rawData -> Single<NetworkData<App>> in return ParseTask<NetworkData<App>>().execute(withInput: rawData) } .asObservable() .flatMap { (data: NetworkData<App>) -> Observable<Event> in return Observable.just(Event.GotAppsForCompany(apps: data.data)) } .catchError { error -> Observable<Event> in return Observable.just(Event.UserProfileError) } } } extension Event { static func loadCompanies (forJwtToken token: String) -> Observable<Event> { let operation = NetworkOperation.getCompanies(forJWTToken: token) let request = NetworkRequest(withOperation: operation) let task = NetworkTask() return task.execute(withInput: request) .flatMap { rawData -> Single<NetworkData<Company>> in let task = ParseTask<NetworkData<Company>>() return task.execute(withInput: rawData) } .map { data -> [Company] in return data.data } .asObservable() .flatMap { (companies: [Company]) -> Observable<Event> in return Observable.just(Event.GotCompanies(comps: companies)) } .catchError { error -> Observable<Event> in return Observable.just(Event.UserProfileError) } } } extension Event { static func loadAds (forPlacementId placementId: Int, andJwtToken token: String, withCompany company: Int?) -> Observable<Event> { guard let company = company else { return Observable.just(Event.GotAds(ads: [])) } let request = LoadAdsRequest(placementId: placementId, token: token, company: company) let task = LoadAdsTask() return task.execute(withInput: request) .toArray() .asObservable() .map({ (ads: [DemoAd]) -> Event in return Event.GotAds(ads: ads) }) .catchError { error -> Observable<Event> in return Observable.just(Event.GotAds(ads: [])) } } } extension Event { static func loadAdResponse (forAd ad: DemoAd?, withPlacementId placementId: Int?) -> Observable<Event> { // return error if not a valid ad somehow guard var ad = ad, let placementId = placementId else { return Observable.just(Event.GotResponse(response: nil, format: AdFormat.unknown)) } ad.placementId = placementId let request = ProcessAdRequest(ad: ad) let task = ProcessAdTask() return task.execute(withInput: request) .flatMap { (response: SAResponse) -> Single<Event> in let format = AdFormat.fromCreative(ad.creative) return Single.just(Event.GotResponse(response: response, format: format)) } .catchError { error -> Single<Event> in return Single.just(Event.GotResponse(response: nil, format: AdFormat.unknown)) } .asObservable() } }
131fd4506335ae9888e452e8c4ae7e0f
34.351485
134
0.595015
false
false
false
false
bananafish911/SmartReceiptsiOS
refs/heads/master
SmartReceipts/ViewControllers/Ad/AdPresentingContainerViewController.swift
agpl-3.0
1
// // AdPresentingContainerViewController.swift // SmartReceipts // // Created by Bogdan Evsenev on 04/06/2017. // Copyright © 2017 Will Baumann. All rights reserved. // import GoogleMobileAds import Viperit fileprivate let BANNER_HEIGHT: CGFloat = 80 class AdPresentingContainerViewController: UIViewController { @IBOutlet fileprivate var adContainerHeight: NSLayoutConstraint? @IBOutlet fileprivate var nativeExpressAdView: GADNativeExpressAdView? @IBOutlet var container: UIView! override func viewDidLoad() { super.viewDidLoad() adContainerHeight?.constant = 0 nativeExpressAdView?.rootViewController = self nativeExpressAdView?.adUnitID = AD_UNIT_ID nativeExpressAdView?.delegate = self DispatchQueue.main.async { self.loadAd() } NotificationCenter.default.addObserver(self, selector: #selector(loadAd), name: NSNotification.Name.SmartReceiptsAdsRemoved, object: nil) } @objc private func loadAd() { if !Database.sharedInstance().hasValidSubscription() { let request = GADRequest() request.testDevices = [kGADSimulatorID, "b5c0a5fccf83835150ed1fac6dd636e6"] nativeExpressAdView?.adSize = getAdSize() nativeExpressAdView?.load(request) } } fileprivate func getAdSize() -> GADAdSize { let adSize = CGSize(width: view.bounds.width, height: BANNER_HEIGHT) return GADAdSizeFromCGSize(adSize) } private func checkAdsStatus() { if Database.sharedInstance().hasValidSubscription() { Logger.debug("Remove ads") UIView.animate(withDuration: 0.3, animations: { self.adContainerHeight?.constant = 0 self.view.layoutSubviews() }) nativeExpressAdView = nil } } deinit { NotificationCenter.default.removeObserver(self) } } extension AdPresentingContainerViewController: GADNativeExpressAdViewDelegate { func nativeExpressAdViewDidReceiveAd(_ nativeExpressAdView: GADNativeExpressAdView) { UIView.animate(withDuration: 0.3, animations: { self.adContainerHeight?.constant = BANNER_HEIGHT self.view.layoutSubviews() }) } func nativeExpressAdView(_ nativeExpressAdView: GADNativeExpressAdView, didFailToReceiveAdWithError error: GADRequestError) { UIView.animate(withDuration: 0.3, animations: { self.adContainerHeight?.constant = 0 self.view.layoutSubviews() }) { _ in nativeExpressAdView.adSize = self.getAdSize() } } } class AdNavigationEntryPoint: UINavigationController { override func viewDidLoad() { let module = Module.build(AppModules.trips) show(module.view, sender: nil) } }
3b8ca021cfe049f883b813d46adcf059
31.208791
129
0.654043
false
false
false
false
NobodyNada/SwiftStack
refs/heads/master
Sources/SwiftStack/Post.swift
mit
1
// // Post.swift // SwiftStack // // Created by FelixSFD on 06.12.16. // // import Foundation // - MARK: The type of the post /** Defines the type of a post. Either a question or an answer - author: FelixSFD */ public enum PostType: String, StringRepresentable { case answer = "answer" case question = "question" } // - MARK: Post /** The base class of `Question`s and `Answer`s - author: FelixSFD - seealso: [StackExchange API](https://api.stackexchange.com/docs/types/post) */ public class Post: Content { // - MARK: Post.Notice /** Represents a notice on a post. - author: FelixSFD */ public struct Notice: JsonConvertible { public init?(jsonString json: String) { do { guard let dictionary = try JSONSerialization.jsonObject(with: json.data(using: String.Encoding.utf8)!, options: .allowFragments) as? [String: Any] else { return nil } self.init(dictionary: dictionary) } catch { return nil } } public init(dictionary: [String: Any]) { self.body = dictionary["body"] as? String if let timestamp = dictionary["creation_date"] as? Int { self.creation_date = Date(timeIntervalSince1970: Double(timestamp)) } self.owner_user_id = dictionary["owner_user_id"] as? Int } public var dictionary: [String: Any] { var dict = [String: Any]() dict["body"] = body dict["creation_date"] = creation_date dict["owner_user_id"] = owner_user_id return dict } public var jsonString: String? { return (try? JsonHelper.jsonString(from: self)) ?? nil } public var body: String? public var creation_date: Date? public var owner_user_id: Int? } // - MARK: Initializers /** Basic initializer without default values */ public override init() { super.init() } /** Initializes the object from a JSON string. - parameter json: The JSON string returned by the API - author: FelixSFD */ public required convenience init?(jsonString json: String) { do { guard let dictionary = try JSONSerialization.jsonObject(with: json.data(using: String.Encoding.utf8)!, options: .allowFragments) as? [String: Any] else { return nil } self.init(dictionary: dictionary) } catch { return nil } } public required init(dictionary: [String: Any]) { super.init(dictionary: dictionary) //only initialize the properties that are not part of the superclass self.comment_count = dictionary["comment_count"] as? Int if let commentsArray = dictionary["comments"] as? [[String: Any]] { var commentsTmp = [Comment]() for commentDictionary in commentsArray { let commentTmp = Comment(dictionary: commentDictionary) commentsTmp.append(commentTmp) } } self.down_vote_count = dictionary["down_vote_count"] as? Int self.downvoted = dictionary["downvoted"] as? Bool if let timestamp = dictionary["creation_date"] as? Int { self.creation_date = Date(timeIntervalSince1970: Double(timestamp)) } if let timestamp = dictionary["last_activity_date"] as? Int { self.last_activity_date = Date(timeIntervalSince1970: Double(timestamp)) } if let timestamp = dictionary["last_edit_date"] as? Int { self.last_edit_date = Date(timeIntervalSince1970: Double(timestamp)) } if let user = dictionary["last_editor"] as? [String: Any] { self.last_editor = User(dictionary: user) } if let urlString = dictionary["share_link"] as? String { self.share_link = URL(string: urlString) } self.title = (dictionary["title"] as? String)?.stringByDecodingHTMLEntities self.up_vote_count = dictionary["up_vote_count"] as? Int } // - MARK: JsonConvertible public override var dictionary: [String: Any] { var dict = super.dictionary dict["creation_date"] = creation_date dict["comment_count"] = comment_count if comments != nil && (comments?.count)! > 0 { var tmpComments = [[String: Any]]() for comment in comments! { tmpComments.append(comment.dictionary) } dict["comments"] = tmpComments } dict["down_vote_count"] = down_vote_count dict["downvoted"] = downvoted dict["last_activity_date"] = last_activity_date dict["last_edit_date"] = last_edit_date dict["last_editor"] = last_editor?.dictionary dict["share_link"] = share_link dict["title"] = title dict["up_vote_count"] = up_vote_count return dict } // - MARK: Fields public var creation_date: Date? public var comment_count: Int? public var comments: [Comment]? public var down_vote_count: Int? public var downvoted: Bool? public var last_activity_date: Date? public var last_edit_date: Date? public var last_editor: User? public var share_link: URL? public var title: String? public var up_vote_count: Int? }
8920704b374567708dcc689d2707399a
26.75
169
0.54479
false
false
false
false
dsantosp12/DResume
refs/heads/master
Sources/App/Controllers/UserController.swift
mit
1
import Vapor import FluentProvider class UserController { func addRoutes(to drop: Droplet) { let userGroup = drop.grouped("api", "v1", "user") // Post userGroup.post(handler: createUser) userGroup.post(User.parameter, "skills", handler: addSkill) userGroup.post(User.parameter, "languages", handler: addLanguage) userGroup.post(User.parameter, "educations", handler: addEducation) userGroup.post(User.parameter, "attachments", handler: addAttachment) // Get userGroup.get(User.parameter, handler: getUser) userGroup.get(User.parameter, "skills", handler: getUserSkills) userGroup.get(User.parameter, "languages", handler: getLanguages) userGroup.get(User.parameter, "educations", handler: getEducation) userGroup.get(User.parameter, "attachments", handler: getAttachment) // Delete userGroup.delete(User.parameter, handler: removeUser) userGroup.delete("skill", Skill.parameter, handler: removeSkill) userGroup.delete("language", Language.parameter, handler: removeLanguage) userGroup.delete("education", Education.parameter, handler: removeEducation) userGroup.delete("attachment", Attachment.parameter, handler: removeAttachment) // Put userGroup.put(User.parameter, handler: updateUser) userGroup.put("skill", Skill.parameter, handler: updateSkill) userGroup.put("language", Language.parameter, handler: updateLanguage) userGroup.put("education", Education.parameter, handler: updateEducation) } // MARK: POSTERS func createUser(_ req: Request) throws -> ResponseRepresentable { guard let json = req.json else { throw Abort.badRequest } let user = try User(json: json) try user.save() return user } func addSkill(_ req: Request) throws -> ResponseRepresentable { guard let json = req.json else { throw Abort.badRequest } let skill = try Skill(json: json) try skill.save() return skill } func addLanguage(_ req: Request) throws -> ResponseRepresentable { let user = try req.parameters.next(User.self) guard var json = req.json else { throw Abort.badRequest } try json.set(Language.userIDKey, user.id) let language = try Language(json: json) try language.save() return language } func addEducation(_ req: Request) throws -> ResponseRepresentable { guard let json = req.json else { throw Abort.badRequest } let education = try Education(json: json) try education.save() return education } func addAttachment(_ req: Request) throws -> ResponseRepresentable { guard let json = req.json else { throw Abort.badRequest } let attachment = try Attachment(json: json) try attachment.save() return attachment } // MARK: GETTERS func getUser(_ req: Request) throws -> ResponseRepresentable { let user = try req.parameters.next(User.self) return user } func getUserSkills(_ req: Request) throws -> ResponseRepresentable { let user = try req.parameters.next(User.self) return try user.skills.all().makeJSON() } func getLanguages(_ req: Request) throws -> ResponseRepresentable { let user = try req.parameters.next(User.self) return try user.languages.all().makeJSON() } func getEducation(_ req: Request) throws -> ResponseRepresentable { let user = try req.parameters.next(User.self) return try user.educations.all().makeJSON() } func getAttachment(_ req: Request) throws -> ResponseRepresentable { let user = try req.parameters.next(User.self) return try user.attachments.all().makeJSON() } // MARK: DELETERS func removeUser(_ req: Request) throws -> ResponseRepresentable { let user = try req.parameters.next(User.self) try user.delete() return Response(status: .ok) } func removeSkill(_ req: Request) throws -> ResponseRepresentable { let skill = try req.parameters.next(Skill.self) try skill.delete() return Response(status: .ok) } func removeLanguage(_ req: Request) throws -> ResponseRepresentable { let language = try req.parameters.next(Language.self) try language.delete() return Response(status: .ok) } func removeEducation(_ req: Request) throws -> ResponseRepresentable { let education = try req.parameters.next(Education.self) try education.delete() return Response(status: .ok) } func removeAttachment(_ req: Request) throws -> ResponseRepresentable { let attachment = try req.parameters.next(Attachment.self) try attachment.delete() return Response(status: .ok) } // MARK: PUTTERS func updateUser(_ req: Request) throws -> ResponseRepresentable { let user = try req.parameters.next(User.self) guard let json = req.json else { throw Abort.badRequest } try user.update(with: json) return user } func updateSkill(_ req: Request) throws -> ResponseRepresentable { let skill = try req.parameters.next(Skill.self) guard let json = req.json else { throw Abort.badRequest } try skill.update(with: json) return skill } func updateLanguage(_ req: Request) throws -> ResponseRepresentable { let language = try req.parameters.next(Language.self) guard let json = req.json else { throw Abort.badRequest } try language.update(with: json) return language } func updateEducation(_ req: Request) throws -> ResponseRepresentable { let education = try req.parameters.next(Education.self) guard let json = req.json else { throw Abort.badRequest } try education.update(with: json) return education } }
a47160bb4e41f13c986ed44b2691714f
24.033898
80
0.663846
false
false
false
false
githubError/KaraNotes
refs/heads/master
KaraNotes/KaraNotes/Attention/Controller/CPFAttentionController.swift
apache-2.0
1
// // CPFAttentionController.swift // KaraNotes // // Created by 崔鹏飞 on 2017/2/15. // Copyright © 2017年 崔鹏飞. All rights reserved. // import UIKit import Alamofire class CPFAttentionController: BaseViewController { fileprivate var collectionView: UICollectionView? fileprivate let flowLayout = UICollectionViewFlowLayout() fileprivate let modalTransitioningDelegate = CPFModalTransitioningDelegate() fileprivate let cellID = "AttentionCell" fileprivate var pageNum:Int = 0 fileprivate var attentionArticleModels: [AttentionArticleModel] = [] override func viewDidLoad() { super.viewDidLoad() setupSubviews() } } // MARK: - setup extension CPFAttentionController { func setupSubviews() -> Void { setupNavigation() // init collectionView setupCollectionView() } func setupNavigation() -> Void { let searchBtn = UIButton(type: .custom) searchBtn.setImage(UIImage.init(named: "search"), for: .normal) searchBtn.frame = CGRect(x: 0, y: 0, width: 20, height: 20) searchBtn.addTarget(self, action: #selector(searchBtnClick), for: .touchUpInside) navigationItem.rightBarButtonItem = UIBarButtonItem(customView: searchBtn) } func setupCollectionView() -> Void { flowLayout.scrollDirection = .vertical flowLayout.itemSize = CGSize(width: self.view.width, height: 250*CPFFitHeight) flowLayout.minimumLineSpacing = 0 collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: flowLayout) if let collectionView = collectionView { view.addSubview(collectionView) collectionView.snp.makeConstraints { make in make.top.left.right.bottom.equalTo(view) } collectionView.backgroundColor = CPFGlobalColor collectionView.register(CPFAttentionCell.self, forCellWithReuseIdentifier: cellID) collectionView.contentInset = UIEdgeInsets(top: 10, left: 0, bottom: 0, right: 0) collectionView.delegate = self collectionView.dataSource = self let refreshHeader = MJRefreshNormalHeader(refreshingTarget: self, refreshingAction: #selector(loadNewDatas)) collectionView.mj_header = refreshHeader collectionView.mj_header.beginRefreshing() collectionView.mj_header.isAutomaticallyChangeAlpha = true let refreshFooter = MJRefreshBackNormalFooter(refreshingTarget: self, refreshingAction: #selector(loadMoreDatas)) refreshFooter?.setTitle("没有更多啦", for: .noMoreData) collectionView.mj_footer = refreshFooter collectionView.mj_footer.isAutomaticallyChangeAlpha = true } } } // MARK: - custom methods extension CPFAttentionController { @objc fileprivate func searchBtnClick() -> Void { let searchCtr = CPFSearchController() navigationController?.pushViewController(searchCtr, animated: true) } } // MARK: - Refresh extension CPFAttentionController { func loadNewDatas() -> Void { print("下拉加载更多") pageNum = 0 let params = ["token_id": getUserInfoForKey(key: CPFUserToken), "pagenum": String(pageNum), "pagesize": "10"] as [String : Any] Alamofire.request(CPFNetworkRoute.getAPIFromRouteType(route: .followArticleList), method: .post, parameters: params, encoding: JSONEncoding.default, headers: [:]).responseJSON { (response) in switch response.result { case .success(let json as JSONDictionary): guard let code = json["code"] as? String else {fatalError()} if code == "1" { guard let results = json["result"] as? [JSONDictionary] else {fatalError("Json 解析失败")} self.attentionArticleModels = results.map({ (json) -> AttentionArticleModel in return AttentionArticleModel.parse(json: json) }) self.collectionView?.reloadData() } else { print("--解析错误--") } case .failure(let error): print("--------\(error.localizedDescription)") default: print("unknow type error") } } self.collectionView?.mj_header.endRefreshing() } func loadMoreDatas() -> Void { pageNum += 1 let params = ["token_id": getUserInfoForKey(key: CPFUserToken), "pagenum": String(pageNum), "pagesize": "10"] as [String : Any] Alamofire.request(CPFNetworkRoute.getAPIFromRouteType(route: .followArticleList), method: .post, parameters: params, encoding: JSONEncoding.default, headers: [:]).responseJSON { (response) in switch response.result { case .success(let json as JSONDictionary): guard let code = json["code"] as? String else {fatalError()} if code == "1" { guard let results = json["result"] as? [JSONDictionary] else {fatalError("Json 解析失败")} let moreModels = results.map({ (json) -> AttentionArticleModel in return AttentionArticleModel.parse(json: json) }) self.attentionArticleModels.append(contentsOf: moreModels) self.collectionView?.reloadData() } else { print("--解析错误--") } case .failure(let error): self.pageNum -= 1 print("--------\(error.localizedDescription)") default: self.pageNum -= 1 print("unknow type error") } } collectionView?.mj_footer.endRefreshingWithNoMoreData() } } extension CPFAttentionController: UICollectionViewDelegate, UICollectionViewDataSource { // DataSource func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return attentionArticleModels.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let attentionCell = collectionView.dequeueReusableCell(withReuseIdentifier: cellID, for: indexPath) as! CPFAttentionCell attentionCell.attentionArticleModel = attentionArticleModels[indexPath.row] if traitCollection.forceTouchCapability == .available { registerForPreviewing(with: self, sourceView: attentionCell) } return attentionCell } // delegate func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let attentModel = attentionArticleModels[indexPath.row] // 相对 keyWindow 的位置 let currentCellItem = collectionView.cellForItem(at: indexPath) as! CPFAttentionCell let keyWindow = UIApplication.shared.keyWindow let currentCellItemRectInSuperView = currentCellItem.superview?.convert(currentCellItem.frame, to: keyWindow) modalTransitioningDelegate.startRect = CGRect(x: 0.0, y: (currentCellItemRectInSuperView?.origin.y)!, width: CPFScreenW, height: currentCellItem.height) let browseArticleVC = CPFBrowseArticleController() browseArticleVC.thumbImage = currentCellItem.thumbImage browseArticleVC.articleTitle = attentModel.article_title browseArticleVC.articleCreateTime = attentModel.article_create_formatTime browseArticleVC.articleAuthorName = getUserInfoForKey(key: CPFUserName) browseArticleVC.articleID = attentModel.article_id browseArticleVC.isMyArticle = false browseArticleVC.transitioningDelegate = modalTransitioningDelegate browseArticleVC.modalPresentationStyle = .custom present(browseArticleVC, animated: true, completion: nil) } } // MARK: - 3D Touch extension CPFAttentionController: UIViewControllerPreviewingDelegate { func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? { let currentCell = previewingContext.sourceView as! CPFAttentionCell let currentIndexPath = collectionView?.indexPath(for: currentCell) let attentModel = attentionArticleModels[(currentIndexPath?.row)!] let keyWindow = UIApplication.shared.keyWindow let currentCellItemRectInSuperView = currentCell.superview?.convert(currentCell.frame, to: keyWindow) modalTransitioningDelegate.startRect = CGRect(x: 0.0, y: (currentCellItemRectInSuperView?.origin.y)!, width: CPFScreenW, height: currentCell.height) let browseArticleVC = CPFBrowseArticleController() browseArticleVC.thumbImage = currentCell.thumbImage browseArticleVC.articleTitle = attentModel.article_title browseArticleVC.articleCreateTime = attentModel.article_create_formatTime browseArticleVC.articleAuthorName = getUserInfoForKey(key: CPFUserName) browseArticleVC.articleID = attentModel.article_id browseArticleVC.isMyArticle = false browseArticleVC.transitioningDelegate = modalTransitioningDelegate browseArticleVC.modalPresentationStyle = .custom browseArticleVC.is3DTouchPreviewing = true return browseArticleVC } func previewingContext(_ previewingContext: UIViewControllerPreviewing, commit viewControllerToCommit: UIViewController) { present(viewControllerToCommit, animated: true, completion: nil) } }
6c0b6ceaf21553993d46419b60ae49e1
39.829268
199
0.643469
false
false
false
false
dclelland/AudioKit
refs/heads/master
AudioKit/Common/Instruments/AKDrumSynths.swift
mit
1
// // DrumSynths.swift // AudioKit // // Created by Jeff Cooper, revision history on Github. // Copyright © 2016 AudioKit. All rights reserved. // import Foundation import AVFoundation /// Kick Drum Synthesizer Instrument public class AKSynthKick: AKPolyphonicInstrument { /// Create the synth kick instrument /// /// - parameter voiceCount: Number of voices (usually two is plenty for drums) /// public init(voiceCount: Int) { super.init(voice: AKSynthKickVoice(), voiceCount: voiceCount) } /// Start playback of a particular voice with MIDI style note and velocity /// /// - parameter voice: Voice to start /// - parameter note: MIDI Note Number /// - parameter velocity: MIDI Velocity (0-127) /// override internal func playVoice(voice: AKVoice, note: Int, velocity: Int) { voice.start() } /// Stop playback of a particular voice /// /// - parameter voice: Voice to stop /// - parameter note: MIDI Note Number /// override internal func stopVoice(voice: AKVoice, note: Int) { } } /// Kick Drum Synthesizer Voice internal class AKSynthKickVoice: AKVoice { var generator: AKOperationGenerator var filter: AKMoogLadder /// Create the synth kick voice override init() { let frequency = AKOperation.lineSegment(AKOperation.trigger, start: 120, end: 40, duration: 0.03) let volumeSlide = AKOperation.lineSegment(AKOperation.trigger, start: 1, end: 0, duration: 0.3) let boom = AKOperation.sineWave(frequency: frequency, amplitude: volumeSlide) generator = AKOperationGenerator(operation: boom) filter = AKMoogLadder(generator) filter.cutoffFrequency = 666 filter.resonance = 0.00 super.init() avAudioNode = filter.avAudioNode generator.start() } /// Function create an identical new node for use in creating polyphonic instruments override func duplicate() -> AKVoice { let copy = AKSynthKickVoice() return copy } /// Tells whether the node is processing (ie. started, playing, or active) override var isStarted: Bool { return generator.isPlaying } /// Function to start, play, or activate the node, all do the same thing override func start() { generator.trigger() } /// Function to stop or bypass the node, both are equivalent override func stop() { } } /// Snare Drum Synthesizer Instrument public class AKSynthSnare: AKPolyphonicInstrument { /// Create the synth snare instrument /// /// - parameter voiceCount: Number of voices (usually two is plenty for drums) /// public init(voiceCount: Int, duration: Double = 0.143, resonance: Double = 0.9) { super.init(voice: AKSynthSnareVoice(duration: duration, resonance:resonance), voiceCount: voiceCount) } /// Start playback of a particular voice with MIDI style note and velocity /// /// - parameter voice: Voice to start /// - parameter note: MIDI Note Number /// - parameter velocity: MIDI Velocity (0-127) /// override internal func playVoice(voice: AKVoice, note: Int, velocity: Int) { let tempVoice = voice as! AKSynthSnareVoice tempVoice.cutoff = (Double(velocity)/127.0 * 1600.0) + 300.0 voice.start() } /// Stop playback of a particular voice /// /// - parameter voice: Voice to stop /// - parameter note: MIDI Note Number /// override public func stopVoice(voice: AKVoice, note: Int) { } } /// Snare Drum Synthesizer Voice internal class AKSynthSnareVoice: AKVoice { var generator: AKOperationGenerator var filter: AKMoogLadder var duration = 0.143 /// Create the synth snare voice init(duration: Double = 0.143, resonance: Double = 0.9) { self.duration = duration self.resonance = resonance let volSlide = AKOperation.lineSegment(AKOperation.trigger, start: 1, end: 0, duration: duration) let white = AKOperation.whiteNoise(amplitude: volSlide) generator = AKOperationGenerator(operation: white) filter = AKMoogLadder(generator) filter.cutoffFrequency = 1666 super.init() avAudioNode = filter.avAudioNode generator.start() } internal var cutoff: Double = 1666 { didSet { filter.cutoffFrequency = cutoff } } internal var resonance: Double = 0.3 { didSet { filter.resonance = resonance } } /// Function create an identical new node for use in creating polyphonic instruments override func duplicate() -> AKVoice { let copy = AKSynthSnareVoice(duration: duration, resonance: resonance) return copy } /// Tells whether the node is processing (ie. started, playing, or active) override var isStarted: Bool { return generator.isPlaying } /// Function to start, play, or activate the node, all do the same thing override func start() { generator.trigger() } /// Function to stop or bypass the node, both are equivalent override func stop() { } }
c0e69a3fffd06879a7cff59851f07921
29.369318
109
0.632928
false
false
false
false
teaxus/TSAppEninge
refs/heads/master
Source/Basic/View/BasicView/TSBasicTextField.swift
mit
1
// // TSBasicTextField.swift // TSAppEngine // // Created by teaxus on 15/12/14. // Copyright © 2015年 teaxus. All rights reserved. // import UIKit public typealias TSTextFieldFinishEdit = (_ textfield:UITextField,_ message:String)->Void public class TSBasicTextField: UITextField { public var blockFinishEdit:TSTextFieldFinishEdit? public var max_char:Int=Int.max//最大输入 public func BlockFinishEdit(action:@escaping TSTextFieldFinishEdit){ blockFinishEdit=action } public var size_design = CGSize(width: Screen_width,height: Screen_height){ didSet{ self.frame = CGRect(x: self.frame.origin.x, y: self.frame.origin.y, width: self.frame.size.width, height: self.frame.size.height) } } override public var frame:CGRect{ set(newValue){ super.frame = CGRect(x: newValue.origin.x/Screen_width*size_design.width, y: newValue.origin.y/Screen_height*size_design.height, width: newValue.size.width/Screen_width*size_design.width, height: newValue.size.height/Screen_height*size_design.height) } get{ return super.frame } } public override init(frame: CGRect) { super.init(frame: frame) initializer() self.frame = frame } func initializer(){ #if swift(>=2.2) NotificationCenter.default.addObserver(self, selector: #selector(self.textfieldDidChange(noti:)), name: NSNotification.Name.UITextFieldTextDidChange, object: nil) #else NSNotificationCenter.defaultCenter().addObserver(self, selector: "textfieldDidChange:", name: UITextFieldTextDidChangeNotification, object: nil) #endif } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) initializer() } deinit{ NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UITextFieldTextDidChange, object: nil) } //MARK:textfield在改变的时候 func textfieldDidChange(noti:NSNotification){ let textfield = noti.object as? TSBasicTextField var string_message = "" if textfield != nil{ if textfield!.text!.length > textfield!.max_char{ textfield?.text = textfield?.text![0..<(textfield!.max_char-1)] string_message = "超出范围" } if textfield!.blockFinishEdit != nil{ textfield!.blockFinishEdit!(textfield!,string_message) } } } }
e6dbdafa8b7d210eacc2b7c0c323ca25
35.277778
174
0.625574
false
false
false
false
Eonil/Editor
refs/heads/develop
Editor4/BashSubprocess.swift
mit
1
// // BashSubprocess.swift // Editor4 // // Created by Hoon H. on 2016/05/15. // Copyright © 2016 Eonil. All rights reserved. // import Foundation.NSData import Foundation.NSString enum BashSubprocessEvent { /// - Parameter 0: /// Printed line. This does not contain ending new-line character. Only line content. case StandardOutputDidPrintLine(String) /// - Parameter 0: /// Printed line. This does not contain ending new-line character. Only line content. case StandardErrorDidPrintLine(String) /// Process finished gracefully. case DidExitGracefully(exitCode: Int32) /// Process halted disgracefully by whatever reason. case DidHaltAbnormally } enum BashSubprocessError: ErrorType { case CannotEncodeCommandUsingUTF8(command: String) } final class BashSubprocess { var onEvent: (BashSubprocessEvent -> ())? private let subproc = SubprocessController() init() throws { subproc.onEvent = { [weak self] in guard let S = self else { return } switch $0 { case .DidReceiveStandardOutput(let data): S.pushStandardOutputData(data) case .DidReceiveStandardError(let data): S.pushStandardErrorData(data) case .DidTerminate: S.emitIncompleteLinesAndClear() switch S.subproc.state { case .Terminated(let exitCode): S.onEvent?(.DidExitGracefully(exitCode: exitCode)) default: fatalError("Bad state management in `Subprocess` class.") } } } try subproc.launchWithProgram(NSURL(fileURLWithPath: "/bin/bash"), arguments: ["--login", "-s"]) } deinit { switch subproc.state { case .Terminated: break default: // Force quitting subproc.kill() } } /// You need to send `exit` command to quit BASH gracefully. func runCommand(command: String) throws { guard let data = (command + "\n").dataUsingEncoding(NSUTF8StringEncoding) else { throw BashSubprocessError.CannotEncodeCommandUsingUTF8(command: command) } subproc.sendToStandardInput(data) } func kill() { subproc.kill() } //////////////////////////////////////////////////////////////// private var standardOutputDecoder = UTF8LineDecoder() private var standardErrorDecoder = UTF8LineDecoder() private func pushStandardOutputData(data: NSData) { standardOutputDecoder.push(data) while let line = standardOutputDecoder.popFirstLine() { onEvent?(.StandardOutputDidPrintLine(line)) } } private func pushStandardErrorData(data: NSData) { standardErrorDecoder.push(data) while let line = standardErrorDecoder.popFirstLine() { onEvent?(.StandardErrorDidPrintLine(line)) } } /// Ensures remaining text to be sent to event observer. /// Called on process finish. private func emitIncompleteLinesAndClear() { onEvent?(.StandardOutputDidPrintLine(standardOutputDecoder.newLineBuffer)) onEvent?(.StandardErrorDidPrintLine(standardErrorDecoder.newLineBuffer)) standardOutputDecoder = UTF8LineDecoder() standardErrorDecoder = UTF8LineDecoder() } } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // MARK: - //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// private struct UTF8LineDecoder { /// UTF-8 decoder needs to be state-ful. var decoder = UTF8() var lines = [String]() var newLineBuffer = "" mutating func push(data: NSData) { // TODO: We can remove this copying with a clever generator. let startPointer = UnsafePointer<UInt8>(data.bytes) let endPointer = startPointer.advancedBy(data.length) var iteratingPointer = startPointer // We need to keep a strong reference to data to make it alive until generator dies. var g = AnyGenerator<UInt8> { [data] in if iteratingPointer == endPointer { return nil } let unit = iteratingPointer.memory iteratingPointer += 1 return unit } push(&g) } mutating func push<G: GeneratorType where G.Element == UInt8>(inout codeUnitGenerator: G) { var ok = true while ok { let result = decoder.decode(&codeUnitGenerator) switch result { case .Result(let unicodeScalar): newLineBuffer.append(unicodeScalar) if newLineBuffer.hasSuffix("\n") { func getLastCharacterDeletedOf(string: String) -> String { var copy = string let endIndex = copy.endIndex copy.removeRange((endIndex.predecessor())..<(endIndex)) return copy } lines.append(getLastCharacterDeletedOf(newLineBuffer)) newLineBuffer = "" } case .EmptyInput: ok = false case .Error: ok = false } } } /// Gets first line and removes it from the buffer if available. /// Otherwise returns `nil`. mutating func popFirstLine() -> String? { return lines.popFirst() } }
ec8b8c4fd2bd00e01e30a8e228e49427
31.695906
128
0.569666
false
false
false
false
envoyproxy/envoy
refs/heads/main
library/swift/mocks/MockStreamPrototype.swift
apache-2.0
2
import Dispatch @_implementationOnly import EnvoyEngine import Foundation /// Mock implementation of `StreamPrototype` which is used to produce `MockStream` instances. @objcMembers public final class MockStreamPrototype: StreamPrototype { private let onStart: ((MockStream) -> Void)? /// Initialize a new instance of the mock prototype. /// /// - parameter onStart: Closure that will be called each time a new stream /// is started from the prototype. init(onStart: @escaping (MockStream) -> Void) { self.onStart = onStart super.init(engine: MockEnvoyEngine()) } public override func start(queue: DispatchQueue = .main) -> Stream { let callbacks = self.createCallbacks(queue: queue) let underlyingStream = MockEnvoyHTTPStream(handle: 0, engine: 0, callbacks: callbacks, explicitFlowControl: false) let stream = MockStream(mockStream: underlyingStream) self.onStart?(stream) return stream } }
6a6373fe448704c43db413303389e9e5
36.37037
93
0.68781
false
false
false
false
peiweichen/SurfingNavigationBar
refs/heads/master
SurfingNavigationBar/SurfingNavigationBar.swift
mit
1
// // SurfingNavigationBar.swift // SurfingNavigationBarDemo // // Created by chenpeiwei on 6/15/16. // Copyright © 2016 chenpeiwei. All rights reserved. // import UIKit extension UINavigationBar { private struct overlayViewKeys { static var DescriptiveName = "surfing_navigation_bar_overlay" } var overlayView: UIView? { get { return objc_getAssociatedObject(self, &overlayViewKeys.DescriptiveName) as? UIView } set { if let newValue = newValue { objc_setAssociatedObject( self, &overlayViewKeys.DescriptiveName, newValue as UIView?, .OBJC_ASSOCIATION_RETAIN_NONATOMIC ) } } } func surfing_setBackgroundColor(backgroundColor:UIColor) { self.setBackgroundImage(UIImage(), forBarMetrics: .Default) if let overlayView = self.overlayView { if !overlayView.isDescendantOfView(self) { self.insertSubview(overlayView, atIndex: 0) } } else { self.overlayView = UIView(frame: CGRect(x: 0, y: -20, width: CGRectGetWidth(self.bounds), height: CGRectGetHeight(self.bounds)+20)) self.overlayView?.userInteractionEnabled = false self.overlayView?.autoresizingMask = [.FlexibleWidth,.FlexibleHeight] self.insertSubview(self.overlayView!, atIndex: 0) } self.overlayView?.backgroundColor = backgroundColor } func surfing_setTranslationY(translationY:CGFloat) { self.transform = CGAffineTransformMakeTranslation(0, translationY) } func surfing_setElementsAlpha(alpha:CGFloat) { self.valueForKey("_leftViews")?.enumerateObjectsUsingBlock({ (view, index, stop) in (view as! UIView).alpha = alpha }) self.valueForKey("_rightViews")?.enumerateObjectsUsingBlock({ (view, index, stop) in (view as! UIView).alpha = alpha }) let titleView = self.valueForKey("_titleView") as? UIView titleView?.alpha = alpha for (_,subview) in self.subviews.enumerate() { guard let UINavigationItemViewClass = NSClassFromString("UINavigationItemView") else{ return } if subview.isKindOfClass(UINavigationItemViewClass) { subview.alpha = alpha break } } } func surfing_reset() { self.setBackgroundImage(nil, forBarMetrics: .Default) self.overlayView?.removeFromSuperview() } }
08f68e4926fc254726b5a80e0ec3da9f
32.475
143
0.596341
false
false
false
false