repo_name
stringlengths
6
91
ref
stringlengths
12
59
path
stringlengths
7
936
license
stringclasses
15 values
copies
stringlengths
1
3
content
stringlengths
61
711k
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
crashoverride777/Swift-AdvertisingHelper
refs/heads/master
Example/SwiftyAdExample/GameScene.swift
mit
3
// // GameScene.swift // SwiftyAds // // Created by Dominik on 04/09/2015. import SpriteKit class GameScene: SKScene { // MARK: - Properties var coins = 0 private lazy var textLabel: SKLabelNode = self.childNode(withName: "textLabel") as! SKLabelNode private lazy var consentLabel: SKLabelNode = self.childNode(withName: "consentLabel") as! SKLabelNode private let swiftyAd: SwiftyAd = .shared private var touchCounter = 15 { didSet { guard touchCounter > 0 else { swiftyAd.isRemoved = true textLabel.text = "Removed all ads" return } textLabel.text = "Remove ads in \(touchCounter) clicks" } } // MARK: - Life Cycle override func didMove(to view: SKView) { textLabel.text = "Remove ads in \(touchCounter) clicks" consentLabel.isHidden = !swiftyAd.isRequiredToAskForConsent } // MARK: - Touches override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { for touch in touches { let location = touch.location(in: self) let node = atPoint(location) guard let viewController = view?.window?.rootViewController else { return } if node == consentLabel { let gameVC = view?.window?.rootViewController as! GameViewController swiftyAd.askForConsent(from: viewController) } defer { touchCounter -= 1 } swiftyAd.showInterstitial(from: viewController, withInterval: 2) } } override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { } override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { } override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) { } }
5f826fe2a7dfaa00c384f5260fd4bc1a
27.514286
105
0.573647
false
false
false
false
J-Mendes/Bliss-Assignement
refs/heads/master
Bliss-Assignement/Bliss-Assignement/Core Layer/Network/Client/NetworkClient+Share.swift
lgpl-3.0
1
// // NetworkClient+Share.swift // Bliss-Assignement // // Created by Jorge Mendes on 13/10/16. // Copyright © 2016 Jorge Mendes. All rights reserved. // import Foundation extension NetworkClient { // MARK: - Dhare internal func shareViaEmail(email: String, url: String, completion: (response: AnyObject, error: NSError?) -> Void) { self.httpManager.POST(NetworkClient.baseUrl + "share?destination_email=" + email + "&content_url=" + url) .responseJSON { (response) -> Void in self.httpManager.manager?.session.invalidateAndCancel() let jsonParse: (json: AnyObject?, error: NSError?) = NetworkClient.jsonObjectFromData(response.data) switch response.result { case .Success: if let json: AnyObject = jsonParse.json { completion(response: json, error: nil) } else { completion(response: "", error: jsonParse.error) } break case .Failure: var errorCode: Int = -1 if let httpResponse: NSHTTPURLResponse = response.response { errorCode = httpResponse.statusCode } completion(response: "", error: NSError(domain: NetworkClient.domain + ".Share", code: errorCode, userInfo: nil)) break } } } }
273d29e8e4134cc419a39f7f469db4e1
35.833333
133
0.523594
false
false
false
false
fandongtongxue/Unsplash
refs/heads/master
Unsplash/Model/UnsplashUserProfileModel.swift
mit
1
// // UnsplashUserProfileModel.swift // Unsplash // // Created by 范东 on 17/2/4. // Copyright © 2017年 范东. All rights reserved. // import UIKit class UnsplashUserProfileModel: NSObject { var small:String! var medium:String! var large:String! // "small": "https://images.unsplash.com/profile-1486133918068-ca64a60d96c6?ixlib=rb-0.3.5\u0026q=80\u0026fm=jpg\u0026crop=faces\u0026cs=tinysrgb\u0026fit=crop\u0026h=32\u0026w=32\u0026s=3ca7e038d4fcaebd3bcfb3d8edc2a0fc", // "medium": "https://images.unsplash.com/profile-1486133918068-ca64a60d96c6?ixlib=rb-0.3.5\u0026q=80\u0026fm=jpg\u0026crop=faces\u0026cs=tinysrgb\u0026fit=crop\u0026h=64\u0026w=64\u0026s=bc1bea8e0a91f6e112355b1bfa1a5be9", // "large": "https://images.unsplash.com/profile-1486133918068-ca64a60d96c6?ixlib=rb-0.3.5\u0026q=80\u0026fm=jpg\u0026crop=faces\u0026cs=tinysrgb\u0026fit=crop\u0026h=128\u0026w=128\u0026s=f26ed28d1fcf08201b98fa2ec45a19ca" }
70b60b06b9601fb049d38946160f1001
51.055556
225
0.77588
false
false
false
false
xeo-it/poggy
refs/heads/master
Poggy/ViewControllers/PoggyToolbar.swift
apache-2.0
1
// // PoggyToolbar.swift // Poggy // // Created by Francesco Pretelli on 30/04/16. // Copyright © 2016 Francesco Pretelli. All rights reserved. // import Foundation import UIKit protocol PoggyToolbarDelegate{ func onPoggyToolbarButtonTouchUpInside() } class PoggyToolbar:UIToolbar{ var mainButton:UIButton = UIButton(type: UIButtonType.Custom) var poggyDelegate:PoggyToolbarDelegate? override func layoutSubviews() { super.layoutSubviews() barStyle = UIBarStyle.BlackOpaque backgroundColor = UIColor.clearColor()// PoggyConstants.POGGY_BLUE mainButton.backgroundColor = PoggyConstants.POGGY_BLUE //mainButton.titleLabel?.font = YNCSS.sharedInstance.getFont(21, style: YNCSS.FontStyle.REGULAR) mainButton.setTitleColor(UIColor.blackColor(), forState: .Normal) mainButton.frame = CGRect(x: 0,y: 0,width: frame.width, height: frame.height) mainButton.addTarget(self, action: #selector(self.onButtonTouchUpInside(_:)), forControlEvents: .TouchUpInside) addSubview(mainButton) } func setButtonTitle(title:String){ mainButton.setTitle(title,forState: UIControlState.Normal) } func onButtonTouchUpInside(sender: UIButton!) { poggyDelegate?.onPoggyToolbarButtonTouchUpInside() } }
e0a80ce894d083995613f79c9b58644a
30.97619
119
0.707899
false
false
false
false
kickstarter/ios-oss
refs/heads/main
Kickstarter-iOS/Features/DiscoveryFilters/Datasource/DiscoveryFiltersDataSource.swift
apache-2.0
1
import Library import UIKit internal final class DiscoveryFiltersDataSource: ValueCellDataSource { internal enum Section: Int { case collectionsHeader case collections case categoriesLoader case favoritesHeader case favorites case categoriesHeader case categories } internal func load(topRows rows: [SelectableRow], categoryId: Int?) { self.set( values: [(title: Strings.Collections(), categoryId: categoryId)], cellClass: DiscoveryFiltersStaticRowCell.self, inSection: Section.collectionsHeader.rawValue ) let rowsAndId = rows.map { (row: $0, categoryId: categoryId) } self.set( values: rowsAndId, cellClass: DiscoverySelectableRowCell.self, inSection: Section.collections.rawValue ) } internal func load(favoriteRows rows: [SelectableRow], categoryId: Int?) { self.set( values: [(title: Strings.Bookmarks(), categoryId: categoryId)], cellClass: DiscoveryFiltersStaticRowCell.self, inSection: Section.favoritesHeader.rawValue ) let rowsAndId = rows.map { (row: $0, categoryId: categoryId) } self.set( values: rowsAndId, cellClass: DiscoverySelectableRowCell.self, inSection: Section.favorites.rawValue ) } internal func load(categoryRows rows: [ExpandableRow], categoryId: Int?) { self.set( values: [(title: Strings.discovery_filters_categories_title(), categoryId: categoryId)], cellClass: DiscoveryFiltersStaticRowCell.self, inSection: Section.categoriesHeader.rawValue ) self.clearValues(section: Section.categories.rawValue) for row in rows { self.appendRow( value: (row: row, categoryId: categoryId), cellClass: DiscoveryExpandableRowCell.self, toSection: Section.categories.rawValue ) if row.isExpanded { for selectableRow in row.selectableRows { self.appendRow( value: (row: selectableRow, categoryId: categoryId), cellClass: DiscoveryExpandedSelectableRowCell.self, toSection: Section.categories.rawValue ) } } } } internal func loadCategoriesLoaderRow() { self.set( values: [()], cellClass: DiscoveryFiltersLoaderCell.self, inSection: Section.categoriesLoader.rawValue ) } internal func deleteCategoriesLoaderRow(_ tableView: UITableView) -> [IndexPath]? { if self.numberOfSections(in: tableView) > Section.categoriesLoader.rawValue, !self[section: Section.categoriesLoader.rawValue].isEmpty { self.clearValues(section: Section.categoriesLoader.rawValue) return [IndexPath(row: 0, section: Section.categoriesLoader.rawValue)] } return nil } internal func selectableRow(indexPath: IndexPath) -> SelectableRow? { if let (row, _) = self[indexPath] as? (SelectableRow, Int?) { return row } return nil } internal func expandableRow(indexPath: IndexPath) -> ExpandableRow? { if let (row, _) = self[indexPath] as? (ExpandableRow, Int?) { return row } return nil } internal func indexPath(forCategoryId categoryId: Int?) -> IndexPath? { for (idx, value) in self[section: Section.categories.rawValue].enumerated() { guard let (row, _) = value as? (ExpandableRow, Int?) else { continue } if row.params.category?.intID == categoryId { return IndexPath(item: idx, section: Section.categories.rawValue) } } return nil } internal func expandedRow() -> Int? { for (idx, value) in self[section: Section.categories.rawValue].enumerated() { guard let (row, _) = value as? (ExpandableRow, Int?) else { continue } if row.isExpanded { return idx } } return nil } internal override func configureCell(tableCell cell: UITableViewCell, withValue value: Any) { switch (cell, value) { case let (cell as DiscoverySelectableRowCell, value as (SelectableRow, Int?)): cell.configureWith(value: value) case let (cell as DiscoveryExpandableRowCell, value as (ExpandableRow, Int?)): cell.configureWith(value: value) case let (cell as DiscoveryExpandedSelectableRowCell, value as (SelectableRow, Int?)): cell.configureWith(value: value) case let (cell as DiscoveryFiltersStaticRowCell, value as (String, Int?)): cell.configureWith(value: value) case let (cell as DiscoveryFiltersLoaderCell, value as Void): cell.configureWith(value: value) default: fatalError("Unrecognized combo (\(cell), \(value)).") } } }
c336ce2ccc9f61297a2c03c8ff6247c2
30.613793
95
0.679538
false
false
false
false
AndrewBennet/readinglist
refs/heads/master
ReadingList/ViewControllers/Settings/General.swift
gpl-3.0
1
import SwiftUI class GeneralSettingsObservable: ObservableObject { @Published var addBooksToTop: Bool = GeneralSettings.addBooksToTopOfCustom { didSet { GeneralSettings.addBooksToTopOfCustom = addBooksToTop } } @Published var progressType = GeneralSettings.defaultProgressType { didSet { GeneralSettings.defaultProgressType = progressType } } @Published var prepopulateLastLanguageSelection = GeneralSettings.prepopulateLastLanguageSelection { didSet { GeneralSettings.prepopulateLastLanguageSelection = prepopulateLastLanguageSelection if !prepopulateLastLanguageSelection { LightweightDataStore.lastSelectedLanguage = nil } } } @Published var restrictSearchResultsTo: LanguageSelection = { if let languageRestriction = GeneralSettings.searchLanguageRestriction { return .some(languageRestriction) } else { return LanguageSelection.none } }() { didSet { if case .some(let selection) = restrictSearchResultsTo { GeneralSettings.searchLanguageRestriction = selection } else { GeneralSettings.searchLanguageRestriction = .none } } } } struct General: View { @EnvironmentObject var hostingSplitView: HostingSettingsSplitView @ObservedObject var settings = GeneralSettingsObservable() private var inset: Bool { hostingSplitView.isSplit } private let languageOptions = [LanguageSelection.none] + LanguageIso639_1.allCases.filter { $0.canFilterGoogleSearchResults }.map { .some($0) } var body: some View { SwiftUI.List { Section( header: HeaderText("Sort Options", inset: hostingSplitView.isSplit), footer: FooterText(""" Configure whether newly added books get added to the top or the bottom of the \ reading list when Custom ordering is used. """, inset: hostingSplitView.isSplit ) ) { Toggle(isOn: $settings.addBooksToTop) { Text("Add Books to Top") } } Section( header: HeaderText("Progress", inset: inset), footer: FooterText("Choose whether to default to Page Number or Percentage when setting progress.", inset: inset) ) { NavigationLink( destination: SelectionForm<ProgressType>( options: [.page, .percentage], selectedOption: $settings.progressType ).navigationBarTitle("Default Progress Type") ) { HStack { Text("Progress Type") Spacer() Text(settings.progressType.description) .foregroundColor(.secondary) } } } Section( header: HeaderText("Language", inset: inset), footer: FooterText(""" By default, Reading List prioritises search results based on their language and your location. To instead \ restrict search results to be of a specific language only, select a language above. """, inset: inset) ) { Toggle(isOn: $settings.prepopulateLastLanguageSelection) { Text("Remember Last Selection") } NavigationLink( destination: SelectionForm<LanguageSelection>( options: languageOptions, selectedOption: $settings.restrictSearchResultsTo ).navigationBarTitle("Language Restriction") ) { HStack { Text("Restrict Search Results") Spacer() Text(settings.restrictSearchResultsTo.description).foregroundColor(.secondary) } } } } .possiblyInsetGroupedListStyle(inset: hostingSplitView.isSplit) } } extension ProgressType: Identifiable { var id: Int { rawValue } } extension LanguageSelection: Identifiable { var id: String { switch self { case .none: return "" // Not in practise used by this form; return some arbitrary unique value case .blank: return "!" case .some(let language): return language.rawValue } } } struct General_Previews: PreviewProvider { static var previews: some View { NavigationView { General().environmentObject(HostingSettingsSplitView()) } } }
4781c2d61b59c7df10ad0b333d611138
36.292308
147
0.570338
false
false
false
false
wordpress-mobile/WordPress-iOS
refs/heads/trunk
WordPress/Classes/ViewRelated/Jetpack/Branding/Coordinator/JetpackBrandingCoordinator.swift
gpl-2.0
1
import UIKit /// A class containing convenience methods for the the Jetpack branding experience class JetpackBrandingCoordinator { static func presentOverlay(from viewController: UIViewController, redirectAction: (() -> Void)? = nil) { let action = redirectAction ?? { JetpackRedirector.redirectToJetpack() } let jetpackOverlayViewController = JetpackOverlayViewController(viewFactory: makeJetpackOverlayView, redirectAction: action) let bottomSheet = BottomSheetViewController(childViewController: jetpackOverlayViewController, customHeaderSpacing: 0) bottomSheet.show(from: viewController) } static func makeJetpackOverlayView(redirectAction: (() -> Void)? = nil) -> UIView { JetpackOverlayView(buttonAction: redirectAction) } static func shouldShowBannerForJetpackDependentFeatures() -> Bool { let phase = JetpackFeaturesRemovalCoordinator.generalPhase() switch phase { case .two: fallthrough case .three: return true default: return false } } }
337366c7f9fce60c6f55f6ea1526500c
34.09375
132
0.691006
false
false
false
false
Himnshu/LoginLib
refs/heads/master
Example/LoginLib/LoginCoordinator.swift
mit
1
// // LoginCoordinator.swift // LoginFramework // // Created by OSX on 28/07/17. // Copyright © 2017 CocoaPods. All rights reserved. // import UIKit import LoginLib class LoginCoordinator: LoginLib.LoginCoordinator { override func start() { super.start() configureAppearance() } override func finish() { super.finish() } func configureAppearance() { // Customize LoginKit. All properties have defaults, only set the ones you want. // Customize the look with background & logo images backgroundImage = #imageLiteral(resourceName: "background") mainLogoImage = #imageLiteral(resourceName: "parseImage") secondaryLogoImage = #imageLiteral(resourceName: "parseImage") // Change colors tintColor = UIColor(red: 52.0/255.0, green: 152.0/255.0, blue: 219.0/255.0, alpha: 1) errorTintColor = UIColor(red: 253.0/255.0, green: 227.0/255.0, blue: 167.0/255.0, alpha: 1) // Change placeholder & button texts, useful for different marketing style or language. loginButtonText = "Sign In" signupButtonText = "Create Account" forgotPasswordButtonText = "Forgot password?" recoverPasswordButtonText = "Recover" namePlaceholder = "Full Name" emailPlaceholder = "E-Mail" passwordPlaceholder = "Password!" repeatPasswordPlaceholder = "Confirm password!" } // MARK: - Completion Callbacks override func login(profile: LoginProfile) { // Handle login via your API print("Login with: email =\(profile.email) username = \(profile.userName)") } override func signup(profile: SignUpProfile) { // Handle signup via your API print("Signup with: name = \(profile.userName) email =\(profile.email)") } override func loginError(error: NSError) { // Handle login error via your API let errorString = error.userInfo["error"] as? String print("Error: \(errorString)") } override func signUpError(error: NSError) { // Handle login error via your API print(error) } override func enterWithFacebook(profile: FacebookProfile) { // Handle Facebook login/signup via your API print("Login/Signup via Facebook with: FB profile =\(profile)") } override func enterWithTwitter(profile: TwitterProfile) { // Handle Facebook login/signup via your API print("Login/Signup via Facebook with: FB profile =\(profile)") } override func recoverPassword(success: Bool) { // Handle password recovery via your API print(success) } override func recoverPasswordError(error: NSError) { print(error) } }
3a80d2193fafd7d92129591aabf73328
31.344828
99
0.633618
false
false
false
false
omniprog/SwiftZSTD
refs/heads/master
Sources/ZSTDProcessor.swift
bsd-3-clause
1
// // ZSTDProcessor.swift // // Created by Anatoli on 12/06/16. // Copyright © 2016 Anatoli Peredera. All rights reserved. // import Foundation /** * Class that supports compression/decompression of an in-memory buffer without using * a dictionary. A compression/decompression context can be used optionally to speed * up processing of multiple buffers. */ public class ZSTDProcessor { let commonProcessor : ZSTDProcessorCommon var currentCL : Int32 = 0 /** * Initializer. * * - paremeter useContext : true if use of context is desired */ public init(useContext : Bool = false) { commonProcessor = ZSTDProcessorCommon(useContext: useContext) } /** * Compress a buffer. Input is sent to the C API without copying by using the * Data.withUnsafeBytes() method. The C API places the output straight into the newly- * created Data instance, which is possible because there are no other references * to the instance at this point, so calling withUnsafeMutableBytes() does not trigger * a copy-on-write. * * - parameter dataIn : input Data * - parameter compressionLevel : must be 1-22, levels >= 20 to be used with caution * - returns: compressed frame */ public func compressBuffer(_ dataIn : Data, compressionLevel : Int32) throws -> Data { guard isValidCompressionLevel(compressionLevel) else { throw ZSTDError.invalidCompressionLevel(cl: compressionLevel) } currentCL = compressionLevel return try commonProcessor.compressBufferCommon(dataIn, compressFrameHelper) } /** * A private helper passed to commonProcessor.compressBufferCommon(). */ private func compressFrameHelper(dst : UnsafeMutableRawPointer, dstCapacity : Int, src : UnsafeRawPointer, srcSize : Int) -> Int { if commonProcessor.compCtx != nil { return ZSTD_compressCCtx(commonProcessor.compCtx, dst, dstCapacity, src, srcSize, currentCL); } else { return ZSTD_compress(dst, dstCapacity, src, srcSize, currentCL) } } /** * Decompress a frame that resulted from a previous compression of a buffer by a call * to compressBuffer(). * * - parameter dataIn: frame to be decompressed * - returns: a Data instance wrapping the decompressed buffer */ public func decompressFrame(_ dataIn : Data) throws -> Data { return try commonProcessor.decompressFrameCommon(dataIn, decompressFrameHelper) } /** * A private helper passed to commonProcessor.decompressFrameCommon(). */ private func decompressFrameHelper(dst : UnsafeMutableRawPointer, dstCapacity : Int, src : UnsafeRawPointer, srcSize : Int) -> Int { if commonProcessor.decompCtx != nil { return ZSTD_decompressDCtx(commonProcessor.decompCtx, dst, dstCapacity, src, srcSize); } else { return ZSTD_decompress(dst, dstCapacity, src, srcSize) } } }
1895766c54e55623aa4e5b29b8d567bf
34.94382
105
0.6402
false
false
false
false
wangyuanou/Coastline
refs/heads/master
Coastline/System/MultiLanguage.swift
mit
1
// // MultiLanguage.swift // Coastline // // Created by 王渊鸥 on 2016/12/20. // Copyright © 2016年 王渊鸥. All rights reserved. // import Foundation public class MultiLanguage { public static var shareInstance:MultiLanguage = { MultiLanguage() }() var bundle:Bundle? init() { if let path = Bundle.main.path(forResource: langName, ofType: "lproj") { bundle = Bundle(path: path) } } public var langName:String { get { let ud = UserDefaults.standard if let lang = ud.object(forKey: "cur_lang") as? String { return lang } else { var lang = "Base" if let langs = ud.object(forKey: "AppleLanguages") as? [String] , langs.count > 0 { if langs[0].hasPrefix("zh") { lang = "zh-Hans" } } ud.set(lang, forKey: "cur_lang") OperationQueue().addOperation { let ud = UserDefaults.standard ud.synchronize() } return lang } } set { if let path = Bundle.main.path(forResource: langName, ofType: "lproj") { bundle = Bundle(path: path) OperationQueue().addOperation { let ud = UserDefaults.standard ud.set(newValue, forKey: "cur_lang") ud.synchronize() } } } } public func str(key:String) -> String? { return bundle?.localizedString(forKey: key, value: nil, table: nil) } public func str(table:String, key:String) -> String? { return bundle?.localizedString(forKey: key, value: nil, table: table) } public func storyboard(name:String) -> UIStoryboard { return UIStoryboard(name: name, bundle: bundle) } } public extension String { var l:String { return NSLocalizedString(self, comment: self) } }
c888ddd5ce5cac253cadb36c344dc5cd
21.424658
87
0.64325
false
false
false
false
LeeShiYoung/DouYu
refs/heads/master
DouYuAPP/DouYuAPP/Classes/Home/View/Yo_HomeGameViewCell.swift
apache-2.0
1
// // Yo_HomeGameViewCell.swift // DouYuAPP // // Created by shying li on 2017/4/1. // Copyright © 2017年 李世洋. All rights reserved. // import UIKit class Yo_HomeGameViewCell: Yo_BaseCollectionViewCell { override func configureView() { super.configureView() setupUI() } public lazy var gameName: UILabel = {[weak self] in let gameName = UILabel() gameName.textColor = UIColor.white gameName.font = UIFont.systemFont(ofSize: 12) gameName.textColor = UIColor.colorWithHex("#c9c9cd") self?.contentView.addSubview(gameName) return gameName }() } extension Yo_HomeGameViewCell { fileprivate func setupUI() { coverImage.snp.remakeConstraints { (maker) in maker.centerX.equalTo(contentView.snp.centerX) maker.centerY.equalTo(contentView.snp.centerY).offset(-10) maker.width.height.equalTo(45) } gameName.snp.makeConstraints { (maker) in maker.top.equalTo(coverImage.snp.bottom).offset(7) maker.centerX.equalTo(coverImage.snp.centerX) } } } extension Yo_HomeGameViewCell { override func configure(Item: Any, indexPath: IndexPath) { let model = Item as? Yo_AnchorBaseGroup gameName.text = model?.tag_name if let iconUrl = URL(string: model?.icon_url ?? "") { coverImage.yo_setImage(iconUrl, placeholder: "", radius: 104) } else { coverImage.image = UIImage(named: "home_more_btn") } } }
d43f7a7aeaeaf8a1605cb107d7acec1e
26.964286
73
0.619413
false
true
false
false
material-motion/material-motion-swift
refs/heads/develop
Pods/MaterialMotion/src/operators/valve.swift
apache-2.0
2
/* Copyright 2016-present The Material Motion Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import IndefiniteObservable extension MotionObservableConvertible { /** A valve creates control flow for a stream. The upstream will be subscribed to when valveStream emits true, and the subscription terminated when the valveStream emits false. */ public func valve<O: MotionObservableConvertible>(openWhenTrue valveStream: O) -> MotionObservable<T> where O.T == Bool { return MotionObservable<T> { observer in var upstreamSubscription: Subscription? let valveSubscription = valveStream.subscribeToValue { shouldOpen in if shouldOpen && upstreamSubscription == nil { upstreamSubscription = self.asStream().subscribeAndForward(to: observer) } if !shouldOpen && upstreamSubscription != nil { upstreamSubscription?.unsubscribe() upstreamSubscription = nil } } return { valveSubscription.unsubscribe() upstreamSubscription?.unsubscribe() upstreamSubscription = nil } } } }
661fb05aa6f39ce88ced2896b5c05d0b
32.244898
123
0.722529
false
false
false
false
atrick/swift
refs/heads/main
SwiftCompilerSources/Sources/SIL/Argument.swift
apache-2.0
2
//===--- Argument.swift - Defines the Argument classes --------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import Basic import SILBridging /// A basic block argument. /// /// Maps to both, SILPhiArgument and SILFunctionArgument. public class Argument : Value, Equatable { public var definingInstruction: Instruction? { nil } public var block: BasicBlock { return SILArgument_getParent(bridged).block } var bridged: BridgedArgument { BridgedArgument(obj: SwiftObject(self)) } public var index: Int { return block.arguments.firstIndex(of: self)! } public static func ==(lhs: Argument, rhs: Argument) -> Bool { lhs === rhs } } final public class FunctionArgument : Argument { public var isExclusiveIndirectParameter: Bool { SILArgument_isExclusiveIndirectParameter(bridged) != 0 } } final public class BlockArgument : Argument { public var isPhiArgument: Bool { block.predecessors.allSatisfy { let term = $0.terminator return term is BranchInst || term is CondBranchInst } } public var incomingPhiOperands: LazyMapSequence<PredecessorList, Operand> { assert(isPhiArgument) let idx = index return block.predecessors.lazy.map { switch $0.terminator { case let br as BranchInst: return br.operands[idx] case let condBr as CondBranchInst: if condBr.trueBlock == self.block { assert(condBr.falseBlock != self.block) return condBr.trueOperands[idx] } else { assert(condBr.falseBlock == self.block) return condBr.falseOperands[idx] } default: fatalError("wrong terminator for phi-argument") } } } public var incomingPhiValues: LazyMapSequence<LazyMapSequence<PredecessorList, Operand>, Value> { incomingPhiOperands.lazy.map { $0.value } } } // Bridging utilities extension BridgedArgument { var argument: Argument { obj.getAs(Argument.self) } var functionArgument: FunctionArgument { obj.getAs(FunctionArgument.self) } }
26c81ff5d95ee470e10da0119acd0e61
28.987805
99
0.664091
false
false
false
false
wireapp/wire-ios
refs/heads/develop
Wire-iOS/Sources/UserInterface/Conversation/Content/Cells/ConfigurationMessageCell/ConversationMessageCellTableViewAdapter.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 WireDataModel import UIKit protocol ConversationMessageCellMenuPresenter: AnyObject { func showMenu() } extension UITableViewCell { @objc func willDisplayCell() { // to be overriden in subclasses } @objc func didEndDisplayingCell() { // to be overriden in subclasses } } class ConversationMessageCellTableViewAdapter<C: ConversationMessageCellDescription>: UITableViewCell, SelectableView, HighlightableView, ConversationMessageCellMenuPresenter { var cellView: C.View var ephemeralCountdownView: EphemeralCountdownView var cellDescription: C? { didSet { longPressGesture.isEnabled = cellDescription?.supportsActions == true doubleTapGesture.isEnabled = cellDescription?.supportsActions == true singleTapGesture.isEnabled = cellDescription?.supportsActions == true } } var topMargin: Float = 0 { didSet { top.constant = CGFloat(topMargin) } } var isFullWidth: Bool = false { didSet { configureConstraints(fullWidth: isFullWidth) } } override var accessibilityIdentifier: String? { get { return cellDescription?.accessibilityIdentifier } set { super.accessibilityIdentifier = newValue } } override var accessibilityLabel: String? { get { return cellDescription?.accessibilityLabel } set { super.accessibilityLabel = newValue } } private var leading: NSLayoutConstraint! private var top: NSLayoutConstraint! private var trailing: NSLayoutConstraint! private var bottom: NSLayoutConstraint! private var ephemeralTop: NSLayoutConstraint! private var longPressGesture: UILongPressGestureRecognizer! private var doubleTapGesture: UITapGestureRecognizer! private var singleTapGesture: UITapGestureRecognizer! var showsMenu = false override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { self.cellView = C.View(frame: .zero) self.cellView.translatesAutoresizingMaskIntoConstraints = false self.ephemeralCountdownView = EphemeralCountdownView() self.ephemeralCountdownView.translatesAutoresizingMaskIntoConstraints = false super.init(style: style, reuseIdentifier: reuseIdentifier) self.focusStyle = .custom self.selectionStyle = .none self.backgroundColor = .clear self.isOpaque = false contentView.addSubview(cellView) contentView.addSubview(ephemeralCountdownView) leading = cellView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor) trailing = cellView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor) top = cellView.topAnchor.constraint(equalTo: contentView.topAnchor) bottom = cellView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor) bottom.priority = UILayoutPriority(999) ephemeralTop = ephemeralCountdownView.topAnchor.constraint(equalTo: cellView.topAnchor) NSLayoutConstraint.activate([ ephemeralCountdownView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor), ephemeralCountdownView.trailingAnchor.constraint(equalTo: cellView.leadingAnchor), ephemeralTop, leading, trailing, top, bottom ]) longPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(onLongPress)) contentView.addGestureRecognizer(longPressGesture) doubleTapGesture = UITapGestureRecognizer(target: self, action: #selector(onDoubleTap)) doubleTapGesture.numberOfTapsRequired = 2 contentView.addGestureRecognizer(doubleTapGesture) singleTapGesture = UITapGestureRecognizer(target: self, action: #selector(onSingleTap)) cellView.addGestureRecognizer(singleTapGesture) singleTapGesture.require(toFail: doubleTapGesture) singleTapGesture.delegate = self } @available(*, unavailable) required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func configure(with object: C.View.Configuration, fullWidth: Bool, topMargin: Float) { cellView.configure(with: object, animated: false) self.isFullWidth = fullWidth self.topMargin = topMargin self.ephemeralCountdownView.isHidden = cellDescription?.showEphemeralTimer == false self.ephemeralCountdownView.message = cellDescription?.message } func configureConstraints(fullWidth: Bool) { let margins = conversationHorizontalMargins leading.constant = fullWidth ? 0 : margins.left trailing.constant = fullWidth ? 0 : -margins.right ephemeralTop.constant = cellView.ephemeralTimerTopInset } override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { super.traitCollectionDidChange(previousTraitCollection) configureConstraints(fullWidth: isFullWidth) } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) UIView.animate(withDuration: 0.35, animations: { self.cellView.isSelected = selected self.layoutIfNeeded() }) } // MARK: - Menu @objc private func onLongPress(_ gestureRecognizer: UILongPressGestureRecognizer) { if gestureRecognizer.state == .began { showMenu() } } override var canBecomeFirstResponder: Bool { return true } override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool { guard let actionController = cellDescription?.actionController else { return false } return actionController.canPerformAction(action) == true } override func forwardingTarget(for aSelector: Selector!) -> Any? { return cellDescription?.actionController } func showMenu() { guard cellDescription?.supportsActions == true else { return } let needsFirstResponder = cellDescription?.delegate?.conversationMessageShouldBecomeFirstResponderWhenShowingMenuForCell(self) registerMenuObservers() let menu = UIMenuController.shared menu.menuItems = ConversationMessageActionController.allMessageActions if needsFirstResponder != false { self.becomeFirstResponder() } menu.showMenu(from: selectionView, rect: selectionRect) } // MARK: - Single Tap Action @objc private func onSingleTap(_ gestureRecognizer: UITapGestureRecognizer) { if gestureRecognizer.state == .recognized && cellDescription?.supportsActions == true { cellDescription?.actionController?.performSingleTapAction() } } // MARK: - Double Tap Action @objc private func onDoubleTap(_ gestureRecognizer: UITapGestureRecognizer) { if gestureRecognizer.state == .recognized && cellDescription?.supportsActions == true { cellDescription?.actionController?.performDoubleTapAction() } } // MARK: - Target / Action private func registerMenuObservers() { NotificationCenter.default.addObserver(self, selector: #selector(menuWillShow), name: UIMenuController.willShowMenuNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(menuDidHide), name: UIMenuController.didHideMenuNotification, object: nil) } @objc private func menuWillShow(_ note: Notification) { showsMenu = true setSelectedByMenu(true, animated: true) NotificationCenter.default.removeObserver(self, name: UIMenuController.willShowMenuNotification, object: nil) } @objc private func menuDidHide(_ note: Notification) { showsMenu = false setSelectedByMenu(false, animated: true) NotificationCenter.default.removeObserver(self, name: UIMenuController.didHideMenuNotification, object: nil) } func setSelectedByMenu(_ isSelected: Bool, animated: Bool) { let animations = { self.selectionView.alpha = isSelected ? 0.4 : 1 } UIView.animate(withDuration: 0.32, animations: animations) } // MARK: - SelectableView var selectionView: UIView! { return cellView.selectionView ?? self } var selectionRect: CGRect { if cellView.selectionView != nil { return cellView.selectionRect } else { return self.bounds } } var highlightContainer: UIView { return self } override func willDisplayCell() { cellDescription?.willDisplayCell() cellView.willDisplay() ephemeralCountdownView.startCountDown() } override func didEndDisplayingCell() { cellDescription?.didEndDisplayingCell() cellView.didEndDisplaying() ephemeralCountdownView.stopCountDown() } override func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool { guard gestureRecognizer == singleTapGesture else { return super.gestureRecognizerShouldBegin(gestureRecognizer) } // We fail the single tap gesture recognizer if there's no single tap action to perform, which gives // other gesture recognizers the opportunity to fire. return cellDescription?.actionController?.singleTapAction != nil } } extension UITableView { func register<C: ConversationMessageCellDescription>(cell: C.Type) { let reuseIdentifier = String(describing: C.self) register(ConversationMessageCellTableViewAdapter<C>.self, forCellReuseIdentifier: reuseIdentifier) } func dequeueConversationCell<C: ConversationMessageCellDescription>(with description: C, for indexPath: IndexPath) -> ConversationMessageCellTableViewAdapter<C> { let reuseIdentifier = String(describing: C.self) let cell = dequeueReusableCell(withIdentifier: reuseIdentifier, for: indexPath) as Any as! ConversationMessageCellTableViewAdapter<C> cell.cellDescription = description cell.configure(with: description.configuration, fullWidth: description.isFullWidth, topMargin: description.topMargin) return cell } }
9094809b233390c82ab34554c2962a55
33.70405
176
0.699192
false
false
false
false
ppraveentr/MobileCore
refs/heads/master
Sources/CoreUtility/Extensions/AttributedLabelProtocol.swift
mit
1
// // AttributedLabelProtocol.swift // MobileCore-CoreUtility // // Created by Praveen P on 20/10/19. // import Foundation import UIKit public typealias LabelLinkHandler = (LinkHandlerModel) -> Void // For Visual update of 'Theme' & 'attributedText' public protocol OptionalLayoutSubview { func updateVisualThemes() } protocol AttributedLabelProtocol where Self: UILabel { // Link handler var linkRanges: [LinkHandlerModel]? { get set } var linkHandler: LabelLinkHandler? { get set } var tapGestureRecognizer: UITapGestureRecognizer { get } // layout var layoutManager: NSLayoutManager { get } var styleProperties: AttributedDictionary { get set } } private extension AssociatedKey { static var textContainer = "textContainer" static var layoutManager = "layoutManager" static var styleProperties = "styleProperties" static var linkRanges = "linkRanges" static var islinkDetectionEnabled = "islinkDetectionEnabled" static var isLinkUnderLineEnabled = "isLinkUnderLineEnabled" static var linkHandler = "linkHandler" static var tapGestureRecognizer = "tapGestureRecognizer" } extension UILabel: AttributedLabelProtocol { public var linkRanges: [LinkHandlerModel]? { get { AssociatedObject.getAssociated(self, key: &AssociatedKey.linkRanges) } set { AssociatedObject<[LinkHandlerModel]>.setAssociated(self, value: newValue, key: &AssociatedKey.linkRanges) } } // LabelThemeProtocol public var islinkDetectionEnabled: Bool { get { AssociatedObject.getAssociated(self, key: &AssociatedKey.islinkDetectionEnabled) { true }! } set { AssociatedObject<Bool>.setAssociated(self, value: newValue, key: &AssociatedKey.islinkDetectionEnabled) } } public var isLinkUnderLineEnabled: Bool { get { AssociatedObject.getAssociated(self, key: &AssociatedKey.isLinkUnderLineEnabled) { false }! } set { AssociatedObject<Bool>.setAssociated(self, value: newValue, key: &AssociatedKey.isLinkUnderLineEnabled) } } public var linkHandler: LabelLinkHandler? { get { AssociatedObject.getAssociated(self, key: &AssociatedKey.linkHandler) } set { AssociatedObject<LabelLinkHandler>.setAssociated(self, value: newValue, key: &AssociatedKey.linkHandler) self.isUserInteractionEnabled = true self.addGestureRecognizer(self.tapGestureRecognizer) } } public var tapGestureRecognizer: UITapGestureRecognizer { AssociatedObject.getAssociated(self, key: &AssociatedKey.tapGestureRecognizer) { UILabel.tapGesture(targer: self) }! } public var layoutManager: NSLayoutManager { AssociatedObject.getAssociated(self, key: &AssociatedKey.layoutManager) { NSLayoutManager() }! } public var textContainer: NSTextContainer { let local: NSTextContainer = AssociatedObject.getAssociated(self, key: &AssociatedKey.textContainer) { self.getTextContainer() }! local.lineFragmentPadding = 0.0 local.maximumNumberOfLines = self.numberOfLines local.lineBreakMode = self.lineBreakMode local.widthTracksTextView = true local.heightTracksTextView = true local.size = self.bounds.size return local } public var styleProperties: AttributedDictionary { get { AssociatedObject.getAssociated(self, key: &AssociatedKey.styleProperties) { self.defaultStyleProperties }! } set { AssociatedObject<AttributedDictionary>.setAssociated(self, value: newValue, key: &AssociatedKey.styleProperties) } } public var htmlText: String { get { "" } set { updateWithHtmlString(text: newValue) } } } extension UILabel: OptionalLayoutSubview { @objc public func updateVisualThemes() { if islinkDetectionEnabled, self.text.isHTMLString, let newValue = self.text { self.text = newValue.stripHTML() self.numberOfLines = 0 updateWithHtmlString(text: newValue) } } private static func tapGesture(targer: AnyObject?) -> UITapGestureRecognizer { UITapGestureRecognizer(target: targer, action: #selector(UILabel.tapGestureRecognized(_:))) } @objc func tapGestureRecognized(_ gesture: UITapGestureRecognizer) { if self == gesture.view, let link = self.didTapAttributedText(gesture)?.first { self.linkHandler?(link) } } fileprivate var offsetXDivisor: CGFloat { switch self.textAlignment { case .center: return 0.5 case .right: return 1.0 default: return 0.0 } } private func getTextContainer() -> NSTextContainer { let container = NSTextContainer() container.replaceLayoutManager(self.layoutManager) self.layoutManager.addTextContainer(container) return container } private var defaultStyleProperties: AttributedDictionary { let paragrahStyle = NSMutableParagraphStyle() paragrahStyle.alignment = self.textAlignment paragrahStyle.lineBreakMode = self.lineBreakMode var properties: AttributedDictionary = [ .paragraphStyle: paragrahStyle, .backgroundColor: self.backgroundColor ?? UIColor.clear ] if let font = self.font { properties[.font] = font } if let color = self.textColor { properties[.foregroundColor] = color } return properties } } extension UILabel { // MARK: Text Formatting func updateWithHtmlString(text: String?) { let att = text?.htmlAttributedString() self.updateTextWithAttributedString(attributedString: att) } func updateTextContainerSize() { var localSize = self.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize) localSize.width = min(localSize.width, self.preferredMaxLayoutWidth) self.frame = CGRect(origin: frame.origin, size: localSize) } func updateTextWithAttributedString(attributedString: NSAttributedString?) { if let attributedString = attributedString { let sanitizedString = self.sanitizeAttributedString(attributedString: attributedString) sanitizedString.addAttributes(self.styleProperties, range: sanitizedString.nsRange()) if islinkDetectionEnabled { updateLinkInText(attributedString: sanitizedString) } self.attributedText = sanitizedString } layoutTextView() } func updateLinkInText(attributedString: NSMutableAttributedString) { self.linkRanges = LinkHandlerModel.appendLink(attributedString: attributedString) } // MARK: Container SetUp func layoutTextView() { updateTextContainerSize() layoutView() } public func didTapAttributedText(_ gesture: UIGestureRecognizer) -> [LinkHandlerModel]? { let indexOfCharacter = layoutManager.indexOfCharacter(self, touchLocation: gesture.location(in: self)) return self.linkRanges?.filter { $0.linkRange.contains(indexOfCharacter) } } // MARK: Text Sanitizing func sanitizeAttributedString(attributedString: NSAttributedString) -> NSMutableAttributedString { guard attributedString.length != 0 else { return attributedString.mutableString() } var range = attributedString.nsRange() guard let praStryle = attributedString.attribute(.paragraphStyle, at: 0, effectiveRange: &range) as? NSParagraphStyle, let mutablePraStryle = praStryle.mutableCopy() as? NSMutableParagraphStyle else { return attributedString.mutableString() } mutablePraStryle.lineBreakMode = .byWordWrapping let restyledString = attributedString.mutableString() restyledString.addParagraphStyle(style: mutablePraStryle) return restyledString } } extension NSLayoutManager { func indexOfCharacter(_ label: UILabel, touchLocation: CGPoint) -> Int { let textContainer = label.textContainer let textStorage = NSTextStorage(attributedString: label.attributedText ?? NSAttributedString(string: "")) textStorage.addLayoutManager(self) let (labelSize, textBoundingBox) = (label.bounds.size, self.usedRect(for: textContainer)) let offsetX = (labelSize.width - textBoundingBox.size.width) * label.offsetXDivisor - textBoundingBox.origin.x let offsetY = (labelSize.height - textBoundingBox.size.height) * 0.5 - textBoundingBox.origin.y let locationOfTouch = CGPoint(x: touchLocation.x - offsetX, y: touchLocation.y - offsetY) let indexOfCharacter = self.characterIndex(for: locationOfTouch, in: textContainer, fractionOfDistanceBetweenInsertionPoints: nil) return indexOfCharacter } }
29c2e65e659f78152fe85bd8413dfba8
39.766055
138
0.697873
false
false
false
false
zwaldowski/Attendant
refs/heads/master
Attendant/AssociationPolicy.swift
mit
1
// // AssociationPolicy.swift // Attendant // // Created by Zachary Waldowski on 4/16/15. // Copyright © 2015-2016 Big Nerd Ranch. All rights reserved. // import ObjectiveC.runtime public enum AssociationPolicy { case Unowned case Strong(atomic: Bool) case Copying(atomic: Bool) var runtimeValue: objc_AssociationPolicy { switch self { case .Strong(false): return .OBJC_ASSOCIATION_RETAIN_NONATOMIC case .Strong(true): return .OBJC_ASSOCIATION_RETAIN case .Copying(false): return .OBJC_ASSOCIATION_COPY_NONATOMIC case .Copying(true): return .OBJC_ASSOCIATION_COPY default: return .OBJC_ASSOCIATION_ASSIGN } } } extension AssociationPolicy: Hashable { public var hashValue: Int { return runtimeValue.hashValue } } public func ==(lhs: AssociationPolicy, rhs: AssociationPolicy) -> Bool { switch (lhs, rhs) { case (.Unowned, .Unowned): return true case (.Strong(let latomic), .Strong(let ratomic)): return latomic == ratomic case (.Copying(let latomic), .Copying(let ratomic)): return latomic == ratomic default: return false } }
8f73e6bc7669b96e559330afbb2af72a
24.4375
72
0.63964
false
false
false
false
heoiu87/WalmartStoreLocator
refs/heads/master
Walmart Store Locator/Walmart Store Locator/ViewController.swift
mit
1
// // ViewController.swift // Walmart Store Locator // // Created by Brian Nguyen on 8/23/15. // Copyright (c) 2015 Samoset & Squanto. All rights reserved. // import UIKit class ViewController: UIViewController, NSURLConnectionDelegate { @IBOutlet weak var CityNameTextBox: UITextField! @IBOutlet weak var ZIPcodeTextBox: UITextField! @IBOutlet weak var LocationsTextView: UITextView! lazy var data = NSMutableData() var locations = Array<NSDictionary>() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func SearchButton(sender: UIButton) { var input = ZIPcodeTextBox.text startConnection(input) } func startConnection(zipcode:String) { let urlPath: String = "http://api.walmartlabs.com/v1/stores?apiKey=teeauzr2tm7867rfk6atybug&zip=\(zipcode)&format=json" var url: NSURL = NSURL(string: urlPath)! var request: NSURLRequest = NSURLRequest(URL: url) var connection: NSURLConnection = NSURLConnection(request: request, delegate: self, startImmediately: false)! connection.start() } func connection(connection: NSURLConnection!, didReceiveData data: NSData!){ self.data.appendData(data) } func connectionDidFinishLoading(connection: NSURLConnection!) { var err: NSError // throwing an error on the line below (can't figure out where the error message is) var jsonResult: Array<NSDictionary> = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as! Array<NSDictionary> locations = jsonResult println(locations) } }
aa362246252e46ee0f6bafd3e9dfe223
33.890909
175
0.69359
false
false
false
false
svbeemen/Eve
refs/heads/master
Eve/Eve/SavedDataManager.swift
mit
1
// // SaveData.swift // Eve // // Created by Sangeeta van Beemen on 24/06/15. // Copyright (c) 2015 Sangeeta van Beemen. All rights reserved. import Foundation import UIKit class SavedDataManager { class var sharedInstance : SavedDataManager { struct Static { static let instance : SavedDataManager = SavedDataManager() } return Static.instance } let defaults = NSUserDefaults.standardUserDefaults() private let PAST_KEY = "pastCycleDates" private let PREDICTED_KEY = "predictedCycleDates" private let PASTMENSTRUATIONS_KEY = "pastMenstruationDates" // Save predicted cycle dates func savePredictedCycleDates(predictedCycleDates: [CycleDate]) { let myData = NSKeyedArchiver.archivedDataWithRootObject(predictedCycleDates) defaults.setObject(myData, forKey: PREDICTED_KEY) } // Retrieve saved predicted cycle dates or return empty array if their are no saved dates. func getPredictedCycleDates() -> [CycleDate] { if (defaults.objectForKey(PREDICTED_KEY) as? NSData) != nil { let savedDated: NSData = defaults.objectForKey(PREDICTED_KEY) as! NSData let myData = NSKeyedUnarchiver.unarchiveObjectWithData(savedDated) as! [CycleDate] return myData } return [CycleDate]() } // Save past cycle dates. func savePastCycleDates(pastCycleDates: [CycleDate]) { let myData = NSKeyedArchiver.archivedDataWithRootObject(pastCycleDates) defaults.setObject(myData, forKey: PAST_KEY) } // Retrieve saved past cycle dates or return empty array if their are no saved dates. func getPastCycleDates() -> [CycleDate] { if (defaults.objectForKey(PAST_KEY) as? NSData) != nil { let savedDated: NSData = defaults.objectForKey(PAST_KEY) as! NSData let myData = NSKeyedUnarchiver.unarchiveObjectWithData(savedDated) as! [CycleDate] return myData } return [CycleDate]() } // Save past menstruation date func savePastMenstruationDates(pastMenstruationDates: [CycleDate]) { let myData = NSKeyedArchiver.archivedDataWithRootObject(pastMenstruationDates) defaults.setObject(myData, forKey: PASTMENSTRUATIONS_KEY) } // Retrieve past menstruation dates or return empty array if their are no saved dates. func getPastMenstruationDates() -> [CycleDate] { if (defaults.objectForKey(PASTMENSTRUATIONS_KEY) as? NSData) != nil { let savedDated: NSData = defaults.objectForKey(PASTMENSTRUATIONS_KEY) as! NSData let myData = NSKeyedUnarchiver.unarchiveObjectWithData(savedDated) as! [CycleDate] return myData } return [CycleDate]() } }
81b8207cca8b3ce54f612ec7559ffc72
32.27907
94
0.665968
false
false
false
false
jduquennoy/Log4swift
refs/heads/master
Log4swift/Appenders/FileAppender.swift
apache-2.0
1
// // FileAppender.swift // Log4swift // // Created by Jérôme Duquennoy on 16/06/2015. // Copyright © 2015 Jérôme Duquennoy. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import Foundation /** This appender will write logs to a file. If file does not exist, it will be created on the first log, or re-created if deleted or moved (compatible with log rotate systems). */ public class FileAppender : Appender { public enum DictionaryKey: String { case FilePath = "FilePath" case MaxFileAge = "MaxFileAge" case MaxFileSize = "MaxFileSize" } @objc public internal(set) var filePath : String { didSet { if let safeHandler = self.fileHandler { safeHandler.closeFile() self.fileHandler = nil } self.filePath = (self.filePath as NSString).expandingTildeInPath didLogFailure = false } } /// The rotation policies to apply. The file will be rotated if at least /// one of the registered policies requests it. /// If none are registered, the file will never be rotated. public var rotationPolicies = [FileAppenderRotationPolicy]() public var maxFileSize: UInt64? /// The maximum number of rotated log files kept. /// Files exceeding this limit will be deleted during rotation. public var maxRotatedFiles: UInt? private var fileHandler: FileHandle? private var currentFileSize: UInt64? private var didLogFailure = false private var loggingMutex = PThreadMutex() @objc public init(identifier: String, filePath: String) { self.fileHandler = nil self.currentFileSize = nil self.filePath = (filePath as NSString).expandingTildeInPath super.init(identifier) } /// - Parameter identifier: the identifier of the appender. /// - Parameter filePath: the path to the logfile. If possible and needed, the directory /// structure will be created when creating the log file. /// - Parameter maxFileSize: the maximum size of the file in octets before rotation is triggered. /// Nil or zero disables the file size trigger for rotation. Default value is nil. /// - Parameter maxFileAge: the maximum age of the file in seconds before rotation is triggered. /// Nil or zero disables the file age trigger for rotation. Default value is nil. public convenience init(identifier: String, filePath: String, rotationPolicies: [FileAppenderRotationPolicy]? = nil) { self.init(identifier: identifier, filePath: filePath) if let rotationPolicies = rotationPolicies { self.rotationPolicies.append(contentsOf: rotationPolicies) } } public required convenience init(_ identifier: String) { self.init(identifier: identifier, filePath: "/dev/null") } public override func update(withDictionary dictionary: Dictionary<String, Any>, availableFormatters: Array<Formatter>) throws { try super.update(withDictionary: dictionary, availableFormatters: availableFormatters) if let safeFilePath = (dictionary[DictionaryKey.FilePath.rawValue] as? String) { self.filePath = safeFilePath } else { self.filePath = "placeholder" throw NSError.Log4swiftError(description: "Missing '\(DictionaryKey.FilePath.rawValue)' parameter for file appender '\(self.identifier)'") } if let maxFileAge = (dictionary[DictionaryKey.MaxFileAge.rawValue] as? Int) { let existingRotationPolicy = self.rotationPolicies.find { ($0 as? DateRotationPolicy) != nil } as? DateRotationPolicy if let existingRotationPolicy = existingRotationPolicy { existingRotationPolicy.maxFileAge = TimeInterval(maxFileAge) } else { self.rotationPolicies.append(DateRotationPolicy(maxFileAge: TimeInterval(maxFileAge))) } } if let maxFileSize = (dictionary[DictionaryKey.MaxFileSize.rawValue] as? Int) { let existingRotationPolicy = self.rotationPolicies.find { ($0 as? SizeRotationPolicy) != nil } as? SizeRotationPolicy if let existingRotationPolicy = existingRotationPolicy { existingRotationPolicy.maxFileSize = UInt64(maxFileSize) } else { self.rotationPolicies.append(SizeRotationPolicy(maxFileSize: UInt64(maxFileSize))) } } } /// This is the only entry point to log. /// It is thread safe, calling that method from multiple threads will not // cause logs to interleave, or mess with the rotation mechanism. public override func performLog(_ log: String, level: LogLevel, info: LogInfoDictionary) { var normalizedLog = log if(!normalizedLog.hasSuffix("\n")) { normalizedLog = normalizedLog + "\n" } loggingMutex.sync { try? rotateFileIfNeeded() guard createFileHandlerIfNeeded() else { return } if let dataToLog = normalizedLog.data(using: String.Encoding.utf8, allowLossyConversion: true) { self.fileHandler?.write(dataToLog) self.rotationPolicies.forEach { $0.appenderDidAppend(data: dataToLog)} } } } /// - returns: true if the file handler can be used, false if not. private func createFileHandlerIfNeeded() -> Bool { let fileManager = FileManager.default do { if !fileManager.fileExists(atPath: self.filePath) { self.fileHandler = nil let directoryPath = (filePath as NSString).deletingLastPathComponent try fileManager.createDirectory(atPath: directoryPath, withIntermediateDirectories: true, attributes: nil) fileManager.createFile(atPath: filePath, contents: nil, attributes: nil) self.currentFileSize = 0 } if self.fileHandler == nil { self.fileHandler = FileHandle(forWritingAtPath: self.filePath) self.fileHandler?.seekToEndOfFile() } self.rotationPolicies.forEach { $0.appenderDidOpenFile(atPath: self.filePath) } didLogFailure = false } catch (let error) { if(!didLogFailure) { NSLog("Appender \(self.identifier) failed to open log file \(self.filePath) : \(error)") didLogFailure = true self.fileHandler = nil } } return self.fileHandler != nil } private func rotateFileIfNeeded() throws { let shouldRotate = self.rotationPolicies.contains { $0.shouldRotate() } guard shouldRotate else { return } self.fileHandler?.closeFile() self.fileHandler = nil let fileManager = FileManager.default let fileUrl = URL(fileURLWithPath: self.filePath) let logFileName = fileUrl.lastPathComponent let logFileDirectory = fileUrl.deletingLastPathComponent() let files = try fileManager.contentsOfDirectory(atPath: logFileDirectory.path) .filter { $0.hasPrefix(logFileName) } .sorted {$0.localizedStandardCompare($1) == .orderedAscending } .reversed() var currentFileIndex = UInt(files.count) try files.forEach { currentFileName in let newFileName = logFileName.appending(".\(currentFileIndex)") let currentFilePath = logFileDirectory.appendingPathComponent(currentFileName) let rotatedFilePath = logFileDirectory.appendingPathComponent(newFileName) if let maxRotatedFiles = self.maxRotatedFiles, currentFileIndex > maxRotatedFiles { try fileManager.removeItem(at: currentFilePath) } else { try fileManager.moveItem(at: currentFilePath, to: rotatedFilePath) } currentFileIndex -= 1 } } }
ad5c689ce64674b968c375630d6841b7
38.293532
141
0.708154
false
false
false
false
yajeka/PS
refs/heads/master
PS/Master/CreatePostViewController.swift
lgpl-3.0
1
// // CreatePostViewController.swift // PS // // Created by Andrew Rudsky on 3/20/16. // Copyright © 2016 hackathon. All rights reserved. // import UIKit class CreatePostViewController : UITableViewController { var extendedSectionCell : Int = -1; var tabC: UITabBarController? override func viewDidLoad() { super.viewDidLoad(); let backgroundView = UIImageView(frame: view.bounds) backgroundView.image = UIImage(named: "background") tableView.backgroundView = backgroundView navigationController?.navigationBar.setBackgroundImage(UIImage(), forBarMetrics: UIBarMetrics.Default) navigationController?.navigationBar.shadowImage = UIImage() navigationController?.navigationBar.translucent = true navigationController?.navigationBar.tintColor = UIColor.whiteColor() toggleDone() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning(); } func doneActivated() { tabC?.selectedIndex = 0 dismissViewControllerAnimated(true, completion: nil) } func toggleDone() { if extendedSectionCell == -1 { navigationItem.rightBarButtonItem = nil; } else { navigationController?.navigationBarHidden = false navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Post", style: UIBarButtonItemStyle.Done, target: self, action: Selector("doneActivated")) } } //MARK: TableView override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: false); if(extendedSectionCell == indexPath.section) { } else { extendedSectionCell = indexPath.section } toggleDone() tableView.reloadData() } override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { var result : CGFloat = 120; if indexPath.section == extendedSectionCell { switch indexPath.row { case 0: break; case 1: result = 140.0; break; case 2: result = 50.0; break; default: break; } } else { switch indexPath.row { case 0: break; case 1: result = 0.0; break; case 2: result = 0.0; break; default: break; } } return result; } }
930a3e6c81e0b55d4ea1b34b87583a89
26.201923
161
0.56082
false
false
false
false
biohazardlover/ROer
refs/heads/master
Roer/Filter.swift
mit
1
import Foundation class Filter: NSObject { var predicates: [String] { var predicates = [String]() for filterCategory in filterCategories { if filterCategory.type == FilterCategoryType.More.rawValue { for filterItem in filterCategory.filterItems ?? [] { if let predicate = filterItem.predicate { predicates.append(predicate) } } } else { if let predicate = filterCategory.selectedFilterItem?.predicate { predicates.append(predicate) } } } return predicates } var sortDescriptors: [NSSortDescriptor] { var sortDescriptors = [NSSortDescriptor]() for filterCategory in filterCategories { if let sortDescriptor = filterCategory.selectedFilterItem?.sortDescriptor { sortDescriptors.append(sortDescriptor) } } return sortDescriptors } var filterCategories = [FilterCategory]() } extension Filter { convenience init(contentsOfURL url: URL) { self.init() if let dictionary = NSDictionary(contentsOf: url) as? [AnyHashable: Any] { if let filterCategories = dictionary["FilterCategories"] as? [[AnyHashable: Any]] { self.filterCategories = filterCategories.map({ (filterCategory) -> FilterCategory in return FilterCategory(contents: filterCategory as [NSObject : AnyObject]) }) } } } }
d4b790b640c1072a410ce2760373cf6e
28.803571
100
0.550629
false
false
false
false
wisonlin/HackingDesigner
refs/heads/master
HackingDesigner/Pages/FeedsViewController.swift
mit
1
// // FeedsViewController.swift // HackingDesigner // // Created by wison on 4/4/16. // Copyright © 2016 HomeStudio. All rights reserved. // import UIKit import Kingfisher import GearRefreshControl import ReachabilitySwift import ImageViewer class FeedsViewController: UITableViewController, ImageProvider, FeedCellDelegate { var feeds = [Feed]() var feedPage = 1 var gearRefreshControl : GearRefreshControl! var fetchFeeds: ((Int, complete: ([Feed]) -> ()) -> ())! var reachability: Reachability? // MARK: - View Life Cycled override func viewDidLoad() { do { reachability = try Reachability.reachabilityForInternetConnection() } catch { reachability = nil } gearRefreshControl = GearRefreshControl(frame: self.view.bounds) gearRefreshControl.addTarget(self, action: #selector(onRefresh), forControlEvents: UIControlEvents.ValueChanged) self.refreshControl = gearRefreshControl gearRefreshControl.beginRefreshing() self.onRefresh() } // MARK: - Pull Refresh func onRefresh() { feedPage = 1 fetchFeeds(feedPage) { (feeds: [Feed]) in self.feeds = feeds self.gearRefreshControl.endRefreshing() self.tableView.reloadData() } } override func scrollViewDidScroll(scrollView: UIScrollView) { gearRefreshControl.scrollViewDidScroll(scrollView) } // MARK: - UITableViewDelegate & DataSource Methods override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return feeds.count } override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 340 } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("PhotoCell") as! FeedCell cell.indexPath = indexPath cell.delegate = self let feed = feeds[indexPath.row] var imageUrl: NSURL! if let imageURL = NSURL(string: feed.images.teaser) { imageUrl = imageURL } if let reachability = reachability { if (reachability.isReachableViaWiFi()) { if let imageURL = NSURL(string: feed.images.normal) { imageUrl = imageURL } } } cell.photoView.kf_setImageWithURL(imageUrl) if let avatarURL = NSURL(string: feed.user.avatarUrl) { cell.avatarView.kf_setImageWithURL(avatarURL) } cell.userNameLabel.text = feed.user.name cell.titleLabel.text = feed.title cell.viewsCountLabel.text = "\(feed.viewsCount) views" cell.likesCountLabel.titleLabel?.text = "\(feed.likesCount) likes" if feeds.count - 3 == indexPath.row { feedPage += 1 fetchFeeds(feedPage) { (feeds: [Feed]) in self.feeds.appendContentsOf(feeds) self.tableView.reloadData() } } return cell } var selectedIndexPath: NSIndexPath! // MARK: - FeedCellDelegate Methods func onFeedCellPhotoTapped(feedCell: FeedCell) { self.selectedIndexPath = feedCell.indexPath let imageProvider = self let buttonAssets = CloseButtonAssets(normal: UIImage(named:"first")!, highlighted: UIImage(named: "second")) let configuration = ImageViewerConfiguration(imageSize: CGSize(width: 10, height: 10), closeButtonAssets: buttonAssets) let imageViewer = ImageViewer(imageProvider: imageProvider, configuration: configuration, displacedView: feedCell.photoView!) self.presentImageViewer(imageViewer) } func onFeedCellLikeButtonTapped(feedCell: FeedCell) { let feed = feeds[feedCell.indexPath!.row] FeedManager().likeFeeds(feed) { (like: Like) in } } // MARK: - ImageProvider Methods func provideImage(completion: UIImage? -> Void) { let feed = self.feeds[selectedIndexPath.row] var imageUrl: NSURL! if let imageURL = NSURL(string: feed.images.normal) { imageUrl = imageURL } if let reachability = reachability { if (reachability.isReachableViaWiFi()) { if let imageURL = NSURL(string: feed.images.hidpi) { imageUrl = imageURL } } } KingfisherManager.sharedManager.retrieveImageWithURL(imageUrl, optionsInfo: nil, progressBlock: nil) { (image, error, cacheType, imageURL) in completion(image) } } func provideImage(atIndex index: Int, completion: UIImage? -> Void) { } }
70d5438b568bb88063117b376b0d24c0
31.031646
149
0.609563
false
false
false
false
admkopec/BetaOS
refs/heads/x86_64
Kernel/Swift Extensions/TextFile.swift
apache-2.0
1
// // TextFile.swift // Kernel // // Created by Adam Kopeć on 3/29/18. // Copyright © 2018 Adam Kopeć. All rights reserved. // import Loggable class TextFile: File, Loggable { let Name: String = "Text File" var text: String { get { return String(utf8Characters: file.Data) ?? "" } set { var buf = ContiguousArray<UInt8>(newValue.utf8) file.Info.Size = newValue.utf8.count file.Data.deallocate() file.Data = MutableData(start: &buf[0], count: buf.count) writeToDisk() } } required init?(partition: Partition, path: String) { super.init(partition: partition, path: path) //MARK: Should I check extension for Plain Text or only for Rich and if fail then force Plain? guard file.Info.Extension == "TXT" || file.Info.Extension == "PLI" || file.Info.Extension == "XML" else { Log("File didn't pass Extension checks for plain text", level: .Error) file.Data.deallocate() return nil } } }
13882ad651fdc187dd6c67871e412bc5
29.971429
113
0.581181
false
false
false
false
JonathanAhrenkiel-Frellsen/WorkWith-fitnes
refs/heads/master
KomITEksamen/KomITEksamen/CelenderViewController.swift
lgpl-3.0
1
// // CelenderViewController.swift // KomITEksamen // // Created by Jonathans Macbook Pro on 26/04/2017. // Copyright © 2017 skycode. All rights reserved. // import UIKit import EventKit import FirebaseAuth import Firebase class CelenderViewController: UIViewController { var eventName = String() var eventStartDate = String() var eventEndDate = String() var activeDays = [String] () override func viewDidLoad() { super.viewDidLoad() let userID = FIRAuth.auth()?.currentUser?.uid // DataService.ds.REF_USER.child(userID!).observeSingleEvent(of: .value, with: { (snapshot) in // if let eventDict = snapshot.value as? Dictionary<String, AnyObject> { // let user = UsersModel(userData: eventDict) // // self.eventName = user.category // // // reformats the string date stored in firebase and formats it as Date // // alternativly i could have stored secundsSince 1970 in firebase af int, and format from there, but i'm lazy xd, this would also solve time zone problems //// let dateFormatter = DateFormatter() //// dateFormatter.dateFormat = "yyyy-MM-dd" //// //// let dateStart = dateFormatter.date(from: user.startDate) //// let dateEnd = dateFormatter.date(from: user.startDate) // // self.eventStartDate = user.startDate // self.eventEndDate = user.endDate // // self.activeDays = user.acriveDays.components(separatedBy: [","]) // // for day in self.activeDays { // let date = Date() // let formatter = DateFormatter() // // formatter.dateFormat = "dd.MM.yyyy" // // let currentDate = formatter.string(from: date) // // //self.getDayOfWeek(today: currentDate) // // print(currentDate) // } // } // }) func getDayOfWeek(today:String)->Int { let formatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd" let todayDate = formatter.date(from: today)! let myCalendar = NSCalendar(calendarIdentifier: NSCalendar.Identifier.gregorian)! let myComponents = myCalendar.components(.weekday, from: todayDate) let weekDay = myComponents.weekday return weekDay! } // let eventStore = EKEventStore(); // // if let calendarForEvent = eventStore.calendarWithIdentifier(self.calendar.calendarIdentifier) { // let newEvent = EKEvent(eventStore: eventStore) // // newEvent.calendar = calendarForEvent // newEvent.title = "Some Event Name" // newEvent.startDate = eventStartDate // newEvent.endDate = eventEndDate // } //let event = EKEvent(eventStore: eventStore) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
3f6cf86487d397d31f1e82277ce35a0f
36.2
172
0.548984
false
false
false
false
Sadmansamee/quran-ios
refs/heads/master
Quran/ConnectionsPool.swift
mit
1
// // ConnectionsPool.swift // Quran // // Created by Mohamed Afifi on 10/30/16. // Copyright © 2016 Quran.com. All rights reserved. // import Foundation import SQLite import CSQLite final class ConnectionsPool { static var `default`: ConnectionsPool = ConnectionsPool() var pool: [String: (uses: Int, connection: Connection)] = [:] func getConnection(filePath: String) throws -> Connection { if let (uses, connection) = pool[filePath] { pool[filePath] = (uses + 1, connection) return connection } else { do { let connection = try Connection(filePath, readonly: false) pool[filePath] = (1, connection) return connection } catch { Crash.recordError(error, reason: "Cannot open connection to sqlite file '\(filePath)'.") throw PersistenceError.openDatabase(error) } } } func close(connection: Connection) { let filePath = String(cString: sqlite3_db_filename(connection.handle, nil)) if let (uses, connection) = pool[filePath] { if uses <= 1 { pool[filePath] = nil // remove it } else { pool[filePath] = (uses - 1, connection) } } else { CLog("Warning: Closing connection multiple times '\(filePath)'") } } }
a6d04f0034e4a9fe5a75861c62115f47
29.12766
104
0.565678
false
false
false
false
ozpopolam/TrivialAsia
refs/heads/master
TrivialAsia/TriviaViewAdapted.swift
mit
1
// // TriviaAdapted.swift // TrivialAsia // // Created by Anastasia Stepanova-Kolupakhina on 25.05.17. // Copyright © 2017 Anastasia Kolupakhina. All rights reserved. // import Foundation class TriviaViewAdapted { var id = 0 var difficulty = "" var question = "" var answers = [String]() init(fromTrivia trivia: Trivia) { id = trivia.id difficulty = trivia.difficulty question = trivia.question answers.append(trivia.correctAnswer) answers.append(contentsOf: trivia.incorrectAnswers) answers.shuffle(withStubbornnessLevel: 3) } }
2cb23397913492aea4929a682ea49c95
21.777778
64
0.660163
false
false
false
false
arvindhsukumar/PredicateEditor
refs/heads/master
Example/Pods/SeedStackViewController/StackViewController/AutoScrollView.swift
mit
1
// // AutoScrollView.swift // Seed // // Created by Indragie Karunaratne on 2016-03-10. // Copyright © 2016 Seed Platform, Inc. All rights reserved. // import UIKit /// A scroll view that automatically scrolls to a subview of its `contentView` /// when the keyboard is shown. This replicates the behaviour implemented by /// `UITableView`. public class AutoScrollView: UIScrollView { private struct Constants { static let DefaultAnimationDuration: NSTimeInterval = 0.25 static let DefaultAnimationCurve = UIViewAnimationCurve.EaseInOut static let ScrollAnimationID = "AutoscrollAnimation" } /// The content view to display inside the container view. Views can also /// be added directly to this view without using the `contentView` property, /// but it simply makes it more convenient for the common case where your /// content fills the bounds of the scroll view. public var contentView: UIView? { willSet { contentView?.removeFromSuperview() } didSet { if let contentView = contentView { addSubview(contentView) updateContentViewConstraints() } } } private var contentViewConstraints: [NSLayoutConstraint]? override public var contentInset: UIEdgeInsets { didSet { updateContentViewConstraints() } } private func updateContentViewConstraints() { if let constraints = contentViewConstraints { NSLayoutConstraint.deactivateConstraints(constraints) } if let contentView = contentView { contentViewConstraints = contentView.activateSuperviewHuggingConstraints(insets: contentInset) } else { contentViewConstraints = nil } } private func commonInit() { let nc = NSNotificationCenter.defaultCenter() nc.addObserver(self, selector: #selector(AutoScrollView.keyboardWillShow(_:)), name: UIKeyboardWillShowNotification, object: nil) nc.addObserver(self, selector: #selector(AutoScrollView.keyboardWillHide(_:)), name: UIKeyboardWillHideNotification, object: nil) } public override init(frame: CGRect) { super.init(frame: frame) commonInit() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } deinit { NSNotificationCenter.defaultCenter().removeObserver(self) } // MARK: Notifications // Implementation based on code from Apple documentation // https://developer.apple.com/library/ios/documentation/StringsTextFonts/Conceptual/TextAndWebiPhoneOS/KeyboardManagement/KeyboardManagement.html @objc private func keyboardWillShow(notification: NSNotification) { let keyboardFrameValue = notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue guard var keyboardFrame = keyboardFrameValue?.CGRectValue() else { return } keyboardFrame = convertRect(keyboardFrame, fromView: nil) let bottomInset: CGFloat let keyboardIntersectionRect = bounds.intersect(keyboardFrame) if !keyboardIntersectionRect.isNull { bottomInset = keyboardIntersectionRect.height let contentInset = UIEdgeInsets(top: 0, left: 0, bottom: bottomInset, right: 0) super.contentInset = contentInset scrollIndicatorInsets = contentInset } else { bottomInset = 0.0 } guard let firstResponder = firstResponder else { return } let firstResponderFrame = firstResponder.convertRect(firstResponder.bounds, toView: self) var contentBounds = CGRect(origin: contentOffset, size: bounds.size) contentBounds.size.height -= bottomInset if !contentBounds.contains(firstResponderFrame.origin) { let duration = notification.userInfo?[UIKeyboardAnimationDurationUserInfoKey] as? NSTimeInterval ?? Constants.DefaultAnimationDuration let curve = notification.userInfo?[UIKeyboardAnimationCurveUserInfoKey] as? UIViewAnimationCurve ?? Constants.DefaultAnimationCurve // Dropping down to the old style UIView animation API because the new API // does not support setting the curve directly. The other option is to take // `curve` and shift it left by 16 bits to turn it into a `UIViewAnimationOptions`, // but that seems uglier than just doing this. UIView.beginAnimations(Constants.ScrollAnimationID, context: nil) UIView.setAnimationCurve(curve) UIView.setAnimationDuration(duration) scrollRectToVisible(firstResponderFrame, animated: false) UIView.commitAnimations() } } @objc private func keyboardWillHide(notification: NSNotification) { super.contentInset = UIEdgeInsetsZero scrollIndicatorInsets = UIEdgeInsetsZero } } private extension UIView { var firstResponder: UIView? { if isFirstResponder() { return self } for subview in subviews { if let responder = subview.firstResponder { return responder } } return nil } }
c4e89abfb847851208f7771674fd6721
38.776119
150
0.669794
false
false
false
false
Malecks/PALette
refs/heads/master
Palette/NavigationTitleView.swift
mit
1
// // NavigationTitleView.swift // Palette // // Created by Alex Mathers on 2017-06-01. // Copyright © 2017 Malecks. All rights reserved. // import UIKit final class NavigationTitleView: UIView { @IBOutlet private weak var containerView: UIView! @IBOutlet private weak var leftIcon: UIImageView! @IBOutlet private weak var centerIcon: UIImageView! @IBOutlet private weak var rightIcon: UIImageView! @IBOutlet private weak var horizontalConstraint: NSLayoutConstraint! private lazy var icons: [UIImageView] = { return [self.leftIcon, self.centerIcon, self.rightIcon] }() lazy var iconOffset: CGFloat = { return (self.containerView.frame.width / 2.0) - (self.leftIcon.frame.width / 2.0) }() var tappedAtIndex: ((Int) -> ())? override func awakeFromNib() { super.awakeFromNib() for (i, icon) in icons.enumerated() { icon.image = icon.image?.withRenderingMode(.alwaysTemplate) icon.tintColor = .lightGray icon.tag = i let tap = UITapGestureRecognizer(target: self, action: #selector(self.didTapAtIndex(sender:))) icon.addGestureRecognizer(tap) } highlightIcon(at: 1) } @objc func didTapAtIndex(sender: UITapGestureRecognizer) { guard let view = sender.view else { return } self.tappedAtIndex?(view.tag) } func scroll(to index: Int) { guard index < icons.count else { return } var offset: CGFloat switch index { case 0: offset = iconOffset case 2: offset = -iconOffset default: offset = 0 } horizontalConstraint.constant = offset UIView.animate(withDuration: 0.25, delay: 0.0, options: .curveEaseOut, animations: { self.highlightIcon(at: index) self.layoutIfNeeded() }, completion: nil) } private func highlightIcon(at index: Int) { guard index < icons.count else { return } for (i, icon) in icons.enumerated() { icon.tintColor = i == index ? .black : .lightGray } } class func instanceFromNib() -> UIView? { let nib = UINib(nibName: "NavigationTitleView", bundle: nil) .instantiate(withOwner: nil, options: nil) for view in nib { if let view = view as? NavigationTitleView { return view } } return nil } }
24e82529745b856589614de614ac6535
29.130952
106
0.591861
false
false
false
false
googlearchive/science-journal-ios
refs/heads/master
ScienceJournalTests/Metadata/ExperimentDataParserTest.swift
apache-2.0
1
/* * Copyright 2019 Google LLC. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import XCTest @testable import third_party_sciencejournal_ios_ScienceJournalOpen class ExperimentDataParserTest: XCTestCase { // MARK: - Properties let trial = Trial() var experimentDataParser: ExperimentDataParser! var sensor1: Sensor! var sensor2: Sensor! let sensorTrialStat1Minimum = 5.0 let sensorTrialStat1Maximum = 6.0 let sensorTrialStat1Average = 5.5 let sensorTrialStat2Minimum = 7.0 let sensorTrialStat2Maximum = 9.0 let sensorTrialStat2Average = 8.0 // MARK: - XCTest override func setUp() { super.setUp() let metadataManager = createMetadataManager() experimentDataParser = ExperimentDataParser(experimentID: "TEST", metadataManager: metadataManager, sensorController: MockSensorController()) sensor1 = Sensor.mock(sensorId: "TestSensorID1", name: "TestSensorName1", textDescription: "Test description 1.", iconName: "test icon 1", unitDescription: "sin") sensor2 = Sensor.mock(sensorId: "TestSensorID2", name: "TestSensorName2", textDescription: "Test description 2.", iconName: "test icon 2") setupTrial() } // MARK: - Test cases func testParsedTrials() { let trials = [Trial(), Trial(), Trial(), Trial()] let parsedTrials = experimentDataParser.parsedTrials(trials) XCTAssertEqual(parsedTrials.count, trials.count, "The number of parsed trials should equal the number of trials.") } func testParsedTrialSensorCount() { let displayTrial = experimentDataParser.parseTrial(trial) let trialSensors = displayTrial.sensors XCTAssertEqual(trialSensors.count, 2, "There should be a trial sensor for each sensor.") } func testParsedTrialSensorTitles() { let experimentTrialData = experimentDataParser.parseTrial(trial) let trialSensors = experimentTrialData.sensors XCTAssertEqual(trialSensors[0].title, "\(sensor1.name) (\(sensor1.unitDescription!))", "The trial sensor title should be the sensor name.") XCTAssertEqual(trialSensors[1].title, sensor2.name, "The trial sensor title should be the sensor name.") } func testParsedTrialSensorTimestamp() { Timestamp.dateFormatter.timeZone = TimeZone(abbreviation: "EDT") let experimentTrialData = experimentDataParser.parseTrial(trial) var expectedDateString: String if #available(iOS 11.0, *) { expectedDateString = "May 18, 2017 at 10:37 AM" } else { expectedDateString = "May 18, 2017, 10:37 AM" } XCTAssertEqual(expectedDateString, experimentTrialData.timestamp.string, "The timestamp should be properly parsed.") } func testParsedTrialSensorDataStats() { let experimentTrialData = experimentDataParser.parseTrial(trial) let trialSensor1 = experimentTrialData.sensors[0] XCTAssertEqual(trialSensor1.minValueString, sensor1.string(for: sensorTrialStat1Minimum), "The `minValueString` should be the same as the sensor's string(for:) string " + "for the minimum data point.") XCTAssertEqual(trialSensor1.maxValueString, sensor1.string(for: sensorTrialStat1Maximum), "The `maxValueString` should be the same as the sensor's string(for:) string " + "for the maximum data point.") XCTAssertEqual(trialSensor1.averageValueString, sensor1.string(for: sensorTrialStat1Average), "The `averageValueString` should be the same as the sensor's string(for:) " + "string for the maximum data point.") let trialSensor2 = experimentTrialData.sensors[1] XCTAssertEqual(trialSensor2.minValueString, sensor1.string(for: sensorTrialStat2Minimum), "The `minValueString` should be the same as the sensor's string(for:) string " + "for the minimum data point.") XCTAssertEqual(trialSensor2.maxValueString, sensor1.string(for: sensorTrialStat2Maximum), "The `maxValueString` should be the same as the sensor's string(for:) string " + "for the maximum data point.") XCTAssertEqual(trialSensor2.averageValueString, sensor1.string(for: sensorTrialStat2Average), "The `averageValueString` should be the same as the sensor's string(for:) " + "string for the maximum data point.") } func testParsedTrialNotesSortOrder() { let note1 = TextNote(text: "First") note1.timestamp = 1000 let note2 = TextNote(text: "Second") note1.timestamp = 2000 let note3 = TextNote(text: "Third") note1.timestamp = 3000 // Trial notes are added in non-chronological order. trial.notes = [note2, note3, note1] let displayTrial = experimentDataParser.parseTrial(trial) XCTAssertEqual(3, displayTrial.notes.count) XCTAssertEqual("First", (displayTrial.notes[0] as! DisplayTextNote).text) XCTAssertEqual("Second", (displayTrial.notes[1] as! DisplayTextNote).text) XCTAssertEqual("Third", (displayTrial.notes[2] as! DisplayTextNote).text) } func testParsedTextNote() { Timestamp.dateFormatter.timeZone = TimeZone(abbreviation: "EDT") let textNote = TextNote(text: "A text note") textNote.timestamp = 1496369345626 let experimentData = experimentDataParser.parseNote(textNote) as! DisplayTextNote XCTAssertEqual("A text note", experimentData.text) var expectedDateString: String if #available(iOS 11.0, *) { expectedDateString = "Jun 1, 2017 at 10:09 PM" } else { expectedDateString = "Jun 1, 2017, 10:09 PM" } XCTAssertEqual(expectedDateString, experimentData.timestamp.string) } func testParsedPictureNote() { Timestamp.dateFormatter.timeZone = TimeZone(abbreviation: "EDT") let pictureNote = PictureNote() pictureNote.timestamp = 1496369345626 pictureNote.filePath = "some_image_path" let experimentData = experimentDataParser.parseNote(pictureNote) as! DisplayPictureNote XCTAssertTrue(experimentData.imagePath!.hasSuffix(pictureNote.filePath!)) var expectedDateString: String if #available(iOS 11.0, *) { expectedDateString = "Jun 1, 2017 at 10:09 PM" } else { expectedDateString = "Jun 1, 2017, 10:09 PM" } XCTAssertEqual(expectedDateString, experimentData.timestamp.string) } func testParsedTrialNote() { let trial = Trial() let textNote = TextNote(text: "Some text here") let displayTextNote = experimentDataParser.parseNote(textNote, forTrial: trial) as! DisplayTextNote XCTAssertEqual("Some text here", displayTextNote.text) XCTAssertEqual(trial.ID, displayTextNote.trialID) let textNote2 = TextNote(text: "Another note") let displayTextNote2 = experimentDataParser.parseNote(textNote2, forTrial: nil) as! DisplayTextNote XCTAssertEqual("Another note", displayTextNote2.text) XCTAssertNil(displayTextNote2.trialID) } func testUnknownNoteType() { // Unknown subclass of Note. class OtherNote: Note {} let otherNote = OtherNote() let experimentData = experimentDataParser.parseNote(otherNote) XCTAssertNil(experimentData, "Unknown note types should return nil.") } func testAlternateTitle() { let experimentTrialData = experimentDataParser.parseTrial(trial) XCTAssertNil(experimentTrialData.title, "Trial title should be nil.") XCTAssertEqual("\(String.runDefaultTitle) 5", experimentTrialData.alternateTitle, "Alternate title should match default plus index+1.") } func testSnapshotTrialNoteTimestamp() { // Create a snapshot note with a sensor snapshot that has a given timestamp. let sensorSnapshot = SensorSnapshot() sensorSnapshot.timestamp = 10000 let snapshotNote = SnapshotNote(snapshots: [sensorSnapshot]) // Create a trial without a crop. let trial = Trial() trial.recordingRange.min = 5000 // Parse it into a display note for the trial. let displaySnapshotNote = experimentDataParser.parseNote(snapshotNote, forTrial: trial) as! DisplaySnapshotNote XCTAssertEqual( "0:05", displaySnapshotNote.snapshots[0].timestamp.string, "The display note timestamp should be the duration after the min recording range.") } func testSnapshotTrialNoteTimestampWithCrop() { // Create a snapshot note with a sensor snapshot that has a given timestamp. let sensorSnapshot = SensorSnapshot() sensorSnapshot.timestamp = 10000 let snapshotNote = SnapshotNote(snapshots: [sensorSnapshot]) // Create a trial with a crop. let trial = Trial() trial.recordingRange.min = 5000 trial.cropRange = ChartAxis(min: 7000, max: 15000) // Parse it into a display note for the trial. let displaySnapshotNote = experimentDataParser.parseNote(snapshotNote, forTrial: trial) as! DisplaySnapshotNote XCTAssertEqual( "0:03", displaySnapshotNote.snapshots[0].timestamp.string, "The display note timestamp should be the duration after the min crop range.") } // MARK: - Setup trial func setupTrial() { // ID, experiment index, creation time, recording range. trial.ID = "TrialId" trial.trialNumberInExperiment = 5 trial.creationDate = Date(milliseconds: 1495118240287) trial.recordingRange.min = 1234 trial.recordingRange.max = 5678 // Stats. let statsCalculator1 = StatCalculator() statsCalculator1.addDataPoint(DataPoint(x: 0, y: sensorTrialStat1Minimum)) statsCalculator1.addDataPoint(DataPoint(x: 1, y: sensorTrialStat1Maximum)) let sensorTrialStats1 = TrialStats(sensorID: sensor1.sensorId) sensorTrialStats1.addStatsFromStatCalculator(statsCalculator1) trial.trialStats.append(sensorTrialStats1) let statsCalculator2 = StatCalculator() statsCalculator2.addDataPoint(DataPoint(x: 0, y: sensorTrialStat2Minimum)) statsCalculator2.addDataPoint(DataPoint(x: 1, y: sensorTrialStat2Maximum)) let sensorTrialStats2 = TrialStats(sensorID: sensor2.sensorId) sensorTrialStats2.addStatsFromStatCalculator(statsCalculator2) trial.trialStats.append(sensorTrialStats2) // Layouts. let sensorLayout1 = SensorLayout(sensorID: sensor1.sensorId, colorPalette: .blue) trial.sensorLayouts.append(sensorLayout1) let sensorLayout2 = SensorLayout(sensorID: sensor2.sensorId, colorPalette: .blue) trial.sensorLayouts.append(sensorLayout2) // Appearance. trial.addSensorAppearance(BasicSensorAppearance(sensor: sensor1), for: sensor1.sensorId) trial.addSensorAppearance(BasicSensorAppearance(sensor: sensor2), for: sensor2.sensorId) } }
6aedbf2a94bb8684cfb1c5703b4c7875
39.775439
99
0.694949
false
true
false
false
recurly/recurly-client-ios
refs/heads/master
RecurlySDK-iOS/Models/REApplePaymentData.swift
mit
1
// // REApplePaymentData.swift // RecurlySDK-iOS // // Created by Carlos Landaverde on 21/6/22. // import Foundation public struct REApplePaymentData: Codable { let paymentData: REApplePaymentDataBody public init(paymentData: REApplePaymentDataBody = REApplePaymentDataBody()) { self.paymentData = paymentData } } public struct REApplePaymentDataBody: Codable { let version: String let data: String let signature: String let header: REApplePaymentDataHeader public init(version: String = String(), data: String = String(), signature: String = String(), header: REApplePaymentDataHeader = REApplePaymentDataHeader()) { self.version = version self.data = data self.signature = signature self.header = header } } public struct REApplePaymentDataHeader: Codable { let ephemeralPublicKey: String let publicKeyHash: String let transactionId: String public init(ephemeralPublicKey: String = String(), publicKeyHash: String = String(), transactionId: String = String()) { self.ephemeralPublicKey = ephemeralPublicKey self.publicKeyHash = publicKeyHash self.transactionId = transactionId } }
47ddc855ac6f72e4bdcb5110088dfb61
26.021277
81
0.677953
false
false
false
false
luosheng/OpenSim
refs/heads/master
OpenSim/SimulatorResetMenuItem.swift
mit
1
// // SimulatorResetMenuItem.swift // OpenSim // // Created by Craig Peebles on 14/10/19. // Copyright © 2019 Luo Sheng. All rights reserved. // import Cocoa class SimulatorResetMenuItem: NSMenuItem { var device: Device! init(device:Device) { self.device = device let title = "\(UIConstants.strings.menuResetSimulatorButton) \(device.name)" super.init(title: title, action: #selector(self.resetSimulator(_:)), keyEquivalent: "") target = self } required init(coder decoder: NSCoder) { fatalError("init(coder:) has not been implemented") } @objc func resetSimulator(_ sender: AnyObject) { let alert: NSAlert = NSAlert() alert.messageText = String(format: UIConstants.strings.actionFactoryResetAlertMessage, device.name) alert.alertStyle = .critical alert.addButton(withTitle: UIConstants.strings.actionFactoryResetAlertConfirmButton) alert.addButton(withTitle: UIConstants.strings.actionFactoryResetAlertCancelButton) let response = alert.runModal() if response == NSApplication.ModalResponse.alertFirstButtonReturn { SimulatorController.factoryReset(device) } } }
464cec6e184f754308a01af1044a1c4a
29.525
107
0.68878
false
false
false
false
devcarlos/NSDateUtils.swift
refs/heads/master
NSDateUtilsDemo/ViewController.swift
mit
1
// // ViewController.swift // NSDateUtilsDemo // // Created by Carlos Alcala on 6/2/16. // Copyright © 2016 Carlos Alcala. All rights reserved. // import UIKit import NSDateUtils class ViewController: UIViewController { let date = NSDate().dateFromString("10/12/2013") 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. } //MARK : Actions @IBAction func shortDate(sender: AnyObject) { //using format: yyyy-MM-dd let shortDate = date.convertToString() self.showAlert(shortDate) } @IBAction func longDate(sender: AnyObject) { //using format: EE, LLL d yyyy, HH:mm let longDate = date.convertToLongString() self.showAlert(longDate) } //MARK : Helper Functions func showAlert(message:String) { let alert = UIAlertController(title: "Date String", message: message, preferredStyle: .Alert) let okAction = UIAlertAction(title: "Ok", style: .Default, handler: nil) alert.addAction(okAction) self.presentViewController(alert, animated: true, completion: nil) } }
230d76079ccc5459ee131df7323249e8
25.519231
101
0.638144
false
false
false
false
warnerbros/cpe-manifest-ios-experience
refs/heads/master
Source/In-Movie Experience/ShoppingSceneDetailCollectionViewCell.swift
apache-2.0
1
// // ShoppingSceneDetailCollectionViewCell.swift // import Foundation import UIKit import CPEData enum ShoppingProductImageType { case product case scene } class ShoppingSceneDetailCollectionViewCell: SceneDetailCollectionViewCell { static let NibName = "ShoppingSceneDetailCollectionViewCell" static let ReuseIdentifier = "ShoppingSceneDetailCollectionViewCellReuseIdentifier" @IBOutlet weak private var imageView: UIImageView! @IBOutlet weak private var bullseyeImageView: UIImageView! @IBOutlet weak private var extraDescriptionLabel: UILabel! var productImageType = ShoppingProductImageType.product private var extraDescription: String? { set { extraDescriptionLabel?.text = newValue } get { return extraDescriptionLabel?.text } } private var currentProduct: ProductItem? { didSet { if currentProduct != oldValue { descriptionText = currentProduct?.brand extraDescription = currentProduct?.name if productImageType == .scene { setImageURL(currentProduct?.sceneImageURL ?? currentProduct?.productImageURL) } else { setImageURL(currentProduct?.productImageURL) } } if currentProduct == nil { currentProductFrameTime = -1 } } } private var currentProductFrameTime = -1.0 private var currentProductSessionDataTask: URLSessionDataTask? var products: [ProductItem]? { didSet { currentProduct = products?.first } } override func currentTimeDidChange() { if let timedEvent = timedEvent, timedEvent.isType(.product) { if let product = timedEvent.product { products = [product] } else { DispatchQueue.global(qos: .userInteractive).async { if let productAPIUtil = CPEXMLSuite.Settings.productAPIUtil { let newFrameTime = productAPIUtil.closestFrameTime(self.currentTime) if newFrameTime != self.currentProductFrameTime { self.currentProductFrameTime = newFrameTime if let currentTask = self.currentProductSessionDataTask { currentTask.cancel() } self.currentProductSessionDataTask = productAPIUtil.getFrameProducts(self.currentProductFrameTime, completion: { [weak self] (products) -> Void in self?.currentProductSessionDataTask = nil DispatchQueue.main.async { self?.products = products } }) } } } } } } override func prepareForReuse() { super.prepareForReuse() products = nil bullseyeImageView.isHidden = true if let task = currentProductSessionDataTask { task.cancel() currentProductSessionDataTask = nil } } override func layoutSubviews() { super.layoutSubviews() if productImageType == .scene, let product = currentProduct, product.bullseyePoint != CGPoint.zero { var bullseyeFrame = bullseyeImageView.frame let bullseyePoint = CGPoint(x: imageView.frame.width * product.bullseyePoint.x, y: imageView.frame.height * product.bullseyePoint.y) bullseyeFrame.origin = CGPoint(x: bullseyePoint.x + imageView.frame.minX - (bullseyeFrame.width / 2), y: bullseyePoint.y + imageView.frame.minY - (bullseyeFrame.height / 2)) bullseyeImageView.frame = bullseyeFrame bullseyeImageView.layer.shadowColor = UIColor.black.cgColor bullseyeImageView.layer.shadowOffset = CGSize(width: 1, height: 1) bullseyeImageView.layer.shadowOpacity = 0.75 bullseyeImageView.layer.shadowRadius = 2 bullseyeImageView.clipsToBounds = false bullseyeImageView.isHidden = false } else { bullseyeImageView.isHidden = true } } private func setImageURL(_ imageURL: URL?) { if let url = imageURL { imageView.contentMode = .scaleAspectFit imageView.sd_setImage(with: url) } else { imageView.sd_cancelCurrentImageLoad() imageView.image = nil } } }
74e4c4ee3e5a90fed1e77576a1c173d8
34.305344
185
0.594162
false
false
false
false
zhangchn/swelly
refs/heads/master
swelly/PTY.swift
gpl-2.0
1
// // PTY.swift // swelly // // Created by ZhangChen on 05/10/2016. // // import Foundation import Darwin protocol PTYDelegate: NSObjectProtocol { func ptyWillConnect(_ pty: PTY) func ptyDidConnect(_ pty: PTY) func pty(_ pty: PTY, didRecv data: Data) func pty(_ pty: PTY, willSend data: Data) func ptyDidClose(_ pty: PTY) } func ctrlKey(_ c: String) throws -> UInt8 { if let c = c.unicodeScalars.first { if !c.isASCII { throw NSError(domain: "PTY", code: 1, userInfo: nil) } return UInt8(c.value) - UInt8("A".unicodeScalars.first!.value + 1) } else { throw NSError(domain: "PTY", code: 2, userInfo: nil) } } func fdZero(_ set: inout fd_set) { set.fds_bits = (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) } func fdSet(_ fd: Int32, set: inout fd_set) { let intOffset = Int(fd / 32) let bitOffset = fd % 32 let mask: __int32_t = 1 << bitOffset switch intOffset { case 0: set.fds_bits.0 = set.fds_bits.0 | mask case 1: set.fds_bits.1 = set.fds_bits.1 | mask case 2: set.fds_bits.2 = set.fds_bits.2 | mask case 3: set.fds_bits.3 = set.fds_bits.3 | mask case 4: set.fds_bits.4 = set.fds_bits.4 | mask case 5: set.fds_bits.5 = set.fds_bits.5 | mask case 6: set.fds_bits.6 = set.fds_bits.6 | mask case 7: set.fds_bits.7 = set.fds_bits.7 | mask case 8: set.fds_bits.8 = set.fds_bits.8 | mask case 9: set.fds_bits.9 = set.fds_bits.9 | mask case 10: set.fds_bits.10 = set.fds_bits.10 | mask case 11: set.fds_bits.11 = set.fds_bits.11 | mask case 12: set.fds_bits.12 = set.fds_bits.12 | mask case 13: set.fds_bits.13 = set.fds_bits.13 | mask case 14: set.fds_bits.14 = set.fds_bits.14 | mask case 15: set.fds_bits.15 = set.fds_bits.15 | mask case 16: set.fds_bits.16 = set.fds_bits.16 | mask case 17: set.fds_bits.17 = set.fds_bits.17 | mask case 18: set.fds_bits.18 = set.fds_bits.18 | mask case 19: set.fds_bits.19 = set.fds_bits.19 | mask case 20: set.fds_bits.20 = set.fds_bits.20 | mask case 21: set.fds_bits.21 = set.fds_bits.21 | mask case 22: set.fds_bits.22 = set.fds_bits.22 | mask case 23: set.fds_bits.23 = set.fds_bits.23 | mask case 24: set.fds_bits.24 = set.fds_bits.24 | mask case 25: set.fds_bits.25 = set.fds_bits.25 | mask case 26: set.fds_bits.26 = set.fds_bits.26 | mask case 27: set.fds_bits.27 = set.fds_bits.27 | mask case 28: set.fds_bits.28 = set.fds_bits.28 | mask case 29: set.fds_bits.29 = set.fds_bits.29 | mask case 30: set.fds_bits.30 = set.fds_bits.30 | mask case 31: set.fds_bits.31 = set.fds_bits.31 | mask default: break } } func fdIsset(_ fd: Int32, _ set: fd_set) -> Bool { let a = fd / 32 let mask: Int32 = 1 << (fd % 32) switch a { case 0: return (set.fds_bits.0 & mask) != 0 case 1: return (set.fds_bits.1 & mask) != 0 case 2: return (set.fds_bits.2 & mask) != 0 case 3: return (set.fds_bits.3 & mask) != 0 case 4: return (set.fds_bits.4 & mask) != 0 case 5: return (set.fds_bits.5 & mask) != 0 case 6: return (set.fds_bits.6 & mask) != 0 case 7: return (set.fds_bits.7 & mask) != 0 case 8: return (set.fds_bits.8 & mask) != 0 case 9: return (set.fds_bits.9 & mask) != 0 case 10: return (set.fds_bits.10 & mask) != 0 case 11: return (set.fds_bits.11 & mask) != 0 case 12: return (set.fds_bits.12 & mask) != 0 case 13: return (set.fds_bits.13 & mask) != 0 case 14: return (set.fds_bits.14 & mask) != 0 case 15: return (set.fds_bits.15 & mask) != 0 case 16: return (set.fds_bits.16 & mask) != 0 case 17: return (set.fds_bits.17 & mask) != 0 case 18: return (set.fds_bits.18 & mask) != 0 case 19: return (set.fds_bits.19 & mask) != 0 case 20: return (set.fds_bits.20 & mask) != 0 case 21: return (set.fds_bits.21 & mask) != 0 case 22: return (set.fds_bits.22 & mask) != 0 case 23: return (set.fds_bits.23 & mask) != 0 case 24: return (set.fds_bits.24 & mask) != 0 case 25: return (set.fds_bits.25 & mask) != 0 case 26: return (set.fds_bits.26 & mask) != 0 case 27: return (set.fds_bits.27 & mask) != 0 case 28: return (set.fds_bits.28 & mask) != 0 case 29: return (set.fds_bits.29 & mask) != 0 case 30: return (set.fds_bits.30 & mask) != 0 case 31: return (set.fds_bits.31 & mask) != 0 default: break } return false } class PTY { weak var delegate: PTYDelegate? var proxyType: ProxyType var proxyAddress: String private var connecting = false private var fd: Int32 = -1 private var pid: pid_t = 0 init(proxyAddress addr:String, proxyType type: ProxyType) { proxyType = type proxyAddress = addr } deinit { close() } func close() { if pid > 0 { kill(pid, SIGKILL) pid = 0 } if fd >= 0 { _ = Darwin.close(fd) fd = -1 delegate?.ptyDidClose(self) } } class func parse(addr: String) -> String { var addr = addr.trimmingCharacters(in: CharacterSet.whitespaces) if addr.contains(" ") { return addr; } var ssh = false var port: String? = nil var fmt: String! if addr.lowercased().hasPrefix("ssh://") { ssh = true let idx = addr.index(addr.startIndex, offsetBy: 6) addr = String(addr[idx...]) } else { if let range = addr.range(of: "://") { addr = String(addr[range.upperBound...]) } } if let range = addr.range(of: ":") { port = String(addr[range.upperBound...]) addr = String(addr[..<range.lowerBound]) } if ssh { if port == nil { port = "22" } fmt = "ssh -o Protocol=2,1 -p %2$@ -x %1$@" } else { if port == nil { port = "23" } if let range = addr.range(of: "@") { addr = String(addr[range.upperBound...]) } fmt = "/usr/bin/telnet -8 %@ -%@" } return String.init(format: fmt, addr, port!) } func connect(addr: String, connectionProtocol: ConnectionProtocol, userName: String!) -> Bool { let slaveName = UnsafeMutablePointer<Int8>.allocate(capacity: Int(PATH_MAX)) let iflag = tcflag_t(bitPattern: Int(ICRNL | IXON | IXANY | IMAXBEL | BRKINT)) let oflag = tcflag_t(bitPattern: Int(OPOST | ONLCR)) let cflag = tcflag_t(bitPattern: Int(CREAD | CS8 | HUPCL)) let lflag = tcflag_t(bitPattern: Int(ICANON | ISIG | IEXTEN | ECHO | ECHOE | ECHOK | ECHOKE | ECHOCTL)) let controlCharacters : (cc_t, cc_t, cc_t, cc_t, cc_t, cc_t, cc_t, cc_t, cc_t, cc_t, cc_t, cc_t, cc_t, cc_t, cc_t, cc_t, cc_t, cc_t, cc_t, cc_t) = try! (ctrlKey("D"), 0xff, 0xff, 0x7f, ctrlKey("W"), ctrlKey("U"), ctrlKey("R"), 0, ctrlKey("C"), 0x1c, ctrlKey("Z"), ctrlKey("Y"), ctrlKey("Q"), ctrlKey("S"), 0xff, 0xff, 1, 0, 0xff, 0) var term = termios(c_iflag: iflag, c_oflag: oflag, c_cflag: cflag, c_lflag: lflag, c_cc: controlCharacters, c_ispeed: speed_t(B38400), c_ospeed: speed_t(B38400)) let ws_col = GlobalConfig.sharedInstance.column let ws_row = GlobalConfig.sharedInstance.row var size = winsize(ws_row: UInt16(ws_row), ws_col: UInt16(ws_col), ws_xpixel: 0, ws_ypixel: 0) //var arguments = PTY.parse(addr: addr).components(separatedBy: " ") pid = forkpty(&fd, slaveName, &term, &size) if pid < 0 { print("Error forking pty: \(errno)") } else if pid == 0 { // child process //kill(0, SIGSTOP) var arguments: [String] var hostAndPort = addr.split(separator: ":") switch connectionProtocol { case .telnet: if hostAndPort.count == 2, let _ = Int(hostAndPort[1]) { arguments = ["/usr/bin/telnet", "-8", String(hostAndPort[0]), String(hostAndPort[1])] } else { arguments = ["/usr/bin/telnet", "-8", String(hostAndPort[0])] } case .ssh: if hostAndPort.count == 2 { if let _ = Int(hostAndPort[1]) { arguments = ["ssh", "-o", "Protocol=2,1", "-p", String(hostAndPort[1]), "-x", userName! + "@" + String(hostAndPort[0])] } else { arguments = ["ssh", "-o", "Protocol=2,1", "-p", "22", "-x", userName! + "@" + String(hostAndPort[0])] } } else { arguments = ["ssh", "-o", "Protocol=2,1", "-p", "22", "-x", userName! + "@" + String(hostAndPort[0])] } if let proxyCommand = Proxy.proxyCommand(address: proxyAddress, type: proxyType) { arguments.append("-o") arguments.append(proxyCommand) } } let argv = UnsafeMutablePointer<UnsafeMutablePointer<Int8>?>.allocate(capacity: arguments.count + 1) for (idx, arg) in arguments.enumerated() { argv[idx] = arg.utf8CString.withUnsafeBytes({ (buf) -> UnsafeMutablePointer<Int8> in let x = UnsafeMutablePointer<Int8>.allocate(capacity: buf.count + 1) memcpy(x, buf.baseAddress, buf.count) x[buf.count] = 0 return x }) } argv[arguments.count] = nil execvp(argv[0], argv) perror(argv[0]) sleep(UINT32_MAX) } else { // parent process var one = 1 let result = ioctl(fd, TIOCPKT, &one) if result == 0 { Thread.detachNewThread { self.readLoop() } } else { print("ioctl failure: erron: \(errno)") } } slaveName.deallocate() connecting = true delegate?.ptyWillConnect(self) return true } func recv(data: Data) { if connecting { connecting = false delegate?.ptyDidConnect(self) } delegate?.pty(self, didRecv: data) } func send(data: Data) { guard fd >= 0 && !connecting else { return } delegate?.pty(self, willSend: data) var length = data.count data.withUnsafeBytes { (bytes: UnsafeRawBufferPointer) in var writefds = fd_set() var errorfds = fd_set() var timeout = timeval() var chunkSize: Int var msg = bytes.baseAddress! while length > 0 { // bzero(&writefds, MemoryLayout<fd_set>.size) // bzero(&errorfds, MemoryLayout<fd_set>.size) fdZero(&writefds) fdZero(&errorfds) fdSet(fd, set: &writefds) fdSet(fd, set: &errorfds) timeout.tv_sec = 0 timeout.tv_usec = 100000 let result = select(fd + 1, nil, &writefds, &errorfds, &timeout) if result == 0 { NSLog("timeout") break } else if result < 0 { self.close() break } if length > 4096 { chunkSize = 4096 } else { chunkSize = length } let size = write(fd, bytes.baseAddress!, chunkSize) if size < 0 { break } msg = msg.advanced(by: size) length -= size } } } func readLoop() { var readfds = fd_set() var errorfds = fd_set() var exit = false let buf = UnsafeMutablePointer<Int8>.allocate(capacity: 4096) var iterationCount = 0 let result = autoreleasepool { () -> Int32 in var result = Int32(0) while !exit { iterationCount += 1 fdZero(&readfds) fdZero(&errorfds) fdSet(fd, set: &readfds) fdSet(fd, set: &errorfds) result = select(fd.advanced(by: 1), &readfds, nil, &errorfds, nil) if result < 0 { print("") break } else if fdIsset(fd, errorfds) { result = Int32(read(fd, buf, 1)) if result == 0 { exit = true } } else if fdIsset(fd, readfds) { result = Int32(read(fd, buf, 4096)) if result > 1 { let d = Data(buffer: UnsafeBufferPointer<Int8>(start: buf.advanced(by: 1), count: Int(result)-1)) DispatchQueue.main.async { self.recv(data: d) } } else if result == 0 { exit = true } } } return result } if result >= 0 { DispatchQueue.main.async { self.close() } } buf.deallocate() } }
6ab3e62ed175d7c0066d979e0c40f3ac
36.415094
340
0.493048
false
false
false
false
hjudi/gelato-helpers
refs/heads/master
gelato-helpers.swift
mit
1
// // gelato-helpers.swift // Hazim Judi // MIT license and all that metal \M/ // import UIKit //Quick access to the app delegate and system version. let getAppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate let version = UIDevice.currentDevice().systemVersion var isiPhone6 : Bool { if UIScreen.mainScreen().bounds.size.height == 667.0 { return true } return false } var isiPhone6Plus : Bool { if UIScreen.mainScreen().bounds.size.height == 736.0 { return true } return false } var isiOS9 : Bool { if version.rangeOfString("9.") != nil { return true } return false } //Lets you specify padding for the text + placeholder text in a UITextField. class PaddingTextField : UITextField { var xPadding = CGFloat(10) var yPadding = CGFloat(1) override func textRectForBounds(bounds: CGRect) -> CGRect { return CGRect(x: xPadding, y: yPadding, width: bounds.width-(xPadding*2), height: bounds.height-(self.yPadding*2)) } override func editingRectForBounds(bounds: CGRect) -> CGRect { return CGRect(x: xPadding, y: yPadding, width: bounds.width-(xPadding*2), height: bounds.height-(self.yPadding*2)) } override func placeholderRectForBounds(bounds: CGRect) -> CGRect { return CGRect(x: xPadding, y: yPadding, width: bounds.width-(xPadding*2), height: bounds.height-(self.yPadding*2)) } } extension NSDate { //Gives you a lean + modern elapsed time estimate string. //Ex. "5m", "13d" ... func getTimeElapsed() -> String { let elapsed = abs(self.timeIntervalSinceNow) if elapsed > 0 && elapsed < 120 { return "Now" } else if elapsed > 120 && elapsed < 3600 { let r = NSString(format: "%.f", elapsed/120) return "\(r)m" } else if elapsed > 3600 && elapsed < 86400 { let r = NSString(format: "%.f", elapsed/3600) return "\(r)h" } else if elapsed > 86400 && elapsed < 604800 { let r = NSString(format: "%.f", elapsed/86400) return "\(r)d" } else if elapsed > 604800 && elapsed < 2419200 { let r = NSString(format: "%.f", elapsed/604800) return "\(r)w" } else if elapsed > 2419200 && elapsed < 29030400 { let r = NSString(format: "%.f", elapsed/2419200) return "\(r)mo" } else { let r = NSString(format: "%.f", elapsed/29030400) return "\(r)y" } } } extension UIViewController { var x : CGFloat { get { return self.view.frame.origin.x } set(newX) { self.view.frame.origin.x = newX } } var y : CGFloat { get { return self.view.frame.origin.y } set(newY) { self.view.frame.origin.y = newY } } var width : CGFloat { get { return self.view.frame.width } set(newW) { self.view.frame.size.width = newW } } var height : CGFloat { get { return self.view.frame.height } set(newH) { self.view.frame.size.height = newH } } } extension UIView { //Removes all subviews. func removeAllSubviews() { for subview in self.subviews { subview.removeFromSuperview() } } //Quick access to get/set frame values without "frame.origin" or "frame.size" var x : CGFloat { get { return self.frame.origin.x } set(newX) { self.frame.origin.x = newX } } var y : CGFloat { get { return self.frame.origin.y } set(newY) { self.frame.origin.y = newY } } var width : CGFloat { get { return self.frame.width } set(newWidth) { self.frame.size.width = newWidth } } var height : CGFloat { get { return self.frame.height } set(newHeight) { self.frame.size.height = newHeight } } } //Self explanatory: turn a 6-character hex value into a UIColor. func hexToColor(hex: String) -> UIColor? { if let hexIntValue = UInt(hex, radix: 16) { return UIColor( red: CGFloat((hexIntValue & 0xFF0000) >> 16) / 255.0, green: CGFloat((hexIntValue & 0x00FF00) >> 8) / 255.0, blue: CGFloat(hexIntValue & 0x0000FF) / 255.0, alpha: CGFloat(1.0) ) } return nil } //Vice versa. func colorToHex(color: UIColor) -> String { let values = color.getRGBA() return String(format: "%02x%02x%02x", Int(values[0]*255), Int(values[1]*255), Int(values[2]*255)) } //If you use NSAttributedString, this is your lucky day. //paragraphStyleWithLineHeight() gives you a quick paragraph style with specified settings. func paragraphStyleWithLineHeight(lineHeight: CGFloat?, alignment: NSTextAlignment?) -> NSParagraphStyle { let paragraphStyle = NSMutableParagraphStyle() if lineHeight != nil { paragraphStyle.lineSpacing = lineHeight! } if alignment != nil { paragraphStyle.alignment = alignment! } return paragraphStyle as NSParagraphStyle } extension Array { // No more nil subscript returns!! subscript (safe index: Int) -> Element? { return indices ~= index ? self[index] : nil } } extension String { //Saved you an extra property var length: Int { return self.characters.count } //We've all had to deal with value inconsistency + REST APIs before func toBool() -> Bool? { switch self { case "True", "true", "yes", "1": return true case "False", "false", "no", "0": return false default: return nil } } //Gives you a simple array of username-valid strings that appear after '@' //"We @all live in the yellow @submarine" -> ["all", "submarine"] func toMentionsArray() -> Array<String> { var arrayOfMentions : Array<String> = [] if self.length > 0 { var string = self var containsMore = true while containsMore == true && string.length > 0 { if let r = string.rangeOfString("@") { if arrayOfMentions.count == 0 && r.endIndex == string.endIndex { containsMore = false; break } var finalMentionRange = r finalMentionRange.startIndex++ var hitAnObstacle = false while hitAnObstacle == false { if finalMentionRange.endIndex == string.endIndex { hitAnObstacle = true break } if String(string[finalMentionRange.endIndex]).rangeOfCharacterFromSet(NSCharacterSet(charactersInString: " .@:!$%^&*()+=?\"\'[]\n")) != nil { hitAnObstacle = true break } finalMentionRange.endIndex++ } if string.substringWithRange(finalMentionRange) != "" { arrayOfMentions.append(string.substringWithRange(finalMentionRange)) } string = string.substringFromIndex(finalMentionRange.endIndex) } else { containsMore = false } } } return arrayOfMentions } //Shortens URL strings down to their 'roots' func minifiedLink(link: String) -> String { var minified = self.lowercaseString.stringByReplacingOccurrencesOfString("http://", withString: "", options: [], range: nil).stringByReplacingOccurrencesOfString("https://", withString: "", options: [], range: nil).stringByReplacingOccurrencesOfString("www.", withString: "", options: [], range: nil) if let r = minified.rangeOfString("/") { let range = r.startIndex..<minified.endIndex minified = minified.stringByReplacingCharactersInRange(range, withString: link) } else { minified += link } return minified } } extension UIImage { //Returns a version of the image with the specified alpha. No more selected state assets! func dimWithAlpha(alpha: CGFloat) -> UIImage { UIGraphicsBeginImageContextWithOptions(self.size, false, self.scale) self.drawInRect(CGRect(origin: CGPointZero, size: self.size), blendMode: .Normal, alpha: alpha) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image } //Fills the opaque parts of an image with the specified color. func fillWithColor(color: UIColor) -> UIImage { UIGraphicsBeginImageContextWithOptions(self.size, false, self.scale) let c = UIGraphicsGetCurrentContext() self.drawInRect(CGRect(origin: CGPointZero, size: self.size), blendMode: .Normal, alpha: 1) CGContextSetBlendMode(c, CGBlendMode.SourceIn) CGContextSetFillColorWithColor(c, color.CGColor) CGContextFillRect(c, CGRect(origin: CGPointZero, size: self.size)) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image } } extension UIColor { //Gives a single-pt image representation of the color, for use as a lazy BG sprite. func toImage() -> UIImage { let rect = CGRectMake(0.0, 0.0, 1.0, 1.0) UIGraphicsBeginImageContext(rect.size) let context = UIGraphicsGetCurrentContext() CGContextSetFillColorWithColor(context, self.CGColor); CGContextFillRect(context, rect); let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image } //Makes the image darker/brighter by the specified percentage. //<White>.darkerByPercentage(percentage: 1.0) -> <Black> func darkerByPercentage(percentage: CGFloat) -> UIColor { var red = CGFloat(); var green = CGFloat(); var blue = CGFloat(); var a = CGFloat() self.getRed(&red, green: &green, blue: &blue, alpha: &a) return UIColor(red: red-percentage, green: green-percentage, blue: blue-percentage, alpha: a) } func lighterByPercentage(percentage: CGFloat) -> UIColor { var red = CGFloat(); var green = CGFloat(); var blue = CGFloat(); var a = CGFloat() self.getRed(&red, green: &green, blue: &blue, alpha: &a) return UIColor(red: red+percentage, green: green+percentage, blue: blue+percentage, alpha: a) } //Gives a 4-value collection of a color's RGBA values. <Red>.getRGBA()[0] -> 1.0 func getRGBA() -> [CGFloat] { var red = CGFloat(); var green = CGFloat(); var blue = CGFloat(); var alpha = CGFloat() self.getRed(&red, green: &green, blue: &blue, alpha: &alpha) return [red,green,blue,alpha] } }
783e7c9de97d283d75b94b1eff1bb3c9
26.81733
308
0.549419
false
false
false
false
adamnemecek/WebMIDIKit
refs/heads/master
Sources/WebMIDIKit/MIDIOutput.swift
mit
1
import CoreMIDI // extension MIDIPacket { //// public typealias ArrayLiteralElement = UInt8 // public init(data: UInt8..., timestamp: MIDITimeStamp = 0) { // assert(data.count < 256) // self.init() // self.timeStamp = timestamp // //// var elements = elements //// with // data.withUnsafeBufferPointer { _ in // // } // fatalError() // } // } func MIDISend(port: MIDIPortRef, endpoint: MIDIEndpointRef, list: UnsafePointer<MIDIPacketList>) { OSAssert(MIDISend(port, endpoint, list)) /// this let's us propagate the events to everyone subscribed to this /// endpoint not just this port, i'm not sure if we actually want this /// but for now, it let's us create multiple ports from different MIDIAccess /// objects and have them all receive the same messages OSAssert(MIDIReceived(endpoint, list)) } public class MIDIOutput: MIDIPort { // @discardableResult // public final func send<S: Sequence>(_ data: S, offset: Double? = nil) -> Self where S.Iterator.Element == UInt8 { // open() // var lst = MIDIPacketList(data) // lst.send(to: self, offset: offset) // // return self // } // // @discardableResult // public final func send(_ list: UnsafePointer<MIDIPacketList>) -> Self { //// packet.send(to: self, offset: 0) //// return self //// fatalError() // MIDISend(port: self.ref, endpoint: self.endpoint.ref, list: list) // return self // } @discardableResult public final func send(_ list: MIDIPacketListBuilder) -> Self { MIDISend(port: self.ref, endpoint: self.endpoint.ref, list: list.list) return self } public final func clear() { endpoint.flush() } // internal convenience init(virtual client: MIDIClient, block: @escaping MIDIReadBlock) { // self.init(client: client, endpoint: VirtualMIDIDestination(client: client, block: block)) // } } // // fileprivate final class VirtualMIDIDestination: VirtualMIDIEndpoint { // init(client: MIDIClient, block: @escaping MIDIReadBlock) { // super.init(ref: MIDIDestinationCreate(ref: client.ref, block: block)) // } //// ths needs to use midi received // http://stackoverflow.com/questions/10572747/why-doesnt-this-simple-coremidi-program-produce-midi-output // func send(lst: UnsafePointer<MIDIPacketList>) { // fatalError() //// MIDISend(ref, endpoint.ref, lst) // } // } // // // fileprivate func MIDIDestinationCreate(ref: MIDIClientRef, block: @escaping MIDIReadBlock) -> MIDIEndpointRef { // var endpoint: MIDIEndpointRef = 0 // MIDIDestinationCreateWithBlock(ref, "Virtual MIDI destination endpoint" as CFString, &endpoint, block) // return endpoint // } //
26abc59ef77281e54adeb16283295df7
33.148148
119
0.655459
false
false
false
false
contentful/contentful.swift
refs/heads/master
Sources/Contentful/Util.swift
mit
1
// // Util.swift // Contentful // // Created by JP Wright on 07.03.18. // Copyright © 2018 Contentful GmbH. All rights reserved. // import Foundation /// Utility method to add two dictionaries of the same time. public func +=<K, V> (left: [K: V], right: [K: V]) -> [K: V] { var result = left right.forEach { key, value in result[key] = value } return result } /// Utility method to add two dictionaries of the same time. public func +<K, V> (left: [K: V], right: [K: V]) -> [K: V] { return left += right } /// Convenience methods for reading from dictionaries without conditional casts. public extension Dictionary where Key: ExpressibleByStringLiteral { /// Extract the String at the specified fieldName. /// /// - Parameter key: The name of the field to extract the `String` from. /// - Returns: The `String` value, or `nil` if data contained is not convertible to a `String`. func string(at key: Key) -> String? { return self[key] as? String } /// Extracts the array of `String` at the specified fieldName. /// /// - Parameter key: The name of the field to extract the `[String]` from /// - Returns: The `[String]`, or nil if data contained is not convertible to an `[String]`. func strings(at key: Key) -> [String]? { return self[key] as? [String] } /// Extracts the `Int` at the specified fieldName. /// /// - Parameter key: The name of the field to extract the `Int` value from. /// - Returns: The `Int` value, or `nil` if data contained is not convertible to an `Int`. func int(at key: Key) -> Int? { return self[key] as? Int } /// Extracts the `Date` at the specified fieldName. /// /// - Parameter key: The name of the field to extract the `Date` value from. /// - Returns: The `Date` value, or `nil` if data contained is not convertible to a `Date`. func int(at key: Key) -> Date? { let dateString = self[key] as? String let date = dateString?.iso8601StringDate return date } /// Extracts the `Entry` at the specified fieldName. /// /// - Parameter key: The name of the field to extract the `Entry` from. /// - Returns: The `Entry` value, or `nil` if data contained does not have contain a Link referencing an `Entry`. func linkedEntry(at key: Key) -> Entry? { let link = self[key] as? Link let entry = link?.entry return entry } /// Extracts the `Asset` at the specified fieldName. /// /// - Parameter key: The name of the field to extract the `Asset` from. /// - Returns: The `Asset` value, or `nil` if data contained does not have contain a Link referencing an `Asset`. func linkedAsset(at key: Key) -> Asset? { let link = self[key] as? Link let asset = link?.asset return asset } /// Extracts the `[Entry]` at the specified fieldName. /// /// - Parameter key: The name of the field to extract the `[Entry]` from. /// - Returns: The `[Entry]` value, or `nil` if data contained does not have contain a Link referencing an `Entry`. func linkedEntries(at key: Key) -> [Entry]? { let links = self[key] as? [Link] let entries = links?.compactMap { $0.entry } return entries } /// Extracts the `[Asset]` at the specified fieldName. /// /// - Parameter key: The name of the field to extract the `[Asset]` from. /// - Returns: The `[Asset]` value, or `nil` if data contained does not have contain a Link referencing an `[Asset]`. func linkedAssets(at key: Key) -> [Asset]? { let links = self[key] as? [Link] let assets = links?.compactMap { $0.asset } return assets } /// Extracts the `Bool` at the specified fieldName. /// /// - Parameter key: The name of the field to extract the `Bool` value from. /// - Returns: The `Bool` value, or `nil` if data contained is not convertible to a `Bool`. func bool(at key: Key) -> Bool? { return self[key] as? Bool } /// Extracts the `Contentful.Location` at the specified fieldName. /// /// - Parameter key: The name of the field to extract the `Contentful.Location` value from. /// - Returns: The `Contentful.Location` value, or `nil` if data contained is not convertible to a `Contentful.Location`. func location(at key: Key) -> Location? { let coordinateJSON = self[key] as? [String: Any] guard let longitude = coordinateJSON?["lon"] as? Double else { return nil } guard let latitude = coordinateJSON?["lat"] as? Double else { return nil } let location = Location(latitude: latitude, longitude: longitude) return location } } // Convenience protocol and accompanying extension for extracting the type of data wrapped in an Optional. internal protocol OptionalProtocol { static func wrappedType() -> Any.Type } extension Optional: OptionalProtocol { internal static func wrappedType() -> Any.Type { return Wrapped.self } }
f100863a7ae18e9b84a02b60a1902386
37.610687
125
0.629893
false
false
false
false
coolsamson7/inject
refs/heads/master
InjectTests/BeanFactoryTest.swift
mit
1
// // BeanFactoryTests.swift // Inject // // Created by Andreas Ernst on 18.07.16. // Copyright © 2016 Andreas Ernst. All rights reserved. // import XCTest import Foundation @testable import Inject class BarFactoryBean: NSObject, FactoryBean { func create() throws -> AnyObject { let result = BarBean() result.name = "factory" result.age = 4711 return result } } class BarBean: NSObject { var name : String = "andi" var age : Int = 51 var weight : Int = 87 } class Data : NSObject, Bean, BeanDescriptorInitializer { // instance data var string : String = "" var int : Int = 0 var float : Float = 0.0 var double : Double = 0.0 var character : Character = Character(" ") var int8 : Int8 = 0 var foo : FooBase? var bar : BarBean? // ClassInitializer func initializeBeanDescriptor(_ beanDescriptor : BeanDescriptor) { beanDescriptor["foo"].inject(InjectBean()) } // Bean func postConstruct() -> Void { //print("post construct \(self)"); } // CustomStringConvertible override var description : String { return "data[string: \(string) foo: \(String(describing: foo))]" } } class FooBase : NSObject, Bean { // Bean func postConstruct() -> Void { //print("post construct \(self)"); } // CustomStringConvertible override var description : String { return "foobase[]" } } class FooBean: FooBase { var name : String? var age : Int = 0 // Bean override func postConstruct() -> Void { //print("post construct \(self)");.auto } // CustomStringConvertible override var description : String { return "foo[name: \(String(describing: name)) age: \(age)]" } } class BeanFactoryTests: XCTestCase { override class func setUp() { Classes.setDefaultBundle(BeanFactoryTests.self) try! BeanDescriptor.forClass(Data.self) // force creation // set tracing Tracer.setTraceLevel("inject", level: .off) // set logging LogManager() .registerLogger("", level : .off, logs: [QueuedLog(name: "async-console", delegate: ConsoleLog(name: "console", synchronize: false))]) } // tests func testXML() { ConfigurationNamespaceHandler(namespace: "configuration") // load parent xml let parentData = try! Foundation.Data(contentsOf: Bundle(for: BeanFactoryTests.self).url(forResource: "parent", withExtension: "xml")!) let childData = try! Foundation.Data(contentsOf: Bundle(for: BeanFactoryTests.self).url(forResource: "application", withExtension: "xml")!) var environment = try! Environment(name: "parent") try! environment.loadXML(parentData) // load child environment = try! Environment(name: "parent", parent: environment) try! environment.loadXML(childData) // check let bean : Data = try! environment.getBean(Data.self, byId: "b1") XCTAssert(bean.string == "b1") let lazy = try! environment.getBean(Data.self, byId: "lazy") XCTAssert(lazy.string == "lazy") let proto1 = try! environment.getBean(Data.self, byId: "prototype") let proto2 = try! environment.getBean(Data.self, byId: "prototype") XCTAssert(proto1 !== proto2) let bar = try! environment.getBean(BarBean.self) XCTAssert(bar.age == 4711) // Measure if false { try! Timer.measure({ var environment = try! Environment(name: "parent") try! environment.loadXML(parentData) // load child environment = try! Environment(name: "child", parent: environment) try! environment.loadXML(childData) // force load! try! environment.getBean(BarBean.self) return true }, times: 1000) } } func testFluent() throws { let parent = try Environment(name: "parent") try parent.getConfigurationManager().addSource(ProcessInfoConfigurationSource()) try parent.getConfigurationManager().addSource(PlistConfigurationSource(name: "Info", forClass: type(of: self))) try parent .define(parent.settings() .setValue(key: "key", value: "key_value")) //.define(parent.bean(ProcessInfoConfigurationSource.self) // .id("x1")) .define(parent.bean(Data.self, id: "b0") .property("string", value: "b0") .property("int", value: 1) .property("float", value: Float(-1.1)) .property("double", value: -2.2)) .define(parent.bean(FooBean.self, id: "foo") .property("name", resolve: "${andi=Andreas?}") .property("age", resolve: "${SIMULATOR_MAINSCREEN_HEIGHT=51}")) /*.define(parent.bean(Bar.self) .id("bar") .abstract() .property("name", resolve: "${andi=Andreas?}")) */ //print(parent.getConfigurationManager().report()) let child = try! Environment(name: "child", parent: parent) try! child .define(child.bean(Data.self) .id("b1") .dependsOn("b0") .property("foo", inject: InjectBean(id: "foo")) .property("string", value: "b1") .property("int", value: 1) .property("int8", value: Int8(1)) .property("float", value: Float(1.1)) .property("double", value: 2.2)) .define(child.bean(Data.self) .id("lazy") .lazy() .property("bar", bean: child.bean(BarBean.self) .property("name", value: "name") .property("age", value: 0) ) .property("string", value: "lazy") .property("int", value: 1) .property("float", value: Float(1.1)) .property("double", value: 2.2)) .define(child.bean(Data.self) .id("prototype") .scope(child.scope("prototype")) .property("string", value: "b1") .property("int", value: 1) .property("float", value: Float(1.1)) .property("double", value: 2.2)) //.define(child.bean(BarFactory.self) // .target("Bar")) //print(parent.getConfigurationManager().report()) // check let bean : Data = try! child.getBean(Data.self, byId: "b1") XCTAssert(bean.string == "b1") let lazy = try! child.getBean(Data.self, byId: "lazy") XCTAssert(lazy.string == "lazy") let proto1 = try! child.getBean(Data.self, byId: "prototype") let proto2 = try! child.getBean(Data.self, byId: "prototype") XCTAssert(proto1 !== proto2) let bar = try! child.getBean(BarBean.self) XCTAssert(bar.age == 0) _ = try! child.getBean(FooBean.self, byId: "foo") //XCTAssert(bar.age == 4711) try! Timer.measure({ let parent = try Environment(name: "parent") try parent.getConfigurationManager().addSource(ProcessInfoConfigurationSource()) try parent .define(parent.settings() .setValue(key: "key", value: "key_value")) //.define(parent.bean(ProcessInfoConfigurationSource.self) // .id("x1")) .define(parent.bean(Data.self, id: "b0") .property("string", value: "b0") .property("int", value: 1) .property("float", value: Float(-1.1)) .property("double", value: -2.2)) .define(parent.bean(FooBean.self, id: "foo") .property("name", resolve: "${andi=Andreas?}") .property("age", resolve: "${SIMULATOR_MAINSCREEN_HEIGHT=51}")).startup() // TODO? /*.define(parent.bean(Bar.self) .id("bar") .abstract() .property("name", resolve: "${andi=Andreas?}")) */ let child = try! Environment(name: "child", parent: parent) try! child .define(child.bean(Data.self) .id("b1") .dependsOn("b0") .property("foo", inject: InjectBean(id: "foo")) .property("string", value: "b1") .property("int", value: 1) .property("int8", value: Int8(1)) .property("float", value: Float(1.1)) .property("double", value: 2.2)) .define(child.bean(Data.self) .id("lazy") .lazy() .property("bar", bean: child.bean(BarBean.self) .property("name", value: "name") .property("age", value: 0) ) .property("string", value: "lazy") .property("int", value: 1) .property("float", value: Float(1.1)) .property("double", value: 2.2)) .define(child.bean(Data.self) .id("prototype") .scope(child.scope("prototype")) .property("string", value: "b1") .property("int", value: 1) .property("float", value: Float(1.1)) .property("double", value: 2.2)).startup() return true }, times: 1000) } }
389f61a2752cd0d62c8e51a866f86a7d
29.490854
148
0.514549
false
false
false
false
JudoPay/JudoKit
refs/heads/master
Carthage/Checkouts/flickrpickr-sdk/Carthage/Checkouts/judokit/Source/Theme.swift
mit
3
// // JudoPayViewController.swift // JudoKit // // Copyright (c) 2016 Alternative Payments Ltd // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import Foundation /// A class which can be used to easily customize the SDKs view public struct Theme { /// A tint color that is used to generate a theme for the judo payment form public var tintColor: UIColor = UIColor(red: 0/255, green: 0/255, blue: 0/255, alpha: 0.42) public var tintActiveColor: UIColor = UIColor(red: 30/255, green: 120/255, blue: 160/255, alpha: 1.0) /// Set the address verification service to true to prompt the user to input his country and post code information public var avsEnabled: Bool = false /// a boolean indicating whether a security message should be shown below the input public var showSecurityMessage: Bool = false /// An array of accepted card configurations (card network and card number length) public var acceptedCardNetworks: [Card.Configuration] = [Card.Configuration(.amex, 15), Card.Configuration(.visa, 16), Card.Configuration(.masterCard, 16), Card.Configuration(.maestro, 16)] // MARK: Buttons /// the title for the payment button public var paymentButtonTitle = "Pay" /// the title for the button when registering a card public var registerCardButtonTitle = "Add card" /// the title for the back button of the navigation controller public var registerCardNavBarButtonTitle = "Add" /// the title for the back button public var backButtonTitle = "< Back" // MARK: Titles /// the title for a payment public var paymentTitle = "Payment" /// the title for a card registration public var registerCardTitle = "Add card" /// the title for a refund public var refundTitle = "Refund" /// the title for an authentication public var authenticationTitle = "Authentication" // MARK: Loading /// when a register card transaction is currently running public var loadingIndicatorRegisterCardTitle = "Adding card..." /// the title of the loading indicator during a transaction public var loadingIndicatorProcessingTitle = "Processing payment..." /// the title of the loading indicator during a redirect to a 3DS webview public var redirecting3DSTitle = "Redirecting..." /// the title of the loading indicator during the verification of the transaction public var verifying3DSPaymentTitle = "Verifying payment" /// the title of the loading indicator during the verification of the card registration public var verifying3DSRegisterCardTitle = "Verifying card" // MARK: Input fields /// the height of the input fields public var inputFieldHeight: CGFloat = 68 // MARK: Security message /// the message that is shown below the input fields the ensure safety when entering card information public var securityMessageString = "Your card details are encrypted using SSL before transmission to our secure payment service provider." /// the text size of the security message public var securityMessageTextSize: CGFloat = 12 // MARK: Colors /** Helper method to identifiy whether to use a dark or light theme - returns: A boolean indicating to use dark or light mode */ public func colorMode() -> Bool { return self.tintColor.greyScale() < 0.5 } /// The default text color public var judoTextColor: UIColor? /// The default navigation bar title color public var judoNavigationBarTitleColor: UIColor? /// The default navigation bar bottom color public var judoNavigationBarBottomColor: UIColor? /// The default navigation bar background color public var judoNavigationBarBackgroundColor: UIColor? /// The color that is used for active input fields public var judoInputFieldTextColor: UIColor? /// The color that is used for active input fields public var judoInputFieldHintTextColor: UIColor? /// The color that is used for the placeholders of the input fields public var judoPlaceholderTextColor: UIColor? /// The color that is used for the border color of the input fields public var judoInputFieldBorderColor: UIColor? /// The background color of the contentView public var judoContentViewBackgroundColor: UIColor? /// The button color public var judoButtonColor: UIColor? /// The title color of the button public var judoButtonTitleColor: UIColor? /// The background color of the loadingView public var judoLoadingBackgroundColor: UIColor? /// The color that is used when an error occurs during entry public var judoErrorColor: UIColor? /// The color of the block that is shown when something is loading public var judoLoadingBlockViewColor: UIColor? /// Input field background color public var judoInputFieldBackgroundColor: UIColor? /** The default text color - returns: A UIColor object */ public func getTextColor() -> UIColor { if self.judoTextColor != nil { return self.judoTextColor! } let dgc = UIColor(red: 0/255, green: 0/255, blue: 0/255, alpha: 0.87) if self.colorMode() { return dgc } else { return dgc.inverseColor() } } /** The default text color - returns: A UIColor object */ public func getNavigationBarTitleColor() -> UIColor { if self.judoNavigationBarTitleColor != nil { return self.judoNavigationBarTitleColor! } let dgc = UIColor(red: 0/255, green: 0/255, blue: 0/255, alpha: 0.87) if self.colorMode() { return dgc } else { return dgc.inverseColor() } } /** The default text color - returns: A UIColor object */ public func getNavigationBarBottomColor() -> UIColor { if self.judoNavigationBarBottomColor != nil { return self.judoNavigationBarBottomColor! } let dgc = UIColor(red: 0/255, green: 0/255, blue: 0/255, alpha: 0.42) if self.colorMode() { return dgc } else { return dgc.inverseColor() } } /** The default text color - returns: A UIColor object */ public func getNavigationBarBackgroundColor() -> UIColor { if self.judoNavigationBarBackgroundColor != nil { return self.judoNavigationBarBackgroundColor! } let dgc = UIColor(red: 245/255, green: 245/255, blue: 245/255, alpha: 1.0) if self.colorMode() { return dgc } else { return dgc.inverseColor() } } /** The color that is used for active input fields - returns: A UIColor object */ public func getInputFieldTextColor() -> UIColor { return self.judoInputFieldTextColor ?? UIColor(red: 0/255, green: 0/255, blue: 0/255, alpha: 0.87) } /** The color that is used for active input fields - returns: A UIColor object */ public func getInputFieldHintTextColor() -> UIColor { return self.judoInputFieldHintTextColor ?? UIColor(red: 0/255, green: 0/255, blue: 0/255, alpha: 0.87) } /** The color that is used for the placeholders of the input fields - returns: A UIColor object */ public func getPlaceholderTextColor() -> UIColor { if self.judoPlaceholderTextColor != nil { return self.judoPlaceholderTextColor! } let lgc = UIColor(red: 0/255, green: 0/255, blue: 0/255, alpha: 0.42) if self.colorMode() { return lgc } else { return lgc.inverseColor() } } /** The color that is used for the border color of the input fields - returns: A UIColor object */ public func getInputFieldBorderColor() -> UIColor { return self.judoInputFieldBorderColor ?? UIColor(red: 180/255, green: 180/255, blue: 180/255, alpha: 1.0) } /** The background color of the contentView - returns: A UIColor object */ public func getContentViewBackgroundColor() -> UIColor { if self.judoContentViewBackgroundColor != nil { return self.judoContentViewBackgroundColor! } let gc = UIColor(red: 245/255, green: 245/255, blue: 245/255, alpha: 1) if self.colorMode() { return gc } else { return UIColor(red: 75/255, green: 75/255, blue: 75/255, alpha: 1) } } /** The button color - returns: A UIColor object */ public func getButtonColor() -> UIColor { return self.judoButtonColor ?? self.tintActiveColor } /** The title color of the button - returns: A UIColor object */ public func getButtonTitleColor() -> UIColor { if self.judoButtonTitleColor != nil { return self.judoButtonTitleColor! } if self.colorMode() { return .white } else { return .black } } /** The background color of the loadingView - returns: A UIColor object */ public func getLoadingBackgroundColor() -> UIColor { if self.judoLoadingBackgroundColor != nil { return self.judoLoadingBackgroundColor! } let lbc = UIColor(red: 210/255, green: 210/255, blue: 210/255, alpha: 0.8) if self.colorMode() { return lbc } else { return lbc.inverseColor() } } /** The color that is used when an error occurs during entry - returns: A UIColor object */ public func getErrorColor() -> UIColor { return self.judoErrorColor ?? UIColor(red: 235/255, green: 55/255, blue: 45/255, alpha: 1.0) } /** The color of the block that is shown when something is loading - returns: A UIColor object */ public func getLoadingBlockViewColor() -> UIColor { if self.judoLoadingBlockViewColor != nil { return self.judoLoadingBlockViewColor! } if self.colorMode() { return .white } else { return .black } } /** Input field background color - returns: A UIColor object */ public func getInputFieldBackgroundColor() -> UIColor { return self.judoInputFieldBackgroundColor ?? self.getContentViewBackgroundColor() } }
d533e0f39c0931817ecb69327742b64b
31.075676
193
0.634311
false
false
false
false
GeekSpeak/GeekSpeak-Show-Timer
refs/heads/master
GeekSpeak Show Timer/AppDelegate.swift
mit
2
import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { struct Constants { static let CurrentTimerFileName = "Current Timer" static let TimerId = "timerViewControllerTimerId" static let TimerNotificationKey = "com.geekspeak.timerNotificationKey" static let TimerDataPath = "TimerData.plist" } var window: UIWindow? var timer: Timer { get { if let timer = _timer { return timer } if let timer = readCurrentTimer() { _timer = timer return timer } else { let timer = Timer() _timer = timer return timer } } set(timer) { _timer = timer } } fileprivate var _timer: Timer? // Convenience property to make intentions clear what is gonig on. var allowDeviceToSleepDisplay: Bool { get { return !UIApplication.shared.isIdleTimerDisabled } set(allowed) { UIApplication.shared.isIdleTimerDisabled = !allowed } } // MARK: App Delegate func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { registerUserDefaults() Appearance.apply() resetTimerIfShowTimeIsZero() registerForTimerNotifications() return true } func application(_ application: UIApplication, willFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { self.window?.makeKeyAndVisible() return true } func applicationWillEnterForeground(_ application: UIApplication) { resetTimerIfShowTimeIsZero() // setAllowDeviceToSleepDisplayForTimer(timer) } func applicationDidBecomeActive(_ application: UIApplication) { timerChangedCountingStatus() } func applicationWillResignActive(_ application: UIApplication) { writeCurrentTimer() } func applicationDidEnterBackground(_ application: UIApplication) { allowDeviceToSleepDisplay = true } func applicationDidReceiveMemoryWarning(_ application: UIApplication) { writeCurrentTimer() } func applicationWillTerminate(_ application: UIApplication) { } func application(_ application: UIApplication, shouldSaveApplicationState coder: NSCoder) -> Bool { unregisterForTimerNotifications() return true } func application(_ application: UIApplication, shouldRestoreApplicationState coder: NSCoder) -> Bool { registerForTimerNotifications() return true } // MARK: - // MARK: Timer Persistance var applicationDocumentsDirectory: URL { return FileManager.default .urls( for: .documentDirectory, in: .userDomainMask) .last! } var savedTimer: URL { return applicationDocumentsDirectory .appendingPathComponent(Constants.CurrentTimerFileName) } func writeCurrentTimer() { writeCurrentTimer(timer) } func writeCurrentTimer(_ timer: Timer) { let name = savedTimer.lastPathComponent let directory = savedTimer.deletingLastPathComponent() let backupName = "\(name) Backup" let backupURL = directory.appendingPathComponent(backupName) let path = savedTimer.path let backupPath = backupURL.path let fileManager = FileManager.default do { if fileManager.fileExists(atPath: backupPath) { try fileManager.removeItem(atPath: backupPath) } if fileManager.fileExists(atPath: path) { try fileManager.moveItem(atPath: path, toPath: backupPath) } if !NSKeyedArchiver.archiveRootObject(timer, toFile: path) { print("Warning: Timer could not be archived to the disk.") } } catch let error as NSError { print("Timer not writen: \(error.localizedDescription)") } } func readCurrentTimer() -> Timer? { var timer: Timer? = .none let fileManager = FileManager.default let path = savedTimer.path if fileManager.fileExists(atPath: path) { let readTimer = NSKeyedUnarchiver.unarchiveObject(withFile: path) if let readTimer = readTimer as? Timer { timer = readTimer } } return timer } func restoreAnySavedTimer() { if let restoredTimer = readCurrentTimer() { timer = restoredTimer } } } // MARK: Additional extension AppDelegate { func registerForTimerNotifications() { let notifyCenter = NotificationCenter.default notifyCenter.addObserver( self, selector: #selector(AppDelegate.timerChangedCountingStatus), name: NSNotification.Name(rawValue: Timer.Constants.CountingStatusChanged), object: timer) } func unregisterForTimerNotifications() { let notifyCenter = NotificationCenter.default // TODO: When I explicitly remove each observer it throws an execption. why? // notifyCenter.removeObserver( self, // forKeyPath: Timer.Constants.CountingStatusChanged) notifyCenter.removeObserver(self) } @objc func timerChangedCountingStatus() { setAllowDeviceToSleepDisplayForTimer(timer) } func setAllowDeviceToSleepDisplayForTimer(_ timer: Timer) { writeCurrentTimer() switch timer.state { case .Ready, .Paused, .PausedAfterComplete: allowDeviceToSleepDisplay = true case .Counting, .CountingAfterComplete: allowDeviceToSleepDisplay = false } } func resetTimerIfShowTimeIsZero() { // reset the timer if it hasn't started, so that it uses the UserDefaults // to set which timing to use (demo or show) let useDemoDurations = UserDefaults.standard .bool(forKey: Timer.Constants.UseDemoDurations) if timer.totalShowTimeElapsed == 0 { if useDemoDurations { timer.reset(usingDemoTiming: true) } else { timer.reset(usingDemoTiming: false) } } } // Setup the default defaults in app memory func registerUserDefaults() { let useDebugTimings: Bool #if DEBUG useDebugTimings = true #else useDebugTimings = false #endif let defaults: [String:AnyObject] = [ Timer.Constants.UseDemoDurations: useDebugTimings as AnyObject ] UserDefaults.standard.register(defaults: defaults) } }
f589cd5b903a1899681e7986ee902b8c
25.264822
99
0.646652
false
false
false
false
mo3bius/My-Simple-Instagram
refs/heads/master
My-Simple-Instagram/Database/Image/Image.swift
mit
1
// // Image.swift // My-Simple-Instagram // // Created by Luigi Aiello on 31/10/17. // Copyright © 2017 Luigi Aiello. All rights reserved. // import Foundation import RealmSwift class Image: Object { // MARK: - Properties @objc dynamic var imageId = "" @objc dynamic var userId = "" @objc dynamic var instaLink: String = "" @objc dynamic var creationTime: Date? @objc dynamic var commentsNumber: Int = 0 @objc dynamic var likesNumber: Int = 0 @objc dynamic var userHasLike: Bool = false @objc dynamic var attribution: String? @objc dynamic var highResolution: String = "" @objc dynamic var standardResolution: String = "" @objc dynamic var thumbnailResolution: String = "" @objc dynamic var locationName: String = "" @objc dynamic var coordinate: String = "" var tags = List<String>() var filters = List<String>() var fileTpe: FileType = .image override static func primaryKey() -> String? { return "imageId" } // MARK: - Constructors convenience init(imageId: String, userId: String, instaLink: String, creationTime: Date?, commentsNumber cn: Int, likesNumber ln: Int, userHasLike: Bool, attribution: String?, highResolution: String, standardResolution: String, thumbnailResolution: String, locationName: String?) { self.init() self.imageId = imageId self.userId = userId self.instaLink = instaLink self.creationTime = creationTime self.commentsNumber = cn self.likesNumber = ln self.userHasLike = userHasLike self.attribution = attribution ?? "" self.highResolution = highResolution self.standardResolution = standardResolution self.thumbnailResolution = thumbnailResolution self.locationName = locationName ?? "" } class func getImage(withId id: String) -> Image? { let predicate = NSPredicate(format: "imageId == %@", id) return Database.shared.query(entitiesOfType: Image.self, where: predicate)?.first } class func getAllImages(withUserID id: String) -> [Image] { let predicate = NSPredicate(format: "userId == %@", id) return Object.all(where: predicate) } }
3061f5f86ef577bb3901b3df1e7bb937
32.093333
89
0.59589
false
false
false
false
mmick66/KDDragAndDropCollectionView
refs/heads/master
Classes/KDDragAndDropCollectionView.swift
mit
1
/* * KDDragAndDropCollectionView.swift * Created by Michael Michailidis on 10/04/2015. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ import UIKit public protocol KDDragAndDropCollectionViewDataSource : UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, indexPathForDataItem dataItem: AnyObject) -> IndexPath? func collectionView(_ collectionView: UICollectionView, dataItemForIndexPath indexPath: IndexPath) -> AnyObject func collectionView(_ collectionView: UICollectionView, moveDataItemFromIndexPath from: IndexPath, toIndexPath to : IndexPath) -> Void func collectionView(_ collectionView: UICollectionView, insertDataItem dataItem : AnyObject, atIndexPath indexPath: IndexPath) -> Void func collectionView(_ collectionView: UICollectionView, deleteDataItemAtIndexPath indexPath: IndexPath) -> Void /* optional */ func collectionView(_ collectionView: UICollectionView, cellIsDraggableAtIndexPath indexPath: IndexPath) -> Bool /* optional */ func collectionView(_ collectionView: UICollectionView, cellIsDroppableAtIndexPath indexPath: IndexPath) -> Bool /* optional */ func collectionView(_ collectionView: UICollectionView, stylingRepresentationView: UIView) -> UIView? } extension KDDragAndDropCollectionViewDataSource { public func collectionView(_ collectionView: UICollectionView, stylingRepresentationView: UIView) -> UIView? { return nil } func collectionView(_ collectionView: UICollectionView, cellIsDraggableAtIndexPath indexPath: IndexPath) -> Bool { return true } func collectionView(_ collectionView: UICollectionView, cellIsDroppableAtIndexPath indexPath: IndexPath) -> Bool { return true } } open class KDDragAndDropCollectionView: UICollectionView, KDDraggable, KDDroppable { required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } public var draggingPathOfCellBeingDragged : IndexPath? var iDataSource : UICollectionViewDataSource? var iDelegate : UICollectionViewDelegate? override open func awakeFromNib() { super.awakeFromNib() } override public init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) { super.init(frame: frame, collectionViewLayout: layout) } // MARK : KDDraggable public func canDragAtPoint(_ point : CGPoint) -> Bool { if let dataSource = self.dataSource as? KDDragAndDropCollectionViewDataSource, let indexPathOfPoint = self.indexPathForItem(at: point) { return dataSource.collectionView(self, cellIsDraggableAtIndexPath: indexPathOfPoint) } return false } public func representationImageAtPoint(_ point : CGPoint) -> UIView? { guard let indexPath = self.indexPathForItem(at: point) else { return nil } guard let cell = self.cellForItem(at: indexPath) else { return nil } UIGraphicsBeginImageContextWithOptions(cell.bounds.size, cell.isOpaque, 0) cell.layer.render(in: UIGraphicsGetCurrentContext()!) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() let imageView = UIImageView(image: image) imageView.frame = cell.frame return imageView } public func stylingRepresentationView(_ view: UIView) -> UIView? { guard let dataSource = self.dataSource as? KDDragAndDropCollectionViewDataSource else { return nil } return dataSource.collectionView(self, stylingRepresentationView: view) } public func dataItemAtPoint(_ point : CGPoint) -> AnyObject? { guard let indexPath = self.indexPathForItem(at: point) else { return nil } guard let dragDropDS = self.dataSource as? KDDragAndDropCollectionViewDataSource else { return nil } return dragDropDS.collectionView(self, dataItemForIndexPath: indexPath) } public func startDraggingAtPoint(_ point : CGPoint) -> Void { self.draggingPathOfCellBeingDragged = self.indexPathForItem(at: point) self.reloadData() } public func stopDragging() -> Void { if let idx = self.draggingPathOfCellBeingDragged { if let cell = self.cellForItem(at: idx) { cell.isHidden = false } } self.draggingPathOfCellBeingDragged = nil self.reloadData() } public func dragDataItem(_ item : AnyObject) -> Void { guard let dragDropDataSource = self.dataSource as? KDDragAndDropCollectionViewDataSource else { return } guard let existngIndexPath = dragDropDataSource.collectionView(self, indexPathForDataItem: item) else { return } dragDropDataSource.collectionView(self, deleteDataItemAtIndexPath: existngIndexPath) if self.animating { self.deleteItems(at: [existngIndexPath]) } else { self.animating = true self.performBatchUpdates({ () -> Void in self.deleteItems(at: [existngIndexPath]) }, completion: { complete -> Void in self.animating = false self.reloadData() }) } } // MARK : KDDroppable public func canDropAtRect(_ rect : CGRect) -> Bool { return (self.indexPathForCellOverlappingRect(rect) != nil) } public func indexPathForCellOverlappingRect( _ rect : CGRect) -> IndexPath? { var overlappingArea : CGFloat = 0.0 var cellCandidate : UICollectionViewCell? let dataSource = self.dataSource as? KDDragAndDropCollectionViewDataSource let visibleCells = self.visibleCells if visibleCells.count == 0 { return IndexPath(row: 0, section: 0) } if isHorizontal && rect.origin.x > self.contentSize.width || !isHorizontal && rect.origin.y > self.contentSize.height { if dataSource?.collectionView(self, cellIsDroppableAtIndexPath: IndexPath(row: visibleCells.count - 1, section: 0)) == true { return IndexPath(row: visibleCells.count - 1, section: 0) } return nil } for visible in visibleCells { let intersection = visible.frame.intersection(rect) if (intersection.width * intersection.height) > overlappingArea { overlappingArea = intersection.width * intersection.height cellCandidate = visible } } if let cellRetrieved = cellCandidate, let indexPath = self.indexPath(for: cellRetrieved), dataSource?.collectionView(self, cellIsDroppableAtIndexPath: indexPath) == true { return self.indexPath(for: cellRetrieved) } return nil } fileprivate var currentInRect : CGRect? public func willMoveItem(_ item : AnyObject, inRect rect : CGRect) -> Void { let dragDropDataSource = self.dataSource as! KDDragAndDropCollectionViewDataSource // its guaranteed to have a data source if let _ = dragDropDataSource.collectionView(self, indexPathForDataItem: item) { // if data item exists return } if let indexPath = self.indexPathForCellOverlappingRect(rect) { dragDropDataSource.collectionView(self, insertDataItem: item, atIndexPath: indexPath) self.draggingPathOfCellBeingDragged = indexPath self.animating = true self.performBatchUpdates({ () -> Void in self.insertItems(at: [indexPath]) }, completion: { complete -> Void in self.animating = false // if in the meantime we have let go if self.draggingPathOfCellBeingDragged == nil { self.reloadData() } }) } currentInRect = rect } public var isHorizontal : Bool { return (self.collectionViewLayout as? UICollectionViewFlowLayout)?.scrollDirection == .horizontal } public var animating: Bool = false public var paging : Bool = false func checkForEdgesAndScroll(_ rect : CGRect) -> Void { if paging == true { return } let currentRect : CGRect = CGRect(x: self.contentOffset.x, y: self.contentOffset.y, width: self.bounds.size.width, height: self.bounds.size.height) var rectForNextScroll : CGRect = currentRect if isHorizontal { let leftBoundary = CGRect(x: -30.0, y: 0.0, width: 30.0, height: self.frame.size.height) let rightBoundary = CGRect(x: self.frame.size.width, y: 0.0, width: 30.0, height: self.frame.size.height) if rect.intersects(leftBoundary) == true { rectForNextScroll.origin.x -= self.bounds.size.width * 0.5 if rectForNextScroll.origin.x < 0 { rectForNextScroll.origin.x = 0 } } else if rect.intersects(rightBoundary) == true { rectForNextScroll.origin.x += self.bounds.size.width * 0.5 if rectForNextScroll.origin.x > self.contentSize.width - self.bounds.size.width { rectForNextScroll.origin.x = self.contentSize.width - self.bounds.size.width } } } else { // is vertical let topBoundary = CGRect(x: 0.0, y: -30.0, width: self.frame.size.width, height: 30.0) let bottomBoundary = CGRect(x: 0.0, y: self.frame.size.height, width: self.frame.size.width, height: 30.0) if rect.intersects(topBoundary) == true { rectForNextScroll.origin.y -= self.bounds.size.height * 0.5 if rectForNextScroll.origin.y < 0 { rectForNextScroll.origin.y = 0 } } else if rect.intersects(bottomBoundary) == true { rectForNextScroll.origin.y += self.bounds.size.height * 0.5 if rectForNextScroll.origin.y > self.contentSize.height - self.bounds.size.height { rectForNextScroll.origin.y = self.contentSize.height - self.bounds.size.height } } } // check to see if a change in rectForNextScroll has been made if currentRect.equalTo(rectForNextScroll) == false { self.paging = true self.scrollRectToVisible(rectForNextScroll, animated: true) let delayTime = DispatchTime.now() + Double(Int64(1 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC) DispatchQueue.main.asyncAfter(deadline: delayTime) { self.paging = false } } } public func didMoveItem(_ item : AnyObject, inRect rect : CGRect) -> Void { let dragDropDS = self.dataSource as! KDDragAndDropCollectionViewDataSource // guaranteed to have a ds if let existingIndexPath = dragDropDS.collectionView(self, indexPathForDataItem: item), let indexPath = self.indexPathForCellOverlappingRect(rect) { if indexPath.item != existingIndexPath.item { dragDropDS.collectionView(self, moveDataItemFromIndexPath: existingIndexPath, toIndexPath: indexPath) self.animating = true self.performBatchUpdates({ () -> Void in self.moveItem(at: existingIndexPath, to: indexPath) }, completion: { (finished) -> Void in self.animating = false self.reloadData() }) self.draggingPathOfCellBeingDragged = indexPath } } // Check Paging var normalizedRect = rect normalizedRect.origin.x -= self.contentOffset.x normalizedRect.origin.y -= self.contentOffset.y currentInRect = normalizedRect self.checkForEdgesAndScroll(normalizedRect) } public func didMoveOutItem(_ item : AnyObject) -> Void { guard let dragDropDataSource = self.dataSource as? KDDragAndDropCollectionViewDataSource, let existngIndexPath = dragDropDataSource.collectionView(self, indexPathForDataItem: item) else { return } dragDropDataSource.collectionView(self, deleteDataItemAtIndexPath: existngIndexPath) if self.animating { self.deleteItems(at: [existngIndexPath]) } else { self.animating = true self.performBatchUpdates({ () -> Void in self.deleteItems(at: [existngIndexPath]) }, completion: { (finished) -> Void in self.animating = false; self.reloadData() }) } if let idx = self.draggingPathOfCellBeingDragged { if let cell = self.cellForItem(at: idx) { cell.isHidden = false } } self.draggingPathOfCellBeingDragged = nil currentInRect = nil } public func dropDataItem(_ item : AnyObject, atRect : CGRect) -> Void { // show hidden cell if let index = draggingPathOfCellBeingDragged, let cell = self.cellForItem(at: index), cell.isHidden == true { cell.alpha = 1 cell.isHidden = false } currentInRect = nil self.draggingPathOfCellBeingDragged = nil self.reloadData() } }
2fac70d9177dca39cc5029b824f566c6
35.339492
179
0.594789
false
false
false
false
ZB0106/MCSXY
refs/heads/master
MCSXY/MCSXY/Macro/UtilsMacro.swift
mit
1
// // UtilsMacro.swift // MCSXY // // Created by 瞄财网 on 2017/6/16. // Copyright © 2017年 瞄财网. All rights reserved. // import UIKit //弹框显示时间 let ALertTimeInterval = 2.0 /****** 宏 ******/ let Screen_Width = UIScreen.main.bounds.size.width let Screen_Height = UIScreen.main.bounds.size.height let Home_Btn_Width = (Screen_Width - 160) / 5 let Home_Btn_Height = Home_Btn_Width + 30 //宽 高 //字体 let H22 = UIFont.systemFont(ofSize: 22) let H20 = UIFont.systemFont(ofSize: 20) let H18 = UIFont.systemFont(ofSize: 18) let H16 = UIFont.systemFont(ofSize: 16) let H15 = UIFont.systemFont(ofSize: 15) let H14 = UIFont.systemFont(ofSize: 14) let H13 = UIFont.systemFont(ofSize: 13) let H12 = UIFont.systemFont(ofSize: 12) let H11 = UIFont.systemFont(ofSize: 11) let H10 = UIFont.systemFont(ofSize: 10) let HB20 = UIFont.boldSystemFont(ofSize: 20) let HB18 = UIFont.boldSystemFont(ofSize:18) let HB16 = UIFont.boldSystemFont(ofSize:16) let HB15 = UIFont.boldSystemFont(ofSize:15) //颜色 func Color_RGB(r:CGFloat,g:CGFloat,b:CGFloat) -> UIColor{ return UIColor.init(red: r / 255.0, green: g / 255.0, blue: b / 255.0, alpha:1.0); } func Color_RGB_Alpha(r:CGFloat,g:CGFloat,b:CGFloat,f:CGFloat) -> UIColor{ return UIColor.init(red: r / 255.0, green: g / 255.0, blue: b / 255.0, alpha: f) } func Color_Random() -> UIColor{ return UIColor(red: CGFloat(arc4random()%256) / 255.0 , green: CGFloat(arc4random()%256) / 255.0 , blue: CGFloat(arc4random()%256) / 255.0 , alpha: 1.0) } let Color_BG = Color_RGB(r: 245, g: 245, b: 245) let Color_Cell_BG = Color_RGB(r: 80, g: 80, b: 80) let Color_Nav = Color_RGB(r: 255, g: 130, b: 86) let Color_TabBar = Color_RGB(r: 255, g: 255, b: 255) let Color_TabBarNormal = Color_RGB(r: 153, g: 153, b: 153) let Color_TabBarSelected = Color_RGB(r: 255, g: 130, b: 86) let Color_StatusBG = Color_RGB(r: 207, g: 52, b: 3) let Color_H1 = Color_RGB(r: 77, g: 77, b: 77) let Color_H2 = Color_RGB(r: 153, g: 153, b: 153) let Color_H3 = Color_RGB(r: 186, g: 149, b: 99) let Color_Line = Color_RGB(r: 245, g: 245, b: 245) let Color_Holder = Color_RGB(r: 210, g: 210, b: 214) let Color_Free = Color_RGB(r: 239, g: 85, b: 34) let Color_VIP = Color_RGB(r: 155, g: 206, b: 120) let Color_White = UIColor.white let Color_Gray = UIColor.gray let Color_LightGray = UIColor.lightGray let Color_Black = UIColor.black let Color_Red = UIColor.red let Color_Clear = UIColor.clear let Color_Green = UIColor.green let Color_Blue = UIColor.blue let Color_Orange = UIColor.orange let Color_Yellow = UIColor.orange // MARK: -Cell相关 let cellHeight = "cellHeight" let headerHeight = "headerHeight" let footerHeight = "footerHeight" let cellDataArray = "cellDataArray"
2b99abdd1cfb946cb825a672520b0815
34.837209
156
0.601233
false
false
false
false
tjw/swift
refs/heads/master
test/SILGen/existential_erasure.swift
apache-2.0
1
// RUN: %target-swift-frontend -module-name existential_erasure -emit-silgen -enable-sil-ownership %s | %FileCheck %s protocol P { func downgrade(_ m68k: Bool) -> Self func upgrade() throws -> Self } protocol Q {} struct X: P, Q { func downgrade(_ m68k: Bool) -> X { return self } func upgrade() throws -> X { return self } } func makePQ() -> P & Q { return X() } func useP(_ x: P) { } func throwingFunc() throws -> Bool { return true } // CHECK-LABEL: sil hidden @$S19existential_erasure5PQtoPyyF : $@convention(thin) () -> () { func PQtoP() { // CHECK: [[PQ_PAYLOAD:%.*]] = open_existential_addr immutable_access [[PQ:%.*]] : $*P & Q to $*[[OPENED_TYPE:@opened(.*) P & Q]] // CHECK: [[P_PAYLOAD:%.*]] = init_existential_addr [[P:%.*]] : $*P, $[[OPENED_TYPE]] // CHECK: copy_addr [[PQ_PAYLOAD]] to [initialization] [[P_PAYLOAD]] // CHECK: destroy_addr [[PQ]] // CHECK-NOT: destroy_addr [[P]] // CHECK-NOT: destroy_addr [[P_PAYLOAD]] // CHECK-NOT: deinit_existential_addr [[PQ]] // CHECK-NOT: destroy_addr [[PQ_PAYLOAD]] useP(makePQ()) } // Make sure uninitialized existentials are properly deallocated when we // have an early return. // CHECK-LABEL: sil hidden @$S19existential_erasure19openExistentialToP1yyAA1P_pKF func openExistentialToP1(_ p: P) throws { // CHECK: bb0(%0 : @trivial $*P): // CHECK: [[OPEN:%.*]] = open_existential_addr immutable_access %0 : $*P to $*[[OPEN_TYPE:@opened\(.*\) P]] // CHECK: [[RESULT:%.*]] = alloc_stack $P // CHECK: [[RESULT_ADDR:%.*]] = init_existential_addr [[RESULT]] : $*P, $[[OPEN_TYPE]] // CHECK: [[FUNC:%.*]] = function_ref @$S19existential_erasure12throwingFuncSbyKF // CHECK: try_apply [[FUNC]]() // // CHECK: bb1([[SUCCESS:%.*]] : @trivial $Bool): // CHECK: [[METHOD:%.*]] = witness_method $[[OPEN_TYPE]], #P.downgrade!1 : {{.*}}, [[OPEN]] // CHECK: apply [[METHOD]]<[[OPEN_TYPE]]>([[RESULT_ADDR]], [[SUCCESS]], [[OPEN]]) // CHECK: dealloc_stack [[RESULT]] // CHECK: return // // CHECK: bb2([[FAILURE:%.*]] : @owned $Error): // CHECK: deinit_existential_addr [[RESULT]] // CHECK: dealloc_stack [[RESULT]] // CHECK: throw [[FAILURE]] // try useP(p.downgrade(throwingFunc())) } // CHECK-LABEL: sil hidden @$S19existential_erasure19openExistentialToP2yyAA1P_pKF func openExistentialToP2(_ p: P) throws { // CHECK: bb0(%0 : @trivial $*P): // CHECK: [[OPEN:%.*]] = open_existential_addr immutable_access %0 : $*P to $*[[OPEN_TYPE:@opened\(.*\) P]] // CHECK: [[RESULT:%.*]] = alloc_stack $P // CHECK: [[RESULT_ADDR:%.*]] = init_existential_addr [[RESULT]] : $*P, $[[OPEN_TYPE]] // CHECK: [[METHOD:%.*]] = witness_method $[[OPEN_TYPE]], #P.upgrade!1 : {{.*}}, [[OPEN]] // CHECK: try_apply [[METHOD]]<[[OPEN_TYPE]]>([[RESULT_ADDR]], [[OPEN]]) // // CHECK: bb1 // CHECK: dealloc_stack [[RESULT]] // CHECK: return // // CHECK: bb2([[FAILURE:%.*]]: @owned $Error): // CHECK: deinit_existential_addr [[RESULT]] // CHECK: dealloc_stack [[RESULT]] // CHECK: throw [[FAILURE]] // try useP(p.upgrade()) } // Same as above but for boxed existentials extension Error { func returnOrThrowSelf() throws -> Self { throw self } } // CHECK-LABEL: sil hidden @$S19existential_erasure12errorHandlerys5Error_psAC_pKF func errorHandler(_ e: Error) throws -> Error { // CHECK: bb0([[ARG:%.*]] : @guaranteed $Error): // CHECK: debug_value [[ARG]] : $Error // CHECK: [[OPEN:%.*]] = open_existential_box [[ARG]] : $Error to $*[[OPEN_TYPE:@opened\(.*\) Error]] // CHECK: [[RESULT:%.*]] = alloc_existential_box $Error, $[[OPEN_TYPE]] // CHECK: [[ADDR:%.*]] = project_existential_box $[[OPEN_TYPE]] in [[RESULT]] : $Error // CHECK: [[FUNC:%.*]] = function_ref @$Ss5ErrorP19existential_erasureE17returnOrThrowSelf{{[_0-9a-zA-Z]*}}F // CHECK: try_apply [[FUNC]]<[[OPEN_TYPE]]>([[ADDR]], [[OPEN]]) // // CHECK: bb1 // CHECK: return [[RESULT]] : $Error // // CHECK: bb2([[FAILURE:%.*]] : @owned $Error): // CHECK: dealloc_existential_box [[RESULT]] // CHECK: throw [[FAILURE]] : $Error // return try e.returnOrThrowSelf() } // rdar://problem/22003864 -- SIL verifier crash when init_existential_addr // references dynamic Self type class EraseDynamicSelf { required init() {} // CHECK-LABEL: sil hidden @$S19existential_erasure16EraseDynamicSelfC7factoryACXDyFZ : $@convention(method) (@thick EraseDynamicSelf.Type) -> @owned EraseDynamicSelf // CHECK: [[ANY:%.*]] = alloc_stack $Any // CHECK: init_existential_addr [[ANY]] : $*Any, $@dynamic_self EraseDynamicSelf // class func factory() -> Self { let instance = self.init() let _: Any = instance return instance } }
a80b14cedc13102db6f67d3b22d30425
34.782946
166
0.619801
false
false
false
false
jwfriese/FrequentFlyer
refs/heads/master
FrequentFlyer/Authentication/AuthMethod.swift
apache-2.0
1
import ObjectMapper struct AuthMethod { let type: AuthType let displayName: String let url: String class DisplayNames { static let basic = "Basic Auth" static let gitHub = "GitHub" static let uaa = "UAA" } init(type: AuthType, displayName: String, url: String) { self.type = type self.displayName = displayName self.url = url } } extension AuthMethod: Equatable {} func ==(lhs: AuthMethod, rhs: AuthMethod) -> Bool { return lhs.type == rhs.type && lhs.displayName == rhs.displayName && lhs.url == rhs.url } extension AuthMethod: ImmutableMappable { init(map: Map) throws { let typeString: String = try map.value("type") let displayNameString: String = try map.value("display_name") var type = AuthType.basic if typeString == "basic" && displayNameString == AuthMethod.DisplayNames.basic { type = .basic } else if typeString == "oauth" && displayNameString == AuthMethod.DisplayNames.gitHub { type = .gitHub } else if typeString == "oauth" && displayNameString == AuthMethod.DisplayNames.uaa { type = .uaa } else { throw MapError(key: "type", currentValue: "", reason: "Failed to map `AuthMethod` with `type` == `\(typeString)` and `display_name` == \(displayNameString)") } self.type = type self.displayName = displayNameString self.url = try map.value("auth_url") } }
cc00997d0fd6540f71b56354b5fc1f65
30.583333
169
0.60686
false
false
false
false
rgkobashi/PhotoSearcher
refs/heads/master
PhotoViewer/Utilities.swift
mit
1
// // Utilities.swift // PhotoViewer // // Created by Rogelio Martinez Kobashi on 2/27/17. // Copyright © 2017 Rogelio Martinez Kobashi. All rights reserved. // import Foundation import UIKit typealias VoidCompletionHandler = () -> () typealias SuceedCompletionHandler = (AnyObject?) -> () typealias ErrorCompletionHandler = (NSError) -> () class Utilities { class func downloadImageFrom(_ urlString: String, suceedHandler: @escaping SuceedCompletionHandler, failedHandler: @escaping ErrorCompletionHandler) { DispatchQueue.global(qos: DispatchQoS.background.qosClass).async { let url = URL(string: urlString) if let url = url { let data = try? Data(contentsOf: url) if let data = data { let image = UIImage(data: data) if let image = image { DispatchQueue.main.async(execute: { () -> Void in suceedHandler(image) }) } else { DispatchQueue.main.async(execute: { () -> Void in let error = NSError(domain: kErrorDomain, code: -1, userInfo: [NSLocalizedDescriptionKey: "Image could not be initialized from the specified data."]) failedHandler(error) }) } } else { DispatchQueue.main.async(execute: { () -> Void in let error = NSError(domain: kErrorDomain, code: -1, userInfo: [NSLocalizedDescriptionKey: "No data returned from the server."]) failedHandler(error) }) } } else { DispatchQueue.main.async(execute: { () -> Void in let error = NSError(domain: kErrorDomain, code: -1, userInfo: [NSLocalizedDescriptionKey: "URL string malformed."]) failedHandler(error) }) } } } class func displayAlertWithTitle(_ title: String?, message: String?, buttonTitle: String, buttonHandler: VoidCompletionHandler?) { let alert = UIAlertController(title: title, message: message, preferredStyle: .alert) let action = UIAlertAction(title: buttonTitle, style: .default) { (alertAction) in buttonHandler?() } alert.addAction(action) UIApplication.shared.windows.first?.rootViewController?.present(alert, animated: true, completion: nil) } class func displayAlertWithTitle(_ title: String?, message: String?, buttonTitle: String, buttonHandler: VoidCompletionHandler?, destructiveTitle: String, destructiveHandler: @escaping VoidCompletionHandler) { let alert = UIAlertController(title: title, message: message, preferredStyle: .alert) let destructiveAction = UIAlertAction(title: destructiveTitle, style: .destructive) { (alertAction) in destructiveHandler() } alert.addAction(destructiveAction) let action = UIAlertAction(title: buttonTitle, style: .default) { (alertAction) in buttonHandler?() } alert.addAction(action) UIApplication.shared.windows.first?.rootViewController?.present(alert, animated: true, completion: nil) } class func openURLWithString(_ string: String) { if let url = URL(string: string) { UIApplication.shared.openURL(url) } } class func stringDifferenceFromTimeStamp(_ timeStamp: Int) -> String { let before = Date(timeIntervalSince1970: TimeInterval(NSNumber(value: timeStamp as Int))) let today = Date() let unitFlags: NSCalendar.Unit = [.hour, .day, .month, .year] let dateComponents = (Calendar.current as NSCalendar).components(unitFlags, from: before, to: today, options: []) if dateComponents.year! > 0 { return "\(dateComponents.year) years ago" } else if dateComponents.month! > 0 { return "\(dateComponents.month) months ago" } else { let days = dateComponents.day if days! > 7 { let weeks = days! / 7 if weeks > 0 { return "\(weeks) weeks ago" } else { return "\(days) days ago" } } else if days == 0 { return "Today" } else { return "\(days) days ago" } } } }
0e21fe25de399b94fb08eaaa05d9ba9f
36.122137
211
0.537323
false
false
false
false
OneBusAway/onebusaway-iphone
refs/heads/develop
Carthage/Checkouts/SwiftEntryKit/Source/MessageViews/EKFormMessageView.swift
apache-2.0
3
// // EKFormMessageView.swift // SwiftEntryKit // // Created by Daniel Huri on 5/15/18. // import UIKit public class EKFormMessageView: UIView { private let scrollViewVerticalOffset: CGFloat = 20 // MARK: Props private let titleLabel = UILabel() private let scrollView = UIScrollView() private let textFieldsContent: [EKProperty.TextFieldContent] private var textFieldViews: [EKTextField] = [] private var buttonBarView: EKButtonBarView! // MARK: Setup public init(with title: EKProperty.LabelContent, textFieldsContent: [EKProperty.TextFieldContent], buttonContent: EKProperty.ButtonContent) { self.textFieldsContent = textFieldsContent super.init(frame: UIScreen.main.bounds) setupScrollView() setupTitleLabel(with: title) setupTextFields(with: textFieldsContent) setupButton(with: buttonContent) setupTapGestureRecognizer() scrollView.layoutIfNeeded() set(.height, of: scrollView.contentSize.height + scrollViewVerticalOffset * 2, priority: .defaultHigh) } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func setupTextFields(with textFieldsContent: [EKProperty.TextFieldContent]) { var textFieldIndex = 0 textFieldViews = textFieldsContent.map { content -> EKTextField in let textField = EKTextField(with: content) scrollView.addSubview(textField) textField.tag = textFieldIndex textFieldIndex += 1 return textField } textFieldViews.first!.layout(.top, to: .bottom, of: titleLabel, offset: 20) textFieldViews.spread(.vertically, offset: 5) textFieldViews.layoutToSuperview(axis: .horizontally) } // Setup tap gesture private func setupTapGestureRecognizer() { let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(tapGestureRecognized)) tapGestureRecognizer.numberOfTapsRequired = 1 addGestureRecognizer(tapGestureRecognizer) } private func setupScrollView() { addSubview(scrollView) scrollView.layoutToSuperview(axis: .horizontally, offset: 20) scrollView.layoutToSuperview(axis: .vertically, offset: scrollViewVerticalOffset) scrollView.layoutToSuperview(.width, .height, offset: -scrollViewVerticalOffset * 2) } private func setupTitleLabel(with content: EKProperty.LabelContent) { scrollView.addSubview(titleLabel) titleLabel.layoutToSuperview(.top, .width) titleLabel.layoutToSuperview(axis: .horizontally) titleLabel.forceContentWrap(.vertically) titleLabel.content = content } private func setupButton(with buttonContent: EKProperty.ButtonContent) { var buttonContent = buttonContent let action = buttonContent.action buttonContent.action = { [weak self] in self?.extractTextFieldsContent() action?() } let buttonsBarContent = EKProperty.ButtonBarContent(with: buttonContent, separatorColor: .clear, expandAnimatedly: true) buttonBarView = EKButtonBarView(with: buttonsBarContent) buttonBarView.clipsToBounds = true scrollView.addSubview(buttonBarView) buttonBarView.expand() buttonBarView.layout(.top, to: .bottom, of: textFieldViews.last!, offset: 20) buttonBarView.layoutToSuperview(.centerX) buttonBarView.layoutToSuperview(.width, offset: -40) buttonBarView.layoutToSuperview(.bottom) buttonBarView.layer.cornerRadius = 5 } private func extractTextFieldsContent() { for (content, textField) in zip(textFieldsContent, textFieldViews) { content.contentWrapper.text = textField.text } } /** Makes a specific text field the first responder */ public func becomeFirstResponder(with textFieldIndex: Int) { textFieldViews[textFieldIndex].makeFirstResponder() } // Tap Gesture @objc func tapGestureRecognized() { endEditing(true) } }
f674e7805824a445638731e6a049bf29
36.882883
145
0.684899
false
false
false
false
mateuszfidosBLStream/MFCircleMenu
refs/heads/master
Example/ViewController.swift
mit
1
// // ViewController.swift // MFCircleMenu // // Created by Mateusz Fidos on 03.05.2016. // Copyright © 2016 mateusz.fidos. All rights reserved. // import UIKit import Foundation import MFCircleMenu class ViewController: UIViewController { var menuController:MFCircleMenu! override func viewDidLoad() { super.viewDidLoad() let mainAction: MainItemActionClosure = { if (self.menuController.menuState == .Closed) { self.menuController.openMenu() } else { self.menuController.closeMenu() } } let itemOneAction: ItemActionClosure = { print("Item One tapped") let controller = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("nextViewController") self.presentViewController(controller, animated: true, completion: nil) } let itemTwoAction: ItemActionClosure = { print("Item Two tapped") } let mainCircle = MFCircleMenuMainItem(action: mainAction, closedStateImage: UIImage(named: "settings")!, openedStateImage: UIImage(named: "soundon")!, text: nil, backgroundColor: UIColor.redColor()) let itemOne = MFCircleMenuOtherItem(action: itemOneAction, image: UIImage(named: "soundon")!, text: "Item One", backgroundColor: nil) let itemTwo = MFCircleMenuOtherItem(action: itemTwoAction, image: UIImage(named: "soundoff")!, text: nil, backgroundColor: UIColor.blueColor()) let itemThree = MFCircleMenuOtherItem(action: itemOneAction, image: UIImage(named: "soundon")!, text: "Item One", backgroundColor: nil) let itemFour = MFCircleMenuOtherItem(action: itemTwoAction, image: UIImage(named: "soundoff")!, text: nil, backgroundColor: UIColor.blueColor()) let itemFive = MFCircleMenuOtherItem(action: itemOneAction, image: UIImage(named: "soundon")!, text: "Item One", backgroundColor: nil) let itemSix = MFCircleMenuOtherItem(action: itemTwoAction, image: UIImage(named: "soundoff")!, text: nil, backgroundColor: UIColor.blueColor()) self.menuController = MFCircleMenu(mainItem: mainCircle, otherItems: [itemOne, itemTwo, itemThree, itemFour, itemFive, itemSix], parent: self.view, adjustToOrientation: false) self.menuController.showAtPosition(MFCircleMenuPosition.TopRight) } @IBAction func showMenu(sender: AnyObject) { self.menuController.showMenu() } @IBAction func hideMenu(sender: AnyObject) { self.menuController.hideMenu() } }
3b9d7569c7c4fa3986445e3a0afd45ff
39.71875
206
0.679969
false
false
false
false
ben-ng/swift
refs/heads/master
validation-test/compiler_crashers_fixed/01351-swift-inflightdiagnostic-fixitreplacechars.swift
apache-2.0
1
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck class A : NSManagedObject { class func b<T: b = g() -> { assert(array: a : a { } var f = c<c) { return x } class B : A { class a(f(mx : l) { return b: b(array: e : NSObject { enum a("], g = [unowned self.d } let a { } class B : l.c { protocol b { var _ = { return { class A { typealias f == b)
51aa2e250bee5f26bb7b7d98bcaec0df
24.62963
79
0.671965
false
false
false
false
castial/HYAlertController
refs/heads/master
HYAlertController/HYShareCollectionCell.swift
mit
2
// // HYShareCollectionCell.swift // Quick-Start-iOS // // Created by work on 2016/11/2. // Copyright © 2016年 hyyy. All rights reserved. // import UIKit class HYShareCollectionCell: UICollectionViewCell { fileprivate lazy var shareImageView: UIImageView = { let imageView = UIImageView (frame: CGRect (x: 15, y: 0, width: self.bounds.size.width - 30, height: self.bounds.size.width - 30)) imageView.contentMode = .scaleAspectFit return imageView }() fileprivate lazy var shareTitleLabel: UILabel = { let label = UILabel (frame: CGRect (x: 0, y: self.shareImageView.frame.maxY + 5, width: self.bounds.size.width, height: 20)) label.textColor = UIColor.lightGray label.font = UIFont.systemFont(ofSize: 12.0) label.textAlignment = .center return label }() override init(frame: CGRect) { super.init(frame: frame) contentView.addSubview(shareImageView) contentView.addSubview(shareTitleLabel) } var action: HYAlertAction? { didSet { self.shareImageView.image = action?.image self.shareTitleLabel.text = action?.title } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } // MARK: - Class Methods extension HYShareCollectionCell { class var ID: String { return "HYShareCollectionCell" } class var cellSize: CGSize { return CGSize(width: HYConstants.shareItemWidth, height: HYConstants.shareItemHeight) } class var cellInset: UIEdgeInsets { return UIEdgeInsets(top: HYConstants.shareItemPadding, left: HYConstants.shareItemPadding, bottom: HYConstants.shareItemPadding, right: HYConstants.shareItemPadding) } } // MARK: - Layout Methods extension HYShareCollectionCell { fileprivate func initLayout(title: String?, image: UIImage?) { } }
15ab488c734bc8dceebdaf8a8f496bde
28.393939
173
0.669588
false
false
false
false
tschob/ContainerController
refs/heads/main
Example/Core/ViewController/TabContainerViewController.swift
mit
1
// // TabContainerViewController.swift // Example // // Created by Hans Seiffert on 06.08.16. // Copyright © 2016 Hans Seiffert. All rights reserved. // import UIKit import ContainerController class TabContainerViewController: UIViewController { @IBAction private func didPressContentAButton(_ sender: AnyObject) { self.cc_ContainerViewController?.display(segue: "showContentA") } @IBAction private func didPressContentBButton(_ sender: AnyObject) { self.cc_ContainerViewController?.display(segue: "showContentB") } @IBAction private func didPressContentCButton(_ sender: AnyObject) { self.cc_ContainerViewController?.display(segue: "showContentC") } // MARK: - Navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { self.cc_setupContainerViewControllerIfNeeded(segue, default: "showContentA", didSetup: { self.cc_ContainerViewController?.delegate = self }) } } extension TabContainerViewController: ContainerViewControllerDelegate { func containerViewController(_ containerViewController: ContainerViewController, willDisplay contentController: UIViewController, isReused: Bool) { guard !isReused else { return } if let navigationController = contentController as? UINavigationController, let contentController = navigationController.viewControllers.first as? ContentViewController { contentController.bottomText = "Text set from the calling UIViewController" } else if let contentController = contentController as? ContentViewController { contentController.bottomText = "Text set from the calling UIViewController" } } }
1e8d48d907f3a1c9d74319e79a1645fa
31.22
148
0.783364
false
false
false
false
google/iosched-ios
refs/heads/master
Source/IOsched/Screens/Schedule/ViewModel/SessionListViewModel.swift
apache-2.0
1
// // Copyright (c) 2017 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import MaterialComponents import FirebaseFirestore /// A type responsible for transforming a list of sessions into conference days and maintaining /// accessory state so the sessions can be displayed. /// - SeeAlso: DefaultScheduleViewModel protocol SessionListViewModel { /// A boolean indicating whether or not the viewmodel should only show saved items (reservations /// and bookmarks). Defaults to false. var shouldShowOnlySavedItems: Bool { get set } /// The filter view model for the schedule maintained by this instance. The filterViewModel /// can be modified to filter the schedule. var filterViewModel: ScheduleFilterViewModel { get } /// A list of days that are further broken down into time slots. /// - SeeAlso: ConferenceDayViewModel, ConferenceTimeSlotViewModel, SessionViewModel var conferenceDays: [ConferenceDayViewModel] { get } /// The slots within a given day, where each slot is a time period roughly one session long. /// Since Google I/O is a multi-track event, slots may contain multiple sessions. func slots(forDayWithIndex index: Int) -> [ConferenceTimeSlotViewModel] /// The sessions in a slot in a given day. /// - SeeAlso: SessionViewModel func events(forDayWithIndex dayIndex: Int, andSlotIndex slotIndex: Int) -> [SessionViewModel] /// Assigns a callback that will be invoked each time the view model updates its data in /// a way that would cause a UI change. The closure is retained by the receiver. func onUpdate(_ viewUpdateCallback: @escaping (_ indexPath: IndexPath?) -> Void) /// Called by the consumer of this class to indicate an update request, i.e. when the user swipes /// down to refresh data. func updateModel() /// Called by other classes to force a view refresh. func updateView() /// This method should be called when changing the status of a bookmark (star). Classes /// implementing this method should use it to write the changes somewhere and call any update /// methods that may be affected by the changes. func toggleBookmark(sessionID: String) /// This method should be called by the consumer of this type whenever a session is selected. /// Types that implement this protocol are then responsible for triggering the appropriate UI /// updates. func didSelectSession(_ session: SessionViewModel) /// This method takes a given session and returns a view controller showing that session's /// details. func detailsViewController(for session: SessionViewModel) -> UIViewController /// This method should be called when the user taps the filter button. func didSelectFilter() /// This method should be called when the account button is tapped. func didSelectAccount() } private enum Formatters { static let dateFormatter: DateFormatter = { let formatter = TimeZoneAwareDateFormatter() formatter.setLocalizedDateFormatFromTemplate("MMMd") return formatter }() static let timeSlotFormatter: DateFormatter = { let formatter = TimeZoneAwareDateFormatter() formatter.dateStyle = .none formatter.timeStyle = .short formatter.timeZone = TimeZone.userTimeZone() return formatter }() static let dateIntervalFormatter: DateIntervalFormatter = { let formatter = DateIntervalFormatter() formatter.dateStyle = .none formatter.timeStyle = .short formatter.timeZone = TimeZone.userTimeZone() return formatter }() } class DefaultSessionListViewModel: SessionListViewModel { init(sessionsDataSource: LazyReadonlySessionsDataSource, bookmarkDataSource: RemoteBookmarkDataSource, reservationDataSource: RemoteReservationDataSource, navigator: ScheduleNavigator) { self.sessionsDataSource = sessionsDataSource self.bookmarkDataSource = bookmarkDataSource self.reservationDataSource = reservationDataSource self.navigator = navigator filterViewModel = ScheduleFilterViewModel() conferenceDays = [] registerForTimezoneUpdates() registerForBookmarkUpdates() registerForReservationsUpdates() updateModel() } lazy private var clashDetector = ReservationClashDetector(sessions: sessionsDataSource, reservations: reservationDataSource) // MARK: - View updates var viewUpdateCallback: ((_ indexPath: IndexPath?) -> Void)? func onUpdate(_ viewUpdateCallback: @escaping (_ indexPath: IndexPath?) -> Void) { self.viewUpdateCallback = viewUpdateCallback updateModel() } func updateView() { viewUpdateCallback?(nil) } deinit { timezoneObserver = nil bookmarkObserver = nil reservationsObserver = nil } // MARK: - Dependencies fileprivate let sessionsDataSource: LazyReadonlySessionsDataSource internal let bookmarkDataSource: RemoteBookmarkDataSource internal let reservationDataSource: RemoteReservationDataSource internal let navigator: ScheduleNavigator // MARK: - Output private lazy var savedItemsViewModel: SavedItemsViewModel = { return SavedItemsViewModel(reservations: reservationDataSource, bookmarks: bookmarkDataSource) }() var filterViewModel: ScheduleFilterViewModel private(set) var conferenceDays: [ConferenceDayViewModel] var shouldShowOnlySavedItems: Bool { get { return savedItemsViewModel.shouldShowOnlySavedItems } set { savedItemsViewModel.shouldShowOnlySavedItems = newValue } } func slots(forDayWithIndex index: Int) -> [ConferenceTimeSlotViewModel] { return conferenceDays.count > 0 ? conferenceDays[index].slots : [] } func events(forDayWithIndex dayIndex: Int, andSlotIndex slotIndex: Int) -> [SessionViewModel] { let unfilteredEvents = slots(forDayWithIndex: dayIndex)[slotIndex].events if filterViewModel.isEmpty && !savedItemsViewModel.shouldShowOnlySavedItems { return unfilteredEvents } else { return unfilteredEvents.filter { event -> Bool in return filterViewModel.shouldShow(topics: event.topics, levels: event.levels, types: event.types) && savedItemsViewModel.shouldShow(event.session) } } } func updateModel() { populateConferenceDays() updateView() } // MARK: - Timezone observing private func timeZoneUpdated() { updateFormatters() updateModel() } private func updateFormatters() { Formatters.dateFormatter.timeZone = TimeZone.userTimeZone() Formatters.timeSlotFormatter.timeZone = TimeZone.userTimeZone() Formatters.dateIntervalFormatter.timeZone = TimeZone.userTimeZone() } private var timezoneObserver: Any? { willSet { if let observer = timezoneObserver { NotificationCenter.default.removeObserver(observer) } } } private func registerForTimezoneUpdates() { timezoneObserver = NotificationCenter.default.addObserver(forName: .timezoneUpdate, object: nil, queue: nil) { [weak self] _ in self?.timeZoneUpdated() } } // MARK: - Data update observing func bookmarksUpdated() { updateModel() } private var bookmarkObserver: Any? { willSet { if let observer = bookmarkObserver { NotificationCenter.default.removeObserver(observer) } } } private func registerForBookmarkUpdates() { bookmarkObserver = NotificationCenter.default.addObserver(forName: .bookmarkUpdate, object: nil, queue: nil) { [weak self] _ in guard let self = self else { return } self.bookmarksUpdated() } } func reservationsUpdated() { updateModel() } private var reservationsObserver: Any? { willSet { if let observer = reservationsObserver { NotificationCenter.default.removeObserver(observer) } } } private func registerForReservationsUpdates() { reservationsObserver = NotificationCenter.default.addObserver(forName: .reservationUpdate, object: nil, queue: nil) { [weak self] _ in self?.reservationsUpdated() } } } // MARK: - Actions extension DefaultSessionListViewModel { func didSelectSession(_ viewModel: SessionViewModel) { navigator.navigate(to: viewModel.session, popToRoot: false) } func detailsViewController(for viewModel: SessionViewModel) -> UIViewController { return navigator.detailsViewController(for: viewModel.session) } func toggleBookmark(sessionID: String) { bookmarkDataSource.toggleBookmark(sessionID: sessionID) } func didSelectFilter() { navigator.navigateToFilter(viewModel: filterViewModel, callback: { self.updateView() }) } func didSelectAccount() { navigator.navigateToAccount() } } // MARK: - Transformer extension DefaultSessionListViewModel { /// This method transforms all inputs into the correct output func conferenceDays(from allSessions: [Session]) -> [ConferenceDayViewModel] { var calendar = Calendar.autoupdatingCurrent calendar.timeZone = TimeZone.userTimeZone() let allDates = allSessions.map { event -> Date in return calendar.startOfDay(for: event.startTimestamp) } let uniqueDates = Set(allDates) // create view models for the individual days return uniqueDates.map { date -> ConferenceDayViewModel in let eventsInThisDay = allSessions.filter { event -> Bool in return calendar.isDate(event.startTimestamp, inSameDayAs: date) } let hours = eventsInThisDay.map { $0.startTimestamp } let uniqueHours = Set(hours) let slots = uniqueHours.map { time -> ConferenceTimeSlotViewModel in let eventsInThisTimeSlot = eventsInThisDay.filter { $0.startTimestamp == time } let eventsViewModels = eventsInThisTimeSlot.map { timedDetailedEvent -> SessionViewModel in return SessionViewModel(session: timedDetailedEvent, bookmarkDataSource: bookmarkDataSource, reservationDataSource: reservationDataSource, clashDetector: clashDetector, scheduleNavigator: navigator) }.sorted(by: <) return ConferenceTimeSlotViewModel(time: time, events: eventsViewModels) }.sorted(by: < ) return ConferenceDayViewModel(day: date, slots: slots) } .sorted(by: < ) } /// Generates a list of conference days from sessions in the sessions data source. func populateConferenceDays() { conferenceDays = conferenceDays(from: sessionsDataSource.sessions) } } // MARK: - View Models /// A type responsible for aggregating events by day. struct ConferenceDayViewModel { let day: Date let slots: [ConferenceTimeSlotViewModel] init(day: Date, slots: [ConferenceTimeSlotViewModel]) { self.day = day self.slots = slots } } extension ConferenceDayViewModel { var dayString: String { return Formatters.dateFormatter.string(from: day) } } extension ConferenceDayViewModel: Comparable { } func == (lhs: ConferenceDayViewModel, rhs: ConferenceDayViewModel) -> Bool { return lhs.day == rhs.day } func < (lhs: ConferenceDayViewModel, rhs: ConferenceDayViewModel) -> Bool { return lhs.day < rhs.day } /// A struct responsible for aggregating events that occur at the same time. In the /// schedule UI, this struct is also responsible for displaying the section header /// titles (which are times). struct ConferenceTimeSlotViewModel { let time: Date var timeSlotString: String let events: [SessionViewModel] init(time: Date, events: [SessionViewModel]) { self.time = time self.events = events self.timeSlotString = Formatters.timeSlotFormatter.string(from: time) } } extension ConferenceTimeSlotViewModel: Comparable { } func == (lhs: ConferenceTimeSlotViewModel, rhs: ConferenceTimeSlotViewModel) -> Bool { return lhs.time == rhs.time && lhs.events == rhs.events } func < (lhs: ConferenceTimeSlotViewModel, rhs: ConferenceTimeSlotViewModel) -> Bool { return lhs.time < rhs.time } /// A type responsible for connecting sessions and session state (like reservation/star status). /// This type is also responsible for transforming struct data into more UI-friendly types. class SessionViewModel { private enum Constants { static let sessionBookmarkedImage = UIImage(named: "ic_session_bookmarked")! static let sessionBookmarkImage = UIImage(named: "ic_session_bookmark-dark")! static let sessionReservedImage = UIImage(named: "ic_session_reserved")! static let sessionWaitlistedImage = UIImage(named: "ic_waitlisted")! static let sessionNotReservedImage = UIImage(named: "ic_session_reserve-dark")! } // Dependencies let session: Session let formattedDateInterval: String let location: String let signIn: SignInInterface let reservationService: FirebaseReservationServiceInterface var timeAndLocation: String { let separator = location.isEmpty ? "" : " / " return[formattedDateInterval, location].joined(separator: separator) } private let reservationDataSource: RemoteReservationDataSource private let bookmarkDataSource: RemoteBookmarkDataSource private let clashDetector: ReservationClashDetector private let navigator: ScheduleNavigator /// Returns the user's reservation status for this session. var reservationStatus: ReservationStatus { return reservationDataSource.reservationStatus(for: session.id) } var bookmarkButtonImage: UIImage { return isBookmarked ? Constants.sessionBookmarkedImage : Constants.sessionBookmarkImage } var bookmarkButtonAccessibilityLabel: String { return isBookmarked ? NSLocalizedString("Session is bookmarked. Tap to remove bookmark.", comment: "Accessibility hint for bookmark button, bookmarked state") : NSLocalizedString("Session is not bookmarked. Tap to add bookmark.", comment: "Accessibility hint for bookmark button, non-bookmarked state.") } var isReservable: Bool { return signIn.currentUser != nil && session.isReservable } var reserveButtonImage: UIImage? { switch reservationStatus { case .reserved: return Constants.sessionReservedImage case .waitlisted: return Constants.sessionWaitlistedImage case .none: return Constants.sessionNotReservedImage } } var reserveButtonAccessibilityLabel: String { switch reservationStatus { case .reserved: return NSLocalizedString("This session is reserved. Double-tap to cancel reservation.", comment: "Icon accessibility label for reserved session button") case .waitlisted: return NSLocalizedString("This session is waitlisted. Double-tap to cancel whitelisting.", comment: "Icon accessibility label for waitlisted session button") case .none: return NSLocalizedString("This session is not reserved. Double-tap to reserve.", comment: "Button icon accessibility label for no session reservation") } } init(session: Session, bookmarkDataSource: RemoteBookmarkDataSource, reservationDataSource: RemoteReservationDataSource, clashDetector: ReservationClashDetector, scheduleNavigator: ScheduleNavigator, signIn: SignInInterface = SignIn.sharedInstance) { self.session = session self.bookmarkDataSource = bookmarkDataSource self.signIn = signIn self.reservationDataSource = reservationDataSource self.reservationService = FirestoreReservationService(sessionID: session.id) navigator = scheduleNavigator formattedDateInterval = Formatters.dateIntervalFormatter.string(from: session.startTimestamp, to: session.endTimestamp) location = session.roomName self.clashDetector = clashDetector } var startTimeStamp: Date { return session.startTimestamp } var title: String { return session.title } var tags: [EventTag] { return session.tags } var topics: [EventTag] { return tags.filter { $0.type == .topic } } var levels: [EventTag] { return tags.filter { $0.type == .level } } var types: [EventTag] { return tags.filter { $0.type == .type } } var isBookmarked: Bool { return bookmarkDataSource.isBookmarked(sessionID: id) } var id: String { return session.id } func reserve() { reservationService.attemptReservation() } func cancelReservation() { reservationService.attemptCancellation() } func attemptReservationAction() { startObservingReservationResult() reservationService.attemptReservation() } private func startObservingReservationResult() { _ = reservationService.onReservationResultUpdate { reservationResult in switch reservationResult { case .clash, .swapClash: self.handleClash() case .cancelled, .cancelCutoff, .cancelUnknown: print("Reservation removed reservation with result: \(reservationResult)") case .reserved: print("Reservation successful") case .waitlisted: print("Waitlist successful") case .swapped, .swapCutoff, .swapWaitlisted, .swapUnknown: print("Swap: \(reservationResult.rawValue)") case .unknown: print("Reservation request returned unknown result") case .cutoff: // Display cutoff error print("Reservation errored with cutoff") } self.stopObservingReservationResults() } } private func stopObservingReservationResults() { reservationService.removeUpdateListeners() } private func handleClash() { let clashes = clashDetector.clashes(for: session) switch clashes.count { case 0: break case 1: guard let clash = clashes.first else { return } navigator.showReservationClashDialog { self.reservationService.attemptSwap(withConflictingSessionID: clash.id) } case _: navigator.showMultiClashDialog() } } } extension SessionViewModel: Comparable { } func == (lhs: SessionViewModel, rhs: SessionViewModel) -> Bool { return lhs.id == rhs.id && lhs.timeAndLocation == rhs.timeAndLocation && lhs.tags == rhs.tags && lhs.reservationStatus == rhs.reservationStatus } func < (lhs: SessionViewModel, rhs: SessionViewModel) -> Bool { return lhs.title < rhs.title } extension SessionViewModel: Hashable { func hash(into hasher: inout Hasher) { hasher.combine(id) hasher.combine(title) hasher.combine(timeAndLocation) } }
7b815102d4d2679b4b858b2afab8c60a
31.824121
101
0.698102
false
false
false
false
hmx101607/mhweibo
refs/heads/master
weibo/weibo/App/viewcontrollers/main/WBTabbarViewController.swift
mit
1
// // WBTabbarViewController.swift // weibo // // Created by mason on 2017/7/29. // Copyright © 2017年 mason. All rights reserved. // import UIKit class WBTabbarViewController: UITabBarController { private lazy var publicBtn = UIButton(type: UIButtonType.custom) override func viewDidLoad() { super.viewDidLoad() //添加控制器页面 addChildViewController(childVCName: "WBHomeViewController", title: "首页", imageName: "tabbar_home") addChildViewController(childVCName: "WBMessageViewController", title: "消息", imageName: "tabbar_message_center") addChildViewController(childVCName: "WBNullViewController", title: "", imageName: "") addChildViewController(childVCName: "WBDiscoverViewController", title: "发现", imageName: "tabbar_discover") addChildViewController(childVCName: "WBMeViewController", title: "我的", imageName: "tabbar_profile") //添加中间位置tabbarItem tabBar.addSubview(publicBtn) publicBtn.setBackgroundImage(UIImage(named: "tabbar_compose_button"), for: .normal) publicBtn.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), for: .highlighted) publicBtn.setImage(UIImage(named: "tabbar_compose_icon_add"), for: .normal) publicBtn.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), for: .highlighted) publicBtn.sizeToFit() publicBtn.center = CGPoint(x: tabBar.center.x, y: tabBar.frame.size.height * 0.5) publicBtn.addTarget(self, action: #selector(buttonTap(button:)), for: .touchUpInside) //1.读取json文件 /* guard let jsonPath = Bundle.main.path(forResource: "MainVCSettings", ofType: "json") else { MLog(message: "json文件不存在") return } //2.从文件中读取数据 guard let data = NSData(contentsOfFile: jsonPath) else { MLog(message: "json文件中午数据") return } //3.解析json文件中的数据 guard let anyObject = try? JSONSerialization.jsonObject(with: data as Data, options: .mutableContainers) else { MLog(message: "解析失败") return } guard let dicArray = anyObject as? [[String : AnyObject]] else { return } for dic in dicArray { guard let chileVCName = dic["vcName"] as? String else { continue } guard let title = dic["title"] as? String else { continue } guard let imageName = dic["imageName"] as? String else { continue } addChildViewController(childVCName: chileVCName, title: title, imageName: imageName) }*/ } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) guard let count = tabBar.items?.count else { MLog(message: "items为空") return } for i in 0..<count{ let item = tabBar.items![i] // 3.如果是下标值为2,则该item不可以和用户交互 if i == 2 { item.isEnabled = false break } } } private func addChildViewController(childVCName: String, title : String, imageName : String) { // 1. 获取命名空间 guard let nameSpace = Bundle.main.infoDictionary!["CFBundleExecutable"] as? String else { MLog(message: "命名空间不存在") return } //2. 根据命名空间和类名确定类是否存在 guard let childVCClass = NSClassFromString(nameSpace + "." + childVCName) else { MLog(message: "该类不存在") return } //3. 获取具体的类的类型 guard let childType = childVCClass as? UIViewController.Type else { MLog(message: "类型不存在") return; } let childVC = childType.init() childVC.title = title childVC.tabBarItem.image = UIImage(named: imageName) childVC.tabBarItem.selectedImage = UIImage(named: imageName + "_highlighted") let nav = UINavigationController(rootViewController: childVC) addChildViewController(nav) } func buttonTap(button : UIButton) { let publicVC = WBPublicViewController() let nav = UINavigationController(rootViewController: publicVC) present(nav, animated: true, completion: nil) } }
e87dac6d6ca864603460e1944cd823c3
35.330579
119
0.601228
false
false
false
false
CalvinChina/Demo
refs/heads/master
Swift3Demo/Swift3Demo/CoreLocation/CoreLocationViewController.swift
mit
1
// // CoreLocationViewController.swift // Swift3Demo // // Created by pisen on 16/10/12. // Copyright © 2016年 丁文凯. All rights reserved. // import UIKit import CoreLocation import MapKit class CoreLocationViewController: UIViewController ,CLLocationManagerDelegate ,MKMapViewDelegate{ @IBOutlet weak var CLMKMapView: MKMapView! let locationManager = CLLocationManager() var myLatitude:CLLocationDegrees! var myLongitude:CLLocationDegrees! var finalLatitude:CLLocationDegrees! var finalLongitude:CLLocationDegrees! var distance:CLLocationDistance! override func viewDidLoad() { super.viewDidLoad() locationManager.delegate = self locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters locationManager.requestAlwaysAuthorization() locationManager.startUpdatingLocation() let tap = UITapGestureRecognizer(target:self ,action:#selector(action(_ :))) CLMKMapView.addGestureRecognizer(tap) // Do any additional setup after loading the view. } func action(_ tap:UITapGestureRecognizer){ let touchPoint = tap.location(in: self.CLMKMapView) let newCoord = CLMKMapView.convert(touchPoint, toCoordinateFrom: self.CLMKMapView) let getLat:CLLocationDegrees = newCoord.latitude let getLon = newCoord.longitude let newCoord2 = CLLocation(latitude:getLat ,longitude:getLon) let newCoord3 = CLLocation(latitude:myLatitude , longitude:myLongitude) finalLatitude = newCoord2.coordinate.longitude finalLongitude = newCoord2.coordinate.longitude print("Original Latitude: \(myLatitude)") print("Original Longitude: \(myLongitude)") print("Final Latitude: \(finalLatitude)") print("Final Longitude: \(finalLongitude)") let distance = newCoord2.distance(from: newCoord3) print("Distance between two points: \(distance)") let newAnnotation = MKPointAnnotation() newAnnotation.coordinate = newCoord newAnnotation.title = "ABC" newAnnotation.subtitle = "abc" CLMKMapView.addAnnotation(newAnnotation) } func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { CLGeocoder().reverseGeocodeLocation(manager.location!) { (placemarks, error) in if(error != nil){ print("reverseGeocodeLocation error:" + error!.localizedDescription) return } if placemarks!.count > 0 { let pm = placemarks![0] as CLPlacemark self.displayLocationInfo(pm) }else{ print("Problem with the data received from geocoder") } } } // 地址信息解析 func displayLocationInfo(_ placemark:CLPlacemark?){ if let containsPlacemark = placemark{ locationManager.stopUpdatingLocation() let locality = (containsPlacemark.locality != nil) ? containsPlacemark.locality : "" let postalCode = (containsPlacemark.postalCode != nil) ? containsPlacemark.postalCode : "" let administrativeArea = (containsPlacemark.administrativeArea != nil) ? containsPlacemark.country : "" let country = (containsPlacemark.country != nil) ? containsPlacemark.country : "" myLongitude = (containsPlacemark.location!.coordinate.longitude) myLatitude = (containsPlacemark.location!.coordinate.latitude) print("Locality: \(locality)") print("PostalCode: \(postalCode)") print("Area: \(administrativeArea)") print("Country: \(country)") print(myLatitude) print(myLongitude) let theSpan:MKCoordinateSpan = MKCoordinateSpanMake(0.1, 0.1) let location:CLLocationCoordinate2D = CLLocationCoordinate2D(latitude:myLatitude,longitude:myLongitude) let theRegion:MKCoordinateRegion = MKCoordinateRegionMake(location,theSpan) CLMKMapView.setRegion(theRegion, animated: true) } } func locationManager(_ manager: CLLocationManager, didFailWithError error: Error){ print("Error while updating location " + error.localizedDescription) } func degreesToRadians(_ degrees: Double) -> Double { return degrees * M_PI / 180.0 } func radiansToDegrees(_ radians: Double) -> Double { return radians * 180.0 / M_PI } func getBearingBetweenTwoPoints1(_ point1:CLLocation , point2:CLLocation) -> Double { let lat1 = degreesToRadians(point1.coordinate.latitude) let lon1 = degreesToRadians(point1.coordinate.longitude) let lat2 = degreesToRadians(point2.coordinate.latitude); let lon2 = degreesToRadians(point2.coordinate.longitude); print("Start latitude: \(point1.coordinate.latitude)") print("Start longitude: \(point1.coordinate.longitude)") print("Final latitude: \(point2.coordinate.latitude)") print("Final longitude: \(point2.coordinate.longitude)") let dLon = lon2 - lon1 let y = sin(dLon) * cos(lat2) let x = cos(lat1) * sin(lat2) - sin(lat1) * cos(lat2) * cos(dLon) let radiansBearing = atan2(y ,x) return radiansToDegrees(radiansBearing) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
6506d5926cd57b2e8e200a3b6fbdc67a
39.540541
116
0.653833
false
false
false
false
tlax/looper
refs/heads/master
looper/View/Camera/Rotate/VCameraRotateImage.swift
mit
1
import UIKit class VCameraRotateImage:UIView { private weak var controller:CCameraRotate! private weak var imageView:UIImageView! private weak var border:VBorder! private weak var layoutBorderTop:NSLayoutConstraint! private weak var layoutBorderLeft:NSLayoutConstraint! private weak var layoutBorderBottom:NSLayoutConstraint! private weak var layoutBorderRight:NSLayoutConstraint! private var borderMargin:CGFloat private let kImageMargin:CGFloat = 120 private let kImageBorder:CGFloat = 2 init(controller:CCameraRotate) { borderMargin = kImageMargin - kImageBorder super.init(frame:CGRect.zero) clipsToBounds = true isUserInteractionEnabled = false translatesAutoresizingMaskIntoConstraints = false self.controller = controller let border:VBorder = VBorder(color:UIColor.black) self.border = border let imageView:UIImageView = UIImageView() imageView.isUserInteractionEnabled = false imageView.translatesAutoresizingMaskIntoConstraints = false imageView.clipsToBounds = true imageView.contentMode = UIViewContentMode.scaleAspectFit imageView.image = controller.record.items.first?.image self.imageView = imageView addSubview(border) addSubview(imageView) NSLayoutConstraint.equals( view:imageView, toView:self, margin:kImageMargin) layoutBorderTop = NSLayoutConstraint.topToTop( view:border, toView:self) layoutBorderBottom = NSLayoutConstraint.bottomToBottom( view:border, toView:self) layoutBorderLeft = NSLayoutConstraint.leftToLeft( view:border, toView:self) layoutBorderRight = NSLayoutConstraint.rightToRight( view:border, toView:self) } required init?(coder:NSCoder) { return nil } override func layoutSubviews() { let width:CGFloat = bounds.maxX let height:CGFloat = bounds.maxY let hrMargin:CGFloat let vrMargin:CGFloat if width <= height { let deltaHeightWidth:CGFloat = height - width let deltaHeightWidth_2:CGFloat = deltaHeightWidth / 2.0 hrMargin = borderMargin vrMargin = borderMargin + deltaHeightWidth_2 } else { let deltaWidthHeight:CGFloat = width - height let deltaWidthHeight_2:CGFloat = deltaWidthHeight / 2.0 vrMargin = borderMargin hrMargin = borderMargin + deltaWidthHeight_2 } layoutBorderTop.constant = vrMargin layoutBorderBottom.constant = -vrMargin layoutBorderLeft.constant = hrMargin layoutBorderRight.constant = -hrMargin super.layoutSubviews() } }
d433297695c394edf71dac1bdcdd7e26
30.642105
67
0.633733
false
false
false
false
flodolo/firefox-ios
refs/heads/main
Shared/NotificationConstants.swift
mpl-2.0
2
// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0 extension Notification.Name { // add a property to allow the observation of firefox accounts public static let FirefoxAccountChanged = Notification.Name("FirefoxAccountChanged") public static let FirefoxAccountStateChange = Notification.Name("FirefoxAccountStateChange") public static let RegisterForPushNotifications = Notification.Name("RegisterForPushNotifications") public static let FirefoxAccountProfileChanged = Notification.Name("FirefoxAccountProfileChanged") public static let FirefoxAccountDeviceRegistrationUpdated = Notification.Name("FirefoxAccountDeviceRegistrationUpdated") public static let PrivateDataClearedHistory = Notification.Name("PrivateDataClearedHistory") public static let PrivateDataClearedDownloadedFiles = Notification.Name("PrivateDataClearedDownloadedFiles") // Fired when the user finishes navigating to a page and the location has changed public static let OnLocationChange = Notification.Name("OnLocationChange") // MARK: Notification UserInfo Keys public static let UserInfoKeyHasSyncableAccount = Notification.Name("UserInfoKeyHasSyncableAccount") // Fired when the login synchronizer has finished applying remote changes public static let DataRemoteLoginChangesWereApplied = Notification.Name("DataRemoteLoginChangesWereApplied") // Fired when a the page metadata extraction script has completed and is being passed back to the native client public static let OnPageMetadataFetched = Notification.Name("OnPageMetadataFetched") public static let ProfileDidStartSyncing = Notification.Name("ProfileDidStartSyncing") public static let ProfileDidFinishSyncing = Notification.Name("ProfileDidFinishSyncing") public static let DatabaseWasRecreated = Notification.Name("DatabaseWasRecreated") public static let DatabaseWasClosed = Notification.Name("DatabaseWasClosed") public static let DatabaseWasReopened = Notification.Name("DatabaseWasReopened") public static let RustPlacesOpened = Notification.Name("RustPlacesOpened") public static let PasscodeDidChange = Notification.Name("PasscodeDidChange") public static let PasscodeDidCreate = Notification.Name("PasscodeDidCreate") public static let PasscodeDidRemove = Notification.Name("PasscodeDidRemove") public static let DynamicFontChanged = Notification.Name("DynamicFontChanged") public static let UserInitiatedSyncManually = Notification.Name("UserInitiatedSyncManually") public static let FaviconDidLoad = Notification.Name("FaviconDidLoad") public static let ReachabilityStatusChanged = Notification.Name("ReachabilityStatusChanged") public static let HomePanelPrefsChanged = Notification.Name("HomePanelPrefsChanged") public static let FileDidDownload = Notification.Name("FileDidDownload") public static let DisplayThemeChanged = Notification.Name("DisplayThemeChanged") // This will eventually replace DisplayThemeChanged public static let ThemeDidChange = Notification.Name("ThemeDidChange") public static let SearchBarPositionDidChange = Notification.Name("SearchBarPositionDidChange") public static let WallpaperDidChange = Notification.Name("WallpaperDidChange") public static let UpdateLabelOnTabClosed = Notification.Name("UpdateLabelOnTabClosed") public static let TopTabsTabClosed = Notification.Name("TopTabsTabClosed") public static let ShowHomepage = Notification.Name("ShowHomepage") public static let TabsTrayDidClose = Notification.Name("TabsTrayDidClose") public static let TabsTrayDidSelectHomeTab = Notification.Name("TabsTrayDidSelectHomeTab") public static let TabsPrivacyModeChanged = Notification.Name("TabsPrivacyModeChanged") public static let OpenClearRecentHistory = Notification.Name("OpenClearRecentHistory") public static let LibraryPanelStateDidChange = Notification.Name("LibraryPanelStateDidChange") public static let SearchSettingsChanged = Notification.Name("SearchSettingsChanged") // MARK: Tab manager // Tab manager creates a toast for undo recently closed tabs and a notification is // fired when user taps on undo button on Toast public static let DidTapUndoCloseAllTabToast = Notification.Name("DidTapUndoCloseAllTabToast") // MARK: Settings public static let BookmarksUpdated = Notification.Name("BookmarksUpdated") public static let ReadingListUpdated = Notification.Name("ReadingListUpdated") public static let TopSitesUpdated = Notification.Name("TopSitesUpdated") public static let HistoryUpdated = Notification.Name("HistoryUpdated") }
2c11ddc52b4ded9f42727e5606315396
47.79798
124
0.79942
false
false
false
false
stormpath/stormpath-swift-example
refs/heads/master
Pods/Stormpath/Stormpath/Networking/APIRequest.swift
mit
1
// // APIRequest.swift // Stormpath // // Created by Edward Jiang on 12/15/16. // Copyright © 2016 Stormpath. All rights reserved. // import UIKit struct APIRequest { let url: URL var method: APIRequestMethod var headers = [String: String]() var body: [String: Any]? var contentType = ContentType.json init(method: APIRequestMethod, url: URL) { self.method = method self.url = url } func send(callback: APIRequestCallback? = nil) { APIClient().execute(request: self, callback: callback) } var asURLRequest: URLRequest { var request = URLRequest(url: url) request.httpMethod = method.rawValue // Set headers request.setValue(ContentType.json.rawValue, forHTTPHeaderField: "Accept") // Default to accept json headers.forEach { (name, value) in request.setValue(value, forHTTPHeaderField: name) } // Encode body if let body = body { request.setValue(contentType.rawValue, forHTTPHeaderField: "Content-Type") switch(contentType) { case .json: request.httpBody = try? JSONSerialization.data(withJSONObject: body, options: []) case .urlEncoded: request.httpBody = body.map { (key, value) -> String in var formUrlEncodedCharacters = CharacterSet.urlQueryAllowed formUrlEncodedCharacters.remove(charactersIn: "+&") let key = key.addingPercentEncoding(withAllowedCharacters: formUrlEncodedCharacters) ?? "" let value = "\(value)".addingPercentEncoding(withAllowedCharacters: formUrlEncodedCharacters) ?? "" return "\(key)=\(value)" } .joined(separator: "&") .data(using: .utf8) } } return request } }
4afca92562740b8155d32fbecbd18bbb
31.639344
119
0.567052
false
false
false
false
evgenyneu/Auk
refs/heads/master
Auk/Utils/iiAutolayoutConstraints.swift
mit
1
// // Collection of shortcuts to create autolayout constraints. // import UIKit class iiAutolayoutConstraints { class func fillParent(_ view: UIView, parentView: UIView, margin: CGFloat = 0, vertically: Bool = false) { var marginFormat = "" if margin != 0 { marginFormat = "-(\(margin))-" } var format = "|\(marginFormat)[view]\(marginFormat)|" if vertically { format = "V:" + format } let constraints = NSLayoutConstraint.constraints(withVisualFormat: format, options: [], metrics: nil, views: ["view": view]) parentView.addConstraints(constraints) } @discardableResult class func alignSameAttributes(_ item: AnyObject, toItem: AnyObject, constraintContainer: UIView, attribute: NSLayoutConstraint.Attribute, margin: CGFloat = 0) -> [NSLayoutConstraint] { let constraint = NSLayoutConstraint( item: item, attribute: attribute, relatedBy: NSLayoutConstraint.Relation.equal, toItem: toItem, attribute: attribute, multiplier: 1, constant: margin) constraintContainer.addConstraint(constraint) return [constraint] } class func equalWidth(_ viewOne: UIView, viewTwo: UIView, constraintContainer: UIView) -> [NSLayoutConstraint] { return equalWidthOrHeight(viewOne, viewTwo: viewTwo, constraintContainer: constraintContainer, isHeight: false) } // MARK: - Equal height and width class func equalHeight(_ viewOne: UIView, viewTwo: UIView, constraintContainer: UIView) -> [NSLayoutConstraint] { return equalWidthOrHeight(viewOne, viewTwo: viewTwo, constraintContainer: constraintContainer, isHeight: true) } @discardableResult class func equalSize(_ viewOne: UIView, viewTwo: UIView, constraintContainer: UIView) -> [NSLayoutConstraint] { var constraints = equalWidthOrHeight(viewOne, viewTwo: viewTwo, constraintContainer: constraintContainer, isHeight: false) constraints += equalWidthOrHeight(viewOne, viewTwo: viewTwo, constraintContainer: constraintContainer, isHeight: true) return constraints } class func equalWidthOrHeight(_ viewOne: UIView, viewTwo: UIView, constraintContainer: UIView, isHeight: Bool) -> [NSLayoutConstraint] { var prefix = "" if isHeight { prefix = "V:" } let constraints = NSLayoutConstraint.constraints(withVisualFormat: "\(prefix)[viewOne(==viewTwo)]", options: [], metrics: nil, views: ["viewOne": viewOne, "viewTwo": viewTwo]) constraintContainer.addConstraints(constraints) return constraints } // MARK: - Align view next to each other @discardableResult class func viewsNextToEachOther(_ views: [UIView], constraintContainer: UIView, margin: CGFloat = 0, vertically: Bool = false) -> [NSLayoutConstraint] { if views.count < 2 { return [] } var constraints = [NSLayoutConstraint]() for (index, view) in views.enumerated() { if index >= views.count - 1 { break } let viewTwo = views[index + 1] constraints += twoViewsNextToEachOther(view, viewTwo: viewTwo, constraintContainer: constraintContainer, margin: margin, vertically: vertically) } return constraints } class func twoViewsNextToEachOther(_ viewOne: UIView, viewTwo: UIView, constraintContainer: UIView, margin: CGFloat = 0, vertically: Bool = false) -> [NSLayoutConstraint] { var marginFormat = "" if margin != 0 { marginFormat = "-\(margin)-" } var format = "[viewOne]\(marginFormat)[viewTwo]" if vertically { format = "V:" + format } let constraints = NSLayoutConstraint.constraints(withVisualFormat: format, options: [], metrics: nil, views: [ "viewOne": viewOne, "viewTwo": viewTwo ]) constraintContainer.addConstraints(constraints) return constraints } @discardableResult class func height(_ view: UIView, value: CGFloat) -> [NSLayoutConstraint] { return widthOrHeight(view, value: value, isHeight: true) } @discardableResult class func width(_ view: UIView, value: CGFloat) -> [NSLayoutConstraint] { return widthOrHeight(view, value: value, isHeight: false) } class func widthOrHeight(_ view: UIView, value: CGFloat, isHeight: Bool) -> [NSLayoutConstraint] { let layoutAttribute = isHeight ? NSLayoutConstraint.Attribute.height : NSLayoutConstraint.Attribute.width let constraint = NSLayoutConstraint( item: view, attribute: layoutAttribute, relatedBy: NSLayoutConstraint.Relation.equal, toItem: nil, attribute: NSLayoutConstraint.Attribute.notAnAttribute, multiplier: 1, constant: value) view.addConstraint(constraint) return [constraint] } }
e642a66c4d43a8fe18c56d169dec79b6
29.559748
126
0.675242
false
false
false
false
p0dee/PDAlertView
refs/heads/master
PDAlertView/AlertBodyView.swift
gpl-2.0
1
// // BodyView.swift // AlertViewMock // // Created by Takeshi Tanaka on 12/23/15. // Copyright © 2015 Takeshi Tanaka. All rights reserved. // import UIKit internal func actionButtonLineWidth() -> Double { let scale = Double(UIScreen.main.scale) return (scale > 2.0 ? 2.0 : 1.0) / scale } fileprivate extension AlertSelectionControl { fileprivate var selectedView: AlertSelectionComponentView? { if let selIdx = self.selectedIndex, selIdx < self.components.count { return self.components[selIdx] } else { return nil } } } internal protocol AlertBodyViewDelegate: class { func bodyView(_ bodyView: AlertBodyView, didSelectedItemAtIndex index: Int) } internal class AlertBodyView: UIView { private let vibracyView = UIVisualEffectView(effect: UIVibrancyEffect(blurEffect: UIBlurEffect(style: .dark))) private let blurView = UIVisualEffectView(effect: UIBlurEffect(style: .light)) private let bgView = UIView() private var bodyMaskView: MaskView? private let contentView = UIStackView() private let titleLabel = UILabel() private let messageLabel = UILabel() private let selectionView = AlertSelectionControl() let accessoryContentView = AccessoryContentView() as UIView var delegate: AlertBodyViewDelegate? var button = UITableViewCell() var title: String? { set { titleLabel.text = newValue } get { return titleLabel.text } } var message: String? { set { messageLabel.text = newValue } get { return messageLabel.text } } override init(frame: CGRect) { super.init(frame: frame) bodyMaskView = MaskView(bodyView: self) self.clipsToBounds = true self.layer.cornerRadius = 7.0 } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } internal override var intrinsicContentSize: CGSize { return CGSize(width: 270, height: UIViewNoIntrinsicMetric) } internal override func willMove(toSuperview newSuperview: UIView?) { setupViews() setupConstraints() } override func layoutSubviews() { super.layoutSubviews() bodyMaskView?.sizeToFit() } //MARK: func addAction(_ action: AlertAction) { selectionView.addButton(with: action.title, style: action.style) bodyMaskView?.setNeedsDisplay() } //MARK: private func setupViews() { vibracyView.translatesAutoresizingMaskIntoConstraints = false self.addSubview(vibracyView) let mask = UIView(frame: vibracyView.bounds) mask.autoresizingMask = [.flexibleWidth, .flexibleHeight] mask.backgroundColor = UIColor.black.withAlphaComponent(0.5) vibracyView.contentView.addSubview(mask) blurView.translatesAutoresizingMaskIntoConstraints = false self.addSubview(blurView) bgView.translatesAutoresizingMaskIntoConstraints = false bgView.backgroundColor = UIColor(white: 1.0, alpha: 0.7) self.addSubview(bgView) bgView.mask = bodyMaskView contentView.translatesAutoresizingMaskIntoConstraints = false contentView.layoutMargins = UIEdgeInsetsMake(20, 18, 12, 18) contentView.axis = .vertical contentView.spacing = 8.0 self.addSubview(contentView) titleLabel.font = UIFont.boldSystemFont(ofSize: 17.0) titleLabel.textAlignment = .center titleLabel.setContentCompressionResistancePriority(UILayoutPriorityDefaultLow, for: .horizontal) contentView.addArrangedSubview(titleLabel) messageLabel.numberOfLines = 0 messageLabel.font = UIFont.systemFont(ofSize: 13.0) messageLabel.textAlignment = .center messageLabel.setContentCompressionResistancePriority(UILayoutPriorityDefaultLow, for: .horizontal) contentView.addArrangedSubview(messageLabel) selectionView.translatesAutoresizingMaskIntoConstraints = false selectionView.addTarget(bodyMaskView, action: #selector(MaskView.selectionViewDidChange(_:)), for: .valueChanged) selectionView.addTarget(self, action: #selector(selectionViewDidTouchUpInside(_:)), for: .touchUpInside) self.addSubview(selectionView) } private func setupConstraints() { var cstrs = [NSLayoutConstraint]() cstrs += NSLayoutConstraint.constraintsToFillSuperview(vibracyView) cstrs += NSLayoutConstraint.constraintsToFillSuperview(blurView) cstrs += NSLayoutConstraint.constraintsToFillSuperview(bgView) let lineWidth = NSNumber(value: actionButtonLineWidth()) let metrics = ["lineWidth" : lineWidth] let views = ["contentView" : contentView, "selectionView" : selectionView] let formatHorizG = "H:|[contentView]|" cstrs += NSLayoutConstraint.constraints(withVisualFormat: formatHorizG, options: .directionLeadingToTrailing, metrics: metrics, views: views) let formatVertG = "V:|-(20)-[contentView]-(20)-[selectionView]|" cstrs += NSLayoutConstraint.constraints(withVisualFormat: formatVertG, options: [.alignAllLeading, .alignAllTrailing], metrics: metrics, views: views) NSLayoutConstraint.activate(cstrs) } @objc private func selectionViewDidTouchUpInside(_ sender: AlertSelectionControl) { if let selIdx = selectionView.selectedIndex { delegate?.bodyView(self, didSelectedItemAtIndex: selIdx) } } private class AccessoryContentView: UIView { override func addSubview(_ view: UIView) { super.addSubview(view) view.translatesAutoresizingMaskIntoConstraints = true view.autoresizingMask = [view.autoresizingMask, .flexibleLeftMargin, .flexibleRightMargin] } override func layoutSubviews() { super.layoutSubviews() for v in self.subviews { var frame = v.frame frame.size.width = min(self.bounds.size.width, frame.size.width) frame.origin.x = (self.bounds.size.width - frame.size.width) * 0.5 frame.origin.y = 0 v.frame = frame } } override var intrinsicContentSize: CGSize { var maxY: CGFloat = 0 for v in subviews { maxY = max(maxY, v.frame.maxY) } return CGSize(width: UIViewNoIntrinsicMetric, height: maxY) } func hasContent() -> Bool { return self.subviews.count > 0 } } private class MaskView: UIView { weak private var bodyView: AlertBodyView? private static let PixelWidth = CGFloat(actionButtonLineWidth()) convenience init(bodyView: AlertBodyView) { self.init() self.backgroundColor = UIColor.clear self.bodyView = bodyView } override func sizeThatFits(_ size: CGSize) -> CGSize { guard let bodyView = bodyView else { return size } return bodyView.bounds.size } override func draw(_ rect: CGRect) { guard let bodyView = bodyView else { return } guard let context = UIGraphicsGetCurrentContext() else { return } context.addRect(bodyView.contentView.frame.insetBy(dx: 0, dy: -20)) //FIXME: for view in bodyView.selectionView.components { if view.isEqual(bodyView.selectionView.selectedView) { continue } context.addRect(CGRect(x: view.frame.origin.x + bodyView.selectionView.frame.origin.x, y: view.frame.origin.y + bodyView.selectionView.frame.origin.y + MaskView.PixelWidth, width: view.frame.size.width, height: view.frame.size.height)) } UIColor.black.setFill() context.fillPath() if let view = bodyView.selectionView.selectedView { let rect = CGRect(x: view.frame.origin.x + bodyView.selectionView.frame.origin.x, y: view.frame.origin.y + bodyView.selectionView.frame.origin.y + MaskView.PixelWidth, width: view.frame.size.width, height: view.frame.size.height) if bodyView.selectionView.axis == .horizontal { context.addRect(rect.insetBy(dx: -MaskView.PixelWidth, dy: 0)) } else { context.addRect(rect.insetBy(dx: 0, dy: -MaskView.PixelWidth)) } UIColor.black.withAlphaComponent(0.5).setFill() context.fillPath() } } @objc func selectionViewDidChange(_ sender: AlertSelectionControl) { setNeedsDisplay() } } }
cb7860524330033986c29ae1af405704
37.313559
251
0.633378
false
false
false
false
huangboju/Moots
refs/heads/master
UICollectionViewLayout/CollectionKit-master/Sources/Layout/InsetLayout.swift
mit
1
// // InsetLayout.swift // CollectionKit // // Created by Luke Zhao on 2017-09-08. // Copyright © 2017 lkzhao. All rights reserved. // import UIKit open class InsetLayout<Data>: WrapperLayout<Data> { public var insets: UIEdgeInsets public var insetProvider: ((CGSize) -> UIEdgeInsets)? public init(_ rootLayout: CollectionLayout<Data>, insets: UIEdgeInsets = .zero) { self.insets = insets super.init(rootLayout) } public init(_ rootLayout: CollectionLayout<Data>, insetProvider: @escaping ((CGSize) -> UIEdgeInsets)) { self.insets = .zero self.insetProvider = insetProvider super.init(rootLayout) } open override var contentSize: CGSize { return rootLayout.contentSize.insets(by: -insets) } open override func layout(collectionSize: CGSize, dataProvider: CollectionDataProvider<Data>, sizeProvider: @escaping (Int, Data, CGSize) -> CGSize) { if let insetProvider = insetProvider { insets = insetProvider(collectionSize) } rootLayout.layout(collectionSize: collectionSize.insets(by: insets), dataProvider: dataProvider, sizeProvider: sizeProvider) } open override func visibleIndexes(activeFrame: CGRect) -> [Int] { return rootLayout.visibleIndexes(activeFrame: activeFrame.inset(by: -insets)) } open override func frame(at: Int) -> CGRect { return rootLayout.frame(at: at) + CGPoint(x: insets.left, y: insets.top) } }
78cc14801af4c8d6352bc158d81fd608
30.617021
106
0.681023
false
false
false
false
blockchain/My-Wallet-V3-iOS
refs/heads/master
Modules/Platform/Sources/PlatformKit/Services/Settings/EmailVerification/EmailVerificationService.swift
lgpl-3.0
1
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import DIKit import RxRelay import RxSwift public final class EmailVerificationService: EmailVerificationServiceAPI { // MARK: - Types private enum ServiceError: Error { case emailNotVerified case pollCancelled } // MARK: - Properties private let syncService: WalletNabuSynchronizerServiceAPI private let settingsService: SettingsServiceAPI & EmailSettingsServiceAPI private let isActiveRelay = BehaviorRelay<Bool>(value: false) // MARK: - Setup init( syncService: WalletNabuSynchronizerServiceAPI = resolve(), settingsService: CompleteSettingsServiceAPI = resolve() ) { self.syncService = syncService self.settingsService = settingsService } public func cancel() -> Completable { Completable .create { [weak self] observer -> Disposable in self?.isActiveRelay.accept(false) observer(.completed) return Disposables.create() } } public func verifyEmail() -> Completable { start() .flatMapCompletable(weak: self) { (self, _) -> Completable in self.syncService.sync().asSingle().asCompletable() } } public func requestVerificationEmail(to email: String, context: FlowContext?) -> Completable { settingsService .update(email: email, context: context) .andThen(syncService.sync().asSingle().asCompletable()) } /// Start polling by triggering the wallet settings fetch private func start() -> Single<Void> { Single .create(weak: self) { (self, observer) -> Disposable in self.isActiveRelay.accept(true) observer(.success(())) return Disposables.create() } .flatMap(waitForVerification) } /// Continues the polling only if it has not been cancelled private func `continue`() -> Single<Void> { isActiveRelay .take(1) .asSingle() .map { isActive in guard isActive else { throw ServiceError.pollCancelled } return () } .flatMap(weak: self) { (self, _: ()) -> Single<Void> in self.settingsService.fetch(force: true).mapToVoid() } } /// Returns a Single that upon subscription waits until the email is verified. /// Only when it streams a value (`Void`) the email is considered `verified`. private func waitForVerification() -> Single<Void> { self.continue() .flatMap(weak: self) { (self, _) -> Single<Void> in self.settingsService /// Get the first value and make sure the stream terminates /// by converting it to a `Single` .valueSingle /// Make sure the email is verified, if not throw an error .map(weak: self) { _, settings -> Void in guard settings.isEmailVerified else { throw ServiceError.emailNotVerified } return () } /// If email is not verified try again .catch { error -> Single<Void> in switch error { case ServiceError.emailNotVerified: return Single<Int> .timer( .seconds(1), scheduler: ConcurrentDispatchQueueScheduler(qos: .background) ) .flatMap(weak: self) { (self, _) -> Single<Void> in self.waitForVerification() } default: return self.cancel().andThen(Single.error(ServiceError.pollCancelled)) } } } } }
7c4751efec98a9360d78ae54fc283395
35.356522
98
0.522363
false
false
false
false
breadwallet/breadwallet-ios
refs/heads/master
breadwallet/src/ViewControllers/HomeScreenViewController.swift
mit
1
// // HomeScreenViewController.swift // breadwallet // // Created by Adrian Corscadden on 2017-11-27. // Copyright © 2017-2019 Breadwinner AG. All rights reserved. // import UIKit class HomeScreenViewController: UIViewController, Subscriber, Trackable { private let walletAuthenticator: WalletAuthenticator private let widgetDataShareService: WidgetDataShareService private let assetList = AssetListTableView() private let subHeaderView = UIView() private let logo = UIImageView(image: UIImage(named: "LogoGradientSmall")) private let total = UILabel(font: Theme.h1Title, color: Theme.primaryText) private let totalAssetsLabel = UILabel(font: Theme.caption, color: Theme.tertiaryText) private let debugLabel = UILabel(font: .customBody(size: 12.0), color: .transparentWhiteText) // debug info private let prompt = UIView() private var promptHiddenConstraint: NSLayoutConstraint! private let toolbar = UIToolbar() private var toolbarButtons = [UIButton]() private let notificationHandler = NotificationHandler() private var shouldShowBuyAndSell: Bool { return (Store.state.experimentWithName(.buyAndSell)?.active ?? false) && (Store.state.defaultCurrencyCode == C.usdCurrencyCode) } private var buyButtonTitle: String { return shouldShowBuyAndSell ? S.HomeScreen.buyAndSell : S.HomeScreen.buy } private let buyButtonIndex = 0 private let tradeButtonIndex = 1 private let menuButtonIndex = 2 private var buyButton: UIButton? { guard toolbarButtons.count == 3 else { return nil } return toolbarButtons[buyButtonIndex] } private var tradeButton: UIButton? { guard toolbarButtons.count == 3 else { return nil } return toolbarButtons[tradeButtonIndex] } var didSelectCurrency: ((Currency) -> Void)? var didTapManageWallets: (() -> Void)? var didTapBuy: (() -> Void)? var didTapTrade: (() -> Void)? var didTapMenu: (() -> Void)? var okToShowPrompts: Bool { //Don't show any prompts on the first couple launches guard UserDefaults.appLaunchCount > 2 else { return false } // On the initial display we need to load the wallets in the asset list table view first. // There's already a lot going on, so don't show the home-screen prompts right away. return !Store.state.wallets.isEmpty } private lazy var totalAssetsNumberFormatter: NumberFormatter = { let formatter = NumberFormatter() formatter.isLenient = true formatter.numberStyle = .currency formatter.generatesDecimalNumbers = true return formatter }() // MARK: - init(walletAuthenticator: WalletAuthenticator, widgetDataShareService: WidgetDataShareService) { self.walletAuthenticator = walletAuthenticator self.widgetDataShareService = widgetDataShareService super.init(nibName: nil, bundle: nil) } deinit { Store.unsubscribe(self) } func reload() { setInitialData() setupSubscriptions() assetList.reload() attemptShowPrompt() } override func viewDidLoad() { assetList.didSelectCurrency = didSelectCurrency assetList.didTapAddWallet = didTapManageWallets addSubviews() addConstraints() setInitialData() setupSubscriptions() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) DispatchQueue.main.asyncAfter(deadline: .now() + promptDelay) { [unowned self] in self.attemptShowPrompt() if !Store.state.isLoginRequired { NotificationAuthorizer().showNotificationsOptInAlert(from: self, callback: { _ in self.notificationHandler.checkForInAppNotifications() }) } } updateTotalAssets() } // MARK: Setup private func addSubviews() { view.addSubview(subHeaderView) subHeaderView.addSubview(logo) subHeaderView.addSubview(totalAssetsLabel) subHeaderView.addSubview(total) subHeaderView.addSubview(debugLabel) view.addSubview(prompt) view.addSubview(toolbar) } private func addConstraints() { let headerHeight: CGFloat = 30.0 let toolbarHeight: CGFloat = 74.0 subHeaderView.constrain([ subHeaderView.leadingAnchor.constraint(equalTo: view.leadingAnchor), subHeaderView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 0.0), subHeaderView.trailingAnchor.constraint(equalTo: view.trailingAnchor), subHeaderView.heightAnchor.constraint(equalToConstant: headerHeight) ]) total.constrain([ total.trailingAnchor.constraint(equalTo: subHeaderView.trailingAnchor, constant: -C.padding[2]), total.centerYAnchor.constraint(equalTo: subHeaderView.topAnchor, constant: C.padding[1])]) totalAssetsLabel.constrain([ totalAssetsLabel.trailingAnchor.constraint(equalTo: total.trailingAnchor), totalAssetsLabel.bottomAnchor.constraint(equalTo: total.topAnchor)]) logo.constrain([ logo.leadingAnchor.constraint(equalTo: subHeaderView.leadingAnchor, constant: C.padding[2]), logo.centerYAnchor.constraint(equalTo: total.centerYAnchor)]) debugLabel.constrain([ debugLabel.leadingAnchor.constraint(equalTo: logo.leadingAnchor), debugLabel.bottomAnchor.constraint(equalTo: logo.topAnchor, constant: -4.0)]) promptHiddenConstraint = prompt.heightAnchor.constraint(equalToConstant: 0.0) prompt.constrain([ prompt.leadingAnchor.constraint(equalTo: view.leadingAnchor), prompt.trailingAnchor.constraint(equalTo: view.trailingAnchor), prompt.topAnchor.constraint(equalTo: subHeaderView.bottomAnchor), promptHiddenConstraint]) addChildViewController(assetList, layout: { assetList.view.constrain([ assetList.view.leadingAnchor.constraint(equalTo: view.leadingAnchor), assetList.view.topAnchor.constraint(equalTo: prompt.bottomAnchor), assetList.view.trailingAnchor.constraint(equalTo: view.trailingAnchor), assetList.view.bottomAnchor.constraint(equalTo: toolbar.topAnchor)]) }) toolbar.constrain([ toolbar.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor), toolbar.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: -C.padding[1]), toolbar.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor, constant: C.padding[1]), toolbar.heightAnchor.constraint(equalToConstant: toolbarHeight) ]) } private func setInitialData() { view.backgroundColor = .darkBackground subHeaderView.backgroundColor = .darkBackground subHeaderView.clipsToBounds = false navigationItem.titleView = UIView() navigationController?.navigationBar.isTranslucent = true navigationController?.navigationBar.shadowImage = #imageLiteral(resourceName: "TransparentPixel") navigationController?.navigationBar.setBackgroundImage(#imageLiteral(resourceName: "TransparentPixel"), for: .default) logo.contentMode = .center total.textAlignment = .right total.text = "0" title = "" if E.isTestnet && !E.isScreenshots { debugLabel.text = "(Testnet)" debugLabel.isHidden = false } else if (E.isTestFlight || E.isDebug), let debugHost = UserDefaults.debugBackendHost { debugLabel.text = "[\(debugHost)]" debugLabel.isHidden = false } else { debugLabel.isHidden = true } totalAssetsLabel.text = S.HomeScreen.totalAssets setupToolbar() updateTotalAssets() } //Returns the added image view so that it can be kept track of for removing later private func addNotificationIndicatorToButton(button: UIButton) -> UIImageView? { guard (button.subviews.last as? UIImageView) == nil else { return nil } // make sure we didn't already add the bell guard let buttonImageView = button.imageView else { return nil } let buyImageFrame = buttonImageView let bellImage = UIImage(named: "notification-bell") let bellImageView = UIImageView(image: bellImage) bellImageView.contentMode = .center let bellWidth = bellImage?.size.width ?? 0 let bellHeight = bellImage?.size.height ?? 0 let bellXOffset = buyImageFrame.center.x + 4 let bellYOffset = buyImageFrame.center.y - bellHeight + 2.0 bellImageView.frame = CGRect(x: bellXOffset, y: bellYOffset, width: bellWidth, height: bellHeight) button.addSubview(bellImageView) return bellImageView } private func setupToolbar() { let buttons = [(buyButtonTitle, #imageLiteral(resourceName: "buy"), #selector(buy)), (S.HomeScreen.trade, #imageLiteral(resourceName: "trade"), #selector(trade)), (S.HomeScreen.menu, #imageLiteral(resourceName: "menu"), #selector(menu))].map { (title, image, selector) -> UIBarButtonItem in let button = UIButton.vertical(title: title, image: image) button.tintColor = .navigationTint button.addTarget(self, action: selector, for: .touchUpInside) return UIBarButtonItem(customView: button) } let paddingWidth = C.padding[2] let flexibleSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil) toolbar.items = [ flexibleSpace, buttons[0], flexibleSpace, buttons[1], flexibleSpace, buttons[2], flexibleSpace ] let buttonWidth = (view.bounds.width - (paddingWidth * CGFloat(buttons.count+1))) / CGFloat(buttons.count) let buttonHeight = CGFloat(44.0) buttons.forEach { $0.customView?.frame = CGRect(x: 0, y: 0, width: buttonWidth, height: buttonHeight) } // Stash the UIButton's wrapped by the toolbar items in case we need add a badge later. buttons.forEach { (toolbarButtonItem) in if let button = toolbarButtonItem.customView as? UIButton { self.toolbarButtons.append(button) } } toolbar.isTranslucent = false toolbar.barTintColor = Theme.secondaryBackground } private func setupSubscriptions() { Store.unsubscribe(self) Store.subscribe(self, selector: { var result = false let oldState = $0 let newState = $1 $0.wallets.values.map { $0.currency }.forEach { currency in result = result || oldState[currency]?.balance != newState[currency]?.balance result = result || oldState[currency]?.currentRate?.rate != newState[currency]?.currentRate?.rate } return result }, callback: { _ in self.updateTotalAssets() self.updateAmountsForWidgets() }) // prompts Store.subscribe(self, name: .didUpgradePin, callback: { _ in if self.currentPromptView?.type == .upgradePin { self.currentPromptView = nil } }) Store.subscribe(self, name: .didWritePaperKey, callback: { _ in if self.currentPromptView?.type == .paperKey { self.currentPromptView = nil } }) Store.subscribe(self, selector: { return ($0.experiments ?? nil) != ($1.experiments ?? nil) }, callback: { _ in // Do a full reload of the toolbar so it's laid out correctly with updated button titles. self.setupToolbar() self.saveEvent("experiment.buySellMenuButton", attributes: ["show": self.shouldShowBuyAndSell ? "true" : "false"]) }) Store.subscribe(self, selector: { $0.wallets.count != $1.wallets.count }, callback: { _ in self.updateTotalAssets() self.updateAmountsForWidgets() }) } private func updateTotalAssets() { let fiatTotal: Decimal = Store.state.wallets.values.map { guard let balance = $0.balance, let rate = $0.currentRate else { return 0.0 } let amount = Amount(amount: balance, rate: rate) return amount.fiatValue }.reduce(0.0, +) totalAssetsNumberFormatter.currencySymbol = Store.state.orderedWallets.first?.currentRate?.currencySymbol ?? "" self.total.text = totalAssetsNumberFormatter.string(from: fiatTotal as NSDecimalNumber) } private func updateAmountsForWidgets() { let info: [CurrencyId: Double] = Store.state.wallets .map { ($0, $1) } .reduce(into: [CurrencyId: Double]()) { if let balance = $1.1.balance { let unit = $1.1.currency.defaultUnit $0[$1.0] = balance.cryptoAmount.double(as: unit) ?? 0 } } widgetDataShareService.updatePortfolio(info: info) widgetDataShareService.quoteCurrencyCode = Store.state.defaultCurrencyCode } // MARK: Actions @objc private func buy() { saveEvent("currency.didTapBuyBitcoin", attributes: [ "buyAndSell": shouldShowBuyAndSell ? "true" : "false" ]) didTapBuy?() } @objc private func trade() { saveEvent("currency.didTapTrade", attributes: [:]) didTapTrade?() } @objc private func menu() { didTapMenu?() } // MARK: - Prompt private let promptDelay: TimeInterval = 0.6 private let inAppNotificationDelay: TimeInterval = 3.0 private var currentPromptView: PromptView? { didSet { if currentPromptView != oldValue { var afterFadeOut: TimeInterval = 0.0 if let oldPrompt = oldValue { afterFadeOut = 0.15 UIView.animate(withDuration: 0.2, animations: { oldValue?.alpha = 0.0 }, completion: { _ in oldPrompt.removeFromSuperview() }) } if let newPrompt = currentPromptView { newPrompt.alpha = 0.0 prompt.addSubview(newPrompt) newPrompt.constrain(toSuperviewEdges: .zero) prompt.layoutIfNeeded() promptHiddenConstraint.isActive = false // fade-in after fade-out and layout UIView.animate(withDuration: 0.2, delay: afterFadeOut + 0.15, options: .curveEaseInOut, animations: { newPrompt.alpha = 1.0 }) } else { promptHiddenConstraint.isActive = true } // layout after fade-out UIView.animate(withDuration: 0.2, delay: afterFadeOut, options: .curveEaseInOut, animations: { self.view.layoutIfNeeded() }) } } } private func attemptShowPrompt() { guard okToShowPrompts else { return } guard currentPromptView == nil else { return } if let nextPrompt = PromptFactory.nextPrompt(walletAuthenticator: walletAuthenticator) { self.saveEvent("prompt.\(nextPrompt.name).displayed") // didSet {} for 'currentPromptView' will display the prompt view currentPromptView = PromptFactory.createPromptView(prompt: nextPrompt, presenter: self) nextPrompt.didPrompt() guard let prompt = currentPromptView else { return } prompt.dismissButton.tap = { [unowned self] in self.saveEvent("prompt.\(nextPrompt.name).dismissed") self.currentPromptView = nil } if !prompt.shouldHandleTap { prompt.continueButton.tap = { [unowned self] in if let trigger = nextPrompt.trigger { Store.trigger(name: trigger) } self.saveEvent("prompt.\(nextPrompt.name).trigger") self.currentPromptView = nil } } } else { currentPromptView = nil } } // MARK: - required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
1eb351af45bc89ad489d77e49d6320c5
38.642369
150
0.604091
false
false
false
false
Aishwarya-Ramakrishnan/sparkios
refs/heads/master
Source/Phone/WebSocketService.swift
mit
1
// Copyright 2016 Cisco Systems Inc // // 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 Starscream import SwiftyJSON class WebSocketService: WebSocketDelegate { static let sharedInstance = WebSocketService() private var socket: WebSocket? private let MessageBatchingIntervalInSec = 0.5 private let ConnectionTimeoutIntervalInSec = 60.0 private var connectionTimeoutTimer: Timer? private var messageBatchingTimer: Timer? private var connectionRetryCounter: ExponentialBackOffCounter private var pendingMessages: [JSON] init() { connectionRetryCounter = ExponentialBackOffCounter(minimum: 0.5, maximum: 32, multiplier: 2) pendingMessages = [JSON]() } deinit { cancelConnectionTimeOutTimer() cancelMessageBatchingTimer() } func connect(_ webSocketUrl: URL) { if socket == nil { socket = createWebSocket(webSocketUrl) guard socket != nil else { Logger.error("Skip connection due to failure of creating socket") return } } if socket!.isConnected { Logger.warn("Web socket is already connected") return } Logger.info("Web socket is being connected") socket?.connect() scheduleConnectionTimeoutTimer() } func disconnect() { guard socket != nil else { Logger.warn("Web socket has not been connected") return } guard socket!.isConnected else { Logger.warn("Web socket is already disconnected") return } Logger.info("Web socket is being disconnected") socket?.disconnect() socket = nil } private func reconnect() { guard socket != nil else { Logger.warn("Web socket has not been connected") return } guard !socket!.isConnected else { Logger.warn("Web socket has already connected") return } Logger.info("Web socket is being reconnected") socket?.connect() } private func createWebSocket(_ webSocketUrl: URL) -> WebSocket? { // Need to check authorization, avoid crash when logout as soon as login guard let authorization = AuthManager.sharedInstance.getAuthorization() else { Logger.error("Failed to create web socket due to no authorization") return nil } socket = WebSocket(url: webSocketUrl) if socket == nil { Logger.error("Failed to create web socket") return nil } socket?.headers.unionInPlace(authorization) socket?.voipEnabled = true socket?.disableSSLCertValidation = true socket?.delegate = self return socket } private func despatch_main_after(_ delay: Double, closure: @escaping () -> Void) { DispatchQueue.main.asyncAfter( deadline: DispatchTime.now() + Double(Int64(delay * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC), execute: closure ) } // MARK: - Websocket Delegate Methods. func websocketDidConnect(socket: WebSocket) { Logger.info("Websocket is connected") connectionRetryCounter.reset() scheduleMessageBatchingTimer() cancelConnectionTimeOutTimer() ReachabilityService.sharedInstance.fetch() } func websocketDidDisconnect(socket: WebSocket, error: NSError?) { cancelMessageBatchingTimer() cancelConnectionTimeOutTimer() guard let code = error?.code, let discription = error?.localizedDescription else { return } Logger.info("Websocket is disconnected: \(code), \(discription)") guard self.socket != nil else { Logger.info("Websocket is disconnected on purpose") return } let backoffTime = connectionRetryCounter.next() if code > Int(WebSocket.CloseCode.normal.rawValue) { // Abnormal disconnection, re-register device. self.socket = nil Logger.error("Abnormal disconnection, re-register device in \(backoffTime) seconds") despatch_main_after(backoffTime) { Spark.phone.register(nil) } } else { // Unexpected disconnection, reconnect socket. Logger.warn("Unexpected disconnection, websocket will reconnect in \(backoffTime) seconds") despatch_main_after(backoffTime) { self.reconnect() } } } func websocketDidReceiveMessage(socket: WebSocket, text: String) { Logger.info("Websocket got some text: \(text)") } func websocketDidReceiveData(socket: WebSocket, data: Data) { let json = JSON(data: data) ackMessage(socket, messageId: json["id"].string!) pendingMessages.append(json) } // MARK: - Websocket Event Handler private func ackMessage(_ socket: WebSocket, messageId: String) { let ack = JSON(["type": "ack", "messageId": messageId]) do { let ackData: Data = try ack.rawData(options: .prettyPrinted) socket.write(data: ackData) } catch { Logger.error("Failed to acknowledge message") } } private func processMessages() { for message in pendingMessages { let eventData = message["data"] if let eventType = eventData["eventType"].string { if eventType.hasPrefix("locus") { Logger.info("locus event: \(eventData.object)") CallManager.sharedInstance.handle(callEventJson: eventData.object) } } } pendingMessages.removeAll() } // MARK: - Web Socket Timers private func scheduledTimerWithTimeInterval(_ timeInterval: TimeInterval, selector: Selector, repeats: Bool) -> Timer { return Timer.scheduledTimer(timeInterval: timeInterval, target: self, selector: selector, userInfo: nil, repeats: repeats) } private func scheduleMessageBatchingTimer() { messageBatchingTimer = scheduledTimerWithTimeInterval(MessageBatchingIntervalInSec, selector: #selector(onMessagesBatchingTimerFired), repeats: true) } private func cancelMessageBatchingTimer() { messageBatchingTimer?.invalidate() messageBatchingTimer = nil } private func scheduleConnectionTimeoutTimer() { connectionTimeoutTimer = scheduledTimerWithTimeInterval(ConnectionTimeoutIntervalInSec, selector: #selector(onConnectionTimeOutTimerFired), repeats: false) } private func cancelConnectionTimeOutTimer() { connectionTimeoutTimer?.invalidate() connectionTimeoutTimer = nil } @objc private func onMessagesBatchingTimerFired() { processMessages() } @objc private func onConnectionTimeOutTimerFired() { Logger.info("Connect timed out, try to reconnect") reconnect() } }
49235964cfb0f722c653a121a5d87e12
33.6625
163
0.629883
false
false
false
false
hq7781/MoneyBook
refs/heads/master
MoneyBook/Model/Payment/ProductManager.swift
mit
1
// // ProductManager.swift // MoneyBook // // Created by HongQuan on 2017/08/15. // Copyright © 2017年 Roan.Hong. All rights reserved. // import Foundation import StoreKit fileprivate var productManagers : Set<ProductManager> = Set() class ProductManager: NSObject, SKProductsRequestDelegate { static var subscriptionProduct : SKProduct? = nil fileprivate var completion : (([SKProduct]?,NSError?) -> Void)? static func getProducts(withProductIdentifiers productIdentifiers : [String],completion:(([SKProduct]?,NSError?) -> Void)?){ let productManager = ProductManager() productManager.completion = completion let request = SKProductsRequest(productIdentifiers: Set(productIdentifiers)) request.delegate = productManager request.start() productManagers.insert(productManager) } static func getSubscriptionProduct(completion:(() -> Void)? = nil) { guard ProductManager.subscriptionProduct == nil else { if let completion = completion { completion() } return } let productIdentifier = "xxx.xxx.xxx.xxx" ProductManager.getProducts(withProductIdentifiers: [productIdentifier], completion: { (_products, error) -> Void in if let product = _products?.first { ProductManager.subscriptionProduct = product } if let completion = completion { completion() } }) } func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse) { var error : NSError? = nil if response.products.count == 0 { error = NSError(domain: "ProductsRequestErrorDomain", code: 0, userInfo: [NSLocalizedDescriptionKey:"プロダクトを取得できませんでした。"]) } completion?(response.products, error) } func request(_ request: SKRequest, didFailWithError error: Error) { let error = NSError(domain: "ProductsRequestErrorDomain", code: 0, userInfo: [NSLocalizedDescriptionKey:"プロダクトを取得できませんでした。"]) completion?(nil,error) productManagers.remove(self) } func requestDidFinish(_ request: SKRequest) { productManagers.remove(self) } }
094c1033ddd9ff68e134a77a3c1c368e
32.676056
97
0.619406
false
false
false
false
mrdepth/EVEUniverse
refs/heads/master
Neocom/Neocom/Character/Skills/Skills.swift
lgpl-2.1
2
// // Skills.swift // Neocom // // Created by Artem Shimanski on 1/22/20. // Copyright © 2020 Artem Shimanski. All rights reserved. // import SwiftUI import EVEAPI import Alamofire import Expressible import Combine struct Skills: View { var editMode: Bool @Environment(\.managedObjectContext) private var managedObjectContext private func getSkills() -> FetchedResultsController<SDEInvType> { let controller = managedObjectContext .from(SDEInvType.self) .filter(/\SDEInvType.published == true && /\SDEInvType.group?.category?.categoryID == SDECategoryID.skill.rawValue) .sort(by: \SDEInvType.group?.groupName, ascending: true) .sort(by: \SDEInvType.typeName, ascending: true) .fetchedResultsController(sectionName: /\SDEInvType.group?.groupName, cacheName: nil) return FetchedResultsController(controller) } private let skills: Lazy<FetchedResultsController<SDEInvType>, Never> = Lazy() var body: some View { let skills = self.skills.get(initial: getSkills()) return SkillsContent(skills: skills, editMode: editMode).navigationBarTitle(Text("Skills")) } } struct SkillsContent: View { var skills: FetchedResultsController<SDEInvType> var editMode: Bool @Environment(\.backgroundManagedObjectContext) private var backgroundManagedObjectContext @EnvironmentObject private var sharedState: SharedState @State private var filter = SkillsFilter.Filter.my @ObservedObject private var pilot = Lazy<DataLoader<Pilot, AFError>, Account>() private func loadPilot(account: Account) -> DataLoader<Pilot, AFError> { DataLoader(Pilot.load(sharedState.esi.characters.characterID(Int(account.characterID)), in: self.backgroundManagedObjectContext).receive(on: RunLoop.main)) } private func subtitle(for skills: [SDEInvType], pilot: Pilot) -> Text { let items = skills.compactMap { type -> (skill: Pilot.Skill, type: SDEInvType, trained: ESI.Skill?, queued: Pilot.SkillQueueItem?)? in guard let skill = Pilot.Skill(type: type) else {return nil} let typeID = Int(type.typeID) let trainedSkill = pilot.trainedSkills[Int(typeID)] let queuedSkill = pilot.skillQueue.filter{$0.queuedSkill.skillID == typeID}.min{$0.queuedSkill.finishedLevel < $1.queuedSkill.finishedLevel} return (skill, type, trainedSkill, queuedSkill) } switch filter { case .my: let skills = items.compactMap{$0.trained} let sp = skills.map{$0.skillpointsInSkill}.reduce(0, +) return Text("\(skills.count) Skills, \(UnitFormatter.localizedString(from: sp, unit: .skillPoints, style: .long))") case .canTrain: let skills = items.filter{($0.trained?.trainedSkillLevel ?? 0) < 5} let mySP = items.compactMap{$0.trained?.skillpointsInSkill}.map{Int64($0)}.reduce(0, +) let totalSP = items.map{i in (1...5).map{Int64(i.skill.skillPoints(at: $0))}.reduce(0, +)}.reduce(0, +) return Text("\(skills.count) Skills, \(UnitFormatter.localizedString(from: totalSP - mySP, unit: .skillPoints, style: .long))") case .notKnown: let skills = items.filter{$0.trained == nil} let sp = skills.map{i in (1...5).map{Int64(i.skill.skillPoints(at: $0))}.reduce(0, +)}.reduce(0, +) return Text("\(skills.count) Skills, \(UnitFormatter.localizedString(from: sp, unit: .skillPoints, style: .long))") case .all: let sp = items.map{i in (1...5).map{Int64(i.skill.skillPoints(at: $0))}.reduce(0, +)}.reduce(0, +) return Text("\(items.count) Skills, \(UnitFormatter.localizedString(from: sp, unit: .skillPoints, style: .long))") } } var body: some View { let pilot = sharedState.account.map{account in self.pilot.get(account, initial: self.loadPilot(account: account))}?.result?.value// ?? .some(.empty) return List { Section(header: SkillsFilter(filter: $filter)) { ForEach(skills.sections, id: \.name) { section in NavigationLink(destination: SkillsPage(skills: section, filter: self.$filter, pilot: pilot, editMode: self.editMode)) { VStack(alignment: .leading) { Text(section.name) pilot.map { pilot in self.subtitle(for: section.objects, pilot: pilot).modifier(SecondaryLabelModifier()) } } } } } }.listStyle(GroupedListStyle()) } } struct SkillsFilter: View { @Binding var filter: Filter enum Filter { case my case canTrain case notKnown case all } var body: some View { Picker("Filter", selection: $filter) { Text("My", comment: "Skill Borwser. My skills.").tag(Filter.my) Text("Can Train", comment: "Skill Borwser").tag(Filter.canTrain) Text("Not Known", comment: "Skill Borwser").tag(Filter.notKnown) Text("All", comment: "Skill Borwser. All skills.").tag(Filter.all) }.pickerStyle(SegmentedPickerStyle()) } } #if DEBUG struct Skills_Previews: PreviewProvider { static var previews: some View { NavigationView { Skills(editMode: false) } .modifier(ServicesViewModifier.testModifier()) } } #endif
3419ead973832cfce57e9e0dcca0005b
42.523438
163
0.624843
false
false
false
false
massimoksi/Gaston
refs/heads/master
Source/UIFont.swift
mit
1
// Copyright (c) 2016 Massimo Peri (@massimoksi) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit public extension UIFont { /** A version of the font with monospaced numbers. */ public var monospacedDigitFont: UIFont { if #available(iOS 9, *) { let oldFontDescriptor = fontDescriptor() let newFontDescriptor = oldFontDescriptor.monospacedDigitFontDescriptor return UIFont(descriptor: newFontDescriptor, size: 0.0) } else { return self } } } // MARK: - private extension UIFontDescriptor { var monospacedDigitFontDescriptor: UIFontDescriptor { let fontDescriptorFeatures = [ [ UIFontFeatureTypeIdentifierKey: kNumberSpacingType, UIFontFeatureSelectorIdentifierKey: kMonospacedNumbersSelector ] ] let fontDescriptorAttributes = [UIFontDescriptorFeatureSettingsAttribute: fontDescriptorFeatures] let fontDescriptor = self.fontDescriptorByAddingAttributes(fontDescriptorAttributes) return fontDescriptor } }
9c4a1f39c19535e0a8d8703020913a3e
36.719298
105
0.717209
false
false
false
false
frtlupsvn/Vietnam-To-Go
refs/heads/master
Pods/Former/Former/Cells/FormTextViewCell.swift
mit
1
// // FormTextViewCell.swift // Former-Demo // // Created by Ryo Aoyama on 7/28/15. // Copyright © 2015 Ryo Aoyama. All rights reserved. // import UIKit public class FormTextViewCell: FormCell, TextViewFormableRow { // MARK: Public public private(set) weak var textView: UITextView! public private(set) weak var titleLabel: UILabel! public func formTextView() -> UITextView { return textView } public func formTitleLabel() -> UILabel? { return titleLabel } public override func updateWithRowFormer(rowFormer: RowFormer) { super.updateWithRowFormer(rowFormer) leftConst.constant = titleLabel.text?.isEmpty ?? true ? 5 : 15 } public override func setup() { super.setup() let titleLabel = UILabel() titleLabel.setContentHuggingPriority(500, forAxis: .Horizontal) titleLabel.translatesAutoresizingMaskIntoConstraints = false contentView.insertSubview(titleLabel, atIndex: 0) self.titleLabel = titleLabel let textView = UITextView() textView.backgroundColor = .clearColor() textView.font = .systemFontOfSize(17) textView.translatesAutoresizingMaskIntoConstraints = false contentView.insertSubview(textView, atIndex: 0) self.textView = textView let constraints = [ NSLayoutConstraint.constraintsWithVisualFormat( "V:|-10-[label(>=0)]", options: [], metrics: nil, views: ["label": titleLabel] ), NSLayoutConstraint.constraintsWithVisualFormat( "V:|-0-[text]-0-|", options: [], metrics: nil, views: ["text": textView] ), NSLayoutConstraint.constraintsWithVisualFormat( "H:[label]-5-[text]-10-|", options: [], metrics: nil, views: ["label": titleLabel, "text": textView] ) ].flatMap { $0 } let leftConst = NSLayoutConstraint( item: titleLabel, attribute: .Leading, relatedBy: .Equal, toItem: contentView, attribute: .Leading, multiplier: 1, constant: 15 ) contentView.addConstraints(constraints + [leftConst]) self.leftConst = leftConst } // MARK: Private private weak var leftConst: NSLayoutConstraint! private weak var rightConst: NSLayoutConstraint! }
927b3717e110222211e37452b9873b81
29.988095
71
0.57648
false
false
false
false
crazypoo/PTools
refs/heads/master
Pods/FluentDarkModeKit/Sources/FluentDarkModeKit/Extensions/UITextField+DarkModeKit.swift
mit
1
// // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // extension UITextField { override open func dmTraitCollectionDidChange(_ previousTraitCollection: DMTraitCollection?) { super.dmTraitCollectionDidChange(previousTraitCollection) if #available(iOS 13.0, *) { return } else { dm_updateDynamicColors() if let dynamicTextColor = textColor?.copy() as? DynamicColor { textColor = dynamicTextColor } keyboardAppearance = { if DMTraitCollection.override.userInterfaceStyle == .dark { return .dark } else { return .default } }() } } } extension UITextField { /// `UITextField` will not call `super.willMove(toWindow:)` in its implementation, so we need to swizzle it separately. static let swizzleTextFieldWillMoveToWindowOnce: Void = { let selector = #selector(willMove(toWindow:)) guard let method = class_getInstanceMethod(UITextField.self, selector) else { assertionFailure(DarkModeManager.messageForSwizzlingFailed(class: UITextField.self, selector: selector)) return } let imp = method_getImplementation(method) class_replaceMethod(UITextField.self, selector, imp_implementationWithBlock({ (self: UITextField, window: UIWindow?) -> Void in let oldIMP = unsafeBitCast(imp, to: (@convention(c) (UITextField, Selector, UIWindow?) -> Void).self) oldIMP(self, selector, window) self.dmTraitCollectionDidChange(nil) } as @convention(block) (UITextField, UIWindow?) -> Void), method_getTypeEncoding(method)) }() }
62722e4cc087c7630ab185001e084006
32.530612
131
0.690201
false
false
false
false
nissivm/DemoShop
refs/heads/master
Demo Shop/Objects/Device.swift
mit
2
// // Device.swift // Demo Shop // // Created by Nissi Vieira Miranda on 1/13/16. // Copyright © 2016 Nissi Vieira Miranda. All rights reserved. // import Foundation class Device { static var IS_IPHONE: Bool { get { if UIDevice.currentDevice().userInterfaceIdiom == .Phone { return true } else { return false } } } static var IS_IPHONE_4: Bool { get { if IS_IPHONE && UIScreen.mainScreen().bounds.size.height == 480.0 { return true } else { return false } } } static var IS_IPHONE_5: Bool { get { if IS_IPHONE && UIScreen.mainScreen().bounds.size.height == 568.0 { return true } else { return false } } } static var IS_IPHONE_6: Bool { get { if IS_IPHONE && UIScreen.mainScreen().bounds.size.height == 667.0 { return true } else { return false } } } static var IS_IPHONE_6_PLUS: Bool { get { if IS_IPHONE && UIScreen.mainScreen().bounds.size.height == 736.0 { return true } else { return false } } } }
bcd031b28a3da5bf01ba384d502beadf
19.363636
77
0.395022
false
false
false
false
lyft/SwiftLint
refs/heads/master
Source/SwiftLintFramework/Rules/MarkRule.swift
mit
1
import Foundation import SourceKittenFramework private let nonSpace = "[^ ]" private let twoOrMoreSpace = " {2,}" private let mark = "MARK:" private let nonSpaceOrTwoOrMoreSpace = "(?:\(nonSpace)|\(twoOrMoreSpace))" private let nonSpaceOrTwoOrMoreSpaceOrNewline = "(?:[^ \n]|\(twoOrMoreSpace))" public struct MarkRule: CorrectableRule, ConfigurationProviderRule { public var configuration = SeverityConfiguration(.warning) public init() {} public static let description = RuleDescription( identifier: "mark", name: "Mark", description: "MARK comment should be in valid format. e.g. '// MARK: ...' or '// MARK: - ...'", kind: .lint, nonTriggeringExamples: [ "// MARK: good\n", "// MARK: - good\n", "// MARK: -\n", "// BOOKMARK", "//BOOKMARK", "// BOOKMARKS" ], triggeringExamples: [ "↓//MARK: bad", "↓// MARK:bad", "↓//MARK:bad", "↓// MARK: bad", "↓// MARK: bad", "↓// MARK: -bad", "↓// MARK:- bad", "↓// MARK:-bad", "↓//MARK: - bad", "↓//MARK:- bad", "↓//MARK: -bad", "↓//MARK:-bad", "↓//Mark: bad", "↓// Mark: bad", "↓// MARK bad", "↓//MARK bad", "↓// MARK - bad", issue1029Example ], corrections: [ "↓//MARK: comment": "// MARK: comment", "↓// MARK: comment": "// MARK: comment", "↓// MARK:comment": "// MARK: comment", "↓// MARK: comment": "// MARK: comment", "↓//MARK: - comment": "// MARK: - comment", "↓// MARK:- comment": "// MARK: - comment", "↓// MARK: -comment": "// MARK: - comment", issue1029Example: issue1029Correction ] ) private let spaceStartPattern = "(?:\(nonSpaceOrTwoOrMoreSpace)\(mark))" private let endNonSpacePattern = "(?:\(mark)\(nonSpace))" private let endTwoOrMoreSpacePattern = "(?:\(mark)\(twoOrMoreSpace))" private let invalidEndSpacesPattern = "(?:\(mark)\(nonSpaceOrTwoOrMoreSpace))" private let twoOrMoreSpacesAfterHyphenPattern = "(?:\(mark) -\(twoOrMoreSpace))" private let nonSpaceOrNewlineAfterHyphenPattern = "(?:\(mark) -[^ \n])" private let invalidSpacesAfterHyphenPattern = "(?:\(mark) -\(nonSpaceOrTwoOrMoreSpaceOrNewline))" private let invalidLowercasePattern = "(?:// ?[Mm]ark:)" private let missingColonPattern = "(?:// ?MARK[^:])" private var pattern: String { return [ spaceStartPattern, invalidEndSpacesPattern, invalidSpacesAfterHyphenPattern, invalidLowercasePattern, missingColonPattern ].joined(separator: "|") } public func validate(file: File) -> [StyleViolation] { return violationRanges(in: file, matching: pattern).map { StyleViolation(ruleDescription: type(of: self).description, severity: configuration.severity, location: Location(file: file, characterOffset: $0.location)) } } public func correct(file: File) -> [Correction] { var result = [Correction]() result.append(contentsOf: correct(file: file, pattern: spaceStartPattern, replaceString: "// MARK:")) result.append(contentsOf: correct(file: file, pattern: endNonSpacePattern, replaceString: "// MARK: ", keepLastChar: true)) result.append(contentsOf: correct(file: file, pattern: endTwoOrMoreSpacePattern, replaceString: "// MARK: ")) result.append(contentsOf: correct(file: file, pattern: twoOrMoreSpacesAfterHyphenPattern, replaceString: "// MARK: - ")) result.append(contentsOf: correct(file: file, pattern: nonSpaceOrNewlineAfterHyphenPattern, replaceString: "// MARK: - ", keepLastChar: true)) return result.unique } private func correct(file: File, pattern: String, replaceString: String, keepLastChar: Bool = false) -> [Correction] { let violations = violationRanges(in: file, matching: pattern) let matches = file.ruleEnabled(violatingRanges: violations, for: self) if matches.isEmpty { return [] } var nsstring = file.contents.bridge() let description = type(of: self).description var corrections = [Correction]() for var range in matches.reversed() { if keepLastChar { range.length -= 1 } let location = Location(file: file, characterOffset: range.location) nsstring = nsstring.replacingCharacters(in: range, with: replaceString).bridge() corrections.append(Correction(ruleDescription: description, location: location)) } file.write(nsstring.bridge()) return corrections } private func violationRanges(in file: File, matching pattern: String) -> [NSRange] { let nsstring = file.contents.bridge() return file.rangesAndTokens(matching: pattern).filter { _, syntaxTokens in return !syntaxTokens.isEmpty && SyntaxKind(rawValue: syntaxTokens[0].type) == .comment }.compactMap { range, syntaxTokens in let identifierRange = nsstring .byteRangeToNSRange(start: syntaxTokens[0].offset, length: 0) return identifierRange.map { NSUnionRange($0, range) } } } } private let issue1029Example = "↓//MARK:- Top-Level bad mark\n" + "↓//MARK:- Another bad mark\n" + "struct MarkTest {}\n" + "↓// MARK:- Bad mark\n" + "extension MarkTest {}\n" private let issue1029Correction = "// MARK: - Top-Level bad mark\n" + "// MARK: - Another bad mark\n" + "struct MarkTest {}\n" + "// MARK: - Bad mark\n" + "extension MarkTest {}\n"
4e9d7c84e509407640ed71672abb8ccc
38.940476
103
0.512072
false
false
false
false
OpenTimeApp/OpenTimeIOSSDK
refs/heads/master
OpenTimeSDK/Classes/OTAPIRawResponse.swift
mit
1
// // APIRawResponse.swift // OpenTime // // Created by Josh Woodcock on 5/10/15. // Copyright (c) 2015 Connecting Open Time, LLC. All rights reserved. // public class OTAPIRawResponse { // Whether or not the request logically succeeded or logically failed. // @SerializedName("success") private var _success: Bool; // The message associated with the success or failed response. // @SerializedName("message") private var _message: String; // String representation of data object. // @SerializedName("data") private var _rawData: AnyObject?; /** Designated constructor. */ public init() { self._success = false; self._message = "Error: Message not parsed from server response"; } /** Gets the success or failure from the response body from the server. - returns: Whether or not the request to the server succeeded. */ public func isSuccessful() -> Bool { return self._success; } /** Gets the message about why the response failed or succeeded. - returns: A message explaining why the request to the server failed or succeeded. */ public func getMessage() -> String { return self._message; } /** Gets a parsed object usually a dictionairy or an array. - returns: nil, an array of dictionaries, or a dictionary with data in it. */ public func getRawData() -> AnyObject? { return self._rawData; } /** Tries to parse data elements from the first level of JSON elements. - parameter responseObject: The object given by AFNetworking by parsing a JSON string. - returns: A raw response object with the values of the first level of the JSON object. */ public static func deserialize(_ responseObject: AnyObject!) -> OTAPIRawResponse { // Setup the raw response object. let rawResponse: OTAPIRawResponse = OTAPIRawResponse(); if(responseObject != nil) { // Try to get the success from the response object. if(OTSerialHelper.keyExists(responseObject, key: "success") == true) { rawResponse._success = responseObject.object(forKey: "success") as! Bool; } // Try to get the message from the response object. if(OTSerialHelper.keyExists(responseObject, key: "message") == true) { rawResponse._message = responseObject.object(forKey: "message") as! String; } // Try to get the data from the response object. if (rawResponse._success == true && OTSerialHelper.keyExists(responseObject, key: "data") == true) { rawResponse._rawData = self._getData(responseObject); } } if(responseObject != nil && rawResponse._success == false) { // Print the response object. print(responseObject, terminator: ""); } return rawResponse; } /** Gets the data element from the response object. - returns: The data element of the response object. */ private static func _getData(_ responseObject: AnyObject) -> AnyObject! { // Try to get the data object. let data: AnyObject! = responseObject["data"]! as AnyObject!; // Set data property of the OTAPIResponse as a typed object. if(data is NSDictionary) { // Its a dictionary. Cast it as a dictionary. return data as! NSDictionary; }else if(data is NSArray){ // Its an array. Cast it as an array. return data as! NSArray; }else{ // Its either empty or something besides an array or dictionary. return data; } } }
db58042066c9a44846d34e85a776981f
31.841667
112
0.587922
false
false
false
false
spacedrabbit/100-days
refs/heads/master
One00Days/One00Days/Day36Playground.playground/Contents.swift
mit
1
//: Playground - noun: a place where people can play // Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it. import UIKit func numbersInArray(var num: Int) -> [Int] { var numArray: [Int] = [] while num % 10 > 0 { numArray.append(num % 10) num = num / 10 } return numArray } func sumNumbers(numbers: [Int]) -> Int { var total: Int = 0 for num in numbers { total += num } return total } func doTheThingFor(num: Int) { var new = numbersInArray(num) var newTotal: Int var newTotalCount: Int = 0 if new.count < 2 { print("final: \(num)") return } repeat { newTotal = sumNumbers(new) newTotalCount = numbersInArray(newTotal).count new = numbersInArray(newTotal) } while newTotalCount > 1 print("final: \(new)") } //doTheThingFor(99999999) doTheThingFor(0) //doTheThingFor(10) doTheThingFor(2) doTheThingFor(1) doTheThingFor(1111111111)
e779094a0677d41989935590ed0bebf2
18.26
101
0.638629
false
false
false
false
PekanMmd/Pokemon-XD-Code
refs/heads/master
Revolution Tool CL/objects/PBRConstant.swift
gpl-2.0
1
// // XDSConstant.swift // Revolution Tool CL // // Created by The Steez on 26/12/2018. // import Foundation enum XDSConstantTypes { // same as classes in script class info case void case integer case float case string case vector case array case codePointer case unknown(Int) var string : String { get { switch self { case .void : return "Void" case .integer : return "Int" case .float : return "Float" case .string : return "String" case .vector : return "Vector" case .array : return "Array" case .codePointer : return "Pointer" case .unknown(let val) : return "Class\(val)" } } } var index : Int { switch self { case .void : return 0 case .integer : return 1 case .float : return 2 case .string : return 3 case .vector : return 4 case .array : return 7 case .codePointer : return 8 case .unknown(let val) : return val } } static func typeWithIndex(_ id: Int) -> XDSConstantTypes { switch id { case 0 : return .void case 1 : return .integer case 2 : return .float case 3 : return .string case 4 : return .vector case 7 : return .array case 8 : return .codePointer default : return .unknown(id) } } static func typeWithName(_ name: String) -> XDSConstantTypes? { // not sure of actual number of types but should be fewer than 100 for i in 0 ..< 100 { let type = XDSConstantTypes.typeWithIndex(i) if type.string == name { return type } } return nil } } class XDSConstant: NSObject { var type: XDSConstantTypes = .void var value: UInt32 = 0 override var description: String { return self.rawValueString } var asFloat: Float { return value.hexToSignedFloat() } var asInt: Int { return value.int32 } var rawValueString: String { switch self.type { case .float: var text = String(format: "%.4f", self.asFloat) if !text.contains(".") { text += ".0" } while text.last == "0" { text.removeLast() } if text.last == "." { text += "0" } return text case .string: return "String(\(self.asInt))" case .vector: return "vector_" + String(format: "%02d", self.asInt) case .integer: return self.asInt >= 0x200 ? self.asInt.hexString() : "\(self.asInt)" case .void: return "Null" case .array: return "array_" + String(format: "%02d", self.asInt) case .codePointer: return XDSExpr.locationIndex(self.asInt).text[0] case .unknown(let i): return XGScriptClass.classes(i).name + "(\(self.asInt))" } } init(type: Int, rawValue: UInt32) { super.init() self.type = XDSConstantTypes.typeWithIndex(type) self.value = rawValue } convenience init(type: XDSConstantTypes, rawValue: Int) { self.init(type: type.index, rawValue: rawValue.unsigned) } class var null: XDSConstant { return XDSConstant(type: 0, rawValue: 0) } class func integer(_ val: Int) -> XDSConstant { return XDSConstant(type: XDSConstantTypes.integer.index, rawValue: val.unsigned) } class func integer(_ val: UInt32) -> XDSConstant { return XDSConstant(type: XDSConstantTypes.integer.index, rawValue: val) } class func float(_ val: Float) -> XDSConstant { return XDSConstant(type: XDSConstantTypes.float.index, rawValue: val.floatToHex()) } }
f702ee1160e8f4c8c12bbc1860b3d865
20.697368
84
0.649788
false
false
false
false
knehez/edx-app-ios
refs/heads/master
Source/DiscussionTopicsViewController.swift
apache-2.0
2
// // DiscussionTopicsViewController.swift // edX // // Created by Jianfeng Qiu on 11/05/2015. // Copyright (c) 2015 edX. All rights reserved. // import Foundation import UIKit public class DiscussionTopicsViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UISearchBarDelegate { public class Environment { private let config: OEXConfig? private let courseDataManager : CourseDataManager private let networkManager : NetworkManager? private weak var router: OEXRouter? private let styles : OEXStyles public init(config: OEXConfig, courseDataManager : CourseDataManager, networkManager: NetworkManager?, router: OEXRouter?, styles: OEXStyles) { self.config = config self.courseDataManager = courseDataManager self.networkManager = networkManager self.router = router self.styles = styles } } private let topics = BackedStream<[DiscussionTopic]>() private let environment: Environment private let courseID : String private let searchBar = UISearchBar() private let loadController : LoadStateViewController private var searchBarTextStyle : OEXTextStyle { return OEXTextStyle(weight: .Normal, size: .XSmall, color: self.environment.styles.neutralBlack()) } private let contentView = UIView() private let tableView = UITableView() public init(environment: Environment, courseID: String) { self.environment = environment self.courseID = courseID self.loadController = LoadStateViewController(styles : environment.styles) super.init(nibName: nil, bundle: nil) let stream = environment.courseDataManager.discussionManagerForCourseWithID(courseID).topics topics.backWithStream(stream.map { return DiscussionTopic.linearizeTopics($0) } ) } public required init(coder aDecoder: NSCoder) { // required by the compiler because UIViewController implements NSCoding, // but we don't actually want to serialize these things fatalError("init(coder:) has not been implemented") } public override func viewDidLoad() { super.viewDidLoad() self.navigationItem.title = OEXLocalizedString("DISCUSSION_TOPICS", nil) self.navigationItem.backBarButtonItem = UIBarButtonItem(title: " ", style: .Plain, target: nil, action: nil) view.backgroundColor = self.environment.styles.standardBackgroundColor() self.view.addSubview(contentView) // Set up tableView tableView.dataSource = self tableView.delegate = self tableView.applyStandardSeparatorInsets() self.contentView.addSubview(tableView) searchBar.placeholder = OEXLocalizedString("SEARCH_ALL_POSTS", nil) searchBar.delegate = self searchBar.showsCancelButton = false searchBar.searchBarStyle = .Minimal searchBar.sizeToFit() tableView.tableHeaderView = searchBar contentView.snp_makeConstraints {make in make.edges.equalTo(self.view) } tableView.snp_makeConstraints { make -> Void in make.edges.equalTo(self.contentView) } // Register tableViewCell tableView.registerClass(DiscussionTopicsCell.self, forCellReuseIdentifier: DiscussionTopicsCell.identifier) loadController.setupInController(self, contentView: contentView) topics.listen(self, success : {[weak self]_ in self?.loadedData() }, failure : {[weak self] error in self?.loadController.state = LoadState.failed(error: error) }) } func loadedData() { self.loadController.state = topics.value?.count == 0 ? LoadState.empty(icon: .NoTopics, message : OEXLocalizedString("UNABLE_TO_LOAD_COURSE_CONTENT", nil)) : .Loaded self.tableView.reloadData() } public override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) if let indexPath = tableView.indexPathForSelectedRow() { tableView.deselectRowAtIndexPath(indexPath, animated: false) } self.navigationController?.setNavigationBarHidden(false, animated: animated) } public func searchBarSearchButtonClicked(searchBar: UISearchBar) { if searchBar.text.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()).isEmpty { return } // TODO: Move this inside the search screen and add a failure + empty cases let apiRequest = DiscussionAPI.searchThreads(courseID: self.courseID, searchText: searchBar.text) environment.networkManager?.taskForRequest(apiRequest) {[weak self] result in if let threads: [DiscussionThread] = result.data, owner = self { owner.environment.router?.showPostsFromController(owner, courseID: owner.courseID, searchResults: threads) } } } public func searchBarTextDidBeginEditing(searchBar: UISearchBar) { searchBar.setShowsCancelButton(true, animated: true) } public func searchBarCancelButtonClicked(searchBar: UISearchBar) { searchBar.resignFirstResponder() self.view.endEditing(true) searchBar.setShowsCancelButton(false, animated: true) } // MARK: - TableView Data and Delegate public func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.topics.value?.count ?? 0 } public func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 50.0 } public func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(DiscussionTopicsCell.identifier, forIndexPath: indexPath) as! DiscussionTopicsCell if let topic = self.topics.value?[indexPath.row] { cell.topic = topic } return cell } public func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { self.view.endEditing(true) if let topic = self.topics.value?[indexPath.row] { environment.router?.showPostsFromController(self, courseID: courseID, topic: topic) } } } extension DiscussionTopicsViewController { public func t_topicsLoaded() -> Stream<[DiscussionTopic]> { return topics } }
2a5fc42416b246e88c9858906e5fcaee
35.340426
173
0.660079
false
false
false
false
blockchain/My-Wallet-V3-iOS
refs/heads/master
Modules/FeatureWalletConnect/Sources/FeatureWalletConnectData/Handlers/TransactionRequestHandler.swift
lgpl-3.0
1
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import AnalyticsKit import BigInt import Combine import DIKit import EthereumKit import FeatureWalletConnectDomain import Foundation import MoneyKit import PlatformKit import ToolKit import WalletConnectSwift final class TransactionRequestHandler: RequestHandler { private let accountProvider: WalletConnectAccountProviderAPI private let analyticsEventRecorder: AnalyticsEventRecorderAPI private let enabledCurrenciesService: EnabledCurrenciesServiceAPI private let getSession: (WCURL) -> Session? private let responseEvent: (WalletConnectResponseEvent) -> Void private let userEvent: (WalletConnectUserEvent) -> Void private var cancellables: Set<AnyCancellable> = [] init( accountProvider: WalletConnectAccountProviderAPI = resolve(), analyticsEventRecorder: AnalyticsEventRecorderAPI = resolve(), enabledCurrenciesService: EnabledCurrenciesServiceAPI = resolve(), getSession: @escaping (WCURL) -> Session?, responseEvent: @escaping (WalletConnectResponseEvent) -> Void, userEvent: @escaping (WalletConnectUserEvent) -> Void ) { self.accountProvider = accountProvider self.analyticsEventRecorder = analyticsEventRecorder self.enabledCurrenciesService = enabledCurrenciesService self.getSession = getSession self.responseEvent = responseEvent self.userEvent = userEvent } func canHandle(request: Request) -> Bool { Method(rawValue: request.method) != nil } func handle(request: Request) { guard let session = getSession(request.url) else { responseEvent(.invalid(request)) return } guard let chainID = session.walletInfo?.chainId else { // No chain ID responseEvent(.invalid(request)) return } guard let network: EVMNetwork = EVMNetwork(int: chainID) else { // Chain not recognised. responseEvent(.invalid(request)) return } guard enabledCurrenciesService.allEnabledCryptoCurrencies.contains(network.cryptoCurrency) else { // Chain recognised, but currently disabled. responseEvent(.invalid(request)) return } accountProvider .defaultAccount(network: network) .map { [responseEvent, analyticsEventRecorder] defaultAccount -> WalletConnectUserEvent? in Self.createEvent( analytics: analyticsEventRecorder, defaultAccount: defaultAccount, network: network, request: request, responseEvent: responseEvent, session: session ) } .sink( receiveValue: { [userEvent, responseEvent] event in guard let event = event else { responseEvent(.invalid(request)) return } userEvent(event) } ) .store(in: &cancellables) } /// Creates a `WalletConnectUserEvent.sendTransaction(,)` or `WalletConnectUserEvent.signTransaction(,)` /// from input data. private static func createEvent( analytics: AnalyticsEventRecorderAPI, defaultAccount: SingleAccount, network: EVMNetwork, request: Request, responseEvent: @escaping (WalletConnectResponseEvent) -> Void, session: Session ) -> WalletConnectUserEvent? { guard let method = Method(rawValue: request.method) else { return nil } guard let transaction = try? request.parameter(of: EthereumJsonRpcTransaction.self, at: 0) else { return nil } let dAppName = session.dAppInfo.peerMeta.name let dAppAddress = session.dAppInfo.peerMeta.url.host ?? "" let dAppLogoURL = session.dAppInfo.peerMeta.icons.first?.absoluteString ?? "" let onTxCompleted: TransactionTarget.TxCompleted = { [analytics] transactionResult in analytics.record( event: method.analyticsEvent( appName: dAppName, action: .confirm ) ) switch transactionResult { case .signed(let string): responseEvent(.signature(string, request)) case .hashed(let txHash, _): responseEvent(.transactionHash(txHash, request)) case .unHashed: break } return .empty() } let onTransactionRejected: () -> AnyPublisher<Void, Never> = { responseEvent(.rejected(request)) return .just(()) } let target = EthereumSendTransactionTarget( dAppAddress: dAppAddress, dAppLogoURL: dAppLogoURL, dAppName: dAppName, method: method.targetMethod, network: network, onTransactionRejected: onTransactionRejected, onTxCompleted: onTxCompleted, transaction: transaction ) return method.userEvent( account: defaultAccount, target: target ) } } extension TransactionRequestHandler { private enum Method: String { case sendTransaction = "eth_sendTransaction" case signTransaction = "eth_signTransaction" var targetMethod: EthereumSendTransactionTarget.Method { switch self { case .sendTransaction: return .send case .signTransaction: return .sign } } func userEvent( account: SingleAccount, target: EthereumSendTransactionTarget ) -> WalletConnectUserEvent { switch self { case .sendTransaction: return .sendTransaction(account, target) case .signTransaction: return .signTransaction(account, target) } } func analyticsEvent( appName: String, action: AnalyticsEvents.New.WalletConnect.Action ) -> AnalyticsEvent { switch self { case .sendTransaction: return AnalyticsEvents.New.WalletConnect .dappRequestActioned( action: action, appName: appName, method: .sendTransaction ) case .signTransaction: return AnalyticsEvents.New.WalletConnect .dappRequestActioned( action: action, appName: appName, method: .signTransaction ) } } } }
658fdf01eada6652ccf78d5b1ffd000e
34.299492
108
0.58585
false
false
false
false
TorIsHere/SwiftyProgressBar
refs/heads/master
SwiftyProgressBar/CircleView.swift
apache-2.0
1
// // CircleView.swift // SwiftyProgressBar // // Created by Kittikorn Ariyasuk on 6/11/16. // Copyright © 2016 TorIsHere. All rights reserved. // import UIKit @IBDesignable open class CircleView: UIView { @IBInspectable open var primaryColor: UIColor = UIColor.blue @IBInspectable open var secondaryColor: UIColor = UIColor.gray @IBInspectable open var bgColor: UIColor = UIColor.gray @IBInspectable open var lineWidth:CGFloat = 6 @IBInspectable open var bgLineWidth:CGFloat = 6 @IBInspectable open var startAngle:CGFloat = -90 @IBInspectable open var endAngle:CGFloat = -90 @IBInspectable open var willDraw:Bool = true var gradientLayer:CAGradientLayer! var pathLayer:CAShapeLayer! var path:UIBezierPath! var bgPath:UIBezierPath! // Only override drawRect: if you perform custom drawing. // An empty implementation adversely affects performance during animation. override open func draw(_ rect: CGRect) { // Drawing code super.draw(rect) let center = CGPoint(x:bounds.width/2, y: bounds.height/2) let radius: CGFloat = max(bounds.width, bounds.height) path = UIBezierPath(arcCenter: center, radius: radius/2 - lineWidth/2, startAngle: self.startAngle.degreesToRadians, endAngle: self.endAngle.degreesToRadians, clockwise: true) path.lineWidth = lineWidth path.lineCapStyle = CGLineCap.round bgPath = UIBezierPath(arcCenter: center, radius: radius/2 - lineWidth/2, startAngle: -90, endAngle: 90, clockwise: true) bgPath.lineWidth = bgLineWidth if willDraw { bgColor.setStroke() bgPath.stroke() //self.drawCircle() } } override public init (frame : CGRect) { super.init(frame : frame) } convenience public init () { self.init(frame:CGRect.zero) } required public init?(coder aDecoder: NSCoder) { //fatalError("init(coder:) has not been implemented") super.init(coder: aDecoder) } }
04484fe9c0a6237b0c6d99f26af8913d
31.027027
78
0.584388
false
false
false
false
criticalmaps/criticalmaps-ios
refs/heads/main
CriticalMapsKit/Sources/NextRideFeature/NextRideCore.swift
mit
1
import Combine import ComposableArchitecture import ComposableCoreLocation import Foundation import Logger import SharedDependencies import SharedModels // MARK: State public struct NextRideFeature: ReducerProtocol { public init() {} @Dependency(\.nextRideService) public var service @Dependency(\.userDefaultsClient) public var userDefaultsClient @Dependency(\.date) public var date @Dependency(\.mainQueue) public var mainQueue @Dependency(\.coordinateObfuscator) public var coordinateObfuscator @Dependency(\.isNetworkAvailable) public var isNetworkAvailable public struct State: Equatable { public init(nextRide: Ride? = nil) { self.nextRide = nextRide } public var nextRide: Ride? public var rideEvents: [Ride] = [] public var userLocation: Coordinate? } // MARK: Actions public enum Action: Equatable { case getNextRide(Coordinate) case nextRideResponse(TaskResult<[Ride]>) case setNextRide(Ride) } // MARK: Reducer /// Reducer handling next ride feature actions public func reduce(into state: inout State, action: Action) -> Effect<Action, Never> { switch action { case let .getNextRide(coordinate): guard userDefaultsClient.rideEventSettings.isEnabled else { logger.debug("NextRide featue is disabled") return .none } guard isNetworkAvailable else { logger.debug("Not fetching next ride. No connectivity") return .none } let obfuscatedCoordinate = coordinateObfuscator.obfuscate( coordinate, .thirdDecimal ) let requestRidesInMonth: Int = queryMonth(for: date.callAsFunction) return .task { await .nextRideResponse( TaskResult { try await service.nextRide( obfuscatedCoordinate, userDefaultsClient.rideEventSettings.eventDistance.rawValue, requestRidesInMonth ) } ) } case let .nextRideResponse(.failure(error)): logger.error("Get next ride failed 🛑 with error: \(error)") return .none case let .nextRideResponse(.success(rides)): guard !rides.isEmpty else { logger.info("Rides array is empty") return .none } guard !rides.map(\.rideType).isEmpty else { logger.info("No upcoming events for filter selection rideType") return .none } state.rideEvents = rides.sortByDateAndFilterBeforeDate(date.callAsFunction) // Sort rides by date and pick the first one with a date greater than now let ride = rides // swiftlint:disable:this sorted_first_last .lazy .filter { guard let type = $0.rideType else { return true } return userDefaultsClient.rideEventSettings.typeSettings .lazy .filter(\.isEnabled) .map(\.type) .contains(type) } .filter(\.enabled) .sorted { lhs, rhs in let byDate = lhs.dateTime < rhs.dateTime guard let userLocation = state.userLocation, let lhsCoordinate = lhs.coordinate, let rhsCoordinate = rhs.coordinate else { return byDate } if Calendar.current.isDate(lhs.dateTime, inSameDayAs: rhs.dateTime) { return lhsCoordinate.distance(from: userLocation) < rhsCoordinate.distance(from: userLocation) } else { return byDate } } .first { ride in ride.dateTime > date() } guard let filteredRide = ride else { logger.info("No upcoming events after filter") return .none } return Effect(value: .setNextRide(filteredRide)) case let .setNextRide(ride): state.nextRide = ride return .none } } } // MARK: Helper enum EventError: Error, LocalizedError { case eventsAreNotEnabled case invalidDateError case rideIsOutOfRangeError case noUpcomingRides case rideTypeIsFiltered case rideDisabled } private func queryMonth(for date: () -> Date = Date.init, calendar: Calendar = .current) -> Int { let currentMonthOfFallback = calendar.dateComponents([.month], from: date()).month ?? 0 guard !calendar.isDateInWeekend(date()) else { // current date is on a weekend return currentMonthOfFallback } guard let startDateOfNextWeekend = calendar.nextWeekend(startingAfter: date())?.start else { return currentMonthOfFallback } guard let month = calendar.dateComponents([.month], from: startDateOfNextWeekend).month else { return currentMonthOfFallback } return max(currentMonthOfFallback, month) } public extension Array where Element == Ride { func sortByDateAndFilterBeforeDate(_ now: () -> Date) -> Self { lazy .sorted(by: \.dateTime) .filter { $0.dateTime > now() } } } extension SharedModels.Coordinate { init(_ location: ComposableCoreLocation.Location) { self = .init( latitude: location.coordinate.latitude, longitude: location.coordinate.longitude ) } }
48c586717676f5a51f7d61e67334d6e3
27.649718
106
0.659436
false
false
false
false
aulas-lab/ads-mobile
refs/heads/master
swift/Funcoes/Funcoes/main.swift
mit
1
// // main.swift // Funcoes // // Created by Mobitec on 19/04/16. // Copyright (c) 2016 Unopar. All rights reserved. // import Foundation func nomeFuncao(param1: String, param2: Int, param3: Float) -> Float { return Float(param2) * param3 } let resultado = nomeFuncao("Teste", 10, 10.1) println("Resultado: \(resultado)") func funcaoSemRetorno1() { println("Chamada da funcao sem retorno 1") } func funcaoSemRetorno2() -> Void { println("Chamada da funcao sem retorno 2") } func contaPositivosNegativos(numeros: [Int]) -> (contaP: Int, contaN: Int) { var cp = 0 var cn = 0 for n in numeros { if n < 0 { cn++; } else { cp++; } } return (cp, cn) } let numeros = [-1, 10, -45, 39, 900]; let contagem = contaPositivosNegativos(numeros) println( "Positivos: \(contagem.contaP) Negativos: \(contagem.contaN)")
73439333ac3a71c1ef02c95233d8d013
19.083333
70
0.572614
false
false
false
false
Motsai/neblina-motiondemo-swift
refs/heads/master
NebCtrlPanel/iOS/NebCtrlPanel/DetailViewController.swift
mit
2
// // DetailViewController.swift // Nebblina Control Panel // // Created by Hoan Hoang on 2015-10-22. // Copyright © 2015 Hoan Hoang. All rights reserved. // import UIKit import CoreBluetooth import QuartzCore import SceneKit let MotionDataStream = Int32(1) let Heading = Int32(2) let LuggageDataLog = Int32(3) let NebCmdList = [NebCmdItem] (arrayLiteral: NebCmdItem(SubSysId: NEBLINA_SUBSYSTEM_GENERAL, CmdId: NEBLINA_COMMAND_GENERAL_INTERFACE_STATE, ActiveStatus: UInt32(NEBLINA_INTERFACE_STATUS_BLE.rawValue), Name: "BLE Data Port", Actuator : ACTUATOR_TYPE_SWITCH, Text: ""), NebCmdItem(SubSysId: NEBLINA_SUBSYSTEM_GENERAL, CmdId: NEBLINA_COMMAND_GENERAL_INTERFACE_STATE, ActiveStatus: UInt32(NEBLINA_INTERFACE_STATUS_UART.rawValue), Name: "UART Data Port", Actuator : ACTUATOR_TYPE_SWITCH, Text: ""), NebCmdItem(SubSysId: NEBLINA_SUBSYSTEM_GENERAL, CmdId: NEBLINA_COMMAND_GENERAL_DEVICE_NAME_SET, ActiveStatus: 0, Name: "Change Device Name", Actuator : ACTUATOR_TYPE_TEXT_FIELD_BUTTON, Text: "Change"), NebCmdItem(SubSysId: NEBLINA_SUBSYSTEM_FUSION, CmdId: NEBLINA_COMMAND_FUSION_SHOCK_SEGMENT_STREAM, ActiveStatus: 0, Name: "Shock Segment Stream", Actuator : ACTUATOR_TYPE_TEXT_FIELD_SWITCH, Text: ""), NebCmdItem(SubSysId: NEBLINA_SUBSYSTEM_FUSION, CmdId: NEBLINA_COMMAND_FUSION_CALIBRATE_FORWARD_POSITION, ActiveStatus: 0, Name: "Calibrate Forward Pos", Actuator : ACTUATOR_TYPE_BUTTON, Text: "Calib Fwrd"), NebCmdItem(SubSysId: NEBLINA_SUBSYSTEM_FUSION, CmdId: NEBLINA_COMMAND_FUSION_CALIBRATE_DOWN_POSITION, ActiveStatus: 0, Name: "Calibrate Down Pos", Actuator : ACTUATOR_TYPE_BUTTON, Text: "Calib Dwn"), NebCmdItem(SubSysId: NEBLINA_SUBSYSTEM_GENERAL, CmdId: NEBLINA_COMMAND_GENERAL_RESET_TIMESTAMP, ActiveStatus: 0, Name: "Reset timestamp", Actuator : ACTUATOR_TYPE_BUTTON, Text: "Reset"), NebCmdItem(SubSysId: NEBLINA_SUBSYSTEM_FUSION, CmdId: NEBLINA_COMMAND_FUSION_FUSION_TYPE, ActiveStatus: 0, Name: "Fusion 9 axis", Actuator : ACTUATOR_TYPE_SWITCH, Text:""), NebCmdItem(SubSysId: NEBLINA_SUBSYSTEM_FUSION, CmdId: NEBLINA_COMMAND_FUSION_QUATERNION_STREAM, ActiveStatus: UInt32(NEBLINA_FUSION_STATUS_QUATERNION.rawValue), Name: "Quaternion Stream", Actuator : ACTUATOR_TYPE_SWITCH, Text: ""), NebCmdItem(SubSysId: NEBLINA_SUBSYSTEM_FUSION, CmdId: NEBLINA_COMMAND_FUSION_PEDOMETER_STREAM, ActiveStatus: UInt32(NEBLINA_FUSION_STATUS_PEDOMETER.rawValue), Name: "Pedometer Stream", Actuator : ACTUATOR_TYPE_SWITCH, Text: ""), NebCmdItem(SubSysId: NEBLINA_SUBSYSTEM_FUSION, CmdId: NEBLINA_COMMAND_FUSION_ROTATION_INFO_STREAM, ActiveStatus: UInt32(NEBLINA_FUSION_STATUS_ROTATION_INFO.rawValue), Name: "Rotation info Stream", Actuator : ACTUATOR_TYPE_TEXT_FIELD_SWITCH, Text: ""), NebCmdItem(SubSysId: NEBLINA_SUBSYSTEM_SENSOR, CmdId: NEBLINA_COMMAND_SENSOR_ACCELEROMETER_STREAM, ActiveStatus: UInt32(NEBLINA_SENSOR_STATUS_ACCELEROMETER.rawValue), Name: "Accelerometer Sensor Stream", Actuator : ACTUATOR_TYPE_SWITCH, Text: ""), NebCmdItem(SubSysId: NEBLINA_SUBSYSTEM_SENSOR, CmdId: NEBLINA_COMMAND_SENSOR_GYROSCOPE_STREAM, ActiveStatus: UInt32(NEBLINA_SENSOR_STATUS_GYROSCOPE.rawValue), Name: "Gyroscope Sensor Stream", Actuator : ACTUATOR_TYPE_SWITCH, Text: ""), NebCmdItem(SubSysId: NEBLINA_SUBSYSTEM_SENSOR, CmdId: NEBLINA_COMMAND_SENSOR_MAGNETOMETER_STREAM, ActiveStatus: UInt32(NEBLINA_SENSOR_STATUS_MAGNETOMETER.rawValue), Name: "Magnetometer Sensor Stream", Actuator : ACTUATOR_TYPE_SWITCH, Text: ""), NebCmdItem(SubSysId: NEBLINA_SUBSYSTEM_SENSOR, CmdId: NEBLINA_COMMAND_SENSOR_ACCELEROMETER_GYROSCOPE_STREAM, ActiveStatus: UInt32(NEBLINA_SENSOR_STATUS_ACCELEROMETER_GYROSCOPE.rawValue), Name: "Accel & Gyro Stream", Actuator : ACTUATOR_TYPE_SWITCH, Text:""), NebCmdItem(SubSysId: NEBLINA_SUBSYSTEM_SENSOR, CmdId: NEBLINA_COMMAND_SENSOR_HUMIDITY_STREAM, ActiveStatus: UInt32(NEBLINA_SENSOR_STATUS_HUMIDITY.rawValue), Name: "Humidity Sensor Stream", Actuator : ACTUATOR_TYPE_SWITCH, Text: ""), NebCmdItem(SubSysId: NEBLINA_SUBSYSTEM_SENSOR, CmdId: NEBLINA_COMMAND_SENSOR_TEMPERATURE_STREAM, ActiveStatus: UInt32(NEBLINA_SENSOR_STATUS_TEMPERATURE.rawValue), Name: "Temperature Sensor Stream", Actuator : ACTUATOR_TYPE_SWITCH, Text: ""), NebCmdItem(SubSysId: NEBLINA_SUBSYSTEM_FUSION, CmdId: NEBLINA_COMMAND_FUSION_LOCK_HEADING_REFERENCE, ActiveStatus: 0, Name: "Lock Heading Ref.", Actuator : ACTUATOR_TYPE_SWITCH, Text: ""), NebCmdItem(SubSysId: NEBLINA_SUBSYSTEM_RECORDER, CmdId: NEBLINA_COMMAND_RECORDER_RECORD, ActiveStatus: UInt32(NEBLINA_RECORDER_STATUS_RECORD.rawValue), Name: "Flash Record", Actuator : ACTUATOR_TYPE_BUTTON, Text: "Start"), NebCmdItem(SubSysId: NEBLINA_SUBSYSTEM_RECORDER, CmdId: NEBLINA_COMMAND_RECORDER_RECORD, ActiveStatus: 0, Name: "Flash Record", Actuator : ACTUATOR_TYPE_BUTTON, Text: "Stop"), NebCmdItem(SubSysId: NEBLINA_SUBSYSTEM_RECORDER, CmdId: NEBLINA_COMMAND_RECORDER_PLAYBACK, ActiveStatus: 0, Name: "Flash Playback", Actuator : ACTUATOR_TYPE_TEXT_FIELD_BUTTON, Text: "Play"), // NebCmdItem(SubSysId: NEBLINA_SUBSYSTEM_RECORDER, CmdId: NEBLINA_COMMAND_RECORDER_SESSION_DOWNLOAD, ActiveStatus: 0, // Name: "Flash Download", Actuator : ACTUATOR_TYPE_BUTTON, Text: "Start"), NebCmdItem(SubSysId: NEBLINA_SUBSYSTEM_LED, CmdId: NEBLINA_COMMAND_LED_STATE, ActiveStatus: 0, Name: "Set LED0 level", Actuator : ACTUATOR_TYPE_TEXT_FIELD, Text: ""), NebCmdItem(SubSysId: NEBLINA_SUBSYSTEM_LED, CmdId: NEBLINA_COMMAND_LED_STATE, ActiveStatus: 0, Name: "Set LED1 level", Actuator : ACTUATOR_TYPE_TEXT_FIELD, Text: ""), NebCmdItem(SubSysId: NEBLINA_SUBSYSTEM_LED, CmdId: NEBLINA_COMMAND_LED_STATE, ActiveStatus: 0, Name: "Set LED2", Actuator : ACTUATOR_TYPE_SWITCH, Text: ""), NebCmdItem(SubSysId: NEBLINA_SUBSYSTEM_EEPROM, CmdId: NEBLINA_COMMAND_EEPROM_READ, ActiveStatus: 0, Name: "EEPROM Read", Actuator : ACTUATOR_TYPE_BUTTON, Text: "Read"), NebCmdItem(SubSysId: NEBLINA_SUBSYSTEM_POWER, CmdId: NEBLINA_COMMAND_POWER_CHARGE_CURRENT, ActiveStatus: 0, Name: "Charge Current in mA", Actuator : ACTUATOR_TYPE_TEXT_FIELD, Text: ""), NebCmdItem(SubSysId: 0xf, CmdId: MotionDataStream, ActiveStatus: 0, Name: "Motion data stream", Actuator : ACTUATOR_TYPE_SWITCH, Text: ""), NebCmdItem(SubSysId: 0xf, CmdId: Heading, ActiveStatus: 0, Name: "Heading", Actuator : ACTUATOR_TYPE_SWITCH, Text: ""), NebCmdItem(SubSysId: 0xf, CmdId: LuggageDataLog, ActiveStatus: 0, Name: "Luggage data logging", Actuator : ACTUATOR_TYPE_SWITCH, Text: ""), NebCmdItem(SubSysId: NEBLINA_SUBSYSTEM_RECORDER, CmdId: NEBLINA_COMMAND_RECORDER_ERASE_ALL, ActiveStatus: 0, Name: "Flash Erase All", Actuator : ACTUATOR_TYPE_BUTTON, Text: "Erase"), NebCmdItem(SubSysId: NEBLINA_SUBSYSTEM_GENERAL, CmdId: NEBLINA_COMMAND_GENERAL_FIRMWARE_UPDATE, ActiveStatus: 0, Name: "Firmware Update", Actuator : ACTUATOR_TYPE_BUTTON, Text: "DFU"), NebCmdItem(SubSysId: NEBLINA_SUBSYSTEM_GENERAL, CmdId: NEBLINA_COMMAND_GENERAL_DEVICE_SHUTDOWN, ActiveStatus: 0, Name: "Shutdown", Actuator : ACTUATOR_TYPE_BUTTON, Text: "Shutdown") ) //let CtrlName = [String](arrayLiteral:"Heading")//, "Test1", "Test2") class DetailViewController: UIViewController, UITextFieldDelegate, NeblinaDelegate, SCNSceneRendererDelegate, UITableViewDataSource { var nebdev : Neblina? { didSet { nebdev!.delegate = self } } //let scene = SCNScene(named: "art.scnassets/Millennium_Falcon/Millennium_Falcon.dae") as SCNScene! //let scene = SCNScene(named: "art.scnassets/SchoolBus/schoolBus.obj")! let sceneShip = SCNScene(named: "art.scnassets/ship.scn")! //let scene = SCNScene(named: "art.scnassets/AstonMartinRapide/rapide.scn")! //let scene = SCNScene(named: "art.scnassets/E-TIE-I/E-TIE-I.3ds.obj")! let sceneCube = SCNScene(named: "art.scnassets/neblina_calibration.dae")! var scene : SCNScene? //let scene = SCNScene(named: "art.scnassets/Neblina_Cube.dae")! //var textview = UITextView() //@IBOutlet weak var detailDescriptionLabel: UILabel! @IBOutlet weak var accelGraph : GraphView! @IBOutlet weak var gyroGraph : GraphView! @IBOutlet weak var magGraph : GraphView! @IBOutlet weak var cmdView: UITableView! @IBOutlet weak var versionLabel: UILabel! @IBOutlet weak var label: UILabel! @IBOutlet weak var flashLabel: UILabel! @IBOutlet weak var dumpLabel: UILabel! @IBOutlet weak var planeCubeSwitch : UISegmentedControl! //var eulerAngles = SCNVector3(x: 0,y:0,z:0) var ship : SCNNode! //= scene.rootNode.childNodeWithName("ship", recursively: true)! let max_count = Int16(15) var prevTimeStamp = UInt32(0) var cnt = Int16(15) var xf = Int16(0) var yf = Int16(0) var zf = Int16(0) var heading = Bool(false) var flashEraseProgress = Bool(false) var PaketCnt = UInt32(0) var dropCnt = UInt32(0) // var curDownloadSession = UInt16(0xFFFF) // var curDownloadOffset = UInt32(0) var curSessionId = UInt16(0) var curSessionOffset = UInt32(0) var sessionCount = UInt8(0) var startDownload = Bool(false) var filepath = String() var file : FileHandle? var downloadRecovering = Bool(false) var playback = Bool(false) var badTimestampCnt = Int(0) var dubTimestampCnt = Int(0) var prevPacket = NeblinaFusionPacket_t(); /* var detailItem: Neblina? { didSet { // Update the view. //self.configureView() //detailItem!.delegate = self nebdev = detailItem nebdev.setPeripheral(detailItem!.id, peripheral : detailItem!.peripheral) nebdev.delegate = self } }*/ func configureView() { // Update the user interface for the detail item. if self.nebdev != nil { //if let label = self.consoleTextView { //label.text = detail.description // } } } func getCmdIdx(_ subsysId : Int32, cmdId : Int32) -> Int { for (idx, item) in NebCmdList.enumerated() { if (item.SubSysId == subsysId && item.CmdId == cmdId) { return idx } } return -1 } override func viewDidLoad() { super.viewDidLoad() cnt = max_count scene = sceneShip // create and add a camera to the scene let cameraNode = SCNNode() cameraNode.camera = SCNCamera() sceneCube.rootNode.addChildNode(cameraNode) let cameraNode1 = SCNNode() sceneShip.rootNode.addChildNode(cameraNode1) //scene?.rootNode.addChildNode(cameraNode) // place the camera cameraNode.position = SCNVector3(x: 0, y: 0, z:20) cameraNode1.position = SCNVector3(x: 0, y: 0, z:20) //cameraNode.position = SCNVector3(x: 0, y: 15, z: 0) //cameraNode.rotation = SCNVector4(0, 0, 1, GLKMathDegreesToRadians(180)) //cameraNode.rotation = SCNVector4(1, 0, 0, GLKMathDegreesToRadians(180)) //cameraNode.rotation = SCNVector3(x: // create and add a light to the scene let lightNode = SCNNode() lightNode.light = SCNLight() lightNode.light!.type = SCNLight.LightType.omni lightNode.position = SCNVector3(x: 0, y: 10, z: 50) sceneCube.rootNode.addChildNode(lightNode) let lightNode1 = SCNNode() lightNode1.light = SCNLight() lightNode1.light!.type = SCNLight.LightType.omni lightNode1.position = SCNVector3(x: 0, y: 10, z: 50) sceneShip.rootNode.addChildNode(lightNode1) // create and add an ambient light to the scene let ambientLightNode = SCNNode() ambientLightNode.light = SCNLight() ambientLightNode.light!.type = SCNLight.LightType.ambient ambientLightNode.light!.color = UIColor.darkGray sceneCube.rootNode.addChildNode(ambientLightNode) let ambientLightNode1 = SCNNode() ambientLightNode1.light = SCNLight() ambientLightNode1.light!.type = SCNLight.LightType.ambient ambientLightNode1.light!.color = UIColor.darkGray sceneShip.rootNode.addChildNode(ambientLightNode1) // retrieve the ship node // ship = scene.rootNode.childNodeWithName("MillenniumFalconTop", recursively: true)! // ship = scene.rootNode.childNodeWithName("ARC_170_LEE_RAY_polySurface1394376_2_2", recursively: true)! ship = scene?.rootNode.childNode(withName: "ship", recursively: true)! //ship = scene.rootNode.childNode(withName: "Mesh258_SCHOOL_BUS2_Group2_Group1_Model", recursively: true)! ship.eulerAngles = SCNVector3Make(GLKMathDegreesToRadians(90), 0, GLKMathDegreesToRadians(180)) // Cube view //ship.eulerAngles = SCNVector3Make(GLKMathDegreesToRadians(-90), GLKMathDegreesToRadians(0), GLKMathDegreesToRadians(0)) //ship.rotation = SCNVector4(1, 0, 0, GLKMathDegreesToRadians(90)) //print("1 - \(ship)") // animate the 3d object //ship.runAction(SCNAction.repeatActionForever(SCNAction.rotateByX(0, y: 2, z: 0, duration: 1))) //ship.runAction(SCNAction.rotateToX(CGFloat(eulerAngles.x), y: CGFloat(eulerAngles.y), z: CGFloat(eulerAngles.z), duration:1 ))// 10, y: 0.0, z: 0.0, duration: 1)) // retrieve the SCNView let scnView = self.view.subviews[0] as! SCNView // set the scene to the view scnView.scene = scene // allows the user to manipulate the camera scnView.allowsCameraControl = true // show statistics such as fps and timing information scnView.showsStatistics = true // configure the view scnView.backgroundColor = UIColor.black // add a tap gesture recognizer let tapGesture = UITapGestureRecognizer(target: self, action: #selector(DetailViewController.handleTap(_:))) scnView.addGestureRecognizer(tapGesture) //scnView.preferredFramesPerSecond = 60 magGraph.valueRanges = [-16000.0...16000.0, -16000.0...16000.0, -16000.0...16000.0] } func textFieldShouldReturn(_ textField: UITextField) -> Bool // called when 'return' key pressed. return NO to ignore. { textField.resignFirstResponder() var value = UInt16(textField.text!) let idx = cmdView.indexPath(for: textField.superview!.superview as! UITableViewCell) let row = ((idx as NSIndexPath?)?.row)! as Int if (value == nil) { value = 0 } switch (NebCmdList[row].SubSysId) { case NEBLINA_SUBSYSTEM_LED: let i = getCmdIdx(NEBLINA_SUBSYSTEM_LED, cmdId: NEBLINA_COMMAND_LED_STATE) nebdev!.setLed(UInt8(row - i), Value: UInt8(value!)) break case NEBLINA_SUBSYSTEM_POWER: nebdev!.setBatteryChargeCurrent(value!) break default: break } return true; } @objc func handleTap(_ gestureRecognize: UIGestureRecognizer) { // retrieve the SCNView let scnView = self.view.subviews[0] as! SCNView // check what nodes are tapped let p = gestureRecognize.location(in: scnView) let hitResults = scnView.hitTest(p, options: nil) // check that we clicked on at least one object if hitResults.count > 0 { // retrieved the first clicked object let result: AnyObject! = hitResults[0] // get its material let material = result.node!.geometry!.firstMaterial! // highlight it SCNTransaction.begin() SCNTransaction.animationDuration = 0.5 // on completion - unhighlight /*SCNTransaction.completionBlock { SCNTransaction.begin() SCNTransaction.animationDuration = 0.5 material.emission.contents = UIColor.black SCNTransaction.commit() } */ material.emission.contents = UIColor.red SCNTransaction.commit() } } override var shouldAutorotate : Bool { return true } override var prefersStatusBarHidden : Bool { return true } override var supportedInterfaceOrientations : UIInterfaceOrientationMask { if UIDevice.current.userInterfaceIdiom == .phone { return .allButUpsideDown } else { return .all } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func switch3DView(_ sender:UISwitch) { if (sender.isOn) { cmdView.isHidden = true let scnView = self.view.subviews[0] as! SCNView scnView.isHidden = false accelGraph.isHidden = false gyroGraph.isHidden = false magGraph.isHidden = false planeCubeSwitch.isHidden = false } else { cmdView.isHidden = false let scnView = self.view.subviews[0] as! SCNView scnView.isHidden = true accelGraph.isHidden = true gyroGraph.isHidden = true magGraph.isHidden = true planeCubeSwitch.isHidden = true } } @IBAction func switch3DObject(_ sender:UISegmentedControl) { if sender.selectedSegmentIndex == 0 { scene = sceneShip ship = scene?.rootNode.childNode(withName: "ship", recursively: true)! let scnView = self.view.subviews[0] as! SCNView // set the scene to the view scnView.scene = scene // allows the user to manipulate the camera // scnView.allowsCameraControl = true // show statistics such as fps and timing information // scnView.showsStatistics = true // configure the view // scnView.backgroundColor = UIColor.black } else { scene = sceneCube ship = scene?.rootNode.childNode(withName: "node", recursively: true)! let scnView = self.view.subviews[0] as! SCNView // set the scene to the view scnView.scene = scene // allows the user to manipulate the camera // scnView.allowsCameraControl = true // show statistics such as fps and timing information // scnView.showsStatistics = true // configure the view // scnView.backgroundColor = UIColor.black } } @IBAction func buttonAction(_ sender:UIButton) { let idx = cmdView.indexPath(for: sender.superview!.superview as! UITableViewCell) let row = ((idx as NSIndexPath?)?.row)! as Int if (nebdev == nil) { return } if (row < NebCmdList.count) { switch (NebCmdList[row].SubSysId) { case NEBLINA_SUBSYSTEM_GENERAL: switch (NebCmdList[row].CmdId) { case NEBLINA_COMMAND_GENERAL_FIRMWARE_UPDATE: nebdev!.firmwareUpdate() print("DFU Command") break case NEBLINA_COMMAND_GENERAL_RESET_TIMESTAMP: nebdev!.resetTimeStamp(Delayed: true) print("Reset timestamp") break case NEBLINA_COMMAND_GENERAL_DEVICE_NAME_SET: let cell = cmdView.cellForRow( at: IndexPath(row: row, section: 0)) if (cell != nil) { let control = cell!.viewWithTag(4) as! UITextField nebdev!.setDeviceName(name: control.text!); // nebdev?.device = nil } break case NEBLINA_COMMAND_GENERAL_DEVICE_SHUTDOWN: nebdev!.shutdown() break default: break } break case NEBLINA_SUBSYSTEM_EEPROM: switch (NebCmdList[row].CmdId) { case NEBLINA_COMMAND_EEPROM_READ: nebdev!.eepromRead(0) break case NEBLINA_COMMAND_EEPROM_WRITE: //UInt8_t eepdata[8] //nebdev.SendCmdEepromWrite(0, eepdata) break default: break } break case NEBLINA_SUBSYSTEM_FUSION: switch (NebCmdList[row].CmdId) { case NEBLINA_COMMAND_FUSION_CALIBRATE_FORWARD_POSITION: nebdev!.calibrateForwardPosition() break case NEBLINA_COMMAND_FUSION_CALIBRATE_DOWN_POSITION: nebdev!.calibrateDownPosition() break default: break } break case NEBLINA_SUBSYSTEM_RECORDER: switch (NebCmdList[row].CmdId) { case NEBLINA_COMMAND_RECORDER_ERASE_ALL: if flashEraseProgress == false { //print("Send Command erase") flashEraseProgress = true; flashLabel.text = "Erasing ..." nebdev!.eraseStorage(false) } case NEBLINA_COMMAND_RECORDER_RECORD: if NebCmdList[row].ActiveStatus == 0 { nebdev?.sessionRecord(false, info: "") } else { nebdev!.sessionRecord(true, info: "") } break case NEBLINA_COMMAND_RECORDER_SESSION_DOWNLOAD: let cell = cmdView.cellForRow( at: IndexPath(row: row, section: 0)) if (cell != nil) { //let control = cell!.viewWithTag(4) as! UITextField //let but = cell!.viewWithTag(2) as! UIButton //but.isEnabled = false curSessionId = 0//UInt16(control.text!)! startDownload = true curSessionOffset = 0 //let filename = String(format:"NeblinaRecord_%d.dat", curSessionId) let dirPaths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true) if dirPaths != nil { filepath = dirPaths[0]// as! String filepath.append(String(format:"/%@/", (nebdev?.device.name!)!)) do { try FileManager.default.createDirectory(atPath: filepath, withIntermediateDirectories: false, attributes: nil) } catch let error as NSError { print(error.localizedDescription); } filepath.append(String(format:"%@_%d.dat", (nebdev?.device.name!)!, curSessionId)) FileManager.default.createFile(atPath: filepath, contents: nil, attributes: nil) do { try file = FileHandle(forWritingAtPath: filepath) } catch { print("file failed \(filepath)")} nebdev?.sessionDownload(true, SessionId : curSessionId, Len: 16, Offset: 0) } } break case NEBLINA_COMMAND_RECORDER_PLAYBACK: let cell = cmdView.cellForRow( at: IndexPath(row: row, section: 0)) if cell != nil { let tf = cell?.viewWithTag(4) as! UITextField let bt = cell?.viewWithTag(2) as! UIButton if playback == true { bt.setTitle("Play", for: .normal) playback = false } else { bt.setTitle("Stop", for: .normal) var n = UInt16(0) if !(tf.text!.isEmpty) { n = (UInt16((tf.text!)))! } nebdev?.sessionPlayback(true, sessionId : n) PaketCnt = 0 playback = true } } break default: break } default: break } } } @IBAction func switchAction(_ sender:UISegmentedControl) { //let tableView = sender.superview?.superview?.superview?.superview as! UITableView let idx = cmdView.indexPath(for: sender.superview!.superview as! UITableViewCell) let row = ((idx as NSIndexPath?)?.row)! as Int if (nebdev == nil) { return } if (row < NebCmdList.count) { switch (NebCmdList[row].SubSysId) { case NEBLINA_SUBSYSTEM_GENERAL: switch (NebCmdList[row].CmdId) { case NEBLINA_COMMAND_GENERAL_INTERFACE_STATUS: //nebdev!.setInterface(sender.selectedSegmentIndex) break case NEBLINA_COMMAND_GENERAL_INTERFACE_STATE: nebdev!.setDataPort(row, Ctrl:UInt8(sender.selectedSegmentIndex)) break; default: break } break case NEBLINA_SUBSYSTEM_FUSION: switch (NebCmdList[row].CmdId) { case NEBLINA_COMMAND_FUSION_MOTION_STATE_STREAM: nebdev!.streamMotionState(sender.selectedSegmentIndex == 1) break case NEBLINA_COMMAND_FUSION_FUSION_TYPE: nebdev!.setFusionType(UInt8(sender.selectedSegmentIndex)) break //case IMU_Data: // nebdev!.streamIMU(sender.selectedSegmentIndex == 1) // break case NEBLINA_COMMAND_FUSION_QUATERNION_STREAM: nebdev!.streamEulerAngle(false) heading = false prevTimeStamp = 0 nebdev!.streamQuaternion(sender.selectedSegmentIndex == 1) let i = getCmdIdx(0xf, cmdId: 1) let cell = cmdView.cellForRow( at: IndexPath(row: i, section: 0)) if (cell != nil) { let sw = cell!.viewWithTag(1) as! UISegmentedControl sw.selectedSegmentIndex = 0 } break case NEBLINA_COMMAND_FUSION_PEDOMETER_STREAM: nebdev!.streamPedometer(sender.selectedSegmentIndex == 1) break case NEBLINA_COMMAND_FUSION_ROTATION_INFO_STREAM: let cell = cmdView.cellForRow( at: IndexPath(row: row, section: 0)) var type = UInt8(0) if cell != nil { let tf = cell?.viewWithTag(4) as! UITextField if !(tf.text!.isEmpty) { type = (UInt8((tf.text!)))! } } nebdev!.streamRotationInfo(sender.selectedSegmentIndex == 1, Type:type) break case NEBLINA_COMMAND_FUSION_EULER_ANGLE_STREAM: nebdev!.streamQuaternion(false) nebdev!.streamEulerAngle(sender.selectedSegmentIndex == 1) break case NEBLINA_COMMAND_FUSION_EXTERNAL_FORCE_STREAM: nebdev!.streamExternalForce(sender.selectedSegmentIndex == 1) break case NEBLINA_COMMAND_FUSION_TRAJECTORY_RECORD: nebdev!.recordTrajectory(sender.selectedSegmentIndex == 1) break; case NEBLINA_COMMAND_FUSION_TRAJECTORY_INFO_STREAM: nebdev!.streamTrajectoryInfo(sender.selectedSegmentIndex == 1) break; // case NEBLINA_COMMAND_FUSION_MAG_STATE: // nebdev!.streamMAG(sender.selectedSegmentIndex == 1) // break; case NEBLINA_COMMAND_FUSION_LOCK_HEADING_REFERENCE: nebdev!.lockHeadingReference() let cell = cmdView.cellForRow( at: IndexPath(row: row, section: 0)) if (cell != nil) { let sw = cell!.viewWithTag(1) as! UISegmentedControl sw.selectedSegmentIndex = 0 } break case NEBLINA_COMMAND_FUSION_SHOCK_SEGMENT_STREAM: var thresh = UInt8(0) let cell = cmdView.cellForRow( at: IndexPath(row: row, section: 0)) if cell != nil { let tf = cell?.viewWithTag(4) as! UITextField thresh = UInt8(tf.text!)! } nebdev!.streamShockSegment(sender.selectedSegmentIndex == 1, threshold: thresh) default: break } case NEBLINA_SUBSYSTEM_LED: let i = getCmdIdx(NEBLINA_SUBSYSTEM_LED, cmdId: NEBLINA_COMMAND_LED_STATE) nebdev!.setLed(UInt8(row - i), Value: UInt8(sender.selectedSegmentIndex)) break case NEBLINA_SUBSYSTEM_RECORDER: switch (NebCmdList[row].CmdId) { case NEBLINA_COMMAND_RECORDER_ERASE_ALL: if (sender.selectedSegmentIndex == 1) { flashEraseProgress = true; } nebdev!.eraseStorage(sender.selectedSegmentIndex == 1) break case NEBLINA_COMMAND_RECORDER_RECORD: nebdev!.sessionRecord(sender.selectedSegmentIndex == 1, info: "") break case NEBLINA_COMMAND_RECORDER_PLAYBACK: nebdev!.sessionPlayback(sender.selectedSegmentIndex == 1, sessionId : 0xffff) if (sender.selectedSegmentIndex == 1) { PaketCnt = 0 } break case NEBLINA_COMMAND_RECORDER_SESSION_READ: // curDownloadSession = 0xFFFF // curDownloadOffset = 0 // nebdev!.sessionRead(curDownloadSession, Len: 32, Offset: curDownloadOffset) break default: break } break case NEBLINA_SUBSYSTEM_EEPROM: switch (NebCmdList[row].CmdId) { case NEBLINA_COMMAND_EEPROM_READ: nebdev!.eepromRead(0) break case NEBLINA_COMMAND_EEPROM_WRITE: //UInt8_t eepdata[8] //nebdev.SendCmdEepromWrite(0, eepdata) break default: break } break case NEBLINA_SUBSYSTEM_SENSOR: switch (NebCmdList[row].CmdId) { case NEBLINA_COMMAND_SENSOR_ACCELEROMETER_STREAM: nebdev!.sensorStreamAccelData(sender.selectedSegmentIndex == 1) break case NEBLINA_COMMAND_SENSOR_GYROSCOPE_STREAM: nebdev?.sensorStreamGyroData(sender.selectedSegmentIndex == 1) break case NEBLINA_COMMAND_SENSOR_HUMIDITY_STREAM: nebdev?.sensorStreamHumidityData(sender.selectedSegmentIndex == 1) break case NEBLINA_COMMAND_SENSOR_MAGNETOMETER_STREAM: nebdev?.sensorStreamMagData(sender.selectedSegmentIndex == 1) break case NEBLINA_COMMAND_SENSOR_PRESSURE_STREAM: nebdev?.sensorStreamPressureData(sender.selectedSegmentIndex == 1) break case NEBLINA_COMMAND_SENSOR_TEMPERATURE_STREAM: nebdev?.sensorStreamTemperatureData(sender.selectedSegmentIndex == 1) break case NEBLINA_COMMAND_SENSOR_ACCELEROMETER_GYROSCOPE_STREAM: nebdev?.sensorStreamAccelGyroData(sender.selectedSegmentIndex == 1) break case NEBLINA_COMMAND_SENSOR_ACCELEROMETER_MAGNETOMETER_STREAM: nebdev?.sensorStreamAccelMagData(sender.selectedSegmentIndex == 1) break default: break } break case 0xf: switch (NebCmdList[row].CmdId) { case Heading: nebdev!.streamQuaternion(false) nebdev!.streamEulerAngle(sender.selectedSegmentIndex == 1) heading = sender.selectedSegmentIndex == 1 var i = getCmdIdx(NEBLINA_SUBSYSTEM_FUSION, cmdId: NEBLINA_COMMAND_FUSION_QUATERNION_STREAM) var cell = cmdView.cellForRow( at: IndexPath(row: i, section: 0)) if (cell != nil) { let control = cell!.viewWithTag(1) as! UISegmentedControl control.selectedSegmentIndex = 0 } i = getCmdIdx(0xF, cmdId: MotionDataStream) cell = cmdView.cellForRow( at: IndexPath(row: i, section: 0)) if (cell != nil) { let control = cell!.viewWithTag(1) as! UISegmentedControl control.selectedSegmentIndex = 0 } i = getCmdIdx(0xF, cmdId: LuggageDataLog) cell = cmdView.cellForRow( at: IndexPath(row: i, section: 0)) if (cell != nil) { let control = cell!.viewWithTag(1) as! UISegmentedControl control.selectedSegmentIndex = 0 } break case MotionDataStream: if sender.selectedSegmentIndex == 0 { nebdev?.disableStreaming() break } nebdev!.streamQuaternion(sender.selectedSegmentIndex == 1) var i = getCmdIdx(NEBLINA_SUBSYSTEM_FUSION, cmdId: NEBLINA_COMMAND_FUSION_QUATERNION_STREAM) var cell = cmdView.cellForRow( at: IndexPath(row: i, section: 0)) if (cell != nil) { let control = cell!.viewWithTag(1) as! UISegmentedControl control.selectedSegmentIndex = sender.selectedSegmentIndex } // nebdev!.streamIMU(sender.selectedSegmentIndex == 1) // i = getCmdIdx(NEBLINA_SUBSYSTEM_FUSION, cmdId: NEBLINA_COMMAND_FUSION_IMU_STATE) // cell = cmdView.cellForRow( at: IndexPath(row: i, section: 0)) // if (cell != nil) { // let control = cell!.viewWithTag(1) as! UISegmentedControl // control.selectedSegmentIndex = sender.selectedSegmentIndex // } nebdev!.sensorStreamMagData(sender.selectedSegmentIndex == 1) i = getCmdIdx(NEBLINA_SUBSYSTEM_FUSION, cmdId: NEBLINA_COMMAND_SENSOR_MAGNETOMETER_STREAM) cell = cmdView.cellForRow( at: IndexPath(row: i, section: 0)) if (cell != nil) { let control = cell!.viewWithTag(1) as! UISegmentedControl control.selectedSegmentIndex = sender.selectedSegmentIndex } nebdev!.streamExternalForce(sender.selectedSegmentIndex == 1) i = getCmdIdx(NEBLINA_SUBSYSTEM_FUSION, cmdId: NEBLINA_COMMAND_FUSION_EXTERNAL_FORCE_STREAM) cell = cmdView.cellForRow( at: IndexPath(row: i, section: 0)) if (cell != nil) { let control = cell!.viewWithTag(1) as! UISegmentedControl control.selectedSegmentIndex = sender.selectedSegmentIndex } nebdev!.streamPedometer(sender.selectedSegmentIndex == 1) i = getCmdIdx(NEBLINA_SUBSYSTEM_FUSION, cmdId: NEBLINA_COMMAND_FUSION_PEDOMETER_STREAM) cell = cmdView.cellForRow( at: IndexPath(row: i, section: 0)) if (cell != nil) { let control = cell!.viewWithTag(1) as! UISegmentedControl control.selectedSegmentIndex = sender.selectedSegmentIndex } nebdev!.streamRotationInfo(sender.selectedSegmentIndex == 1, Type : 1) i = getCmdIdx(NEBLINA_SUBSYSTEM_FUSION, cmdId: NEBLINA_COMMAND_FUSION_ROTATION_INFO_STREAM) cell = cmdView.cellForRow( at: IndexPath(row: i, section: 0)) if (cell != nil) { let control = cell!.viewWithTag(1) as! UISegmentedControl control.selectedSegmentIndex = sender.selectedSegmentIndex } i = getCmdIdx(0xF, cmdId: Heading) cell = cmdView.cellForRow( at: IndexPath(row: i, section: 0)) if (cell != nil) { let control = cell!.viewWithTag(1) as! UISegmentedControl control.selectedSegmentIndex = 0 } i = getCmdIdx(0xF, cmdId: LuggageDataLog) cell = cmdView.cellForRow( at: IndexPath(row: i, section: 0)) if (cell != nil) { let control = cell!.viewWithTag(1) as! UISegmentedControl control.selectedSegmentIndex = 0 } break case LuggageDataLog: if sender.selectedSegmentIndex == 0 { nebdev!.disableStreaming() nebdev!.sessionRecord(false, info: "") break } else { nebdev!.sensorStreamAccelGyroData(true) nebdev!.sensorStreamMagData(true) nebdev!.sensorStreamPressureData(true) nebdev!.sensorStreamTemperatureData(true) nebdev!.sessionRecord(true, info: "") } var i = getCmdIdx(NEBLINA_SUBSYSTEM_FUSION, cmdId: NEBLINA_COMMAND_FUSION_QUATERNION_STREAM) var cell = cmdView.cellForRow( at: IndexPath(row: i, section: 0)) i = getCmdIdx(0xF, cmdId: Heading) cell = cmdView.cellForRow( at: IndexPath(row: i, section: 0)) if (cell != nil) { let control = cell!.viewWithTag(1) as! UISegmentedControl control.selectedSegmentIndex = 0 } i = getCmdIdx(0xF, cmdId: MotionDataStream) cell = cmdView.cellForRow( at: IndexPath(row: i, section: 0)) if (cell != nil) { let control = cell!.viewWithTag(1) as! UISegmentedControl control.selectedSegmentIndex = 0 } break default: break } break default: break } } /* else { switch (row - NebCmdList.count) { case 0: nebdev.streamQuaternion(false) nebdev.streamEulerAngle(true) heading = sender.selectedSegmentIndex == 1 let i = getCmdIdx(NEB_CTRL_SUBSYS_MOTION_ENG, cmdId: Quaternion) let cell = cmdView.cellForRowAtIndexPath( NSIndexPath(forRow: i, inSection: 0)) if (cell != nil) { let sw = cell!.viewWithTag(1) as! UISegmentedControl sw.selectedSegmentIndex = 0 } break default: break } }*/ } //func renderer(renderer: SCNSceneRenderer, // updateAtTime time: NSTimeInterval) { // let ship = renderer.scene!.rootNode.childNodeWithName("ship", recursively: true)! // // // } // func didReceiveFusionData(type : UInt8, data : FusionPacket) { // print("\(data)") // } func updateUI(status : NeblinaSystemStatus_t) { for idx in 0...NebCmdList.count - 1 { switch (NebCmdList[idx].SubSysId) { case NEBLINA_SUBSYSTEM_GENERAL: switch (NebCmdList[idx].CmdId) { case NEBLINA_COMMAND_GENERAL_INTERFACE_STATE: //let cell = cmdView.view(atColumn: 0, row: idx, makeIfNecessary: false)! as NSView let cell = cmdView.cellForRow( at: IndexPath(row: idx, section: 0)) if cell != nil { let control = cell?.viewWithTag(1) as! UISegmentedControl if NebCmdList[idx].ActiveStatus & UInt32(status.interface) == 0 { control.selectedSegmentIndex = 0 } else { control.selectedSegmentIndex = 1 } } default: break } case NEBLINA_SUBSYSTEM_FUSION: //let cell = cmdView.view(atColumn: 0, row: idx, makeIfNecessary: false)! as NSView let cell = cmdView.cellForRow( at: IndexPath(row: idx, section: 0)) if cell != nil { let control = cell?.viewWithTag(1) as! UISegmentedControl if NebCmdList[idx].ActiveStatus & status.fusion == 0 { control.selectedSegmentIndex = 0 } else { control.selectedSegmentIndex = 1 } } case NEBLINA_SUBSYSTEM_SENSOR: //print("\(NebCmdList[idx])") let cell = cmdView.cellForRow( at: IndexPath(row: idx, section: 0)) if cell != nil { //let cell = cmdView.view(atColumn: 0, row: idx, makeIfNecessary: false)! as NSView let control = cell?.viewWithTag(1) as! UISegmentedControl if NebCmdList[idx].CmdId == NEBLINA_COMMAND_SENSOR_ACCELEROMETER_GYROSCOPE_STREAM { if NebCmdList[idx].ActiveStatus == UInt32(NEBLINA_SENSOR_STATUS_ACCELEROMETER_GYROSCOPE.rawValue) { print("Accel_Gyro button \(status.sensor) ") } } if (NebCmdList[idx].ActiveStatus & UInt32(status.sensor)) == 0 { control.selectedSegmentIndex = 0 } else { control.selectedSegmentIndex = 1 } } default: break } } } // MARK: Neblina func didConnectNeblina(sender : Neblina) { // Switch to BLE interface prevTimeStamp = 0; nebdev!.getSystemStatus() nebdev!.getFirmwareVersion() } func didReceiveResponsePacket(sender : Neblina, subsystem : Int32, cmdRspId : Int32, data : UnsafePointer<UInt8>, dataLen : Int) { print("didReceiveResponsePacket : \(subsystem) \(cmdRspId)") switch subsystem { case NEBLINA_SUBSYSTEM_GENERAL: switch (cmdRspId) { case NEBLINA_COMMAND_GENERAL_SYSTEM_STATUS: let d = UnsafeMutableRawPointer(mutating: data).load(as: NeblinaSystemStatus_t.self)// UnsafeBufferPointer<NeblinaSystemStatus_t>(data)) print(" \(d)") updateUI(status: d) break case NEBLINA_COMMAND_GENERAL_FIRMWARE_VERSION: let vers = UnsafeMutableRawPointer(mutating: data).load(as: NeblinaFirmwareVersion_t.self) let b = (UInt32(vers.firmware_build.0) & 0xFF) | ((UInt32(vers.firmware_build.1) & 0xFF) << 8) | ((UInt32(vers.firmware_build.2) & 0xFF) << 16) print("\(vers) ") versionLabel.text = String(format: "API:%d, Firm. Ver.:%d.%d.%d-%d", vers.api, vers.firmware_major, vers.firmware_minor, vers.firmware_patch, b ) break default: break } break case NEBLINA_SUBSYSTEM_FUSION: switch cmdRspId { case NEBLINA_COMMAND_FUSION_QUATERNION_STREAM: break default: break } break case NEBLINA_SUBSYSTEM_RECORDER: switch (cmdRspId) { case NEBLINA_COMMAND_RECORDER_ERASE_ALL: flashLabel.text = "Flash erased" flashEraseProgress = false break case NEBLINA_COMMAND_RECORDER_RECORD: let session = Int16(data[1]) | (Int16(data[2]) << 8) if (data[0] != 0) { flashLabel.text = String(format: "Recording session %d", session) } else { flashLabel.text = String(format: "Recorded session %d", session) } break case NEBLINA_COMMAND_RECORDER_PLAYBACK: let session = Int16(data[1]) | (Int16(data[2]) << 8) if (data[0] != 0) { flashLabel.text = String(format: "Playing session %d", session) } else { flashLabel.text = String(format: "Playback sess %d finished %u packets", session, nebdev!.getPacketCount()) playback = false let i = getCmdIdx(NEBLINA_SUBSYSTEM_RECORDER, cmdId: NEBLINA_COMMAND_RECORDER_PLAYBACK) let cell = cmdView.cellForRow( at: IndexPath(row: i, section: 0)) if (cell != nil) { let sw = cell!.viewWithTag(2) as! UIButton sw.setTitle("Play", for: .normal) } } break default: break } break case NEBLINA_SUBSYSTEM_SENSOR: //nebdev?.getFirmwareVersion() break default: break } } func didReceiveRSSI(sender : Neblina, rssi : NSNumber) { } // // General data // func didReceiveGeneralData(sender : Neblina, respType: Int32, cmdRspId : Int32, data : UnsafeRawPointer, dataLen : Int, errFlag : Bool) { switch (cmdRspId) { default: break } } func didReceiveFusionData(sender : Neblina, respType : Int32, cmdRspId : Int32, data : NeblinaFusionPacket_t, errFlag : Bool) { //let errflag = Bool(type.rawValue & 0x80 == 0x80) //let id = FusionId(rawValue: type.rawValue & 0x7F)! as FusionId //dumpLabel.text = String(format: "Total packet %u @ %0.2f pps, drop \(dropCnt)", nebdev!.getPacketCount(), nebdev!.getDataRate()) switch (cmdRspId) { case NEBLINA_COMMAND_FUSION_MOTION_STATE_STREAM: break case NEBLINA_COMMAND_FUSION_EULER_ANGLE_STREAM: // // Process Euler Angle // //let ship = scene.rootNode.childNodeWithName("ship", recursively: true)! let x = (Int16(data.data.0) & 0xff) | (Int16(data.data.1) << 8) let xrot = Float(x) / 10.0 let y = (Int16(data.data.2) & 0xff) | (Int16(data.data.3) << 8) let yrot = Float(y) / 10.0 let z = (Int16(data.data.4) & 0xff) | (Int16(data.data.5) << 8) let zrot = Float(z) / 10.0 if (heading) { ship.eulerAngles = SCNVector3Make(GLKMathDegreesToRadians(90), 0, GLKMathDegreesToRadians(180) - GLKMathDegreesToRadians(xrot)) } else { ship.eulerAngles = SCNVector3Make(GLKMathDegreesToRadians(180) - GLKMathDegreesToRadians(yrot), GLKMathDegreesToRadians(xrot), GLKMathDegreesToRadians(180) - GLKMathDegreesToRadians(zrot)) } label.text = String("Euler - Yaw:\(xrot), Pitch:\(yrot), Roll:\(zrot)") break case NEBLINA_COMMAND_FUSION_QUATERNION_STREAM: // // Process Quaternion // //let ship = scene.rootNode.childNodeWithName("ship", recursively: true)! let x = (Int16(data.data.0) & 0xff) | (Int16(data.data.1) << 8)//w let xq = Float(x) / 32768.0 let y = (Int16(data.data.2) & 0xff) | (Int16(data.data.3) << 8)//x let yq = Float(y) / 32768.0 let z = (Int16(data.data.4) & 0xff) | (Int16(data.data.5) << 8)//y let zq = Float(z) / 32768.0 let w = (Int16(data.data.6) & 0xff) | (Int16(data.data.7) << 8)//z let wq = Float(w) / 32768.0 ship.orientation = SCNQuaternion(-zq, xq, yq, wq)// ship //ship.orientation = SCNQuaternion(-yq, wq, xq, zq)// ship //ship.orientation = SCNQuaternion(xq, yq, zq, wq) //ship.orientation = SCNQuaternion(yq, -xq, -zq, wq)// cube label.text = String("Quat - w:\(xq), x:\(yq), y:\(zq), z:\(wq)") if (prevTimeStamp == data.timestamp) { var diff = Bool(false) if prevPacket.data.0 != data.data.0 { diff = true } else if prevPacket.data.1 != data.data.1 { diff = true } else if prevPacket.data.2 != data.data.2 { diff = true } else if prevPacket.data.3 != data.data.3 { diff = true } else if prevPacket.data.4 != data.data.4 { diff = true } else if prevPacket.data.5 != data.data.5 { diff = true } else if prevPacket.data.6 != data.data.6 { diff = true } else if prevPacket.data.7 != data.data.7 { diff = true } else if prevPacket.data.8 != data.data.8 { diff = true } else if prevPacket.data.9 != data.data.9 { diff = true } else if prevPacket.data.10 != data.data.10 { diff = true } else if prevPacket.data.11 != data.data.11 { diff = true } if diff == true { badTimestampCnt += 1 } else { dubTimestampCnt += 1 } } //print("\(badTimestampCnt), \(dubTimestampCnt)") if (prevTimeStamp == 0 || data.timestamp <= prevTimeStamp) { prevTimeStamp = data.timestamp; prevPacket = data; } else { let tdiff = data.timestamp - prevTimeStamp; if (tdiff > 49000) { dropCnt += 1 //dumpLabel.text = String("\(dropCnt) Drop : \(tdiff), \(badTimestampCnt)") } prevTimeStamp = data.timestamp prevPacket = data } break case NEBLINA_COMMAND_FUSION_EXTERNAL_FORCE_STREAM: // // Process External Force // //let ship = scene.rootNode.childNodeWithName("ship", recursively: true)! let x = (Int16(data.data.0) & 0xff) | (Int16(data.data.1) << 8) let xq = x / 1600 let y = (Int16(data.data.2) & 0xff) | (Int16(data.data.3) << 8) let yq = y / 1600 let z = (Int16(data.data.4) & 0xff) | (Int16(data.data.5) << 8) let zq = z / 1600 cnt -= 1 if (cnt <= 0) { cnt = max_count //if (xf != xq || yf != yq || zf != zq) { let pos = SCNVector3(CGFloat(xf/cnt), CGFloat(yf/cnt), CGFloat(zf/cnt)) ship.position = pos xf = xq yf = yq zf = zq //} } else { //if (abs(xf) <= abs(xq)) { xf += xq //} //if (abs(yf) <= abs(yq)) { yf += yq //} //if (abs(xf) <= abs(xq)) { zf += zq //} } label.text = String("Extrn Force - x:\(xq), y:\(yq), z:\(zq)") //print("Extrn Force - x:\(xq), y:\(yq), z:\(zq)") break /* case NEBLINA_COMMAND_FUSION_MAG_STATE: // // Mag data // //let ship = scene.rootNode.childNodeWithName("ship", recursively: true)! let x = (Int16(data.data.0) & 0xff) | (Int16(data.data.1) << 8) let xq = x let y = (Int16(data.data.2) & 0xff) | (Int16(data.data.3) << 8) let yq = y let z = (Int16(data.data.4) & 0xff) | (Int16(data.data.5) << 8) let zq = z label.text = String("Mag - x:\(xq), y:\(yq), z:\(zq)") //ship.rotation = SCNVector4(Float(xq), Float(yq), 0, GLKMathDegreesToRadians(90)) break */ case NEBLINA_COMMAND_FUSION_PEDOMETER_STREAM: let stridelen = data.data.9; let totaldistance = UInt16(data.data.10) + (UInt16(data.data.11) << 8) label.text = String("Stride = \(stridelen), dist = \(totaldistance)") break case NEBLINA_COMMAND_FUSION_SHOCK_SEGMENT_STREAM: let ax = (Int16(data.data.0) & 0xff) | (Int16(data.data.1) << 8) let ay = (Int16(data.data.2) & 0xff) | (Int16(data.data.3) << 8) let az = (Int16(data.data.4) & 0xff) | (Int16(data.data.5) << 8) // label.text = String("Accel - x:\(xq), y:\(yq), z:\(zq)") accelGraph.add(double3(Double(ax), Double(ay), Double(az))) let gx = (Int16(data.data.6) & 0xff) | (Int16(data.data.7) << 8) let gy = (Int16(data.data.8) & 0xff) | (Int16(data.data.9) << 8) let gz = (Int16(data.data.10) & 0xff) | (Int16(data.data.11) << 8) gyroGraph.add(double3(Double(gx), Double(gy), Double(gz))) break default: break } } func didReceivePmgntData(sender : Neblina, respType : Int32, cmdRspId : Int32, data : UnsafePointer<UInt8>, dataLen: Int, errFlag : Bool) { let value = UInt16(data[0]) | (UInt16(data[1]) << 8) if (cmdRspId == NEBLINA_COMMAND_POWER_CHARGE_CURRENT) { let i = getCmdIdx(NEBLINA_SUBSYSTEM_POWER, cmdId: NEBLINA_COMMAND_POWER_CHARGE_CURRENT) let cell = cmdView.cellForRow( at: IndexPath(row: i, section: 0)) if (cell != nil) { let control = cell!.viewWithTag(3) as! UITextField control.text = String(value) } } } func didReceiveLedData(sender : Neblina, respType : Int32, cmdRspId : Int32, data : UnsafePointer<UInt8>, dataLen: Int, errFlag : Bool) { switch (cmdRspId) { case NEBLINA_COMMAND_LED_STATUS: let i = getCmdIdx(NEBLINA_SUBSYSTEM_LED, cmdId: NEBLINA_COMMAND_LED_STATUS) var cell = cmdView.cellForRow( at: IndexPath(row: i, section: 0)) if (cell != nil) { let tf = cell!.viewWithTag(3) as! UITextField tf.text = String(data[0]) } cell = cmdView.cellForRow( at: IndexPath(row: i + 1, section: 0)) if (cell != nil) { let tf = cell!.viewWithTag(3) as! UITextField tf.text = String(data[1]) } cell = cmdView.cellForRow( at: IndexPath(row: i + 2, section: 0)) if (cell != nil) { let sw = cell!.viewWithTag(1) as! UISegmentedControl if (data[2] != 0) { sw.selectedSegmentIndex = 1 } else { sw.selectedSegmentIndex = 0 } } break default: break } } // // Debug // func didReceiveDebugData(sender : Neblina, respType : Int32, cmdRspId : Int32, data : UnsafePointer<UInt8>, dataLen : Int, errFlag : Bool) { //print("Debug \(type) data \(data)") switch (cmdRspId) { case NEBLINA_COMMAND_DEBUG_DUMP_DATA: dumpLabel.text = String(format: "%02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x", data[0], data[1], data[2], data[3], data[4], data[5], data[6], data[7], data[8], data[9], data[10], data[11], data[12], data[13], data[14], data[15]) break default: break } } func didReceiveRecorderData(sender : Neblina, respType : Int32, cmdRspId : Int32, data : UnsafePointer<UInt8>, dataLen: Int, errFlag : Bool) { switch (cmdRspId) { case NEBLINA_COMMAND_RECORDER_ERASE_ALL: flashLabel.text = "Flash erased" flashEraseProgress = false break case NEBLINA_COMMAND_RECORDER_RECORD: let session = Int16(data[1]) | (Int16(data[2]) << 8) if (data[0] != 0) { flashLabel.text = String(format: "Recording session %d", session) } else { flashLabel.text = String(format: "Recorded session %d", session) } break case NEBLINA_COMMAND_RECORDER_PLAYBACK: let session = Int16(data[1]) | (Int16(data[2]) << 8) if (data[0] != 0) { flashLabel.text = String(format: "Playing session %d", session) } else { flashLabel.text = String(format: "End session %d, %u", session, nebdev!.getPacketCount()) playback = false let i = getCmdIdx(NEBLINA_SUBSYSTEM_RECORDER, cmdId: NEBLINA_COMMAND_RECORDER_PLAYBACK) let cell = cmdView.cellForRow( at: IndexPath(row: i, section: 0)) if (cell != nil) { let sw = cell!.viewWithTag(2) as! UIButton sw.setTitle("Play", for: .normal) } } break case NEBLINA_COMMAND_RECORDER_SESSION_DOWNLOAD: if (errFlag == false && dataLen > 0) { if dataLen < 4 { break } let offset = UInt32(UInt32(data[0]) | (UInt32(data[1]) << 8) | (UInt32(data[2]) << 16) | (UInt32(data[3]) << 24)) if curSessionOffset != offset { // packet loss print("SessionDownload \(curSessionOffset), \(offset), \(data) \(dataLen)") if downloadRecovering == false { nebdev?.sessionDownload(false, SessionId: curSessionId, Len: 12, Offset: curSessionOffset) downloadRecovering = true } } else { downloadRecovering = false let d = NSData(bytes: data + 4, length: dataLen - 4) //writing if file != nil { file?.write(d as Data) } curSessionOffset += UInt32(dataLen-4) flashLabel.text = String(format: "Downloading session %d : %u", curSessionId, curSessionOffset) } //print("\(curSessionOffset), \(data)") } else { print("End session \(filepath)") print(" Download End session errflag") flashLabel.text = String(format: "Downloaded session %d : %u", curSessionId, curSessionOffset) if (dataLen > 0) { let d = NSData(bytes: data, length: dataLen) //writing if file != nil { file?.write(d as Data) } } file?.closeFile() let i = getCmdIdx(NEBLINA_SUBSYSTEM_RECORDER, cmdId: NEBLINA_COMMAND_RECORDER_SESSION_DOWNLOAD) if i < 0 { break } // let cell = cmdView.view(atColumn: 0, row: i, makeIfNecessary: false)! as NSView // cellForRowAtIndexPath( NSIndexPath(forRow: i, inSection: 0)) // let sw = cell.viewWithTag(2) as! NSButton // sw.isEnabled = true } break default: break } } func didReceiveEepromData(sender : Neblina, respType : Int32, cmdRspId : Int32, data : UnsafePointer<UInt8>, dataLen: Int, errFlag : Bool) { switch (cmdRspId) { case NEBLINA_COMMAND_EEPROM_READ: let pageno = UInt16(data[0]) | (UInt16(data[1]) << 8) dumpLabel.text = String(format: "EEP page [%d] : %02x %02x %02x %02x %02x %02x %02x %02x", pageno, data[2], data[3], data[4], data[5], data[6], data[7], data[8], data[9]) break case NEBLINA_COMMAND_EEPROM_WRITE: break; default: break } } // // Sensor data // func didReceiveSensorData(sender : Neblina, respType : Int32, cmdRspId : Int32, data : UnsafePointer<UInt8>, dataLen : Int, errFlag : Bool) { switch (cmdRspId) { case NEBLINA_COMMAND_SENSOR_ACCELEROMETER_STREAM: let x = (Int16(data[4]) & 0xff) | (Int16(data[5]) << 8) let xq = x let y = (Int16(data[6]) & 0xff) | (Int16(data[7]) << 8) let yq = y let z = (Int16(data[8]) & 0xff) | (Int16(data[9]) << 8) let zq = z label.text = String("Accel - x:\(xq), y:\(yq), z:\(zq)") accelGraph.add(double3(Double(x), Double(y), Double(z))) // rxCount += 1 break case NEBLINA_COMMAND_SENSOR_GYROSCOPE_STREAM: let x = (Int16(data[4]) & 0xff) | (Int16(data[5]) << 8) let xq = x let y = (Int16(data[6]) & 0xff) | (Int16(data[7]) << 8) let yq = y let z = (Int16(data[8]) & 0xff) | (Int16(data[9]) << 8) let zq = z label.text = String("Gyro - x:\(xq), y:\(yq), z:\(zq)") gyroGraph.add(double3(Double(x), Double(y), Double(z))) //rxCount += 1 break case NEBLINA_COMMAND_SENSOR_HUMIDITY_STREAM: let x = (Int32(data[4]) & 0xff) | (Int32(data[5]) << 8) | (Int32(data[6]) << 16) | (Int32(data[7]) << 24) let xf = Float(x) / 100.0; label.text = String("Humidity : \(xf)") break case NEBLINA_COMMAND_SENSOR_MAGNETOMETER_STREAM: // // Mag data // //let ship = scene.rootNode.childNodeWithName("ship", recursively: true)! let x = (Int16(data[4]) & 0xff) | (Int16(data[5]) << 8) let y = (Int16(data[6]) & 0xff) | (Int16(data[7]) << 8) let z = (Int16(data[8]) & 0xff) | (Int16(data[9]) << 8) label.text = String("Mag - x:\(x), y:\(y), z:\(z)") magGraph.add(double3(Double(x), Double(y), Double(z))) //rxCount += 1 //ship.rotation = SCNVector4(Float(xq), Float(yq), 0, GLKMathDegreesToRadians(90)) break case NEBLINA_COMMAND_SENSOR_PRESSURE_STREAM: break case NEBLINA_COMMAND_SENSOR_TEMPERATURE_STREAM: let x = (Int32(data[4]) & 0xff) | (Int32(data[5]) << 8) | (Int32(data[6]) << 16) | (Int32(data[7]) << 24) let xf = Float(x) / 100.0; label.text = String("Temperature : \(xf)") //print("Temperature \(xf)") break case NEBLINA_COMMAND_SENSOR_ACCELEROMETER_GYROSCOPE_STREAM: let x = (Int16(data[4]) & 0xff) | (Int16(data[5]) << 8) let y = (Int16(data[6]) & 0xff) | (Int16(data[7]) << 8) let z = (Int16(data[8]) & 0xff) | (Int16(data[9]) << 8) label.text = String("IMU - x:\(x), y:\(y), z:\(z)") accelGraph.add(double3(Double(x), Double(y), Double(z))) let gx = (Int16(data[10]) & 0xff) | (Int16(data[11]) << 8) let gy = (Int16(data[12]) & 0xff) | (Int16(data[13]) << 8) let gz = (Int16(data[14]) & 0xff) | (Int16(data[15]) << 8) gyroGraph.add(double3(Double(gx), Double(gy), Double(gz))) //rxCount += 1 break case NEBLINA_COMMAND_SENSOR_ACCELEROMETER_MAGNETOMETER_STREAM: let x = (Int16(data[4]) & 0xff) | (Int16(data[5]) << 8) let y = (Int16(data[6]) & 0xff) | (Int16(data[7]) << 8) let z = (Int16(data[8]) & 0xff) | (Int16(data[9]) << 8) label.text = String("Accel - x:\(x), y:\(y), z:\(z)") accelGraph.add(double3(Double(x), Double(y), Double(z))) let mx = (Int16(data[10]) & 0xff) | (Int16(data[11]) << 8) let my = (Int16(data[12]) & 0xff) | (Int16(data[13]) << 8) let mz = (Int16(data[14]) & 0xff) | (Int16(data[15]) << 8) magGraph.add(double3(Double(mx), Double(my), Double(mz))) break default: break } cmdView.setNeedsDisplay() } func didReceiveBatteryLevel(sender: Neblina, level: UInt8) { print("Batt level \(level)") } // MARK : UITableView func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return /*FusionCmdList.count + */NebCmdList.count //+ CtrlName.count //return 1//detailItem } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cellView = tableView.dequeueReusableCell(withIdentifier: "CellCommand", for: indexPath) let labelView = cellView.viewWithTag(255) as! UILabel // let switchCtrl = cellView.viewWithTag(2) as! UIControl//UISegmentedControl // var buttonCtrl = cellView.viewWithTag(3) as! UIButton // buttonCtrl.hidden = true //switchCtrl.addTarget(self, action: "switchAction:", forControlEvents: UIControlEvents.ValueChanged) /* if (indexPath!.row < FusionCmdList.count) { labelView.text = FusionCmdList[indexPath!.row].Name //NebApiName[indexPath!.row] as String//"Row \(row)"//"self.objects.objectAtIndex(row) as! String } else */ if ((indexPath as NSIndexPath).row < /*FusionCmdList.count + */NebCmdList.count) { labelView.text = NebCmdList[(indexPath as NSIndexPath).row].Name// - FusionCmdList.count].Name switch (NebCmdList[(indexPath as NSIndexPath).row].Actuator) { case ACTUATOR_TYPE_SWITCH: let control = cellView.viewWithTag(NebCmdList[(indexPath as NSIndexPath).row].Actuator) as! UISegmentedControl control.isHidden = false let b = cellView.viewWithTag(2) as! UIButton b.isHidden = true let t = cellView.viewWithTag(3) as! UITextField t.isHidden = true break case ACTUATOR_TYPE_BUTTON: let control = cellView.viewWithTag(NebCmdList[(indexPath as NSIndexPath).row].Actuator) as! UIButton control.isHidden = false if !NebCmdList[(indexPath as NSIndexPath).row].Text.isEmpty { control.setTitle(NebCmdList[(indexPath as NSIndexPath).row].Text, for: UIControl.State()) } let s = cellView.viewWithTag(1) as! UISegmentedControl s.isHidden = true let t = cellView.viewWithTag(3) as! UITextField t.isHidden = true break case ACTUATOR_TYPE_TEXT_FIELD: let control = cellView.viewWithTag(NebCmdList[(indexPath as NSIndexPath).row].Actuator) as! UITextField control.isHidden = false if !NebCmdList[(indexPath as NSIndexPath).row].Text.isEmpty { control.text = NebCmdList[(indexPath as NSIndexPath).row].Text } let s = cellView.viewWithTag(1) as! UISegmentedControl s.isHidden = true let b = cellView.viewWithTag(2) as! UIButton b.isHidden = true break case ACTUATOR_TYPE_TEXT_FIELD_BUTTON: let tfcontrol = cellView.viewWithTag(4) as! UITextField tfcontrol.isHidden = false /* if !NebCmdList[(indexPath! as NSIndexPath).row].Text.isEmpty { tfcontrol.text = NebCmdList[(indexPath! as NSIndexPath).row].Text }*/ let bucontrol = cellView.viewWithTag(2) as! UIButton bucontrol.isHidden = false if !NebCmdList[(indexPath as NSIndexPath).row].Text.isEmpty { bucontrol.setTitle(NebCmdList[(indexPath as NSIndexPath).row].Text, for: UIControl.State()) } let s = cellView.viewWithTag(1) as! UISegmentedControl s.isHidden = true let t = cellView.viewWithTag(3) as! UITextField t.isHidden = true break case ACTUATOR_TYPE_TEXT_FIELD_SWITCH: let tfcontrol = cellView.viewWithTag(4) as! UITextField tfcontrol.isHidden = false let bucontrol = cellView.viewWithTag(1) as! UISegmentedControl bucontrol.isHidden = false let s = cellView.viewWithTag(2) as! UIButton s.isHidden = true let t = cellView.viewWithTag(3) as! UITextField t.isHidden = true break default: //switchCtrl.enabled = false // switchCtrl.hidden = true // buttonCtrl.hidden = true break } } // else { // labelView.text = CtrlName[indexPath!.row /*- FusionCmdList.count*/ - NebCmdList.count] //NebApiName[indexPath!.row] as String//"Row \(row)"//"self.objects.objectAtIndex(row) as! String // } //cellView.textLabel!.text = NebApiName[indexPath!.row] as String//"Row \(row)"//"self.objects.objectAtIndex(row) as! String return cellView; } func tableView(_ tableView: UITableView, canEditRowAtIndexPath indexPath: IndexPath?) -> Bool { return false } func scrollViewDidScroll(_ scrollView: UIScrollView) { if (nebdev == nil) { return } nebdev!.getSystemStatus() } }
67275fe00f58196a8ad6761e2d2a2654
35.748144
192
0.654256
false
false
false
false
gtranchedone/NFYU
refs/heads/master
NFYU/Services/APIClient.swift
mit
1
// // APIClient.swift // NFYU // // Created by Gianluca Tranchedone on 05/11/2015. // Copyright © 2015 Gianluca Tranchedone. All rights reserved. // import Foundation import CoreLocation protocol APIRequestSerializer { func buildURLRequestToFetchForecastsForLocationWithCoordinate(_ coordinate: CLLocationCoordinate2D) -> URLRequest } typealias SerializedAPIResponse = (error: NSError?, forecasts: [Forecast]?, locationInfo: LocationInfo?) protocol APIResponseSerializer { func parseForecastsAPIResponseData(_ data: Data) -> SerializedAPIResponse } class APIClient: AnyObject { var session = URLSession.shared let requestSerializer: APIRequestSerializer let responseSerializer: APIResponseSerializer init(requestSerializer: APIRequestSerializer, responseSerializer: APIResponseSerializer) { self.requestSerializer = requestSerializer self.responseSerializer = responseSerializer } // The completion block is always called on the main queue func fetchForecastsForLocationWithCoordinate(_ coordinate: CLLocationCoordinate2D, completionBlock: @escaping (NSError?, [Forecast]?, LocationInfo?) -> ()) { let request = requestSerializer.buildURLRequestToFetchForecastsForLocationWithCoordinate(coordinate) let task = session.dataTask(with: request, completionHandler: { [weak self] (data, response, error) -> Void in var locationInfo: LocationInfo? var forecasts: [Forecast]? var finalError = error if let data = data { let parsedResponse = self?.responseSerializer.parseForecastsAPIResponseData(data) locationInfo = parsedResponse?.locationInfo forecasts = parsedResponse?.forecasts finalError = parsedResponse?.error } self?.logResponse(response, error: finalError as NSError?, forecasts: forecasts, locationInfo: locationInfo) OperationQueue.main.addOperation({ () -> Void in completionBlock(finalError as NSError?, forecasts, locationInfo) }) }) logRequest(request) task.resume() } fileprivate func logRequest(_ request: URLRequest) { // use print instead of debugPrint for pretty printing print("Performing \(request.httpMethod!) request to \(request.url!)", terminator: "\n\n") } fileprivate func logResponse(_ response: URLResponse?, error: NSError?, forecasts: [Forecast]?, locationInfo: LocationInfo?) { // use print instead of debugPrint for pretty printing print("Received response for URL \(response?.url) with error -> \(error)\nlocationInfo -> \(locationInfo)\nforecasts -> \(forecasts)", terminator: "\n\n") } }
21957d180f98d7e6f84bba020214c5f6
39.57971
162
0.69
false
false
false
false
CJGitH/QQMusic
refs/heads/master
QQMusic/Classes/Other/Tool/QQTimeTool.swift
mit
1
// // QQTimeTool.swift // QQMusic // // Created by chen on 16/5/17. // Copyright © 2016年 chen. All rights reserved. // import UIKit class QQTimeTool: NSObject { class func getFormatTime(time: NSTimeInterval) -> String { // time 123 // 03:12 let min = Int(time / 60) let sec = Int(time) % 60 let resultStr = String(format: "%02d:%02d", min, sec) return resultStr } class func getTimeInterval(formatTime: String) -> NSTimeInterval { // 00:00.89 -> 多少秒 let minAndSec = formatTime.componentsSeparatedByString(":") if minAndSec.count == 2 { // 分钟 let min = NSTimeInterval(minAndSec[0]) ?? 0 // 秒数 let sec = NSTimeInterval(minAndSec[1]) ?? 0 return min * 60 + sec } return 0 } }
96c9a830db6aea6419380ddc79d6a97a
18.215686
70
0.47449
false
false
false
false
tbergmen/TableViewModel
refs/heads/master
Example/TableViewModel/FeedExample/FeedCell.swift
mit
1
/* Copyright (c) 2016 Tunca Bergmen <[email protected]> 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 class FeedCell: UITableViewCell { @IBOutlet var profileImageView: UIImageView! @IBOutlet var nameLabel: UILabel! @IBOutlet var timeLabel: UILabel! @IBOutlet var commentTextView: UITextView! @IBOutlet var likeButton: UIButton! @IBOutlet var shareButton: UIButton! var cellHeight: Float = 0 var onLike: ((FeedItem) -> ())? var onShare: ((FeedItem) -> ())? override func awakeFromNib() { profileImageView.layer.cornerRadius = 4 } @IBAction func likeAction() { onLike?(feedItem) } @IBAction func shareAction() { onShare?(feedItem) } var feedItem: FeedItem! { didSet { nameLabel.text = feedItem.user.name profileImageView.image = feedItem.user.profilePicture timeLabel.text = feedItem.time commentTextView.text = feedItem.comment calculateCellHeight() } } func calculateCellHeight() { if let feedItem = self.feedItem { let baseHeight: Float = 70 let commentViewHeight = textViewHeight(feedItem.comment, width: 256, font: UIFont.systemFontOfSize(13)) cellHeight = baseHeight + commentViewHeight } } func textViewHeight(text: String, width: Float, font: UIFont) -> Float { let attributedText = NSAttributedString(string: text, attributes: [NSFontAttributeName: font]) let textViewMargin: Float = 10 let size = attributedText.boundingRectWithSize(CGSizeMake(CGFloat(width - textViewMargin), CGFloat.max), options: NSStringDrawingOptions.UsesLineFragmentOrigin, context: nil) return Float(size.height) } }
7b49373e6a3529ca33b4a499dded2df7
34.734177
115
0.704215
false
false
false
false
Sahilberi/ImageTextField
refs/heads/master
Source/ImageTextField.swift
mit
1
// // ImageTextField.swift // ImageTextField // // Created by Sahil on 22/02/17. // Copyright © 2017 SahilBeri. All rights reserved. // import UIKit @IBDesignable class ImageTextField: UITextField { var textFieldBorderStyle: UITextBorderStyle = .roundedRect // Provides left padding for image override func leftViewRect(forBounds bounds: CGRect) -> CGRect { var textRect = super.leftViewRect(forBounds: bounds) textRect.origin.x += padding return textRect } // Provides right padding for image override func rightViewRect(forBounds bounds: CGRect) -> CGRect { var textRect = super.rightViewRect(forBounds: bounds) textRect.origin.x -= padding return textRect } @IBInspectable var fieldImage: UIImage? = nil { didSet { updateView() } } @IBInspectable var padding: CGFloat = 0 @IBInspectable var color: UIColor = UIColor.gray { didSet { updateView() } } @IBInspectable var bottomColor: UIColor = UIColor.clear { didSet { if bottomColor == UIColor.clear { self.borderStyle = .roundedRect } else { self.borderStyle = .bezel } self.setNeedsDisplay() } } func updateView() { if let image = fieldImage { leftViewMode = UITextFieldViewMode.always let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 20, height: 20)) imageView.image = image // Note: In order for your image to use the tint color, you have to select the image in the Assets.xcassets and change the "Render As" property to "Template Image". imageView.tintColor = color leftView = imageView } else { leftViewMode = UITextFieldViewMode.never leftView = nil } // Placeholder text color attributedPlaceholder = NSAttributedString(string: placeholder != nil ? placeholder! : "", attributes:[NSForegroundColorAttributeName: color]) } override func draw(_ rect: CGRect) { let path = UIBezierPath() path.move(to: CGPoint(x: self.bounds.origin.x, y: self.bounds.height - 0.5)) path.addLine(to: CGPoint(x: self.bounds.size.width, y: self.bounds.height - 0.5)) path.lineWidth = 0.5 self.bottomColor.setStroke() path.stroke() } }
273f6b526f087a3a764bfc620b36a047
26.790123
170
0.666371
false
false
false
false
AgaKhanFoundation/WCF-iOS
refs/heads/main
Demo/Pods/Nimble/Sources/Nimble/Expectation.swift
bsd-3-clause
2
internal func execute<T>(_ expression: Expression<T>, _ style: ExpectationStyle, _ predicate: Predicate<T>, to: String, description: String?, captureExceptions: Bool = true) -> (Bool, FailureMessage) { func run() -> (Bool, FailureMessage) { let msg = FailureMessage() msg.userDescription = description msg.to = to do { let result = try predicate.satisfies(expression) result.message.update(failureMessage: msg) if msg.actualValue == "" { msg.actualValue = "<\(stringify(try expression.evaluate()))>" } return (result.toBoolean(expectation: style), msg) } catch let error { msg.stringValue = "unexpected error thrown: <\(error)>" return (false, msg) } } var result: (Bool, FailureMessage) = (false, FailureMessage()) if captureExceptions { let capture = NMBExceptionCapture(handler: ({ exception -> Void in let msg = FailureMessage() msg.stringValue = "unexpected exception raised: \(exception)" result = (false, msg) }), finally: nil) capture.tryBlock { result = run() } } else { result = run() } return result } public struct Expectation<T> { public let expression: Expression<T> public init(expression: Expression<T>) { self.expression = expression } public func verify(_ pass: Bool, _ message: FailureMessage) { let handler = NimbleEnvironment.activeInstance.assertionHandler handler.assert(pass, message: message, location: expression.location) } /// Tests the actual value using a matcher to match. @discardableResult public func to(_ predicate: Predicate<T>, description: String? = nil) -> Self { let (pass, msg) = execute(expression, .toMatch, predicate, to: "to", description: description) verify(pass, msg) return self } /// Tests the actual value using a matcher to not match. @discardableResult public func toNot(_ predicate: Predicate<T>, description: String? = nil) -> Self { let (pass, msg) = execute(expression, .toNotMatch, predicate, to: "to not", description: description) verify(pass, msg) return self } /// Tests the actual value using a matcher to not match. /// /// Alias to toNot(). @discardableResult public func notTo(_ predicate: Predicate<T>, description: String? = nil) -> Self { return toNot(predicate, description: description) } // see: // - `async` for extension // - NMBExpectation for Objective-C interface }
85c1639a9993e310a834264ebfb845ff
34.328947
201
0.612663
false
false
false
false
immustard/MSTTools_Swift
refs/heads/master
MSTTools_Swift/Categories/UILabelMST.swift
mit
1
// // UILabelMST.swift // MSTTools_Swift // // Created by 张宇豪 on 2017/6/7. // Copyright © 2017年 张宇豪. All rights reserved. // import UIKit extension UILabel { public func mst_addLongPressCopyMenu() { isUserInteractionEnabled = true let longPress: UILongPressGestureRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(mp_showCopyMenu)) addGestureRecognizer(longPress) } @objc private func mp_showCopyMenu() { becomeFirstResponder() UIMenuController.shared.setTargetRect(frame, in: superview!) UIMenuController.shared.setMenuVisible(self.isFirstResponder, animated: true) } open override var canBecomeFocused: Bool { return true } // 可以响应的方法 open override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool { return action == #selector(UIResponderStandardEditActions.copy(_:)) } // 针对于响应方法的实现 open override func copy(_ sender: Any?) { UIPasteboard.general.string = text } }
cafcd28423995d81b27781dcbe59f20e
26.717949
132
0.66235
false
false
false
false
coach-plus/ios
refs/heads/master
CoachPlus/helperclasses/DropdownAlert.swift
mit
1
// // DropdownAlert.swift // CoachPlus // // Created by Breit, Maurice on 26.03.17. // Copyright © 2017 Mathandoro GbR. All rights reserved. // import Foundation import NotificationBannerSwift class DropdownAlert { static let errorBgColor = UIColor.red static let errorTextColor = UIColor.white static let errorTitle = L10n.error static let errorTime = 3 static let successTitle = L10n.success static func error(message: String) { let msg = message.localize() let banner = NotificationBanner(title: self.errorTitle, subtitle: msg, style: .danger) banner.show() } static func success(message: String) { let banner = NotificationBanner(title: self.successTitle, subtitle: message, style: .success) banner.show() } }
693113f2a95dce3c8d116e7dc597da1e
24.030303
101
0.664649
false
false
false
false
vnu/Flickz
refs/heads/master
Flickz/Movie.swift
mit
1
// // Movie.swift // Flickz // // Created by Vinu Charanya on 2/5/16. // Copyright © 2016 vnu. All rights reserved. // import UIKit /* Sample Data { poster_path: "/k1QUCjNAkfRpWfm1dVJGUmVHzGv.jpg", adult: false, overview: "Based upon Marvel Comics’ most unconventional anti-hero, DEADPOOL tells the origin story of former Special Forces operative turned mercenary Wade Wilson, who after being subjected to a rogue experiment that leaves him with accelerated healing powers, adopts the alter ego Deadpool. Armed with his new abilities and a dark, twisted sense of humor, Deadpool hunts down the man who nearly destroyed his life.", release_date: "2016-02-09", genre_ids: [ 35, 12, 28, 878 ], id: 293660, original_title: "Deadpool", original_language: "en", title: "Deadpool", backdrop_path: "/n1y094tVDFATSzkTnFxoGZ1qNsG.jpg", popularity: 20.322214, vote_count: 131, video: false, vote_average: 6.05 } */ import Foundation import UIKit class Movie { // MARK: Properties var posterPath: String? var adult: Bool var overview: String var releaseDate: String var genreIds: Array<Int> var ID: Int var originalTitle: String var originalLanguage: String var title: String var backdropPath: String? var popularity: Double var voteCount: Int var video: Bool var voteAverage: Double // MARK: Initialization init(posterPath: String, adult: Bool, overview: String, releaseDate: String, genreIds: Array<Int>, ID: Int, originalTitle: String, originalLanguage: String, title: String, backdropPath: String, popularity: Double, voteCount: Int, video: Bool, voteAverage: Double) { // Initialize stored properties. self.posterPath = posterPath self.adult = adult self.overview = overview self.releaseDate = releaseDate self.genreIds = genreIds self.ID = ID self.originalTitle = originalTitle self.originalLanguage = originalLanguage self.title = title self.backdropPath = backdropPath self.popularity = popularity self.voteCount = voteCount self.video = video self.voteAverage = voteAverage } init(jsonResult: NSDictionary) { // Initialize stored properties. self.posterPath = jsonResult["poster_path"] as? String self.adult = jsonResult["adult"] as! Bool self.overview = jsonResult["overview"] as! String self.releaseDate = jsonResult["release_date"] as! String self.genreIds = jsonResult["genre_ids"] as! Array<Int> self.ID = jsonResult["id"] as! Int self.originalTitle = jsonResult["original_title"] as! String self.originalLanguage = jsonResult["original_language"] as! String self.title = jsonResult["title"] as! String self.backdropPath = jsonResult["backdrop_path"] as? String self.popularity = jsonResult["popularity"] as! Double self.voteCount = jsonResult["vote_count"] as! Int self.video = jsonResult["video"] as! Bool self.voteAverage = jsonResult["vote_average"] as! Double } func lowResPosterURL() -> NSURL?{ let baseUrl = "https://image.tmdb.org/t/p/w92" if let posterPath = self.posterPath{ return NSURL(string:"\(baseUrl)\(posterPath)")! } return nil } func highResPosterURL() -> NSURL?{ let baseUrl = "https://image.tmdb.org/t/p/original" if let posterPath = self.posterPath{ return NSURL(string:"\(baseUrl)\(posterPath)")! } return nil } func movieReleaseDate() -> String{ let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd" if let movieDate = dateFormatter.dateFromString(self.releaseDate) { dateFormatter.dateStyle = NSDateFormatterStyle.LongStyle return dateFormatter.stringFromDate(movieDate) } return "--" } }
6a73ff00398cea76d0ee8e2e89eaac77
30.88
418
0.661731
false
false
false
false
material-components/material-components-ios
refs/heads/develop
components/AppBar/tests/unit/AppBarNavigationControllerTests.swift
apache-2.0
2
// Copyright 2018-present the Material Components for iOS authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import XCTest import MaterialComponents.MaterialAppBar private class MockAppBarNavigationControllerDelegate: NSObject, MDCAppBarNavigationControllerDelegate { var trackingScrollView: UIScrollView? func appBarNavigationController( _ navigationController: MDCAppBarNavigationController, trackingScrollViewFor trackingScrollViewForViewController: UIViewController, suggestedTrackingScrollView: UIScrollView? ) -> UIScrollView? { return trackingScrollView } } class AppBarNavigationControllerTests: XCTestCase { var navigationController: MDCAppBarNavigationController! override func setUp() { super.setUp() navigationController = MDCAppBarNavigationController() } override func tearDown() { navigationController = nil super.tearDown() } // MARK: - AppBar injection func testInitializingWithRootViewControllerInjectsAnAppBar() { // Given let viewController = UIViewController() // When let navigationController = MDCAppBarNavigationController(rootViewController: viewController) // Then XCTAssertEqual( viewController.children.count, 1, "Expected there to be exactly one child view controller added to the view" + " controller.") XCTAssertEqual( navigationController.topViewController, viewController, "The navigation controller's top view controller is supposed to be the pushed" + " view controller, but it is \(viewController).") XCTAssertTrue( viewController.children.first is MDCFlexibleHeaderViewController, "The injected view controller is not a flexible header view controller, it is" + "\(String(describing: viewController.children.first)) instead.") if let headerViewController = viewController.children.first as? MDCFlexibleHeaderViewController { XCTAssertEqual( headerViewController.headerView.frame.height, headerViewController.headerView.maximumHeight) } } func testPushingAViewControllerInjectsAnAppBar() { // Given let viewController = UIViewController() // When navigationController.pushViewController(viewController, animated: false) // Then XCTAssertEqual( viewController.children.count, 1, "Expected there to be exactly one child view controller added to the view" + " controller.") XCTAssertEqual( navigationController.topViewController, viewController, "The navigation controller's top view controller is supposed to be the pushed" + " view controller, but it is \(viewController).") XCTAssertTrue( viewController.children.first is MDCFlexibleHeaderViewController, "The injected view controller is not a flexible header view controller, it is" + "\(String(describing: viewController.children.first)) instead.") if let headerViewController = viewController.children.first as? MDCFlexibleHeaderViewController { XCTAssertEqual( headerViewController.headerView.frame.height, headerViewController.headerView.maximumHeight) } } func testPushingAnAppBarContainerViewControllerDoesNotInjectAnAppBar() { // Given let viewController = UIViewController() let container = MDCAppBarContainerViewController(contentViewController: viewController) // When navigationController.pushViewController(container, animated: false) // Then XCTAssertEqual( container.children.count, 2, "An App Bar container view controller should have exactly two child view" + " controllers. A failure of this assertion implies that the navigation" + " controller may have injected another App Bar.") } func testPushingAContainedAppBarContainerViewControllerDoesNotInjectAnAppBar() { // Given let viewController = UIViewController() let container = MDCAppBarContainerViewController(contentViewController: viewController) let nestedContainer = UIViewController() nestedContainer.addChild(container) nestedContainer.view.addSubview(container.view) container.didMove(toParent: nestedContainer) // When navigationController.pushViewController(nestedContainer, animated: false) // Then XCTAssertEqual( nestedContainer.children.count, 1, "The view controller hierarchy already has one app bar view controller, but it" + " appears to have possibly added another.") } func testPushingAViewControllerWithAFlexibleHeaderDoesNotInjectAnAppBar() { // Given let viewController = UIViewController() let fhvc = MDCFlexibleHeaderViewController() viewController.addChild(fhvc) viewController.view.addSubview(fhvc.view) fhvc.didMove(toParent: viewController) // When navigationController.pushViewController(viewController, animated: false) // Then XCTAssertEqual( viewController.children.count, 1, "The navigation controller may have injected another App Bar when it shouldn't" + " have.") } // MARK: - traitCollectionDidChangeBlock support func testInitializingWithRootViewControllerDoesNotSetTraitCollectionDidChangeBlock() { // Given let viewController = UIViewController() // When let _ = MDCAppBarNavigationController(rootViewController: viewController) // Then let injectedAppBarViewController = viewController.children.first as! MDCAppBarViewController XCTAssertNotNil(injectedAppBarViewController) XCTAssertNil(injectedAppBarViewController.traitCollectionDidChangeBlock) } func testPushingAViewControllerAssignsTraitCollectionDidChangeBlock() { // Given let viewController = UIViewController() let block: ((MDCFlexibleHeaderViewController, UITraitCollection?) -> Void)? = { _, _ in } navigationController.traitCollectionDidChangeBlockForAppBarController = block // When navigationController.pushViewController(viewController, animated: false) // Then let injectedAppBarViewController = viewController.children.first as! MDCAppBarViewController XCTAssertNotNil(injectedAppBarViewController) XCTAssertNotNil(injectedAppBarViewController.traitCollectionDidChangeBlock) } func testPushingAnAppBarContainerViewControllerDoesNotAssignTraitCollectionDidChangeBlock() { // Given let viewController = UIViewController() let container = MDCAppBarContainerViewController(contentViewController: viewController) var blockSemaphore = false let block: ((MDCFlexibleHeaderViewController, UITraitCollection?) -> Void)? = { _, _ in blockSemaphore = true } container.appBarViewController.traitCollectionDidChangeBlock = block // When navigationController.pushViewController(container, animated: false) container.appBarViewController.traitCollectionDidChange(nil) // Then XCTAssertTrue(blockSemaphore) } func testPushingAContainedAppBarContainerViewControllerDoesNotAssignTraitCollectionDidChangeBlock() { // Given let viewController = UIViewController() let container = MDCAppBarContainerViewController(contentViewController: viewController) let nestedContainer = UIViewController() nestedContainer.addChild(container) nestedContainer.view.addSubview(container.view) container.didMove(toParent: nestedContainer) var blockSemaphore = false let block: ((MDCFlexibleHeaderViewController, UITraitCollection?) -> Void)? = { _, _ in blockSemaphore = true } container.appBarViewController.traitCollectionDidChangeBlock = block // When navigationController.pushViewController(nestedContainer, animated: false) container.appBarViewController.traitCollectionDidChange(nil) // Then XCTAssertTrue(blockSemaphore) } // MARK: - The rest func testStatusBarStyleIsFetchedFromFlexibleHeaderViewController() { // Given let viewController = UIViewController() // When navigationController.pushViewController(viewController, animated: false) // Then let appBar = navigationController.appBar(for: viewController) XCTAssertNotNil(appBar, "Could not retrieve the injected App Bar.") if let appBar = appBar { XCTAssertEqual( navigationController.childForStatusBarStyle, appBar.headerViewController, "The navigation controller should be using the injected app bar's flexible" + "header view controller for status bar style updates.") } } func testInfersFirstTrackingScrollViewByDefault() { // Given let viewController = UIViewController() let scrollView1 = UIScrollView() viewController.view.addSubview(scrollView1) let scrollView2 = UIScrollView() viewController.view.addSubview(scrollView2) // When navigationController.pushViewController(viewController, animated: false) // Then guard let appBarViewController = navigationController.appBarViewController(for: viewController) else { XCTFail("No app bar view controller found.") return } XCTAssertEqual(appBarViewController.headerView.trackingScrollView, scrollView1) } func testDelegateCanReturnNilTrackingScrollView() { // Given let viewController = UIViewController() let scrollView1 = UIScrollView() viewController.view.addSubview(scrollView1) let scrollView2 = UIScrollView() viewController.view.addSubview(scrollView2) let delegate = MockAppBarNavigationControllerDelegate() navigationController.delegate = delegate // When delegate.trackingScrollView = nil navigationController.pushViewController(viewController, animated: false) // Then guard let appBarViewController = navigationController.appBarViewController(for: viewController) else { XCTFail("No app bar view controller found.") return } XCTAssertNil(appBarViewController.headerView.trackingScrollView) } func testDelegateCanPickDifferentTrackingScrollView() { // Given let viewController = UIViewController() let scrollView1 = UIScrollView() viewController.view.addSubview(scrollView1) let scrollView2 = UIScrollView() viewController.view.addSubview(scrollView2) let delegate = MockAppBarNavigationControllerDelegate() navigationController.delegate = delegate // When delegate.trackingScrollView = scrollView2 navigationController.pushViewController(viewController, animated: false) // Then guard let appBarViewController = navigationController.appBarViewController(for: viewController) else { XCTFail("No app bar view controller found.") return } XCTAssertEqual(appBarViewController.headerView.trackingScrollView, scrollView2) } }
c38779fd5fa530472549866846de98a9
33.95679
99
0.752693
false
false
false
false
Ossey/WeiBo
refs/heads/master
XYWeiBo/XYWeiBo/Classes/Tools/Extension/NSDate-Extension.swift
apache-2.0
1
// // NSDate-Extension.swift // XYWeiBo // // Created by xiaomage on 16/4/8. // Copyright © 2016年 sey. All rights reserved. // import UIKit extension NSDate { class func createDateString(createAtStr : String) -> String { // 1.创建时间格式化对象 let fmt = DateFormatter() fmt.dateFormat = "EEE MM dd HH:mm:ss Z yyyy" fmt.locale = NSLocale(localeIdentifier: "en") as Locale! // 2.将字符串时间,转成NSDate类型 guard let createDate = fmt.date(from: createAtStr) else { return "" } // 3.创建当前时间 let nowDate = NSDate() // 4.计算创建时间和当前时间的时间差 let interval = Int(nowDate.timeIntervalSince(createDate)) // 5.对时间间隔处理 // 5.1.显示刚刚 if interval < 60 { return "刚刚" } // 5.2.59分钟前 if interval < 60 * 60 { return "\(interval / 60)分钟前" } // 5.3.11小时前 if interval < 60 * 60 * 24 { return "\(interval / (60 * 60))小时前" } // 5.4.创建日历对象 let calendar = NSCalendar.current // 5.5.处理昨天数据: 昨天 12:23 if calendar.isDateInYesterday(createDate) { fmt.dateFormat = "昨天 HH:mm" let timeStr = fmt.string(from: createDate) return timeStr } // 5.6.处理一年之内: 02-22 12:22 let cmps = calendar.component(.year, from: createDate) if cmps < 1 { fmt.dateFormat = "MM-dd HH:mm" let timeStr = fmt.string(from: createDate) return timeStr } // 5.7.超过一年: 2014-02-12 13:22 fmt.dateFormat = "yyyy-MM-dd HH:mm" let timeStr = fmt.string(from: createDate) return timeStr } }
4685a9a66dcb828d35de077a2df7071c
25.411765
65
0.504454
false
false
false
false
L-Zephyr/Drafter
refs/heads/master
Sources/Drafter/Parser/OC/ObjcMessageParser.swift
mit
1
// // ObjcMessageParser.swift // drafterPackageDescription // // Created by LZephyr on 2017/11/8. // import Foundation import SwiftyParse class ObjcMessageParser: ConcreteParserType { var parser: TokenParser<[MethodInvokeNode]> { return messageSend.continuous.map({ (methods) -> [MethodInvokeNode] in var result = methods for method in methods { result.append(contentsOf: method.params.reduce([]) { $0 + $1.invokes }) } return result }) } } // MARK: - Parser extension ObjcMessageParser { /// 解析一个方法调用 /** message_send = '[' receiver param_selector ']' */ var messageSend: TokenParser<MethodInvokeNode> { let msg = curry(MethodInvokeNode.ocInit) <^> receiver <*> paramSelector return msg.between(token(.leftSquare), token(.rightSquare)) <?> "message_send解析失败" } /// 调用方 /** receiver = message_send | NAME */ var receiver: TokenParser<MethodInvoker> { return lazy(self.messageSend) => toMethodInvoker() <|> token(.name) => toMethodInvoker() <?> "receiver解析失败" } /// 参数列表 /** param_selector = param_list | NAME */ var paramSelector: TokenParser<[InvokeParam]> { return paramList <|> { [InvokeParam(name: $0.text, invokes: [])] } <^> token(.name) <?> "param_selector解析失败" } /// 带具体参数的列表 /** param_list = (param)+ */ var paramList: TokenParser<[InvokeParam]> { return param.many1 <?> "param_list解析失败" } /// 参数 /** param = NAME ':' param_body */ var param: TokenParser<InvokeParam> { return curry(InvokeParam.init) <^> (curry({ "\($0.text)\($1.text)" }) <^> token(.name) <*> token(.colon)) <*> paramBody } /// 解析具体参数内容,参数中的方法调用也解析出来 var paramBody: TokenParser<[MethodInvokeNode]> { return { lazy(self.messageSend).continuous.run($0) ?? [] } <^> anyOpenTokens(until: token(.rightSquare) <|> token(.name) *> token(.colon)) } } // MARK: - Helper extension ObjcMessageParser { func toMethodInvoker() -> (MethodInvokeNode) -> MethodInvoker { return { invoke in .method(invoke) } } func toMethodInvoker() -> (Token) -> MethodInvoker { return { token in .name(token.text) } } } extension MethodInvokeNode { static func ocInit(_ invoker: MethodInvoker, _ params: [InvokeParam]) -> MethodInvokeNode { let invoke = MethodInvokeNode() invoke.isSwift = false invoke.invoker = invoker invoke.params = params return invoke } }
85775b2e2fd5c306a4ab7596a3165308
24.522936
95
0.558231
false
false
false
false
ReSwift/ReSwift-Todo-Example
refs/heads/master
ReSwift-Todo/DateConverter.swift
mit
1
// // DateConverter.swift // ReSwift-Todo // // Created by Christian Tietze on 13/09/16. // Copyright © 2016 ReSwift. All rights reserved. // import Foundation extension Calendar { func dateFromISOComponents(year: Int, month: Int, day: Int) -> Date? { // Without custom checks, "12-945-23" does work. guard (1...12).contains(month) && (1...31).contains(day) else { return nil } var components = DateComponents() components.year = year components.month = month components.day = day return self.date(from: components) } } class DateConverter { init() { } /// Expects `isoDateString` to start with `2016-09-13` /// (YYYY-MM-DD) and extracts these values. func date(isoDateString string: String, calendar: Calendar = Calendar.autoupdatingCurrent) -> Date? { let parts = string.split(separator: "-") .map(String.init) .compactMap { Int($0) } guard parts.count >= 3 else { return nil } return calendar.dateFromISOComponents(year: parts[0], month: parts[1], day: parts[2]) } static var isoFormatter: DateFormatter = { let formatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd" formatter.locale = Locale(identifier: "en_US_POSIX") return formatter }() func string(date: Date) -> String { return DateConverter.isoFormatter.string(from: date) } }
870c1d46c132815336f5ccfdbdb9b308
24.482759
105
0.610284
false
false
false
false
mleiv/MEGameTracker
refs/heads/master
MEGameTracker/Models/CoreData/Data Rows/DataEventsable.swift
mit
1
// // DataEventsable.swift // MEGameTracker // // Created by Emily Ivie on 4/15/16. // Copyright © 2016 Emily Ivie. All rights reserved. // import Foundation import CoreData public protocol DataEventsable { /// The serialized event data stored (can be edited, like during base import, but this is not recommended) var rawEventDictionary: [CodableDictionary] { get } /// A reference to the current core data manager. /// (Default provided for CodableCoreDataStorable objects.) var defaultManager: CodableCoreDataManageable { get } } extension DataEventsable { typealias DataEventsableType = DataEvent // public func getDataEvents(with manager: CodableCoreDataManageable?) -> [DataEvent] { // let manager = manager ?? CoreDataManager.current // return (try? manager.decoder.decode([DataEvent].self, from: rawEventDictionary)) ?? [] // } public func getRelatedDataEvents( context: NSManagedObjectContext? ) -> NSSet { let ids = getIdsFromRawEventDictionary() guard !ids.isEmpty else { return NSSet() } let manager = type(of: defaultManager).init(context: context) let directEvents = DataEvent.getAll(ids: ids, with: manager) let relatedEventIds = ids + directEvents.flatMap({ $0.dependentOn?.events ?? [] }) // yes Flat Map let allEvents: [DataEvents] = manager.getAll { fetchRequest in fetchRequest.predicate = NSPredicate(format: "(%K in %@)", "id", relatedEventIds) } return NSSet(array: allEvents) } private func getIdsFromRawEventDictionary() -> [String] { return rawEventDictionary.map { $0["id"] as? String }.filter({ $0 != nil }).map({ $0! }) } } private struct DataEventsableDecodedEventId: Codable { let id: String }
14dc7c59954e747514d977eaebd0d0a0
34.235294
110
0.676683
false
false
false
false
cwwise/CWWeChat
refs/heads/master
CWWeChat/ChatModule/CWChatKit/Message/View/CWChatUIConstant.swift
mit
2
// // CWChatUIConstant.swift // CWWeChat // // Created by chenwei on 16/6/22. // Copyright © 2016年 chenwei. All rights reserved. // import UIKit // 上下留白 let kMessageCellTopMargin: CGFloat = 2.0 let kMessageCellBottomMargin: CGFloat = 12.0 let kChatTextMaxWidth = kScreenWidth * 0.58 //图片 let kChatImageMaxWidth = kScreenWidth * 0.45 let kChatImageMinWidth = kScreenWidth * 0.25 let kChatVoiceMaxWidth = kScreenWidth * 0.3 let defaultHeadeImage = CWAsset.Default_head.image public struct ChatCellUI { static let bubbleTopMargin: CGFloat = 2 static let bubbleBottomMargin: CGFloat = 11 static let left_cap_insets = UIEdgeInsets(top: 32, left: 40, bottom: 20, right: 40) /// 左边气泡背景区域 间距 static let left_edge_insets = UIEdgeInsets(top: 2+10, left: 17, bottom: 11+9.5, right: 17) static let right_cap_insets = UIEdgeInsets(top: 32, left: 40, bottom: 20, right: 40) /// 右边气泡背景区域 间距 static let right_edge_insets = UIEdgeInsets(top: 2+10, left: 17, bottom: 11+9.5, right: 17) } //MARK: UI相关 public struct ChatSessionCellUI { static let headerImageViewLeftPadding:CGFloat = 10.0 static let headerImageViewTopPadding:CGFloat = 10.0 } /* let kTimeMessageCellHeight: CGFloat = 30.0 // cell布局中的间距 let kMessageCellMargin: CGFloat = 10.0 /// 头像 let kAvaterImageViewWidth: CGFloat = 40.0 let kAvaterImageViewMargin: CGFloat = 10.0 /// 名称 let kNameLabelHeight: CGFloat = 14.0 let kNameLabelSpaceX: CGFloat = 12.0 let kNamelabelSpaceY: CGFloat = 1.0 let kAvatarToMessageContent: CGFloat = 5.0 let kMessageCellEdgeOffset: CGFloat = 6.0 public let kChatTextAttribute = [NSAttributedStringKey.foregroundColor:UIColor.black, NSAttributedStringKey.font: UIFont.fontTextMessageText()] */
43bec6779ba82a2d001abb5d16567ae2
24.871429
95
0.705135
false
false
false
false
noppoMan/aws-sdk-swift
refs/heads/main
Sources/Soto/Services/SageMaker/SageMaker_Error.swift
apache-2.0
1
//===----------------------------------------------------------------------===// // // This source file is part of the Soto for AWS open source project // // Copyright (c) 2017-2020 the Soto project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of Soto project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// // THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT. import SotoCore /// Error enum for SageMaker public struct SageMakerErrorType: AWSErrorType { enum Code: String { case conflictException = "ConflictException" case resourceInUse = "ResourceInUse" case resourceLimitExceeded = "ResourceLimitExceeded" case resourceNotFound = "ResourceNotFound" } private let error: Code public let context: AWSErrorContext? /// initialize SageMaker public init?(errorCode: String, context: AWSErrorContext) { guard let error = Code(rawValue: errorCode) else { return nil } self.error = error self.context = context } internal init(_ error: Code) { self.error = error self.context = nil } /// return error code string public var errorCode: String { self.error.rawValue } /// There was a conflict when you attempted to modify an experiment, trial, or trial component. public static var conflictException: Self { .init(.conflictException) } /// Resource being accessed is in use. public static var resourceInUse: Self { .init(.resourceInUse) } /// You have exceeded an Amazon SageMaker resource limit. For example, you might have too many training jobs created. public static var resourceLimitExceeded: Self { .init(.resourceLimitExceeded) } /// Resource being access is not found. public static var resourceNotFound: Self { .init(.resourceNotFound) } } extension SageMakerErrorType: Equatable { public static func == (lhs: SageMakerErrorType, rhs: SageMakerErrorType) -> Bool { lhs.error == rhs.error } } extension SageMakerErrorType: CustomStringConvertible { public var description: String { return "\(self.error.rawValue): \(self.message ?? "")" } }
339bc1c0e0189fe635718f5536d3f56b
34.893939
122
0.652174
false
false
false
false
huangxinping/XPKit-swift
refs/heads/master
Source/Extensions/UIKit/UIDevice+XPKit.swift
mit
1
// // UIDevice+XPKit.swift // XPKit // // The MIT License (MIT) // // Copyright (c) 2015 - 2016 Fabrizio Brancati. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import Foundation import UIKit // MARK: - Private variables - /// Used to store the XPUniqueIdentifier in defaults private let XPUniqueIdentifierDefaultsKey = "XPUniqueIdentifier" private let XPUserUniqueIdentifierDefaultsKey = "XPUserUniqueIdentifier" // MARK: - Global functions - /** Get the iOS version string - returns: Get the iOS version string */ public func IOS_VERSION() -> String { return UIDevice.currentDevice().systemVersion } /** Compare system versions - parameter v: Version, like "9.0" - returns: Returns a Bool */ public func SYSTEM_VERSION_EQUAL_TO(v: String) -> Bool { return UIDevice.currentDevice().systemVersion.compare(v, options: .NumericSearch) == .OrderedSame } /** Compare system versions - parameter v: Version, like "9.0" - returns: Returns a Bool */ public func SYSTEM_VERSION_GREATER_THAN(v: String) -> Bool { return UIDevice.currentDevice().systemVersion.compare(v, options: .NumericSearch) == .OrderedDescending } /** Compare system versions - parameter v: Version, like "9.0" - returns: Returns a Bool */ public func SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v: String) -> Bool { return UIDevice.currentDevice().systemVersion.compare(v, options: .NumericSearch) != .OrderedAscending } /** Compare system versions - parameter v: Version, like "9.0" - returns: Returns a Bool */ public func SYSTEM_VERSION_LESS_THAN(v: String) -> Bool { return UIDevice.currentDevice().systemVersion.compare(v, options: .NumericSearch) == .OrderedAscending } /** Compare system versions - parameter v: Version, like "9.0" - returns: Returns a Bool */ public func SYSTEM_VERSION_LESS_THAN_OR_EQUAL_TO(v: String) -> Bool { return UIDevice.currentDevice().systemVersion.compare(v, options: .NumericSearch) != .OrderedDescending } /** Returns if the iOS version is greater or equal to choosed one - returns: Returns if the iOS version is greater or equal to choosed one */ public func IS_IOS_5_OR_LATER() -> Bool { return UIDevice.currentDevice().systemVersion.floatValue >= 5.0 } /** Returns if the iOS version is greater or equal to choosed one - returns: Returns if the iOS version is greater or equal to choosed one */ public func IS_IOS_6_OR_LATER() -> Bool { return UIDevice.currentDevice().systemVersion.floatValue >= 6.0 } /** Returns if the iOS version is greater or equal to choosed one - returns: Returns if the iOS version is greater or equal to choosed one */ public func IS_IOS_7_OR_LATER() -> Bool { return UIDevice.currentDevice().systemVersion.floatValue >= 7.0 } /** Returns if the iOS version is greater or equal to choosed one - returns: Returns if the iOS version is greater or equal to choosed one */ public func IS_IOS_8_OR_LATER() -> Bool { return UIDevice.currentDevice().systemVersion.floatValue >= 8.0 } /** Returns if the iOS version is greater or equal to choosed one - returns: Returns if the iOS version is greater or equal to choosed one */ public func IS_IOS_9_OR_LATER() -> Bool { return UIDevice.currentDevice().systemVersion.floatValue >= 9.0 } /// This extesion adds some useful functions to UIDevice public extension UIDevice { // MARK: - Class functions - /** Returns the device platform string Example: "iPhone7,2" - returns: Returns the device platform string */ public static func devicePlatform() -> String { var name: [Int32] = [CTL_HW, HW_MACHINE] var size: Int = 2 sysctl(&name, 2, nil, &size, &name, 0) var hw_machine = [CChar](count: Int(size), repeatedValue: 0) sysctl(&name, 2, &hw_machine, &size, &name, 0) let hardware: String = String.fromCString(hw_machine)! return hardware } /** Returns the user-friendly device platform string Example: "iPad Air (Cellular)" - returns: Returns the user-friendly device platform string */ public static func devicePlatformString() -> String { let platform: String = self.devicePlatform() switch platform { // iPhone case "iPhone1,1": return "iPhone 2G" case "iPhone1,2": return "iPhone 3G" case "iPhone2,1": return "iPhone 3GS" case "iPhone3,1": return "iPhone 4 (GSM)" case "iPhone3,2": return "iPhone 4 (Rev. A)" case "iPhone3,3": return "iPhone 4 (CDMA)" case "iPhone4,1": return "iPhone 4S" case "iPhone5,1": return "iPhone 5 (GSM)" case "iPhone5,2": return "iPhone 5 (CDMA)" case "iPhone5,3": return "iPhone 5c (GSM)" case "iPhone5,4": return "iPhone 5c (Global)" case "iPhone6,1": return "iPhone 5s (GSM)" case "iPhone6,2": return "iPhone 5s (Global)" case "iPhone7,1": return "iPhone 6 Plus" case "iPhone7,2": return "iPhone 6" case "iPhone8,1": return "iPhone 6s" case "iPhone8,2": return "iPhone 6s Plus" case "iPhone8,4": return "iPhone SE" // iPod case "iPod1,1": return "iPod Touch 1G" case "iPod2,1": return "iPod Touch 2G" case "iPod3,1": return "iPod Touch 3G" case "iPod4,1": return "iPod Touch 4G" case "iPod5,1": return "iPod Touch 5G" case "iPod7,1": return "iPod Touch 6G" // iPad case "iPad1,1": return "iPad 1" case "iPad2,1": return "iPad 2 (WiFi)" case "iPad2,2": return "iPad 2 (GSM)" case "iPad2,3": return "iPad 2 (CDMA)" case "iPad2,4": return "iPad 2 (32nm)" case "iPad3,1": return "iPad 3 (WiFi)" case "iPad3,2": return "iPad 3 (CDMA)" case "iPad3,3": return "iPad 3 (GSM)" case "iPad3,4": return "iPad 4 (WiFi)" case "iPad3,5": return "iPad 4 (GSM)" case "iPad3,6": return "iPad 4 (CDMA)" case "iPad4,1": return "iPad Air (WiFi)" case "iPad4,2": return "iPad Air (Cellular)" case "iPad4,3": return "iPad Air (China)" case "iPad5,3": return "iPad Air 2 (WiFi)" case "iPad5,4": return "iPad Air 2 (Cellular)" // iPad mini case "iPad2,5": return "iPad mini (WiFi)" case "iPad2,6": return "iPad mini (GSM)" case "iPad2,7": return "iPad mini (CDMA)" case "iPad4,4": return "iPad mini 2 (WiFi)" case "iPad4,5": return "iPad mini 2 (Cellular)" case "iPad4,6": return "iPad mini 2 (China)" case "iPad4,7": return "iPad mini 3 (WiFi)" case "iPad4,8": return "iPad mini 3 (Cellular)" case "iPad4,9": return "iPad mini 3 (China)" // iPad Pro 9.7 case "iPad6,3": return "iPad Pro 9.7 (WiFi)" case "iPad6,4": return "iPad Pro 9.7 (Cellular)" // iPad Pro 12.9 case "iPad6,7": return "iPad Pro 12.9 (WiFi)" case "iPad6,8": return "iPad Pro 12.9 (Cellular)" // Apple TV case "AppleTV2,1": return "Apple TV 2G" case "AppleTV3,1": return "Apple TV 3G" case "AppleTV3,2": return "Apple TV 3G" case "AppleTV5,3": return "Apple TV 4G" // Apple Watch case "Watch1,1": return "Apple Watch 38mm" case "Watch1,2": return "Apple Watch 42mm" // Simulator case "i386", "x86_64": return "Simulator" default: return platform } } /** Check if the current device is an iPad - returns: Returns true if it's an iPad, fasle if not */ public static func isiPad() -> Bool { if self.devicePlatform().substringToIndex(4) == "iPad" { return true } else { return false } } /** Check if the current device is an iPhone - returns: Returns true if it's an iPhone, false if not */ public static func isiPhone() -> Bool { if self.devicePlatform().substringToIndex(6) == "iPhone" { return true } else { return false } } /** Check if the current device is an iPod - returns: Returns true if it's an iPod, false if not */ public static func isiPod() -> Bool { if self.devicePlatform().substringToIndex(4) == "iPod" { return true } else { return false } } /** Check if the current device is an Apple TV - returns: Returns true if it's an Apple TV, false if not */ public static func isAppleTV() -> Bool { if self.devicePlatform().substringToIndex(7) == "AppleTV" { return true } else { return false } } /** Check if the current device is an Apple Watch - returns: Returns true if it's an Apple Watch, false if not */ public static func isAppleWatch() -> Bool { if self.devicePlatform().substringToIndex(5) == "Watch" { return true } else { return false } } /** Check if the current device is a Simulator - returns: Returns true if it's a Simulator, false if not */ public static func isSimulator() -> Bool { if self.devicePlatform() == "i386" || self.devicePlatform() == "x86_64" { return true } else { return false } } /** Check if the current device has a Retina display - returns: Returns true if it has a Retina display, false if not */ @available( *, deprecated = 1.4.0, message = "Use isRetina() in UIScreen class") public static func isRetina() -> Bool { return UIScreen.isRetina() } /** Check if the current device has a Retina HD display - returns: Returns true if it has a Retina HD display, false if not */ @available( *, deprecated = 1.4.0, message = "Use isRetinaHD() in UIScreen class") public static func isRetinaHD() -> Bool { return UIScreen.isRetinaHD() } /** Returns the iOS version without the subversion Example: 7 - returns: Returns the iOS version */ public static func iOSVersion() -> Int { return Int(UIDevice.currentDevice().systemVersion.substringToCharacter(".")!)! } /** Private, used to get the system info - parameter typeSpecifier: Type of the system info - returns: Return the sysyem info */ private static func getSysInfo(typeSpecifier: Int32) -> Int { var name: [Int32] = [CTL_HW, typeSpecifier] var size: Int = 2 sysctl(&name, 2, nil, &size, &name, 0) var results: Int = 0 sysctl(&name, 2, &results, &size, &name, 0) return results } /** Returns the current device CPU frequency - returns: Returns the current device CPU frequency */ public static func cpuFrequency() -> Int { return self.getSysInfo(HW_CPU_FREQ) } /** Returns the current device BUS frequency - returns: Returns the current device BUS frequency */ public static func busFrequency() -> Int { return self.getSysInfo(HW_TB_FREQ) } /** Returns the current device RAM size - returns: Returns the current device RAM size */ public static func ramSize() -> Int { return self.getSysInfo(HW_MEMSIZE) } /** Returns the current device CPU number - returns: Returns the current device CPU number */ public static func cpuNumber() -> Int { return self.getSysInfo(HW_NCPU) } /** Returns the current device total memory - returns: Returns the current device total memory */ public static func totalMemory() -> Int { return self.getSysInfo(HW_PHYSMEM) } /** Returns the current device non-kernel memory - returns: Returns the current device non-kernel memory */ public static func userMemory() -> Int { return self.getSysInfo(HW_USERMEM) } /** Returns the current device total disk space - returns: Returns the current device total disk space */ public static func totalDiskSpace() throws -> AnyObject { let attributes: NSDictionary = try NSFileManager.defaultManager().attributesOfFileSystemForPath(NSHomeDirectory()) return attributes.objectForKey(NSFileSystemSize)! } /** Returns the current device free disk space - returns: Returns the current device free disk space */ public static func freeDiskSpace() throws -> AnyObject { let attributes: NSDictionary = try NSFileManager.defaultManager().attributesOfFileSystemForPath(NSHomeDirectory()) return attributes.objectForKey(NSFileSystemFreeSize)! } /** Generate an unique identifier and store it into standardUserDefaults - returns: Returns a unique identifier as a String */ public static func uniqueIdentifier() -> String { var UUID: String? if UIDevice.currentDevice().respondsToSelector(Selector("identifierForVendor")) { UUID = UIDevice.currentDevice().identifierForVendor!.UUIDString } else { let defaults = NSUserDefaults.standardUserDefaults() UUID = defaults.objectForKey(XPUniqueIdentifierDefaultsKey) as? String if UUID == nil { UUID = String.generateUUID() defaults.setObject(UUID, forKey: XPUniqueIdentifierDefaultsKey) defaults.synchronize() } } return UUID! } /** Save the unique identifier or update it if there is and it is changed. Is useful for push notification to know if the unique identifier has changed and needs to be send to server - parameter uniqueIdentifier: The unique identifier to save or update if needed. (Must be NSData or NSString) - parameter block: The execution block that know if the unique identifier is valid and has to be updated. You have to handle the case if it is valid and the update is needed or not */ public static func updateUniqueIdentifier(uniqueIdentifier: NSObject, block: (isValid: Bool, hasToUpdateUniqueIdentifier: Bool, oldUUID: String?) -> ()) { var userUUID: String = "" var savedUUID: String? = nil var isValid = false, hasToUpdate = false if uniqueIdentifier.isKindOfClass(NSData) { let data: NSData = uniqueIdentifier as! NSData userUUID = data.convertToUTF8String() } else if uniqueIdentifier.isKindOfClass(NSString) { let string: NSString = uniqueIdentifier as! NSString userUUID = string.convertToAPNSUUID() as String } isValid = userUUID.isUUIDForAPNS() if isValid { let defaults: NSUserDefaults = NSUserDefaults.standardUserDefaults() savedUUID = defaults.stringForKey(XPUserUniqueIdentifierDefaultsKey) if savedUUID == nil || savedUUID != userUUID { defaults.setObject(userUUID, forKey: XPUserUniqueIdentifierDefaultsKey) defaults.synchronize() hasToUpdate = true } } block(isValid: isValid, hasToUpdateUniqueIdentifier: hasToUpdate, oldUUID: userUUID) } }
f0d21e3685bdcfa7ee1e598bee27353d
28.216963
193
0.699656
false
false
false
false
Subberbox/Subber-api
refs/heads/master
Sources/App/Controllers/VendorController.swift
mit
2
// // VendorController.swift // subber-api // // Created by Hakon Hanesand on 11/15/16. // // import Foundation import Vapor import HTTP import Turnstile import Auth extension Vendor { func shouldAllow(request: Request) throws { guard let vendor = try? request.vendor() else { throw try Abort.custom(status: .forbidden, message: "Method \(request.method) is not allowed on resource Vendor(\(throwableId())) by this user. Must be logged in as Vendor(\(throwableId())).") } guard try vendor.throwableId() == throwableId() else { throw try Abort.custom(status: .forbidden, message: "This Vendor(\(vendor.throwableId()) does not have access to resource Vendor(\(throwableId()). Must be logged in as Vendor(\(throwableId()).") } } } final class VendorController: ResourceRepresentable { func index(_ request: Request) throws -> ResponseRepresentable { return try request.vendor().makeJSON() } func show(_ request: Request, vendor: Vendor) throws -> ResponseRepresentable { try vendor.shouldAllow(request: request) return try vendor.makeJSON() } func create(_ request: Request) throws -> ResponseRepresentable { var vendor: Vendor = try request.extractModel() try vendor.save() let node = try request.json().node let username: String = try node.extract("username") let password: String = try node.extract("password") let usernamePassword = UsernamePassword(username: username, password: password) try request.vendorSubject().login(credentials: usernamePassword, persist: true) return vendor } func modify(_ request: Request, vendor: Vendor) throws -> ResponseRepresentable { try vendor.shouldAllow(request: request) var vendor: Vendor = try request.patchModel(vendor) try vendor.save() return try Response(status: .ok, json: vendor.makeJSON()) } func makeResource() -> Resource<Vendor> { return Resource( index: index, store: create, show: show, modify: modify ) } }
40af6c649c942adcdd096b661cd65a5f
30.7
206
0.633619
false
false
false
false
playgroundscon/Playgrounds
refs/heads/master
Playgrounds/Controller/PresentationsThursdayDataSource.swift
gpl-3.0
1
// // ThursdayScheduleViewController.swift // Playgrounds // // Created by Andyy Hope on 18/11/16. // Copyright © 2016 Andyy Hope. All rights reserved. // import UIKit final class PresentationsThursdayDataSource: NSObject { var day: ScheduleDay = ScheduleDay(sessions: []) } extension PresentationsThursdayDataSource: UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return day.sessions.count } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 1 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell: ScheduleSpeakerCell = tableView.dequeueReusableCell(for: indexPath) let session = day.sessions[indexPath.section] let speaker = session.speaker cell.headingLabel.text = session.presentation.title cell.subheadingLabel.text = speaker.name cell.avatarImageView.image = UIImage(named: speaker.resource) return cell } func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "HH:mma" let date = Date(timeIntervalSince1970: TimeInterval(day.sessions[section].time.rawValue)) return dateFormatter.string(from: date) } }
dcb8f488ee9687474b9d7f49a33626dd
31.295455
100
0.695989
false
false
false
false
narner/AudioKit
refs/heads/master
Playgrounds/AudioKitPlaygrounds/Playgrounds/Effects.playground/Pages/Tanh Distortion.xcplaygroundpage/Contents.swift
mit
1
//: ## Tanh Distortion //: ## //: import AudioKitPlaygrounds import AudioKit let file = try AKAudioFile(readFileName: playgroundAudioFiles[0]) let player = try AKAudioPlayer(file: file) player.looping = true var distortion = AKTanhDistortion(player) distortion.pregain = 1.0 distortion.postgain = 1.0 distortion.postiveShapeParameter = 1.0 distortion.negativeShapeParameter = 1.0 AudioKit.output = distortion AudioKit.start() player.play() //: User Interface Set up import AudioKitUI class LiveView: AKLiveViewController { override func viewDidLoad() { addTitle("Tanh Distortion") addView(AKResourcesAudioFileLoaderView(player: player, filenames: playgroundAudioFiles)) addView(AKButton(title: "Stop Distortion") { button in let node = distortion node.isStarted ? node.stop() : node.play() button.title = node.isStarted ? "Stop Distortion" : "Start Distortion" }) addView(AKSlider(property: "Pre-gain", value: distortion.pregain, range: 0 ... 10) { sliderValue in distortion.pregain = sliderValue }) addView(AKSlider(property: "Post-gain", value: distortion.postgain, range: 0 ... 10) { sliderValue in distortion.postgain = sliderValue }) addView(AKSlider(property: "Postive Shape Parameter", value: distortion.postiveShapeParameter, range: -10 ... 10 ) { sliderValue in distortion.postiveShapeParameter = sliderValue }) addView(AKSlider(property: "Negative Shape Parameter", value: distortion.negativeShapeParameter, range: -10 ... 10 ) { sliderValue in distortion.negativeShapeParameter = sliderValue }) } } import PlaygroundSupport PlaygroundPage.current.needsIndefiniteExecution = true PlaygroundPage.current.liveView = LiveView()
ebb735b73623fc7a8c3bf91be5815aeb
29.984127
109
0.65625
false
false
false
false
jimmy54/iRime
refs/heads/master
iRime/Keyboard/tasty-imitation-keyboard/Model/DefaultKeyboard.swift
gpl-3.0
1
// // DefaultKeyboard.swift // TransliteratingKeyboard // // Created by Alexei Baboulevitch on 7/10/14. // Copyright (c) 2014 Alexei Baboulevitch ("Archagon"). All rights reserved. // func defaultKeyboard() -> Keyboard { let defaultKeyboard = Keyboard() let df = NSString.userDefaultsInGroup() /** * 中文输入法 */ for key in ["Q", "W", "E", "R", "T", "Y", "U", "I", "O", "P"] { let keyModel = Key(.character) keyModel.setLetter(key) defaultKeyboard.addKey(keyModel, row: 0, page: 0) } for key in ["A", "S", "D", "F", "G", "H", "J", "K", "L"] { let keyModel = Key(.character) keyModel.setLetter(key) defaultKeyboard.addKey(keyModel, row: 1, page: 0) } var keyModel = Key(.modeChange) keyModel.setLetter("符") keyModel.toMode = 3 defaultKeyboard.addKey(keyModel, row: 2, page: 0) for key in ["Z", "X", "C", "V", "B", "N", "M"] { let keyModel = Key(.character) keyModel.setLetter(key) defaultKeyboard.addKey(keyModel, row: 2, page: 0) } var backspace = Key(.backspace) defaultKeyboard.addKey(backspace, row: 2, page: 0) var keyModeChangeNumbers = Key(.modeChange) keyModeChangeNumbers.uppercaseKeyCap = "123" keyModeChangeNumbers.toMode = 1 defaultKeyboard.addKey(keyModeChangeNumbers, row: 3, page: 0) var keyboardChange = Key(.keyboardChange) defaultKeyboard.addKey(keyboardChange, row: 3, page: 0) var settings = Key(.settings) var enInput = Key(.modeChange) enInput.uppercaseKeyCap = "英" enInput.uppercaseOutput = "英" enInput.lowercaseKeyCap = "英" enInput.toMode = 4 defaultKeyboard.addKey(enInput, row: 3, page: 0) let chineseInput = Key(.modeChange) chineseInput.uppercaseKeyCap = "中" chineseInput.uppercaseOutput = "中" chineseInput.lowercaseKeyCap = "中" chineseInput.toMode = 0 var spaceTitle = "中文键盘"; if let schemaId = df?.object(forKey: CURRENT_SCHEMA_NAME) { spaceTitle = schemaId as! String; } spaceTitle = spaceTitle + "(⇌)" var space = Key(.space) space.uppercaseKeyCap = spaceTitle space.lowercaseKeyCap = spaceTitle space.uppercaseOutput = " " space.lowercaseOutput = " " defaultKeyboard.addKey(space, row: 3, page: 0) var returnKey = Key(.return) returnKey.uppercaseKeyCap = "return" returnKey.uppercaseOutput = "\n" returnKey.lowercaseOutput = "\n" defaultKeyboard.addKey(returnKey, row: 3, page: 0) //-------------中文符号------------------------ for key in ["1", "2", "3", "4", "5", "6", "7", "8", "9", "0"] { let keyModel = Key(.specialCharacter) keyModel.setLetter(key) defaultKeyboard.addKey(keyModel, row: 0, page: 3) } let row = cornerBracketEnabled ? ["-", "/", ":", ";", "(", ")", "$", "@", "「", "」"] : ["-", "/", ":", ";", "(", ")", "$", "@", "“", "”"] for key in row { let keyModel = Key(.specialCharacter) keyModel.setLetter(key) keyModel.toMode = -1 defaultKeyboard.addKey(keyModel, row: 1, page: 3) } var keyModeChangeSpecialCharacters = Key(.modeChange) keyModeChangeSpecialCharacters.uppercaseKeyCap = "#+=" keyModeChangeSpecialCharacters.toMode = 2 for key in ["。", ",", "+", "_", "、", "?", "!", ".", ","] { let keyModel = Key(.specialCharacter) keyModel.setLetter(key) keyModel.toMode = -1 defaultKeyboard.addKey(keyModel, row: 2, page: 3) } defaultKeyboard.addKey(Key(backspace), row: 2, page: 3) var back = Key(.modeChange) back.setLetter("返回") back.toMode = -1 defaultKeyboard.addKey(back, row: 3, page: 3) defaultKeyboard.addKey(keyModeChangeSpecialCharacters, row: 3, page: 3) space = Key(.space) space.uppercaseKeyCap = "中文符号" space.lowercaseKeyCap = "中文符号" space.uppercaseOutput = " " space.lowercaseOutput = " " defaultKeyboard.addKey(Key(space), row: 3, page: 3) defaultKeyboard.addKey(Key(returnKey), row: 3, page: 3) //-------------------------------------------- /** * 英文键盘 */ for key in ["Q", "W", "E", "R", "T", "Y", "U", "I", "O", "P"] { let keyModel = Key(.character) keyModel.setLetter(key) defaultKeyboard.addKey(keyModel, row: 0, page: 4) } for key in ["A", "S", "D", "F", "G", "H", "J", "K", "L"] { let keyModel = Key(.character) keyModel.setLetter(key) defaultKeyboard.addKey(keyModel, row: 1, page: 4) } keyModel = Key(.shift) defaultKeyboard.addKey(keyModel, row: 2, page: 4) for key in ["Z", "X", "C", "V", "B", "N", "M"] { let keyModel = Key(.character) keyModel.setLetter(key) defaultKeyboard.addKey(keyModel, row: 2, page: 4) } backspace = Key(.backspace) defaultKeyboard.addKey(backspace, row: 2, page: 4) back = Key(.modeChange) back.setLetter("返回") back.toMode = -1 defaultKeyboard.addKey(back, row: 3, page: 4) keyModeChangeNumbers = Key(.modeChange) keyModeChangeNumbers.uppercaseKeyCap = "123" keyModeChangeNumbers.toMode = 1 defaultKeyboard.addKey(keyModeChangeNumbers, row: 3, page: 4) keyModeChangeSpecialCharacters = Key(.modeChange) keyModeChangeSpecialCharacters.uppercaseKeyCap = "#+=" keyModeChangeSpecialCharacters.toMode = 2 defaultKeyboard.addKey(keyModeChangeSpecialCharacters, row: 3, page: 4) let dot = Key(.specialCharacter) dot.uppercaseKeyCap = "." dot.uppercaseOutput = "." dot.lowercaseKeyCap = "." dot.setLetter(".") // defaultKeyboard.addKey(dot, row: 3, page: 4) // keyboardChange = Key(.KeyboardChange) // defaultKeyboard.addKey(keyboardChange, row: 3, page: 4) // settings = Key(.Settings) space = Key(.space) space.uppercaseKeyCap = "英文键盘" space.lowercaseKeyCap = "英文键盘" space.uppercaseOutput = " " space.lowercaseOutput = " " defaultKeyboard.addKey(space, row: 3, page: 4) returnKey = Key(.return) returnKey.uppercaseKeyCap = "return" returnKey.uppercaseOutput = "\n" returnKey.lowercaseOutput = "\n" defaultKeyboard.addKey(returnKey, row: 3, page: 4) //数字键盘 for key in ["1", "2", "3", "4", "5", "6", "7", "8", "9", "0"] { let keyModel = Key(.specialCharacter) keyModel.setLetter(key) defaultKeyboard.addKey(keyModel, row: 0, page: 1) } for key in ["-", "/", ":", ";", "(", ")", "$", "&", "@", "\""] { let keyModel = Key(.specialCharacter) keyModel.setLetter(key) keyModel.toMode = -1 defaultKeyboard.addKey(keyModel, row: 1, page: 1) } for key in [".", ",", "。", "'", "…", "?", "!", "'", "."] { let keyModel = Key(.specialCharacter) keyModel.setLetter(key) keyModel.toMode = -1 defaultKeyboard.addKey(keyModel, row: 2, page: 1) } defaultKeyboard.addKey(Key(backspace), row: 2, page: 1) // keyModeChangeLetters = Key(.ModeChange) // keyModeChangeLetters.uppercaseKeyCap = "ABC" // keyModeChangeLetters.toMode = 0 // defaultKeyboard.addKey(keyModeChangeLetters, row: 3, page: 1) // defaultKeyboard.addKey(Key(chineseInput), row: 3, page: 1) back = Key(.modeChange) back.setLetter("返回") back.toMode = -1 defaultKeyboard.addKey(back, row: 3, page: 1) // defaultKeyboard.addKey(Key(enInput), row: 3, page: 1) keyModeChangeSpecialCharacters = Key(.modeChange) keyModeChangeSpecialCharacters.uppercaseKeyCap = "#+=" keyModeChangeSpecialCharacters.toMode = 2 defaultKeyboard.addKey(keyModeChangeSpecialCharacters, row: 3, page: 1) space = Key(.space) space.uppercaseKeyCap = "数字键盘" space.lowercaseKeyCap = "数字键盘" space.uppercaseOutput = " " space.lowercaseOutput = " " defaultKeyboard.addKey(Key(space), row: 3, page: 1) defaultKeyboard.addKey(Key(returnKey), row: 3, page: 1) /** * 特殊符号 */ for key in ["[", "]", "{", "}", "#", "%", "^", "*", "+", "="] { let keyModel = Key(.specialCharacter) keyModel.setLetter(key) keyModel.toMode = -1 defaultKeyboard.addKey(keyModel, row: 0, page: 2) } for key in ["_", "\\", "|", "~", "<", ">", "€", "£", "¥", "•"] { let keyModel = Key(.specialCharacter) keyModel.setLetter(key) keyModel.toMode = -1 defaultKeyboard.addKey(keyModel, row: 1, page: 2) } // defaultKeyboard.addKey(Key(keyModeChangeNumbers), row: 2, page: 2) for key in [".", ",", "?", "!", "'", "……", "《", "》", "~"] { let keyModel = Key(.specialCharacter) keyModel.setLetter(key) keyModel.toMode = -1 defaultKeyboard.addKey(keyModel, row: 2, page: 2) } defaultKeyboard.addKey(Key(backspace), row: 2, page: 2) // defaultKeyboard.addKey(Key(keyModeChangeLetters), row: 3, page: 2) // defaultKeyboard.addKey(Key(chineseInput), row: 3, page: 2) // defaultKeyboard.addKey(Key(enInput), row: 3, page: 2) back = Key(.modeChange) back.setLetter("返回") back.toMode = -1 defaultKeyboard.addKey(Key(back), row: 3, page: 2) space = Key(.space) space.uppercaseKeyCap = "英文符号" space.lowercaseKeyCap = "英文符号" space.uppercaseOutput = " " space.lowercaseOutput = " " defaultKeyboard.addKey(Key(space), row: 3, page: 2) defaultKeyboard.addKey(Key(returnKey), row: 3, page: 2) return defaultKeyboard }
a39c1d08489a02eaff1912435236756b
28.675676
140
0.573163
false
false
false
false
ismailbozk/DateIntervalPicker
refs/heads/master
DateIntervalPicker/DateIntervalPickerExample/SecondDemoVC.swift
mit
1
// // SecondDemoVC.swift // DateIntervalPicker // // Created by Ismail Bozkurt on 10/04/2016. // The MIT License (MIT) // // Copyright (c) 2016 Ismail Bozkurt // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import UIKit class SecondDemoVC: UIViewController, DateIntervalPickerViewDelegate { @IBOutlet weak var beginDateLabel: UILabel! @IBOutlet weak var endDateLabel: UILabel! var dateIntervalPickerView: DateIntervalPickerView! override func viewDidLoad() { super.viewDidLoad() self.dateIntervalPickerView = DateIntervalPickerView() self.view.addSubview(self.dateIntervalPickerView) self.dateIntervalPickerView.translatesAutoresizingMaskIntoConstraints = false self.dateIntervalPickerView.ib_addTopConstraintToSuperViewWithMargin(40.0) self.dateIntervalPickerView.ib_addLeadConstraintToSuperViewWithMargin(0.0) self.dateIntervalPickerView.ib_addTrailingConstraintToSuperViewWithMargin(0.0) self.dateIntervalPickerView.ib_addHeightConstraint(400.0) self.dateIntervalPickerView.layoutIfNeeded() self.dateIntervalPickerView.delegate = self self.dateIntervalPickerView.startDate = NSDate() self.dateIntervalPickerView.endDate = NSDate(timeInterval: -(60 * 60 * 24 * 2), sinceDate: NSDate()) self.dateIntervalPickerView.rangeBackgroundColor = UIColor.purpleColor() self.dateIntervalPickerView.reload() self.beginDateLabel.text = self.dateIntervalPickerView.startDate.description self.endDateLabel.text = self.dateIntervalPickerView.endDate.description } // MARK: DateIntervalPickerViewDelegate func dateIntervalPickerView(dateIntervalPickerView: DateIntervalPickerView, didUpdateStartDate startDate: NSDate) { self.beginDateLabel.text = startDate.description } func dateIntervalPickerView(dateIntervalPickerView: DateIntervalPickerView, didUpdateEndDate endDate: NSDate) { self.endDateLabel.text = endDate.description } }
eeaadd4898827fb562d5850d3763920e
44.735294
119
0.747588
false
false
false
false