repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
210 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
dasmer/EmojiKit
EmojiKit/EmojiFetcher.swift
1
4504
// // Fetcher.swift // EmojiKit // // Created by Dasmer Singh on 12/20/15. // Copyright © 2015 Dastronics Inc. All rights reserved. // import Foundation private let AllEmojiArray: [Emoji] = { guard let path = Bundle(for: EmojiFetchOperation.self).path(forResource: "AllEmoji", ofType: "json"), let data = try? Data(contentsOf: URL(fileURLWithPath: path)), let jsonObject = try? JSONSerialization.jsonObject(with: data, options: []), let jsonDictionaries = jsonObject as? [JSONDictionary] else { return [] } return jsonDictionaries.compactMap { Emoji(dictionary: $0) } }() private let AllEmojiDictionary: [String: Emoji] = { var dictionary = Dictionary<String, Emoji>(minimumCapacity:AllEmojiArray.count) AllEmojiArray.forEach { dictionary[$0.character] = $0 } return dictionary }() public struct EmojiFetcher { // MARK: - Properties private let backgroundQueue: OperationQueue = { let queue = OperationQueue() queue.qualityOfService = .userInitiated return queue }() // MARK: - Initializers public init() {} // MARK: - Functions public func query(_ searchString: String, completion: @escaping (([Emoji]) -> Void)) { cancelFetches() let operation = EmojiFetchOperation(searchString: searchString) operation.completionBlock = { if operation.isCancelled { return; } DispatchQueue.main.async { completion(operation.results) } } backgroundQueue.addOperation(operation) } public func cancelFetches() { backgroundQueue.cancelAllOperations() } public func isEmojiRepresentedByString(_ string: String) -> Bool { return AllEmojiDictionary[string] != nil } } private final class EmojiFetchOperation: Operation { // MARK: - Properties let searchString: String var results: [Emoji] = [] // MARK: - Initializers init(searchString: String) { self.searchString = searchString } // MARK: - NSOperation override func main() { if let emoji = AllEmojiDictionary[searchString] { // If searchString is an emoji, return emoji as the result results = [emoji] } else { // Otherwise, search emoji list for all emoji whose name, aliases or groups match searchString. results = resultsForSearchString(searchString) } } // MARK: - Functions private func resultsForSearchString(_ searchString: String) -> [Emoji] { let lowercaseSearchString = searchString.lowercased() guard !isCancelled else { return [] } var results = [Emoji]() // Matches of the full names of the emoji results += AllEmojiArray.filter { $0.name.hasPrefix(lowercaseSearchString) } guard !isCancelled else { return [] } // Matches of individual words in the name results += AllEmojiArray.filter { emoji in guard results.index(of: emoji) == nil else { return false } var validResult = false let emojiNameWords = emoji.name.split{$0 == " "}.map(String.init) for emojiNameWord in emojiNameWords { if emojiNameWord.hasPrefix(lowercaseSearchString) { validResult = true break } } return validResult } guard !isCancelled else { return [] } // Alias matches results += AllEmojiArray.filter { emoji in guard results.index(of: emoji) == nil else { return false } var validResult = false for alias in emoji.aliases { if alias.hasPrefix(lowercaseSearchString) { validResult = true break } } return validResult } guard !isCancelled else { return [] } // Group matches results += AllEmojiArray.filter { emoji in guard results.index(of: emoji) == nil else { return false } var validResult = false for group in emoji.groups { if lowercaseSearchString.hasPrefix(group) { validResult = true break } } return validResult } guard !isCancelled else { return [] } return results } }
mit
03ba6033ce7280437cd78fcf85fd1347
25.964072
107
0.585165
5.02567
false
false
false
false
thesecretlab/ultimate-swift-video
Layers-OSX/Layers-OSX/AppDelegate.swift
1
949
// // AppDelegate.swift // Layers-OSX // // Created by Jon Manning on 20/11/2014. // Copyright (c) 2014 Secret Lab. All rights reserved. // import Cocoa @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { @IBOutlet weak var window: NSWindow! @IBOutlet weak var animatableView: FancyMacView! func applicationDidFinishLaunching(aNotification: NSNotification) { // Insert code here to initialize your application let animation = CABasicAnimation(keyPath: "position") animation.byValue = NSValue(point: NSPoint(x: 0, y: -50)) animation.autoreverses = true animation.duration = 1.0 animation.repeatCount = HUGE self.animatableView.layer?.addAnimation(animation, forKey: "move") } func applicationWillTerminate(aNotification: NSNotification) { // Insert code here to tear down your application } }
mit
2f87e8ee0c90510a6d5eb38ada9e6770
23.973684
74
0.671233
4.792929
false
false
false
false
codefellows/sea-c19-ios
Code/F2Session1/F2Demo/ViewController.swift
1
1307
// // ViewController.swift // F2Demo // // Created by Bradley Johnson on 8/4/14. // Copyright (c) 2014 learnswift. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var myFirstSlider: UISlider! var name = "John" override func viewDidLoad() { super.viewDidLoad() var mySwitch = UISwitch(frame: CGRect(x: 20, y: 30, width: 120, height: 30)) self.view.addSubview(mySwitch) self.myFirstSlider.value = 0.0 } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) self.myFirstSlider.frame = CGRect(x: 0, y: 180, width: self.view.bounds.width, height: 33) // self.myFirstSlider.setValue(1.0, animated: true) } func setNewName(name: String) { self.name = name } @IBAction func sliderDidSlide(sender: UISlider) { if self.myFirstSlider.value > 0.5 { self.view.backgroundColor = UIColor.redColor() } else { self.view.backgroundColor = UIColor.blueColor() } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
9fcf0fc7baa124c76047a18b7ae0e8d3
24.134615
98
0.598317
4.271242
false
false
false
false
debugsquad/metalic
metalic/View/Main/VSpinner.swift
1
919
import UIKit class VSpinner:UIImageView { private let kAnimationDuration:TimeInterval = 0.7 init() { super.init(frame:CGRect.zero) let images:[UIImage] = [ #imageLiteral(resourceName: "assetLoader0"), #imageLiteral(resourceName: "assetLoader1"), #imageLiteral(resourceName: "assetLoader2"), #imageLiteral(resourceName: "assetLoader3"), #imageLiteral(resourceName: "assetLoader4"), #imageLiteral(resourceName: "assetLoader5") ] isUserInteractionEnabled = false translatesAutoresizingMaskIntoConstraints = false clipsToBounds = true animationDuration = kAnimationDuration animationImages = images contentMode = UIViewContentMode.center startAnimating() } required init?(coder:NSCoder) { fatalError() } }
mit
44e3ba6fc4c4161626037303ac9e2c12
26.848485
57
0.616975
5.67284
false
false
false
false
gautier-gdx/Hexacon
Example/ExaconExample/ViewController.swift
1
1753
// // ViewController.swift // ExaconExample // // Created by Gautier Gdx on 13/03/16. // Copyright © 2016 Gautier-gdx. All rights reserved. // import UIKit import Hexacon final class ViewController: UIViewController { // MARK: - data let iconArray: [UIImage] = ["Burglar","Businesswoman-1","Hacker","Ninja","Rapper-2","Rasta","Rocker","Surfer","Telemarketer-Woman-2"].map { UIImage(named: $0)! } var dataArray = [UIImage]() // MARK: - subviews private lazy var hexagonalView: HexagonalView = { [unowned self] in let view = HexagonalView(frame: self.view.bounds) view.hexagonalDataSource = self view.hexagonalDelegate = self return view }() //MARK: UIViewController lifecycle override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor(red: 18/255, green: 52/255, blue: 86/255, alpha: 1) for _ in 0...10 { dataArray += iconArray } view.addSubview(hexagonalView) } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) hexagonalView.reloadData() } } extension ViewController: HexagonalViewDataSource { func hexagonalView(hexagonalView: HexagonalView, imageForIndex index: Int) -> UIImage? { return dataArray[index] } func numberOfItemInHexagonalView(hexagonalView: HexagonalView) -> Int { print(dataArray.count) return dataArray.count - 1 } } extension ViewController: HexagonalViewDelegate { func hexagonalView(hexagonalView: HexagonalView, didSelectItemAtIndex index: Int) { print("didSelectItemAtIndex: \(index)") } }
mit
ea76efab8bbbbb38b965de2a77b94518
25.545455
165
0.635274
4.231884
false
false
false
false
RocketChat/Rocket.Chat.iOS
Rocket.Chat/Views/Cells/Chat/ChatMessageImageView.swift
1
3875
// // ChatMessageImageView.swift // Rocket.Chat // // Created by Rafael K. Streit on 03/10/16. // Copyright © 2016 Rocket.Chat. All rights reserved. // import UIKit import FLAnimatedImage protocol ChatMessageImageViewProtocol: class { func openImageFromCell(attachment: UnmanagedAttachment, thumbnail: FLAnimatedImageView) func openImageFromCell(url: URL, thumbnail: FLAnimatedImageView) } final class ChatMessageImageView: ChatMessageAttachmentView { override static var defaultHeight: CGFloat { return 250 } var isLoadable = true weak var delegate: ChatMessageImageViewProtocol? var attachment: Attachment! { didSet { if oldValue != nil && oldValue.identifier == attachment.identifier { Log.debug("attachment is cached") return } updateMessageInformation() } } @IBOutlet weak var labelTitle: UILabel! @IBOutlet weak var detailText: UILabel! @IBOutlet weak var detailTextIndicator: UILabel! @IBOutlet weak var detailTextHeightConstraint: NSLayoutConstraint! @IBOutlet weak var fullHeightConstraint: NSLayoutConstraint! @IBOutlet weak var activityIndicatorImageView: UIActivityIndicatorView! @IBOutlet weak var imageView: FLAnimatedImageView! { didSet { imageView.layer.cornerRadius = 3 imageView.layer.borderColor = UIColor.lightGray.withAlphaComponent(0.1).cgColor imageView.layer.borderWidth = 1 } } private lazy var tapGesture: UITapGestureRecognizer = { return UITapGestureRecognizer(target: self, action: #selector(didTapView)) }() private func getImage() -> URL? { guard let imageURL = attachment.fullImageURL() else { return nil } if imageURL.absoluteString.starts(with: "http://") { isLoadable = false detailText.text = "" labelTitle.text = attachment.title + " (" + localized("alert.insecure_image.title") + ")" imageView.contentMode = UIView.ContentMode.center imageView.image = UIImage(named: "Resource Unavailable") return nil } labelTitle.text = attachment.title detailText.text = attachment.descriptionText detailTextIndicator.isHidden = attachment.descriptionText?.isEmpty ?? true let availableWidth = frame.size.width let fullHeight = ChatMessageImageView.heightFor(with: availableWidth, description: attachment.descriptionText) fullHeightConstraint.constant = fullHeight detailTextHeightConstraint.constant = fullHeight - ChatMessageImageView.defaultHeight return imageURL } fileprivate func updateMessageInformation() { let containsGesture = gestureRecognizers?.contains(tapGesture) ?? false if !containsGesture { addGestureRecognizer(tapGesture) } guard let imageURL = getImage() else { return } activityIndicatorImageView.startAnimating() ImageManager.loadImage(with: imageURL, into: imageView) { [weak self] _, _ in self?.activityIndicatorImageView.stopAnimating() } } @objc func didTapView() { if isLoadable { if let unmanaged = UnmanagedAttachment(attachment) { delegate?.openImageFromCell(attachment: unmanaged, thumbnail: imageView) } } else { guard let imageURL = attachment.fullImageURL() else { return } if imageURL.absoluteString.contains("http://") { Ask(key: "alert.insecure_image", buttonB: localized("chat.message.open_browser"), handlerB: { _ in MainSplitViewController.chatViewController?.openURL(url: imageURL) }).present() } } } }
mit
5444b9f05aa03ff91e395dfdb823f245
33.900901
118
0.65333
5.403068
false
false
false
false
creatubbles/ctb-api-swift
CreatubblesAPIClient/Sources/Database/DatabaseService.swift
1
15163
// // DatabaseService.swift // CreatubblesAPIClient // // Copyright (c) 2017 Creatubbles Pte. 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 UIKit import RealmSwift import Realm class DatabaseService: NSObject { let realm = DatabaseService.prepareRealm() fileprivate class func prepareRealmConfig() -> Realm.Configuration { // The app group may be not accessible for testing purposes. That's why we added a failover below. guard let appGroupIdentifier = AppGroupConfigurator.identifier, let appGroupURL: URL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: appGroupIdentifier) else { return Realm.Configuration.defaultConfiguration } let realmURL = appGroupURL.appendingPathComponent("db.realm") var configuration = Realm.Configuration.defaultConfiguration let originalDefaultRealmURL = configuration.fileURL configuration.fileURL = realmURL if let defaultURL = originalDefaultRealmURL, FileManager.default.fileExists(atPath: defaultURL.path) && !FileManager.default.fileExists(atPath: realmURL.path) { do { try FileManager.default.moveItem(atPath: defaultURL.path, toPath: realmURL.path) } catch let error as NSError { Logger.log(.error, "Realm migration error: \(error)") } } return configuration } fileprivate class func prepareRealm() -> Realm { let realmConfiguration = prepareRealmConfig() do { return try Realm(configuration: realmConfiguration) } catch let realmError { Logger.log(.error, "Realm error error: \(realmError)") do { let url = realmConfiguration.fileURL try FileManager.default.removeItem(at: url!) } catch let fileManagerError { Logger.log(.error, "File manager error: \(fileManagerError)") } } return try! Realm(configuration: realmConfiguration) } func saveCreationUploadSessionToDatabase(_ creationUploadSession: CreationUploadSession) { let creationUploadSessionEntity = getUploadSessionEntityFromCreationUploadSession(creationUploadSession) if let creationUploadSessionEntityFromDatabase = fetchASingleCreationUploadSessionWithLocalIdentifier(creationUploadSession.localIdentifier) { do { try realm.write({ () -> Void in deleteOldDatabaseObjects(creationUploadSessionEntityFromDatabase) }) } catch let error { print(error) } } do { try realm.write({ () -> Void in realm.add(creationUploadSessionEntity, update: true) }) } catch let error { print(error) } } func deleteOldDatabaseObjects(_ creationUploadSessionEntity: CreationUploadSessionEntity) { if let creationEntity = creationUploadSessionEntity.creationEntity { realm.delete(creationEntity) } if let creationUploadEntity = creationUploadSessionEntity.creationUploadEntity { realm.delete(creationUploadEntity) } if let creationDataEntity = creationUploadSessionEntity.creationDataEntity { realm.delete(creationDataEntity) } } func fetchAllCreationUploadSessionEntities() -> Array<CreationUploadSessionEntity> { let realmObjects = realm.objects(CreationUploadSessionEntity.self) var creationUploadSessionEntitiesArray = [CreationUploadSessionEntity]() for entity in realmObjects { creationUploadSessionEntitiesArray.append(entity) } return creationUploadSessionEntitiesArray } func fetchAllCreationUploadSessions(_ requestSender: RequestSender) -> Array<CreationUploadSession> { let sessionEntities = fetchAllCreationUploadSessionEntities() var sessions = [CreationUploadSession]() for entity in sessionEntities { let session = CreationUploadSession(creationUploadSessionEntity: entity, requestSender: requestSender) sessions.append(session) } return sessions } func fetchASingleCreationUploadSessionWithLocalIdentifier(_ localIdentifier: String) -> CreationUploadSessionEntity? { let creationUploadSessionEntities = realm.objects(CreationUploadSessionEntity.self).filter("localIdentifier = %@", localIdentifier) return creationUploadSessionEntities.first } func getAllActiveUploadSessions(_ requestSender: RequestSender) -> Array<CreationUploadSession> { var activeUploadSessions = [CreationUploadSession]() let predicate = NSPredicate(format: "stateRaw < \(CreationUploadSessionState.serverNotified.rawValue)") let uploadSessionEntities = realm.objects(CreationUploadSessionEntity.self).filter(predicate) for uploadSessionEntity in uploadSessionEntities { activeUploadSessions.append(CreationUploadSession(creationUploadSessionEntity: uploadSessionEntity, requestSender: requestSender)) } return activeUploadSessions } func getAllFinishedUploadSessions(_ requestSender: RequestSender) -> Array<CreationUploadSession> { var finishedUploadSessions = [CreationUploadSession]() let predicate = NSPredicate(format: "stateRaw >= \(CreationUploadSessionState.serverNotified.rawValue)") let uploadSessionEntities = realm.objects(CreationUploadSessionEntity.self).filter(predicate) for uploadSessionEntity in uploadSessionEntities { finishedUploadSessions.append(CreationUploadSession(creationUploadSessionEntity: uploadSessionEntity, requestSender: requestSender)) } return finishedUploadSessions } func getAllActiveUploadSessionsPublicData(_ requestSender: RequestSender) -> Array<CreationUploadSessionPublicData> { let activeUploads = getAllActiveUploadSessions(requestSender) var activeUploadsPublicData = [CreationUploadSessionPublicData]() for activeUpload in activeUploads { activeUploadsPublicData.append(CreationUploadSessionPublicData(creationUploadSession: activeUpload)) } return activeUploadsPublicData } func getAllFinishedUploadSessionPublicData(_ requestSender: RequestSender) -> Array<CreationUploadSessionPublicData> { let finishedUploads = getAllFinishedUploadSessions(requestSender) var finishedUploadsPublicData = [CreationUploadSessionPublicData]() for finishedUpload in finishedUploads { finishedUploadsPublicData.append(CreationUploadSessionPublicData(creationUploadSession: finishedUpload)) } return finishedUploadsPublicData } func removeUploadSession(withIdentifier identifier: String) { if let entity = realm.object(ofType: CreationUploadSessionEntity.self, forPrimaryKey: identifier) { do { try realm.write { realm.delete(entity) } } catch let error { Logger.log(.error, "Error during removing upload session: \(error)") } } } func removeAllUploadSessions() { do { try realm.write { realm.deleteAll() } } catch let error { Logger.log(.error, "Error duting database clear: \(error)") } } // MARK: - Transforms fileprivate func getUploadSessionEntityFromCreationUploadSession(_ creationUploadSession: CreationUploadSession) -> CreationUploadSessionEntity { let creationUploadSessionEntity = CreationUploadSessionEntity() creationUploadSessionEntity.stateRaw.value = creationUploadSession.state.rawValue creationUploadSessionEntity.imageFileName = creationUploadSession.imageFileName creationUploadSessionEntity.relativeImageFilePath = creationUploadSession.relativeFilePath creationUploadSessionEntity.creationDataEntity = getNewCreationDataEntityFromCreationData(creationUploadSession.creationData) creationUploadSessionEntity.localIdentifier = creationUploadSession.localIdentifier if let creation = creationUploadSession.creation { creationUploadSessionEntity.creationEntity = getCreationEntityFromCreation(creation) } if let creationUpload = creationUploadSession.creationUpload { creationUploadSessionEntity.creationUploadEntity = getCreationUploadEntityFromCreationUpload(creationUpload) } return creationUploadSessionEntity } fileprivate func getNewCreationDataEntityFromCreationData(_ newCreationData: NewCreationData) -> NewCreationDataEntity { let newCreationDataEntity = NewCreationDataEntity() newCreationDataEntity.localIdentifier = newCreationData.localIdentifier newCreationDataEntity.reflectionText = newCreationData.reflectionText newCreationDataEntity.reflectionVideoUrl = newCreationData.reflectionVideoUrl newCreationDataEntity.dataTypeRaw.value = newCreationData.dataType.rawValue newCreationDataEntity.storageTypeRaw.value = newCreationData.storageType.rawValue newCreationDataEntity.uploadExtensionRaw = newCreationData.uploadExtension.stringValue newCreationData.creatorIds?.forEach { creatorIdentifier in let idEntity = CreatorIdString() idEntity.creatorIdString = creatorIdentifier newCreationDataEntity.creatorIds.append(idEntity) } newCreationData.galleryIds?.forEach { galleryIdentifier in let idEntity = GalleryIdString() idEntity.galleryIdString = galleryIdentifier newCreationDataEntity.galleryIds.append(idEntity) } newCreationDataEntity.creationYear.value = newCreationData.creationYear newCreationDataEntity.creationMonth.value = newCreationData.creationMonth return newCreationDataEntity } fileprivate func getCreationEntityFromCreation(_ creation: Creation) -> CreationEntity { let creationEntity = CreationEntity() creationEntity.identifier = creation.identifier creationEntity.name = creation.name for name in creation.translatedNames { creationEntity.translatedNameEntities.append(getNameTranslationObjectEntityFromNameTranslationObject(name)) } creationEntity.createdAt = creation.createdAt creationEntity.updatedAt = creation.updatedAt creationEntity.imageStatus.value = creation.imageStatus creationEntity.bubblesCount.value = creation.bubblesCount creationEntity.commentsCount.value = creation.commentsCount creationEntity.viewsCount.value = creation.viewsCount creationEntity.lastBubbledAt = creation.lastBubbledAt creationEntity.lastCommentedAt = creation.lastCommentedAt creationEntity.lastSubmittedAt = creation.lastSubmittedAt creationEntity.approved.value = creation.approved creationEntity.shortUrl = creation.shortUrl creationEntity.createdAtAge = creation.createdAtAge for (key, value) in creation.createdAtAgePerCreator { let createdAtAgePerCreatorDict = CreatedAtAgePerCreatorDict() createdAtAgePerCreatorDict.key = key createdAtAgePerCreatorDict.value = value creationEntity.createdAtAgePerCreatorDict?.append(createdAtAgePerCreatorDict) } creationEntity.reflectionText = creation.reflectionText creationEntity.reflectionVideoUrl = creation.reflectionVideoUrl creationEntity.imageOriginalUrl = creation.imageOriginalUrl creationEntity.imageFullViewUrl = creation.imageFullViewUrl creationEntity.imageListViewUrl = creation.imageListViewUrl creationEntity.imageListViewRetinaUrl = creation.imageListViewRetinaUrl creationEntity.imageMatrixViewUrl = creation.imageMatrixViewUrl creationEntity.imageMatrixViewRetinaUrl = creation.imageMatrixViewRetinaUrl creationEntity.imageGalleryMobileUrl = creation.imageGalleryMobileUrl creationEntity.imageExploreMobileUrl = creation.imageExploreMobileUrl creationEntity.imageShareUrl = creation.imageShareUrl creationEntity.video480Url = creation.video480Url creationEntity.video720Url = creation.video720Url creationEntity.objFileUrl = creation.objFileUrl creationEntity.playIFrameUrl = creation.playIFrameUrl creationEntity.playIFrameUrlIsMobileReady.value = creation.playIFrameUrlIsMobileReady creationEntity.contentType = creation.contentType creation.tags?.forEach { creationTag in let tagString = CreationTagString() tagString.tag = creationTag creationEntity.tags.append(tagString) } return creationEntity } fileprivate func getNameTranslationObjectEntityFromNameTranslationObject(_ nameTranslationObject: NameTranslationObject) -> NameTranslationObjectEntity { let nameTranslationObjectEntity = NameTranslationObjectEntity() nameTranslationObjectEntity.code = nameTranslationObject.code nameTranslationObjectEntity.name = nameTranslationObject.name nameTranslationObjectEntity.original.value = nameTranslationObject.original return nameTranslationObjectEntity } fileprivate func getCreationUploadEntityFromCreationUpload(_ creationUpload: CreationUpload) -> CreationUploadEntity { let creationUploadEntity = CreationUploadEntity() creationUploadEntity.identifier = creationUpload.identifier creationUploadEntity.uploadUrl = creationUpload.uploadUrl creationUploadEntity.contentType = creationUpload.contentType creationUploadEntity.pingUrl = creationUpload.pingUrl creationUploadEntity.completedAt = creationUpload.completedAt return creationUploadEntity } }
mit
1eb7ae856492e7304aef6ab56dec712a
43.994065
168
0.726373
5.448437
false
true
false
false
material-components/material-components-ios
components/Buttons/examples/ButtonsTypicalUseSwiftExample.swift
2
4679
// Copyright 2016-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 Foundation import UIKit import MaterialComponents.MaterialButtons import MaterialComponents.MaterialButtons_Theming import MaterialComponents.MaterialContainerScheme class ButtonsTypicalUseSwiftExample: UIViewController { let floatingButtonPlusDimension = CGFloat(24) let kMinimumAccessibleButtonSize = CGSize(width: 64, height: 48) var containerScheme = MDCContainerScheme() override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor(white: 0.9, alpha: 1.0) //let titleColor = UIColor.white let backgroundColor = UIColor(white: 0.1, alpha: 1.0) let containedButton = MDCButton() containedButton.applyContainedTheme(withScheme: containerScheme) containedButton.setTitle("Tap Me Too", for: UIControl.State()) containedButton.sizeToFit() let containedButtonVerticalInset = min(0, -(kMinimumAccessibleButtonSize.height - containedButton.bounds.height) / 2) let containedButtonHorizontalInset = min(0, -(kMinimumAccessibleButtonSize.width - containedButton.bounds.width) / 2) containedButton.hitAreaInsets = UIEdgeInsets( top: containedButtonVerticalInset, left: containedButtonHorizontalInset, bottom: containedButtonVerticalInset, right: containedButtonHorizontalInset) containedButton.translatesAutoresizingMaskIntoConstraints = false containedButton.addTarget(self, action: #selector(tap), for: .touchUpInside) view.addSubview(containedButton) let textButton = MDCButton() textButton.applyTextTheme(withScheme: MDCContainerScheme()) textButton.setTitle("Touch me", for: UIControl.State()) textButton.sizeToFit() let textButtonVerticalInset = min(0, -(kMinimumAccessibleButtonSize.height - textButton.bounds.height) / 2) let textButtonHorizontalInset = min(0, -(kMinimumAccessibleButtonSize.width - textButton.bounds.width) / 2) textButton.hitAreaInsets = UIEdgeInsets( top: textButtonVerticalInset, left: textButtonHorizontalInset, bottom: textButtonVerticalInset, right: textButtonHorizontalInset) textButton.translatesAutoresizingMaskIntoConstraints = false textButton.addTarget(self, action: #selector(tap), for: .touchUpInside) view.addSubview(textButton) let floatingButton = MDCFloatingButton() floatingButton.backgroundColor = backgroundColor floatingButton.sizeToFit() floatingButton.translatesAutoresizingMaskIntoConstraints = false floatingButton.addTarget(self, action: #selector(tap), for: .touchUpInside) let plusShapeLayer = ButtonsTypicalUseSupplemental.createPlusShapeLayer(floatingButton) floatingButton.layer.addSublayer(plusShapeLayer) floatingButton.accessibilityLabel = "Create" view.addSubview(floatingButton) let views = [ "contained": containedButton, "text": textButton, "floating": floatingButton, ] centerView(view: textButton, onView: self.view) view.addConstraints( NSLayoutConstraint.constraints( withVisualFormat: "V:[contained]-40-[text]-40-[floating]", options: .alignAllCenterX, metrics: nil, views: views)) } // MARK: Private private func centerView(view: UIView, onView: UIView) { onView.addConstraint( NSLayoutConstraint( item: view, attribute: .centerX, relatedBy: .equal, toItem: onView, attribute: .centerX, multiplier: 1.0, constant: 0.0)) onView.addConstraint( NSLayoutConstraint( item: view, attribute: .centerY, relatedBy: .equal, toItem: onView, attribute: .centerY, multiplier: 1.0, constant: -20.0)) } @objc func tap(_ sender: Any) { print("\(type(of: sender)) was tapped.") } } extension ButtonsTypicalUseSwiftExample { @objc class func catalogMetadata() -> [String: Any] { return [ "breadcrumbs": ["Buttons", "Buttons (Swift)"], "primaryDemo": false, "presentable": false, ] } }
apache-2.0
cf653434bd1147957d911d88ab048e5b
33.91791
91
0.722163
4.688377
false
false
false
false
CD1212/Doughnut
Pods/GRDB.swift/GRDB/Core/Cursor.swift
1
12158
extension Array { /// Creates an array containing the elements of a cursor. /// /// let cursor = try String.fetchCursor(db, "SELECT 'foo' UNION ALL SELECT 'bar'") /// let strings = try Array(cursor) // ["foo", "bar"] public init<C: Cursor>(_ cursor: C) throws where C.Element == Element { self.init() while let element = try cursor.next() { append(element) } } } extension Set { /// Creates a set containing the elements of a cursor. /// /// let cursor = try String.fetchCursor(db, "SELECT 'foo' UNION ALL SELECT 'foo'") /// let strings = try Set(cursor) // ["foo"] public init<C: Cursor>(_ cursor: C) throws where C.Element == Element { self.init() while let element = try cursor.next() { insert(element) } } } /// A type that supplies the values of some external resource, one at a time. /// /// ## Overview /// /// The most common way to iterate over the elements of a cursor is to use a /// `while` loop: /// /// let cursor = ... /// while let element = try cursor.next() { /// ... /// } /// /// ## Relationship with standard Sequence and IteratorProtocol /// /// Cursors share traits with lazy sequences and iterators from the Swift /// standard library. Differences are: /// /// - Cursor types are classes, and have a lifetime. /// - Cursor iteration may throw errors. /// - A cursor can not be repeated. /// /// The protocol comes with default implementations for many operations similar /// to those defined by Swift's LazySequenceProtocol: /// /// - `func contains(Self.Element)` /// - `func contains(where: (Self.Element) throws -> Bool)` /// - `func enumerated()` /// - `func filter((Self.Element) throws -> Bool)` /// - `func first(where: (Self.Element) throws -> Bool)` /// - `func flatMap<ElementOfResult>((Self.Element) throws -> ElementOfResult?)` /// - `func flatMap<SegmentOfResult>((Self.Element) throws -> SegmentOfResult)` /// - `func forEach((Self.Element) throws -> Void)` /// - `func joined()` /// - `func map<T>((Self.Element) throws -> T)` /// - `func reduce<Result>(Result, (Result, Self.Element) throws -> Result)` public protocol Cursor : class { /// The type of element traversed by the cursor. associatedtype Element /// Advances to the next element and returns it, or nil if no next element /// exists. Once nil has been returned, all subsequent calls return nil. func next() throws -> Element? } /// A type-erased cursor of Element. /// /// This cursor forwards its next() method to an arbitrary underlying cursor /// having the same Element type, hiding the specifics of the underlying /// cursor. public class AnyCursor<Element> : Cursor { /// Creates a cursor that wraps a base cursor but whose type depends only on /// the base cursor’s element type public init<C: Cursor>(_ base: C) where C.Element == Element { element = base.next } /// Creates a cursor that wraps the given closure in its next() method public init(_ body: @escaping () throws -> Element?) { element = body } /// Advances to the next element and returns it, or nil if no next /// element exists. public func next() throws -> Element? { return try element() } private let element: () throws -> Element? } extension Cursor { /// Returns a Boolean value indicating whether the cursor contains an /// element that satisfies the given predicate. /// /// - parameter predicate: A closure that takes an element of the cursor as /// its argument and returns a Boolean value that indicates whether the /// passed element represents a match. /// - returns: true if the cursor contains an element that satisfies /// predicate; otherwise, false. public func contains(where predicate: (Element) throws -> Bool) throws -> Bool { while let element = try next() { if try predicate(element) { return true } } return false } /// Returns a cursor of pairs (n, x), where n represents a consecutive /// integer starting at zero, and x represents an element of the cursor. /// /// let cursor = try String.fetchCursor(db, "SELECT 'foo' UNION ALL SELECT 'bar'") /// let c = cursor.enumerated() /// while let (n, x) = c.next() { /// print("\(n): \(x)") /// } /// // Prints: "0: foo" /// // Prints: "1: bar" public func enumerated() -> EnumeratedCursor<Self> { return EnumeratedCursor(self) } /// Returns the elements of the cursor that satisfy the given predicate. public func filter(_ isIncluded: @escaping (Element) throws -> Bool) -> FilterCursor<Self> { return FilterCursor(self, isIncluded) } /// Returns the first element of the cursor that satisfies the given /// predicate or nil if no such element is found. public func first(where predicate: (Element) throws -> Bool) throws -> Element? { while let element = try next() { if try predicate(element) { return element } } return nil } /// Returns a cursor over the concatenated non-nil results of mapping /// transform over this cursor. public func flatMap<ElementOfResult>(_ transform: @escaping (Element) throws -> ElementOfResult?) -> MapCursor<FilterCursor<MapCursor<Self, ElementOfResult?>>, ElementOfResult> { return map(transform).filter { $0 != nil }.map { $0! } } /// Returns a cursor over the concatenated results of mapping transform /// over self. public func flatMap<SegmentOfResult: Sequence>(_ transform: @escaping (Element) throws -> SegmentOfResult) -> FlattenCursor<MapCursor<Self, IteratorCursor<SegmentOfResult.Iterator>>> { return flatMap { try IteratorCursor(transform($0)) } } /// Returns a cursor over the concatenated results of mapping transform /// over self. public func flatMap<SegmentOfResult: Cursor>(_ transform: @escaping (Element) throws -> SegmentOfResult) -> FlattenCursor<MapCursor<Self, SegmentOfResult>> { return map(transform).joined() } /// Calls the given closure on each element in the cursor. public func forEach(_ body: (Element) throws -> Void) throws { while let element = try next() { try body(element) } } /// Returns a cursor over the results of the transform function applied to /// this cursor's elements. public func map<T>(_ transform: @escaping (Element) throws -> T) -> MapCursor<Self, T> { return MapCursor(self, transform) } /// Returns the result of calling the given combining closure with each /// element of this sequence and an accumulating value. public func reduce<Result>(_ initialResult: Result, _ nextPartialResult: (Result, Element) throws -> Result) throws -> Result { var result = initialResult while let element = try next() { result = try nextPartialResult(result, element) } return result } } extension Cursor where Element: Equatable { /// Returns a Boolean value indicating whether the cursor contains the /// given element. public func contains(_ element: Element) throws -> Bool { while let e = try next() { if e == element { return true } } return false } } extension Cursor where Element: Cursor { /// Returns the elements of this cursor of cursors, concatenated. public func joined() -> FlattenCursor<Self> { return FlattenCursor(self) } } extension Cursor where Element: Sequence { /// Returns the elements of this cursor of sequences, concatenated. public func joined() -> FlattenCursor<MapCursor<Self, IteratorCursor<Self.Element.Iterator>>> { return flatMap { $0 } } } /// An enumeration of the elements of a cursor. /// /// To create an instance of `EnumeratedCursor`, call the `enumerated()` method /// on a cursor: /// /// let cursor = try String.fetchCursor(db, "SELECT 'foo' UNION ALL SELECT 'bar'") /// let c = cursor.enumerated() /// while let (n, x) = c.next() { /// print("\(n): \(x)") /// } /// // Prints: "0: foo" /// // Prints: "1: bar" public final class EnumeratedCursor<Base: Cursor> : Cursor { init(_ base: Base) { self.index = 0 self.base = base } /// Advances to the next element and returns it, or nil if no next /// element exists. public func next() throws -> (Int, Base.Element)? { guard let element = try base.next() else { return nil } defer { index += 1 } return (index, element) } private var index: Int private var base: Base } /// A cursor whose elements consist of the elements of some base cursor that /// also satisfy a given predicate. public final class FilterCursor<Base: Cursor> : Cursor { init(_ base: Base, _ isIncluded: @escaping (Base.Element) throws -> Bool) { self.base = base self.isIncluded = isIncluded } /// Advances to the next element and returns it, or nil if no next /// element exists. public func next() throws -> Base.Element? { while let element = try base.next() { if try isIncluded(element) { return element } } return nil } private let base: Base private let isIncluded: (Base.Element) throws -> Bool } /// A cursor consisting of all the elements contained in each segment contained /// in some Base cursor. /// /// See Cursor.joined(), Cursor.flatMap(_:), Sequence.flatMap(_:) public final class FlattenCursor<Base: Cursor> : Cursor where Base.Element: Cursor { init(_ base: Base) { self.base = base } /// Advances to the next element and returns it, or nil if no next /// element exists. public func next() throws -> Base.Element.Element? { while true { if let element = try inner?.next() { return element } guard let inner = try base.next() else { return nil } self.inner = inner } } private var inner: Base.Element? private let base: Base } /// A Cursor whose elements consist of those in a Base Cursor passed through a /// transform function returning Element. /// /// See Cursor.map(_:) public final class MapCursor<Base: Cursor, Element> : Cursor { init(_ base: Base, _ transform: @escaping (Base.Element) throws -> Element) { self.base = base self.transform = transform } /// Advances to the next element and returns it, or nil if no next /// element exists. public func next() throws -> Element? { guard let element = try base.next() else { return nil } return try transform(element) } private let base: Base private let transform: (Base.Element) throws -> Element } /// A Cursor whose elements are those of a sequence iterator. public final class IteratorCursor<Base: IteratorProtocol> : Cursor { /// Creates a cursor from a sequence iterator. public init(_ base: Base) { self.base = base } /// Creates a cursor from a sequence. public init<S: Sequence>(_ s: S) where S.Iterator == Base { self.base = s.makeIterator() } /// Advances to the next element and returns it, or nil if no next /// element exists. public func next() -> Base.Element? { return base.next() } private var base: Base } extension Sequence { /// Returns a cursor over the concatenated results of mapping transform /// over self. public func flatMap<SegmentOfResult: Cursor>(_ transform: @escaping (Iterator.Element) throws -> SegmentOfResult) -> FlattenCursor<MapCursor<IteratorCursor<Self.Iterator>, SegmentOfResult>> { return IteratorCursor(self).flatMap(transform) } }
gpl-3.0
007f13d023cda5017347a1cf26cd27be
34.337209
195
0.621339
4.442982
false
false
false
false
LuisMarinheiro/FastlaneExample
FastlaneExample/ViewControllers/RepositoriesViewController.swift
4
2393
// // ViewController.swift // FastlaneExample // // Created by Ivan Bruel on 30/05/2017. // Copyright © 2017 Swift Aveiro. All rights reserved. // import UIKit import SnapKit import RxSwift import RxCocoa final class RepositoriesViewController: UIViewController { // MARK: - Views fileprivate lazy var tableView: UITableView = { let tableView = UITableView() tableView.register(DetailTableViewCell.self, forCellReuseIdentifier: DetailTableViewCell.reuseIdentifier) return tableView }() fileprivate let disposeBag = DisposeBag() // MARK: - ViewModel fileprivate let viewModel: RepositoriesViewModel // MARK: - Initializers init(viewModel: RepositoriesViewModel) { self.viewModel = viewModel super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("RepositoriesViewController should never be initialized by Storyboard") } } // MARK: - Lifecycle extension RepositoriesViewController { override func loadView() { super.loadView() view.addSubview(tableView) tableView.snp.makeConstraints { make in make.edges.equalTo(view) } } override func viewDidLoad() { super.viewDidLoad() setup() loadRepositories(username: "ivanbruel") } } // MARK: - Setup extension RepositoriesViewController { fileprivate func setup() { viewModel.items .bind(to: tableView.rx.items(cellIdentifier: DetailTableViewCell.reuseIdentifier, cellType: DetailTableViewCell.self)) { _, viewModel, cell in cell.textLabel?.text = viewModel.name cell.detailTextLabel?.text = viewModel.stars }.disposed(by: disposeBag) } fileprivate func loadRepositories(username: String) { title = username viewModel .getRepositories(username: "ivanbruel") .subscribeResult(onSuccess: nil) { [weak self] error in self?.showAlert(error: error) }.disposed(by: disposeBag) } } // MARK: - Alert extension RepositoriesViewController { fileprivate func showAlert(error: RepositoriesError) { let controller = UIAlertController(title: error.message, message: nil, preferredStyle: .alert) controller.addAction(UIAlertAction(title: "Dismiss", style: .default, handler: nil)) present(controller, animated: true, completion: nil) } }
mit
29f72f5840b5c3e61d115cb4aa5c5d4e
25.577778
109
0.691472
4.755467
false
false
false
false
liuchuo/LeetCode-practice
Swift/617. Merge Two Binary Trees.swift
1
556
// 617. Merge Two Binary Trees // 100 ms func mergeTrees(_ t1: TreeNode?, _ t2: TreeNode?) -> TreeNode? { let root = mergeNote(t1, t2) root?.left = mergeTrees(t1?.left, t2?.left) root?.right = mergeTrees(t1?.right, t2?.right) return root } func mergeNote(_ t1: TreeNode?, _ t2: TreeNode?) -> TreeNode? { if let c1 = t1, let c2 = t2 { return TreeNode(c1.val + c2.val) } else if let c1 = t1 { return TreeNode(c1.val) } else if let c2 = t2 { return TreeNode(c2.val) } else { return nil } }
gpl-3.0
7a36bb0ba18d39a6513f096576bcdc24
25.52381
64
0.57554
2.957447
false
false
false
false
Abedalkareem/AMChoice
AMChoice/AMChoice/Classes/AMChoiceView.swift
1
7312
// // AMRadioButton.swift // SDQ // // Created by abedalkareem omreyh on 2/11/17. // Copyright © 2017 abedalkareem omreyh. All rights reserved. // GitHub: https://github.com/Abedalkareem/AMChoice // import UIKit @IBDesignable public class AMChoiceView: UIView { // MARK: - Properties /// The object that acts as the delegate of the AMChoice. /// The delegate must implement the AMChoiceDelegate protocol. public weak var delegate: AMChoiceDelegate? /// TableViewCell separator style. public var separatorStyle: UITableViewCell.SeparatorStyle = .singleLine /// TableViewCell text font. public var font: UIFont? /// The type of selection in the choices. `.single` is the default. public var selectionType: SelectionType = .single /// The choices that will be shown in the view, all items should implement the Selectable protocol. public var data: [Selectable] = [] { didSet { // set selected item index if there is defult selected item if let index = data.firstIndex(where: { $0.isSelected }) { lastIndexPath = IndexPath(item: index, section: 0) } tableView.reloadData() // when data set, reload tableview } } /// The height of the cell, the default is `50`. @IBInspectable public var cellHeight: CGFloat = 50 /// Selected status image. @IBInspectable public var selectedImage: UIImage? /// Unselected status image. @IBInspectable public var unselectedImage: UIImage? /// The arrow image, by default there is no arrow image. @IBInspectable public var arrowImage: UIImage? /// If your app language right to left you need to set it to true, the default is false which means `LTR`. @IBInspectable public var isRightToLeft: Bool = false // MARK: - Private Properties private var tableView: UITableView! private var lastIndexPath: IndexPath? private var cellReuseIdentifier = "RadioTableViewCell" // MARK: - init override init(frame: CGRect) { super.init(frame: frame) setup() } required init?(coder: NSCoder) { super.init(coder: coder) setup() } private func setup() { tableView = UITableView() tableView.delegate = self tableView.dataSource = self tableView.register(RadioTableViewCell.self, forCellReuseIdentifier: cellReuseIdentifier) #if TARGET_INTERFACE_BUILDER self.data = [DummyInterfaceBuilderItem(title: "Item 1", isSelected: false, isUserSelectEnable: true), DummyInterfaceBuilderItem(title: "Item 2", isSelected: true, isUserSelectEnable: true), DummyInterfaceBuilderItem(title: "Item 3", isSelected: false, isUserSelectEnable: true)] #endif addSubview(tableView) makeConstraints() } private func makeConstraints() { tableView.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ tableView.topAnchor.constraint(equalTo: topAnchor), tableView.bottomAnchor.constraint(equalTo: bottomAnchor), tableView.leadingAnchor.constraint(equalTo: leadingAnchor), tableView.trailingAnchor.constraint(equalTo: trailingAnchor) ]) } override public func layoutSubviews() { super.layoutSubviews() tableView.separatorStyle = .none } // MARK: - Public methods /// Get all selected items. /// /// - returns: An array of selectable items that selected. public func getSelectedItems() -> [Selectable] { let selectedItem = data.filter { (item) -> Bool in return item.isSelected == true } return selectedItem } /// Get all selected items as string. /// /// - parameter separator: A string to insert between /// each of the elements in this sequence. The default separator is the comma. /// /// - returns: A string with selected items. public func getSelectedItemsJoined(separator: String = ",") -> String { return data.filter { $0.isSelected } .map { String($0.title) } .joined(separator: separator) } } // MARK: - UITableViewDelegate, UITableViewDataSource extension AMChoiceView: UITableViewDelegate, UITableViewDataSource { public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return data.count } public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let cell = tableView .dequeueReusableCell(withIdentifier: cellReuseIdentifier, for: indexPath) as? RadioTableViewCell else { assertionFailure("Failed to get the tableview cell") return UITableViewCell() } let item = data[indexPath.row] cell.setupWith(item, arrowImage: arrowImage, selectedImage: selectedImage, unselectedImage: unselectedImage, font: font) return cell } public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return cellHeight } public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { delegate?.didSelectRowAt(indexPath: indexPath) // if item is unselectable.. return and don't select. guard data[indexPath.row].isUserSelectEnable == true else { return } // if selection type single then select one item and remove selection from other if selectionType == .single { for i in 0..<data.count { data[i].isSelected = false } data[indexPath.row].isSelected = true } else { // if selection type multible then select item pressed let item = data[indexPath.row] item.isSelected = !item.isSelected } if let lastIndexPath = lastIndexPath { tableView.reloadRows(at: [lastIndexPath], with: .automatic) } tableView.reloadRows(at: [indexPath], with: .automatic) lastIndexPath = indexPath } } /// The delegate of a AMChoice object must adopt the AMChoiceDelegate protocol. /// The method of the protocol allow the delegate to get notfiy when a choice selected. @objc public protocol AMChoiceDelegate: AnyObject { /// Called when a choice selected. /// /// - parameter indexPath: Contain the index of selected choice. func didSelectRowAt(indexPath: IndexPath) } /// A protocol that should be implimented by any class that need to be used in the `AMChoiceView`. @objc public protocol Selectable { /// Is the item selected. var isSelected: Bool { get set } /// The title that will be shown in the row. var title: String { get set } /// If false, the user can't select this choice. var isUserSelectEnable: Bool { get set } } /// A dummy items used to show the a dummy rows in the interface builder (Storyboard). class DummyInterfaceBuilderItem: NSObject, Selectable { public var title: String public var isSelected: Bool = false public var isUserSelectEnable: Bool = true // set it false if you want to make this item unselectable init(title: String, isSelected: Bool, isUserSelectEnable: Bool) { self.title = title self.isSelected = isSelected self.isUserSelectEnable = isUserSelectEnable } } /// There are two types of selection, single and multiple. /// Single means that the user can select one object, while multiple means /// the user can select multiple items. @objc public enum SelectionType: NSInteger { case single case multiple }
mit
4694f701b89b60240d3ac7b4532f4669
31.207048
109
0.704144
4.644854
false
false
false
false
htomcat/CleanSwiftTableView
CleanSwiftTableView/CleanSwiftTableView/CleanSwiftViewController.swift
1
2753
// // CleanSwiftViewController.swift // CleanSwiftTableView // // Created by htomcat on 2017/10/14. // // import UIKit protocol CleanSwiftViewControllerInput { func displayList(_ viewModel: CleanSwift.MapInfos.ViewModel) } protocol CleanSwiftViewControllerOutput { func fetchDataStore(_ request: CleanSwift.MapInfos.Request) } class CleanSwiftViewController: UIViewController { var output: CleanSwiftViewControllerOutput? var router: (NSObjectProtocol & CleanSwiftRoutingLogic & CleanSwiftDataPassing)? let tableViewDelegate = CleanSwiftTableViewDelegate() let tableViewDatasource = CleanSwiftTableViewDatasource() private lazy var tableView: UITableView = self.createTableView() // MARK: Object lifecycle override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) CleanSwiftConfigurator.shared.configure(self) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) CleanSwiftConfigurator.shared.configure(self) } private func createTableView() -> UITableView { let view = UITableView() view.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: self.view.bounds.height) view.delegate = tableViewDelegate view.dataSource = tableViewDatasource view.register(UITableViewCell.self, forCellReuseIdentifier: "Cell") return view } // MARK: Routing override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let scene = segue.identifier { let selector = NSSelectorFromString("routeTo\(scene)WithSegue:") if let router = router, router.responds(to: selector) { router.perform(selector, with: segue) } } } // MARK: View lifecycle override func viewDidLoad() { super.viewDidLoad() navigationItem.title = "Capital" view.addSubview(tableView) fetchDataStore() } // MARK: Event Handler private func doSomethingOnLoad() { } private func doSomething(request: CleanSwift.MapInfos.Request) { } private func fetchDataStore() { let request = CleanSwift.MapInfos.Request() output?.fetchDataStore(request) } } // MARK: - CleanSwiftViewControllerInput extension CleanSwiftViewController: CleanSwiftViewControllerInput { func displayList(_ viewModel: CleanSwift.MapInfos.ViewModel) { tableViewDatasource.dataStore = viewModel.infos tableView.reloadData() } }
mit
f647e568ba08f9c038a591389a6ce953
28.923913
84
0.657465
5.051376
false
false
false
false
kaorimatz/KZSideDrawerController
Example/KZSideDrawerController/DrawerSettingsViewController.swift
1
10481
// // DrawerSettingsViewController.swift // KZSideDrawerController // // Created by Satoshi Matsumoto on 1/3/16. // Copyright © 2016 Satoshi Matsumoto. All rights reserved. // import UIKit import KZSideDrawerController import PureLayout class DrawerSettingsViewController: UITableViewController { // MARK: - Drawer Controller private var drawerController: KZSideDrawerController? { return navigationController?.parentViewController as? KZSideDrawerController } private var drawerLeftViewController: UIViewController? private var drawerRightViewController: UIViewController? // MARK: - Shadow Opacity private var shadowOpacity: Float { return drawerController?.shadowOpacity ?? 0 } private lazy var shadowOpacityLabel: UILabel = { let label = UILabel() label.translatesAutoresizingMaskIntoConstraints = false label.text = NSString(format: "%.2f", self.shadowOpacity) as String return label }() private lazy var shadowOpacitySlider: UISlider = { let slider = UISlider() slider.translatesAutoresizingMaskIntoConstraints = false slider.minimumValue = 0 slider.maximumValue = 1 slider.value = self.shadowOpacity slider.addTarget(self, action: "didChangeShadowOpacity:", forControlEvents: .ValueChanged) return slider }() private lazy var shadowOpacityCell: UITableViewCell = { let cell = UITableViewCell() cell.translatesAutoresizingMaskIntoConstraints = false cell.selectionStyle = .None cell.contentView.addSubview(self.shadowOpacityLabel) cell.contentView.addSubview(self.shadowOpacitySlider) self.shadowOpacityLabel.autoPinEdgesToSuperviewMarginsExcludingEdge(.Right) self.shadowOpacityLabel.autoSetDimension(.Width, toSize: 40) self.shadowOpacitySlider.autoPinEdgesToSuperviewMarginsExcludingEdge(.Left) self.shadowOpacitySlider.autoPinEdge(.Left, toEdge: .Right, ofView: self.shadowOpacityLabel, withOffset: 8) return cell }() func didChangeShadowOpacity(sender: UISlider) { drawerController?.shadowOpacity = sender.value shadowOpacityLabel.text = NSString(format: "%.2f", shadowOpacity) as String } // MARK: - Left Drawer private var leftDrawerEnabled: Bool { return drawerController?.leftViewController != nil } private lazy var leftDrawerEnabledSwitch: UISwitch = { let enabledSwitch = UISwitch() enabledSwitch.translatesAutoresizingMaskIntoConstraints = false enabledSwitch.on = self.leftDrawerEnabled enabledSwitch.addTarget(self, action: "didChangeLeftDrawerEnabled:", forControlEvents: .ValueChanged) return enabledSwitch }() private lazy var leftDrawerEnabledCell: UITableViewCell = { let cell = UITableViewCell() cell.translatesAutoresizingMaskIntoConstraints = false cell.selectionStyle = .None cell.contentView.addSubview(self.leftDrawerEnabledSwitch) self.leftDrawerEnabledSwitch.autoCenterInSuperview() return cell }() func didChangeLeftDrawerEnabled(sender: UISwitch) { if sender.on { drawerController?.leftViewController = drawerLeftViewController } else { drawerLeftViewController = drawerController?.leftViewController drawerController?.leftViewController = nil } } // MARK: - Right Drawer private var rightDrawerEnabled: Bool { return drawerController?.rightViewController != nil } private lazy var rightDrawerEnabledSwitch: UISwitch = { let enabledSwitch = UISwitch() enabledSwitch.translatesAutoresizingMaskIntoConstraints = false enabledSwitch.on = self.rightDrawerEnabled enabledSwitch.addTarget(self, action: "didChangeRightDrawerEnabled:", forControlEvents: .ValueChanged) return enabledSwitch }() private lazy var rightDrawerEnabledCell: UITableViewCell = { let cell = UITableViewCell() cell.translatesAutoresizingMaskIntoConstraints = false cell.selectionStyle = .None cell.contentView.addSubview(self.rightDrawerEnabledSwitch) self.rightDrawerEnabledSwitch.autoCenterInSuperview() return cell }() func didChangeRightDrawerEnabled(sender: UISwitch) { if sender.on { drawerController?.rightViewController = drawerRightViewController } else { drawerRightViewController = drawerController?.rightViewController drawerController?.rightViewController = nil } } // MARK: - Left Drawer Width private var leftDrawerWidth: CGFloat { return drawerController?.leftDrawerWidth ?? 0 } private lazy var leftDrawerWidthLabel: UILabel = { let label = UILabel() label.translatesAutoresizingMaskIntoConstraints = false label.text = NSString(format: "%.f", self.leftDrawerWidth) as String return label }() private lazy var leftDrawerWidthSlider: UISlider = { let slider = UISlider() slider.translatesAutoresizingMaskIntoConstraints = false slider.minimumValue = 0 slider.maximumValue = Float(self.view.frame.width) slider.value = Float(self.leftDrawerWidth) slider.addTarget(self, action: "didChangeLeftDrawerWidth:", forControlEvents: .ValueChanged) return slider }() private lazy var leftDrawerWidthCell: UITableViewCell = { let cell = UITableViewCell() cell.translatesAutoresizingMaskIntoConstraints = false cell.selectionStyle = .None cell.contentView.addSubview(self.leftDrawerWidthLabel) cell.contentView.addSubview(self.leftDrawerWidthSlider) self.leftDrawerWidthLabel.autoPinEdgesToSuperviewMarginsExcludingEdge(.Right) self.leftDrawerWidthLabel.autoSetDimension(.Width, toSize: 40) self.leftDrawerWidthSlider.autoPinEdgesToSuperviewMarginsExcludingEdge(.Left) self.leftDrawerWidthSlider.autoPinEdge(.Left, toEdge: .Right, ofView: self.leftDrawerWidthLabel, withOffset: 8) return cell }() func didChangeLeftDrawerWidth(sender: UISlider) { drawerController?.leftDrawerWidth = CGFloat(sender.value) leftDrawerWidthLabel.text = NSString(format: "%.f", leftDrawerWidth) as String } // MARK: - Right Drawer Width private var rightDrawerWidth: CGFloat { return drawerController?.rightDrawerWidth ?? 0 } private lazy var rightDrawerWidthLabel: UILabel = { let label = UILabel() label.translatesAutoresizingMaskIntoConstraints = false label.text = NSString(format: "%.f", self.rightDrawerWidth) as String return label }() private lazy var rightDrawerWidthSlider: UISlider = { let slider = UISlider() slider.translatesAutoresizingMaskIntoConstraints = false slider.minimumValue = 0 slider.maximumValue = Float(self.view.frame.width) slider.value = Float(self.rightDrawerWidth) slider.addTarget(self, action: "didChangeRightDrawerWidth:", forControlEvents: .ValueChanged) return slider }() private lazy var rightDrawerWidthCell: UITableViewCell = { let cell = UITableViewCell() cell.translatesAutoresizingMaskIntoConstraints = false cell.selectionStyle = .None cell.contentView.addSubview(self.rightDrawerWidthLabel) cell.contentView.addSubview(self.rightDrawerWidthSlider) self.rightDrawerWidthLabel.autoPinEdgesToSuperviewMarginsExcludingEdge(.Right) self.rightDrawerWidthLabel.autoSetDimension(.Width, toSize: 40) self.rightDrawerWidthSlider.autoPinEdgesToSuperviewMarginsExcludingEdge(.Left) self.rightDrawerWidthSlider.autoPinEdge(.Left, toEdge: .Right, ofView: self.rightDrawerWidthLabel, withOffset: 8) return cell }() func didChangeRightDrawerWidth(sender: UISlider) { drawerController?.rightDrawerWidth = CGFloat(sender.value) rightDrawerWidthLabel.text = NSString(format: "%.f", rightDrawerWidth) as String } // MARK: - Managing the View override func viewDidLoad() { super.viewDidLoad() let menuImage = UIImage(named: "ic_menu") let leftMenuButtonItem = UIBarButtonItem(image: menuImage, style: .Plain, target: self, action: "didTapLeftMenuButtonItem:") navigationItem.leftBarButtonItem = leftMenuButtonItem let rightMenuButtonItem = UIBarButtonItem(image: menuImage, style: .Plain, target: self, action: "didTapRightMenuButtonItem:") navigationItem.rightBarButtonItem = rightMenuButtonItem } // MARK: - Configuring a Table View override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { if indexPath.section == 0 { return shadowOpacityCell } else if indexPath.section == 1 { return leftDrawerEnabledCell } else if indexPath.section == 2 { return rightDrawerEnabledCell } else if indexPath.section == 3 { return leftDrawerWidthCell } else { return rightDrawerWidthCell } } override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 5 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 1 } override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { if section == 0 { return "Shadow opacity" } else if section == 1 { return "Left drawer" } else if section == 2 { return "Right drawer" } else if section == 3 { return "Left drawer width" } else { return "Right drawer width" } } // MARK: - Handling the Menu Button func didTapLeftMenuButtonItem(_: UIBarButtonItem) { drawerController?.openDrawer(side: .Left, animated: true) { finished in if finished { print("openDrawer finished") } } } func didTapRightMenuButtonItem(_: UIBarButtonItem) { drawerController?.openDrawer(side: .Right, animated: true) { finished in if finished { print("openDrawer finished") } } } }
mit
c253b5fc0a593d777a22491f58ff08bf
36.163121
134
0.690076
5.527426
false
false
false
false
leizh007/HiPDA
HiPDA/HiPDA/General/Protocols/DataLoadable.swift
1
3682
// // DataLoadable.swift // HiPDA // // Created by leizh007 on 2017/5/17. // Copyright © 2017年 HiPDA. All rights reserved. // import Foundation import MJRefresh // MARK: - DataLoadStatus enum DataLoadStatus { case normal case noResult case tapToLoad case loading case pullDownRefreshing case pullUpLoading } // MARK: - TapToLoadDelegate protocol TapToLoadDelegate: class { func tapToLoad() } // MARK: - DataLoadDelegate protocol DataLoadDelegate: class { func loadNewData() func loadMoreData() } extension DataLoadDelegate { func loadNewData() {} func loadMoreData() {} } // MARK: - DataLoadable protocol DataLoadable: TapToLoadDelegate { weak var dataLoadDelegate: DataLoadDelegate? { set get } var hasRefreshHeader: Bool { set get } var hasLoadMoreFooter: Bool { set get } var status: DataLoadStatus { set get } var noResultView: NoResultView { set get } var refreshHeader: MJRefreshNormalHeader? { set get } var loadMoreFooter: MJRefreshBackNormalFooter? { set get } var isScrollEnabled: Bool { set get } } // MARK: - Property didSet extension DataLoadable where Self: UIView { func didSetHasRefreshHeader() { if hasRefreshHeader { let header = MJRefreshNormalHeader { [weak self] _ in self?.status = .pullDownRefreshing self?.dataLoadDelegate?.loadNewData() } header?.lastUpdatedTimeLabel.isHidden = true header?.stateLabel.textColor = #colorLiteral(red: 0.3977642059, green: 0.4658440351, blue: 0.5242295265, alpha: 1) refreshHeader = header } else { refreshHeader = nil } } func didSetHasLoadMoreFooter() { if hasLoadMoreFooter { let footer = MJRefreshBackNormalFooter { [weak self] _ in self?.status = .pullUpLoading self?.dataLoadDelegate?.loadMoreData() } footer?.stateLabel.textColor = #colorLiteral(red: 0.3977642059, green: 0.4658440351, blue: 0.5242295265, alpha: 1) loadMoreFooter = footer } else { loadMoreFooter = nil } } func didSetStatus() { switch status { case .noResult: fallthrough case .tapToLoad: fallthrough case .loading: noResultView.status = status isScrollEnabled = false if noResultView.superview == nil { addSubview(noResultView) } default: isScrollEnabled = true UIView.animate(withDuration: 0.1, delay: 0, options: .allowUserInteraction, animations: { self.noResultView.alpha = 0.0 }, completion: { _ in self.noResultView.removeFromSuperview() self.noResultView.alpha = 1.0 }) } } } // MARK: - TapToLoadDelegate extension DataLoadable { func tapToLoad() { if let delegate = dataLoadDelegate, hasRefreshHeader { status = .loading delegate.loadNewData() } } } // MARK: - Data Load extension DataLoadable { func refreshing() { refreshHeader?.beginRefreshing() } func endRefreshing() { refreshHeader?.endRefreshing() } func loadMore() { loadMoreFooter?.beginRefreshing() } func endLoadMore() { loadMoreFooter?.endRefreshing() } func endLoadMoreWithNoMoreData() { loadMoreFooter?.endRefreshingWithNoMoreData() } func resetNoMoreData() { loadMoreFooter?.resetNoMoreData() } }
mit
33f76b780fbe2889a3644e337d0a7a6c
24.372414
126
0.605599
4.627673
false
false
false
false
AlvinL33/TownHunt
TownHunt/PinListInPackTableViewController.swift
1
3559
// // PinListInPackTableViewController.swift // TownHunt // Copyright © 2016 LeeTech. All rights reserved. // import UIKit class PinListInPackTableViewController: UITableViewController { var listOfPins: [PinLocation]! = [] var filePath = "" @IBAction func doneButtonNav(_ sender: AnyObject) { if let destNavCon = presentingViewController as? UINavigationController{ if let targetController = destNavCon.topViewController as? PinPackEditorViewController{ print(listOfPins) targetController.gamePins = listOfPins } } NotificationCenter.default.post(name: Notification.Name(rawValue: "load"), object: nil) self.dismiss(animated: true, completion: nil) } @IBAction func helpButtonTapped(_ sender: Any) { displayAlertMessage(alertTitle: "Help", alertMessage: "Here is a list of all the pins in the pack. Swipe left on a pin and tap delete to remove the pin from the pack. Tap a pin to find out more information about the pin. There is an option to delete the pin here aswell.\n\nOnce you are finished, tap 'Done' to return to the map.") } override func viewDidLoad() { super.viewDidLoad() listOfPins = listOfPins.sorted{ ($0.title)! < ($1.title)! } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return listOfPins.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> PinCell { let cell = tableView.dequeueReusableCell(withIdentifier: "PinCell", for: indexPath) as! PinCell let pin = listOfPins[(indexPath as NSIndexPath).row] cell.titleLabel.text = pin.title cell.hintLabel.text = pin.hint cell.codewordLabel.text = "Answer: \(pin.codeword)" cell.pointValLabel.text = "(\(String(pin.pointVal)) Points)" return cell } private func deletePin(indexPath: IndexPath){ listOfPins.remove(at: (indexPath as NSIndexPath).row) tableView.deleteRows(at: [indexPath], with: UITableViewRowAnimation.automatic) } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let selectedPin = listOfPins[indexPath.row] let alertCon = UIAlertController(title: selectedPin.title, message: "Hint: \(selectedPin.hint)\n\nAbout: \(selectedPin.codeword)\n\nPoints: \(String(selectedPin.pointVal))", preferredStyle: .alert) alertCon.addAction(UIAlertAction(title: "Delete", style: .destructive, handler: {action in self.deletePin(indexPath: indexPath) })) alertCon.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) self.present(alertCon, animated: true, completion: nil) } override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == UITableViewCellEditingStyle.delete { deletePin(indexPath: indexPath) } } }
apache-2.0
cae16c743f56035cf495b4a7e4090c2d
41.86747
339
0.679876
4.808108
false
false
false
false
yunzixun/V2ex-Swift
Model/TopicCommentModel.swift
1
13078
// // TopicCommentModel.swift // V2ex-Swift // // Created by huangfeng on 3/24/16. // Copyright © 2016 Fin. All rights reserved. // import UIKit import Alamofire import Ji import YYText import Kingfisher protocol V2CommentAttachmentImageTapDelegate : class { func V2CommentAttachmentImageSingleTap(_ imageView:V2CommentAttachmentImage) } /// 评论中的图片 class V2CommentAttachmentImage:AnimatedImageView { /// 父容器中第几张图片 var index:Int = 0 /// 图片地址 var imageURL:String? weak var attachmentDelegate : V2CommentAttachmentImageTapDelegate? init(){ super.init(frame: CGRect(x: 0, y: 0, width: 80, height: 80)) self.autoPlayAnimatedImage = false; self.contentMode = .scaleAspectFill self.clipsToBounds = true self.isUserInteractionEnabled = true } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func willMove(toSuperview newSuperview: UIView?) { super.willMove(toSuperview: newSuperview) if self.image != nil { return } if let imageURL = self.imageURL , let URL = URL(string: imageURL) { self.kf.setImage(with: URL, placeholder: nil, options: nil, completionHandler: { (image, error, cacheType, imageURL) -> () in if let image = image { if image.size.width < 80 && image.size.height < 80 { self.contentMode = .bottomLeft } } }) } } override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { let touch = touches.first let tapCount = touch?.tapCount if let tapCount = tapCount { if tapCount == 1 { self.handleSingleTap(touch!) } } //取消后续的事件响应 self.next?.touchesCancelled(touches, with: event) } func handleSingleTap(_ touch:UITouch){ self.attachmentDelegate?.V2CommentAttachmentImageSingleTap(self) } } class TopicCommentModel: NSObject,BaseHtmlModelProtocol { var replyId:String? var avata: String? var userName: String? var date: String? var comment: String? var favorites: Int = 0 var textLayout:YYTextLayout? var images:NSMutableArray = NSMutableArray() //楼层 var number:Int = 0 var textAttributedString:NSMutableAttributedString? required init(rootNode: JiNode) { super.init() let id = rootNode.xPath("table/tr/td[3]/div[1]/div[attribute::id]").first?["id"] if let id = id { if id.hasPrefix("thank_area_") { self.replyId = id.replacingOccurrences(of: "thank_area_", with: "") } } self.avata = rootNode.xPath("table/tr/td[1]/img").first?["src"] self.userName = rootNode.xPath("table/tr/td[3]/strong/a").first?.content self.date = rootNode.xPath("table/tr/td[3]/span").first?.content if let str = rootNode.xPath("table/tr/td[3]/div[@class='fr']/span").first?.content , let no = Int(str){ self.number = no; } if let favorite = rootNode.xPath("table/tr/td[3]/span[2]").first?.content { let array = favorite.components(separatedBy: " ") if array.count == 2 { if let i = Int(array[1]){ self.favorites = i } } } //构造评论内容 let commentAttributedString:NSMutableAttributedString = NSMutableAttributedString(string: "") let nodes = rootNode.xPath("table/tr/td[3]/div[@class='reply_content']/node()") self.preformAttributedString(commentAttributedString, nodes: nodes) let textContainer = YYTextContainer(size: CGSize(width: SCREEN_WIDTH - 24, height: 9999)) self.textLayout = YYTextLayout(container: textContainer, text: commentAttributedString) self.textAttributedString = commentAttributedString } func preformAttributedString(_ commentAttributedString:NSMutableAttributedString,nodes:[JiNode]) { for element in nodes { if element.name == "text" , let content = element.content{//普通文本 commentAttributedString.append(NSMutableAttributedString(string: content,attributes: [NSAttributedStringKey.font:v2ScaleFont(14) , NSAttributedStringKey.foregroundColor:V2EXColor.colors.v2_TopicListTitleColor])) commentAttributedString.yy_lineSpacing = 5 } else if element.name == "img" ,let imageURL = element["src"] {//图片 let image = V2CommentAttachmentImage() image.imageURL = imageURL let imageAttributedString = NSMutableAttributedString.yy_attachmentString(withContent: image, contentMode: .scaleAspectFit , attachmentSize: CGSize(width: 80,height: 80), alignTo: v2ScaleFont(14), alignment: .bottom) commentAttributedString.append(imageAttributedString) image.index = self.images.count self.images.add(imageURL) } else if element.name == "a" ,let content = element.content,let url = element["href"]{//超链接 //递归处理所有子节点,主要是处理下 a标签下包含的img标签 let subNodes = element.xPath("./node()") if subNodes.first?.name != "text" && subNodes.count > 0 { self.preformAttributedString(commentAttributedString, nodes: subNodes) } if content.Lenght > 0 { let attr = NSMutableAttributedString(string: content ,attributes: [NSAttributedStringKey.font:v2ScaleFont(14)]) attr.yy_setTextHighlight(NSMakeRange(0, content.Lenght), color: V2EXColor.colors.v2_LinkColor, backgroundColor: UIColor(white: 0.95, alpha: 1), userInfo: ["url":url], tapAction: { (view, text, range, rect) -> Void in if let highlight = text.yy_attribute(YYTextHighlightAttributeName, at: UInt(range.location)) ,let url = (highlight as AnyObject).userInfo["url"] as? String { AnalyzeURLHelper.Analyze(url) } }, longPressAction: nil) commentAttributedString.append(attr) } } else if element.name == "br" { commentAttributedString.yy_appendString("\n") } else if let content = element.content{//其他 commentAttributedString.append(NSMutableAttributedString(string: content,attributes: [NSAttributedStringKey.foregroundColor:V2EXColor.colors.v2_TopicListTitleColor])) } } } } //MARK: - Request extension TopicCommentModel { class func replyWithTopicId(_ topic:TopicDetailModel, content:String, completionHandler: @escaping (V2Response) -> Void){ let url = V2EXURL + "t/" + topic.topicId! V2User.sharedInstance.getOnce(url) { (response) -> Void in if response.success { let prames = [ "content":content, "once":V2User.sharedInstance.once! ] as [String:Any] Alamofire.request(url, method: .post, parameters: prames, headers: MOBILE_CLIENT_HEADERS).responseJiHtml { (response) -> Void in if let location = response.response?.allHeaderFields["Etag"] as? String{ if location.Lenght > 0 { completionHandler(V2Response(success: true)) } else { completionHandler(V2Response(success: false, message: "回帖失败")) } //不管成功还是失败,更新一下once if let jiHtml = response .result.value{ V2User.sharedInstance.once = jiHtml.xPath("//*[@name='once'][1]")?.first?["value"] } return } completionHandler(V2Response(success: false,message: "请求失败")) } } else{ completionHandler(V2Response(success: false,message: "获取once失败,请重试")) } } } class func replyThankWithReplyId(_ replyId:String , token:String ,completionHandler: @escaping (V2Response) -> Void) { let url = V2EXURL + "thank/reply/" + replyId + "?t=" + token Alamofire.request(url, method: .post, headers: MOBILE_CLIENT_HEADERS).responseString { (response: DataResponse<String>) -> Void in if response.result.isSuccess { if let result = response.result.value { if result.Lenght == 0 { completionHandler(V2Response(success: true)) return; } } } completionHandler(V2Response(success: false)) } } } //MARK: - Method extension TopicCommentModel { /** 用某一条评论,获取和这条评论有关的所有评论 - parameter array: 所有的评论数组 - parameter firstComment: 这条评论 - returns: 某一条评论相关的评论,里面包含它自己 */ class func getRelevantCommentsInArray(_ allCommentsArray:[TopicCommentModel], firstComment:TopicCommentModel) -> [TopicCommentModel] { var relevantComments:[TopicCommentModel] = [] var users = getUsersOfComment(firstComment) //当前会话所有相关的用户( B 回复 A, C 回复 B, D 回复 C, 查看D的对话时, D C B 为相关联用户) var relateUsers:Set<String> = users for comment in allCommentsArray { //被回复人所@的人也加进对话,但是不递归获取所有关系链(可能获取到无意义的数据) if let username = comment.userName, users.contains(username) { let commentUsers = getUsersOfComment(comment) relateUsers = relateUsers.union(commentUsers) } //只找到点击的位置,之后就不找了 if comment == firstComment { break; } } users.insert(firstComment.userName!) for comment in allCommentsArray { //判断评论中是否@的所有用户和会话相关联的用户无关,是的话则证明这条评论是和别人讲的,不属于当前对话 let commentUsers = getUsersOfComment(comment) let intersectUsers = commentUsers.intersection(relateUsers) if commentUsers.count > 0 && intersectUsers.count <= 0 { continue; } if let username = comment.userName { if users.contains(username) { relevantComments.append(comment) } } //只找到点击的位置,之后就不找了 if comment == firstComment { break; } } return relevantComments } //获取评论中 @ 了多少用户 class func getUsersOfComment(_ comment:TopicCommentModel) -> Set<String> { //获取到所有YYTextHighlight ,用以之后获取 这条评论@了多少用户 var textHighlights:[YYTextHighlight] = [] comment.textAttributedString!.enumerateAttribute(NSAttributedStringKey(rawValue: YYTextHighlightAttributeName), in: NSMakeRange(0, comment.textAttributedString!.length), options: []) { (attribute, range, stop) -> Void in if let highlight = attribute as? YYTextHighlight { textHighlights.append(highlight) } } //获取这条评论 @ 了多少用户 var users:Set<String> = [] for highlight in textHighlights { if let url = highlight.userInfo?["url"] as? String{ let result = AnalyzURLResultType(url: url) if case .member(let member) = result { users.insert(member.username) } } } return users } }
mit
185a7d2bf1f94236d5078a80b490caf9
38.977419
232
0.551279
4.78125
false
false
false
false
AleksandarPetrov/Money-Design-Pattern-in-Swift
Classes/Swift/Currency.swift
1
5213
// // Currency.swift // iTestMoneyDesignPatternSwift // // Created by Aleksandar Petrov on 7/27/15. // Copyright (c) 2015 Aleksandar Petrov. All rights reserved. // import Foundation /// Currency protocol defines the minimum interface needed to represent it public protocol Currency: Equatable { /// The Currency code var code: String { get } /// The name of the currency var name: String { get } // The number of decimal places used to express any minor units for the currency var minorUnits: Int { get } /// The Currency symbol/sign var symbol: String? { get } // The Currency decimal separator var separator: String? { get } // The Currency grouping separator var delimiter: String? { get } /// Default constructor init(code: String, name: String, minorUnits: Int, symbol: String?, separator: String?, delimiter: String?) } /// Currency Convenience constructor public extension Currency { init?(isoCurrencyCode: String) { guard let locale = Locale.locale(for: isoCurrencyCode) else { return nil } let formatter = NumberFormatter.currencyFormatter formatter.locale = locale self.init(code: isoCurrencyCode, name: Locale.current.localizedString(forCurrencyCode: isoCurrencyCode) ?? isoCurrencyCode, minorUnits: formatter.maximumFractionDigits, symbol: formatter.currencySymbol, separator: formatter.currencyDecimalSeparator, delimiter: formatter.currencyGroupingSeparator) } } public extension Currency { // MARK: - Equatable static func == (lhs: Self, rhs: Self) -> Bool { return lhs.code == rhs.code } } /// Format helpers public extension Currency { /// Returns a String containing the formatted ammount func string(from number: NSNumber, locale: Locale? = nil) -> String? { guard let locale = locale ?? Locale.locale(for: self.code) else { return nil } return currencyFormatter(with: locale).string(from: number) } /// Returns a NSNumber containing the formatted ammount func number(from string: String, locale: Locale? = nil) -> NSNumber? { guard let locale = locale ?? Locale.locale(for: self.code) else { return nil } return currencyFormatter(with: locale).number(from: string) } /// The currency formatter factory func currencyFormatter(with locale: Locale) -> NumberFormatter { let formatter = NumberFormatter.currencyFormatter formatter.locale = locale formatter.maximumFractionDigits = minorUnits formatter.currencySymbol = symbol formatter.currencyDecimalSeparator = separator formatter.currencyGroupingSeparator = delimiter return formatter } } /// Crypto currency types (Bitcoin etc) should refine CryptoCurrency. public protocol CryptoCurrency: Currency { } /// LocaleCurrency a refinement of Currency so we can get it from Locale. public struct LocaleCurrency: Currency { // MARK: - Currency public var code: String public var name: String public var minorUnits: Int public var symbol: String? public var separator: String? public var delimiter: String? public init(code: String, name: String, minorUnits: Int, symbol: String?, separator: String?, delimiter: String?) { self.code = code self.name = name self.minorUnits = minorUnits self.symbol = symbol self.separator = separator self.delimiter = delimiter } } /// LocaleCurrency Convenience constructors public extension LocaleCurrency { init?(localeIdentifier: String) { // Check for valid identifier if !Locale.availableIdentifiers.contains(localeIdentifier) { return nil } let localeCanonicalIdentifier = Locale.canonicalIdentifier(from: localeIdentifier) let locale = Locale(identifier: localeCanonicalIdentifier) self.init(locale: locale) } init?(locale: Locale = Locale.current) { guard let currencyCode = locale.currencyCode else { return nil } let formatter = NumberFormatter.currencyFormatter formatter.locale = locale self.init(code: currencyCode, name: locale.localizedString(forCurrencyCode: currencyCode) ?? currencyCode, minorUnits: formatter.maximumFractionDigits, symbol: formatter.currencySymbol, separator: formatter.currencyDecimalSeparator, delimiter: formatter.currencyGroupingSeparator) } } /// LocaleCurrency factory methods public extension LocaleCurrency { static func current() -> LocaleCurrency? { return Self(locale: Locale.current) } static func currency(for locale: Locale) -> LocaleCurrency? { return Self(locale: locale) } } // MARK: - Helpers private extension NumberFormatter { static var currencyFormatter: NumberFormatter { let formatter = NumberFormatter() formatter.numberStyle = .currency return formatter } }
mit
3e0fa90972d36514f933604d9e6de66b
30.029762
119
0.663533
5.051357
false
false
false
false
LYM-mg/MGDYZB
MGDYZB/MGDYZB/Class/Home/View/HomeTitlesView.swift
1
7018
// // HomeTitlesView.swift // MGDYZB // // Created by ming on 16/10/25. // Copyright © 2016年 ming. All rights reserved. // import UIKit private let kScrollLineH: CGFloat = 2 private let kNormalColor : (CGFloat, CGFloat, CGFloat) = (85, 85, 85) private let kSelectColor : (CGFloat, CGFloat, CGFloat) = (255, 128, 0) // MARK:- 定义协议 @objc protocol HomeTitlesViewDelegate: NSObjectProtocol { @objc optional func HomeTitlesViewDidSetlected(_ homeTitlesView: HomeTitlesView, selectedIndex: Int) } class HomeTitlesView: UIView { // MARK: - 属性 var titles: [String] var titleLabels: [UILabel] = [UILabel]() var normalTitleLabelTextColor: UIColor? var selectedTitleLabelTextColor: UIColor? fileprivate var currentIndex : Int = 0 weak var deledate: HomeTitlesViewDelegate? var HomeTitlesViewWhenTitleSelect : ((_ homeTitlesView: HomeTitlesView, _ selectedIndex: Int) -> ())? // MARK: - lazy属性 fileprivate lazy var scrollView: UIScrollView = { let scrollView = UIScrollView() scrollView.showsHorizontalScrollIndicator = false scrollView.bounces = false return scrollView }() fileprivate lazy var scrollLine : UIView = { [unowned self] in let scrollLine = UIView() scrollLine.backgroundColor = (self.selectedTitleLabelTextColor != nil) ? self.selectedTitleLabelTextColor : UIColor.KSelectedColorForPageTitle() return scrollLine }() // MARK:- 自定义构造函数 // MARK:- 自定义构造函数 init(frame: CGRect, titles: [String]) { self.titles = titles super.init(frame: frame) self.backgroundColor = UIColor(r: 166, g: 166, b: 166, a: 0.2) setUpMainView() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } // MARK: - 初始化UI extension HomeTitlesView { fileprivate func setUpMainView() { // 1.添加UIScrollView addSubview(scrollView) scrollView.frame = bounds // 2.添加title对应的Label setupTitleLabels() // 3.设置底线和滚动的滑块 setupBottomLineAndScrollLine() } fileprivate func setupTitleLabels() { // 0.确定label的一些frame的值 let labelW: CGFloat = kScreenW/CGFloat(self.titles.count) let labelH: CGFloat = frame.height - kScrollLineH let labelY: CGFloat = 0 for (index, title) in self.titles.enumerated() { // 1.创建UILabel let labelX : CGFloat = labelW * CGFloat(index) let label = UILabel(frame: CGRect(x: labelX, y: labelY, width: labelW, height: labelH)) // 2.设置Label属性 label.textAlignment = .center label.text = title label.tag = index label.textColor = UIColor.RGBColor(red: 85, green: 85, blue: 85) label.font = UIFont.systemFont(ofSize: 16.0) // 3.将label添加到scrollView中 scrollView.addSubview(label) titleLabels.append(label) // 4.给Label添加手势 label.isUserInteractionEnabled = true let tapGes = UITapGestureRecognizer(target: self, action: #selector(HomeTitlesView.titleLabelClick(_:))) label.addGestureRecognizer(tapGes) } } fileprivate func setupBottomLineAndScrollLine() { // 1.添加底线 let bottomLine = UIView() bottomLine.backgroundColor = UIColor.lightGray let lineH : CGFloat = 0.5 bottomLine.frame = CGRect(x: 0, y: frame.height - lineH, width: frame.width, height: lineH) addSubview(bottomLine) // 2.添加scrollLine // 2.1.获取第一个Label guard let firstLabel = titleLabels.first else { return } firstLabel.textColor = (normalTitleLabelTextColor != nil) ? normalTitleLabelTextColor : UIColor.KNormalColorForPageTitle() // 2.2.设置scrollLine的属性 scrollView.addSubview(scrollLine) scrollLine.frame = CGRect(x: firstLabel.frame.origin.x, y: frame.height - kScrollLineH, width: firstLabel.frame.width, height: kScrollLineH) } } // MARK:- 监听Label的点击 extension HomeTitlesView { @objc func titleLabelClick(_ tap: UITapGestureRecognizer) { // 0.获取当前Label guard let currentLabel = tap.view as? UILabel else { return } // 1.如果是重复点击同一个Title,那么直接返回 if currentLabel.tag == currentIndex { return } // 2.获取之前的Label let oldLabel = titleLabels[currentIndex] // 3.切换文字的颜色 currentLabel.textColor = (selectedTitleLabelTextColor != nil) ? selectedTitleLabelTextColor : UIColor.KSelectedColorForPageTitle() oldLabel.textColor = (normalTitleLabelTextColor != nil) ? normalTitleLabelTextColor : UIColor.KNormalColorForPageTitle() // 4.保存最新Label的下标值 currentIndex = currentLabel.tag // 5.滚动条位置发生改变 let scrollLineX = CGFloat(currentIndex) * scrollLine.frame.width UIView.animate(withDuration: 0.15, animations: { () -> Void in self.scrollLine.frame.origin.x = scrollLineX }) // 6.回调或代理 // if (self.HomeTitlesViewWhenTitleSelect != nil) { // self.HomeTitlesViewWhenTitleSelect!(HomeTitlesView: self, selectedIndex: currentIndex) // } deledate?.HomeTitlesViewDidSetlected!(self, selectedIndex: currentIndex) } } // MARK:- 对外暴露的接口方法 extension HomeTitlesView { func setTitleWithProgress(_ progress : CGFloat, sourceIndex : Int, targetIndex : Int) { // 1.取出sourceLabel/targetLabel let sourceLabel = titleLabels[sourceIndex] let targetLabel = titleLabels[targetIndex] // 2.处理滑块的逻辑 let moveTotalX = targetLabel.frame.origin.x - sourceLabel.frame.origin.x let moveX = moveTotalX * progress scrollLine.frame.origin.x = sourceLabel.frame.origin.x + moveX // 3.颜色的渐变(复杂) // 3.1.取出变化的范围 let colorDelta = (kSelectColor.0 - kNormalColor.0, kSelectColor.1 - kNormalColor.1, kSelectColor.2 - kNormalColor.2) // 3.2.变化sourceLabel sourceLabel.textColor = UIColor(r: CGFloat(kSelectColor.0 - colorDelta.0 * progress), g: CGFloat(kSelectColor.1 - colorDelta.1 * progress), b: CGFloat(kSelectColor.2 - colorDelta.2 * progress)) // 3.2.变化targetLabel targetLabel.textColor = UIColor(r: kNormalColor.0 + colorDelta.0 * progress, g: kNormalColor.1 + colorDelta.1 * progress, b: kNormalColor.2 + colorDelta.2 * progress) // 4.记录最新的index currentIndex = targetIndex } }
mit
7ea03ffad14d39a6d3d360ec79b6bd1c
35.355191
201
0.636705
4.649196
false
false
false
false
sharath-cliqz/browser-ios
Client/Cliqz/Frontend/Browser/ControlCenter/ControlCenterViewController.swift
2
11493
// // ControlCenterViewController.swift // Client // // Created by Mahmoud Adam on 12/27/16. // Copyright © 2016 CLIQZ. All rights reserved. // import UIKit //TODO: Localization & Telemetry protocol ControlCenterViewDelegate: class { func controlCenterViewWillClose(_ antitrackingView: UIView) func reloadCurrentPage() } class ControlCenterViewController: UIViewController { //MARK: - Constants fileprivate let controlCenterThemeColor = UIConstants.CliqzThemeColor fileprivate let urlBarHeight: CGFloat = 40.0 //MARK: - Variables internal var visible = false //MARK: Views fileprivate var blurryBackgroundView: UIVisualEffectView! fileprivate var backgroundView: UIView! fileprivate var panelSegmentedControl: UISegmentedControl! fileprivate var panelSegmentedSeparator = UIView() fileprivate var panelSegmentedContainerView = UIView() fileprivate var panelContainerView = UIView() //MARK: data fileprivate let trackedWebViewID: Int! fileprivate let isPrivateMode: Bool! fileprivate var currentURl: URL! //MARK: panels fileprivate lazy var antitrackingPanel: AntitrackingPanel = { // Temporary changing forget mode design for Control Center let antitrackingPanel = AntitrackingPanel(webViewID: self.trackedWebViewID, url: self.currentURl, privateMode: false) antitrackingPanel.controlCenterPanelDelegate = self antitrackingPanel.delegate = self.delegate return antitrackingPanel }() fileprivate lazy var adBlockerPanel: AdBlockerPanel = { // Temporary changing forget mode design for Control Center let adBlockerPanel = AdBlockerPanel(webViewID: self.trackedWebViewID, url: self.currentURl, privateMode: false) adBlockerPanel.controlCenterPanelDelegate = self adBlockerPanel.delegate = self.delegate return adBlockerPanel }() fileprivate lazy var antiPhishingPanel: AntiPhishingPanel = { // Temporary changing forget mode design for Control Center let antiPhishingPanel = AntiPhishingPanel(webViewID: self.trackedWebViewID, url: self.currentURl, privateMode: false) antiPhishingPanel.controlCenterPanelDelegate = self antiPhishingPanel.delegate = self.delegate return antiPhishingPanel }() //MARK: Delegates weak var controlCenterDelegate: ControlCenterViewDelegate? = nil weak var delegate: BrowserNavigationDelegate? = nil //MARK: - Init init(webViewID: Int, url: URL, privateMode: Bool = false) { trackedWebViewID = webViewID isPrivateMode = privateMode self.currentURl = url super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } //MARK: - View LifeCycle override func viewDidLoad() { super.viewDidLoad() // Background let blurEffect = UIBlurEffect(style: .light) self.blurryBackgroundView = UIVisualEffectView(effect: blurEffect) self.view.insertSubview(blurryBackgroundView, at: 0) // Hack to change blurriness color of the background according to the design requirment. UIVisualEffectView doesn't provide API to change the color, it assigns default grey color, but we need white. for i in self.blurryBackgroundView.subviews { if i.backgroundColor != nil { i.backgroundColor = self.backgroundColor().withAlphaComponent(0.7) } } self.backgroundView = UIView() self.backgroundView.backgroundColor = UIColor.clear self.view.addSubview(self.backgroundView) // Segmented control panelSegmentedContainerView.backgroundColor = self.controlCenterThemeColor self.view.addSubview(panelSegmentedContainerView) let antiTrakcingTitle = NSLocalizedString("Anti-Tracking", tableName: "Cliqz", comment: "Anti-Trakcing panel name on control center.") let adBlockingTitle = NSLocalizedString("Ad-Blocking", tableName: "Cliqz", comment: "Ad-Blocking panel name on control center.") let antiPhishingTitle = NSLocalizedString("Anti-Phishing", tableName: "Cliqz", comment: "Anti-Phishing panel name on control center.") panelSegmentedControl = UISegmentedControl(items: [antiTrakcingTitle, adBlockingTitle, antiPhishingTitle]) panelSegmentedControl.tintColor = UIColor.white panelSegmentedControl.backgroundColor = self.controlCenterThemeColor panelSegmentedControl.addTarget(self, action: #selector(switchPanel), for: .valueChanged) self.panelSegmentedControl.selectedSegmentIndex = 0 panelSegmentedContainerView.addSubview(panelSegmentedControl) panelSegmentedSeparator.backgroundColor = UIColor(rgb: 0xB1B1B1) panelSegmentedContainerView.addSubview(panelSegmentedSeparator) view.addSubview(panelContainerView) // Temporary changing forget mode design for Control Center /* if let privateMode = self.isPrivateMode, privateMode == true { panelSegmentedContainerView.backgroundColor = self.backgroundColor().withAlphaComponent(0.0) } */ } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) if isPrivateMode { self.panelSegmentedSeparator.isHidden = true } else { self.panelSegmentedSeparator.isHidden = false } self.showPanelViewController(self.antitrackingPanel) } override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() self.setupConstraints() } //MARK: - Helper methods fileprivate func setupConstraints() { let panelLayout = OrientationUtil.controlPanelLayout() blurryBackgroundView.snp.makeConstraints { (make) in make.left.right.bottom.equalTo(self.view) make.top.equalTo(self.view) } if panelLayout != .landscapeRegularSize { backgroundView.snp.makeConstraints { (make) in make.left.right.bottom.equalTo(self.view) make.top.equalTo(self.view) } panelSegmentedContainerView.snp.makeConstraints { make in make.left.right.equalTo(self.view) make.top.equalTo(self.view) make.height.equalTo(45) } panelSegmentedControl.snp.makeConstraints { make in make.centerY.equalTo(panelSegmentedContainerView) make.left.equalTo(panelSegmentedContainerView).offset(10) make.right.equalTo(panelSegmentedContainerView).offset(-10) make.height.equalTo(30) } panelContainerView.snp.makeConstraints { make in make.top.equalTo(self.panelSegmentedContainerView.snp.bottom).offset(10) make.left.right.bottom.equalTo(self.view) } panelSegmentedSeparator.snp.makeConstraints { make in make.left.equalTo(panelSegmentedContainerView) make.width.equalTo(panelSegmentedContainerView) make.bottom.equalTo(panelSegmentedContainerView) make.height.equalTo(1) } } else { backgroundView.snp.makeConstraints { (make) in make.top.left.right.bottom.equalTo(self.view) } panelSegmentedContainerView.snp.makeConstraints { make in make.left.right.equalTo(self.view) make.top.equalTo(self.view) make.height.equalTo(45) } panelSegmentedControl.snp.makeConstraints { make in make.centerY.equalTo(panelSegmentedContainerView) make.left.equalTo(panelSegmentedContainerView).offset(10) make.right.equalTo(panelSegmentedContainerView).offset(-10) make.height.equalTo(30) } panelContainerView.snp.makeConstraints { make in make.top.equalTo(self.panelSegmentedContainerView.snp.bottom).offset(10) make.left.right.bottom.equalTo(self.view) } panelSegmentedSeparator.snp.makeConstraints { make in make.left.equalTo(panelSegmentedContainerView) make.width.equalTo(panelSegmentedContainerView) make.bottom.equalTo(panelSegmentedContainerView) make.height.equalTo(1) } } } fileprivate func backgroundColor() -> UIColor { if self.isPrivateMode == true { // Temporary changing forget mode design for Control Center return UIColor.white //UIColor(rgb: 0x222222) } return UIColor.white } //MARK: Switching panels @objc fileprivate func switchPanel(_ sender: UISegmentedControl) { self.hideCurrentPanelViewController() var newPanel: ControlCenterPanel? switch sender.selectedSegmentIndex { case 0: newPanel = self.antitrackingPanel case 1: newPanel = self.adBlockerPanel case 2: newPanel = self.antiPhishingPanel default: break } if let panel = newPanel { TelemetryLogger.sharedInstance.logEvent(.ControlCenter("click", nil, panel.getViewName(), nil)) self.showPanelViewController(panel) } } fileprivate func showPanelViewController(_ viewController: UIViewController) { addChildViewController(viewController) self.panelContainerView.addSubview(viewController.view) viewController.view.snp.makeConstraints { make in make.top.left.right.bottom.equalTo(self.panelContainerView) } viewController.didMove(toParentViewController: self) } fileprivate func hideCurrentPanelViewController() { if let panel = childViewControllers.first { panel.willMove(toParentViewController: nil) panel.view.removeFromSuperview() panel.removeFromParentViewController() } } } //MARK: - ControlCenterPanelDelegate extension ControlCenterViewController : ControlCenterPanelDelegate { func closeControlCenter() { let panelLayout = OrientationUtil.controlPanelLayout() self.controlCenterDelegate?.controlCenterViewWillClose(self.view) if panelLayout != .landscapeRegularSize { UIView.animate(withDuration: 0.2, animations: { var p = self.view.center p.y -= self.view.frame.size.height self.view.center = p }, completion: { (finished) in if finished { self.view.removeFromSuperview() self.removeFromParentViewController() } }) } else{ UIView.animate(withDuration: 0.08, animations: { self.view.frame.origin.x = self.view.frame.origin.x + self.view.frame.size.width }, completion: { (finished) in if finished { self.view.removeFromSuperview() self.removeFromParentViewController() } }) } } func reloadCurrentPage() { self.controlCenterDelegate?.reloadCurrentPage() } }
mpl-2.0
1fe4705e93a2eaa162be99beffeac4e3
36.678689
200
0.656283
5.073731
false
false
false
false
niklasberglund/SwiftChinese
SwiftChineseExample/SwiftChineseExample/ViewController.swift
1
1878
// // ViewController.swift // SwiftChineseExample // // Created by Niklas Berglund on 2016-12-02. // Copyright © 2016 Klurig. All rights reserved. // import UIKit import SwiftChinese class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() do { // Latest CC-CEDICT let exportInfo = try DictionaryExportInfo.latestDictionaryExportInfo() let export = DictionaryExport(exportInfo: exportInfo!) // Download the dictionary export export.download(onCompletion: { (exportContent, error) in guard error == nil else { debugPrint("Unable to download dictionary export. Aborting.") return } // Dictionary object used for getting translations let dictionary = Dictionary() debugPrint("Number of entries in dictionary before import: " + String(dictionary.numberOfEntries())) // Do an import let importer = Importer(dictionaryExport: export) importer.importTranslations(onProgress: { (totalEntries, progressedEntries) in // Progress update debugPrint("progressedEntries: \(progressedEntries), totalEntries: \(totalEntries)") }, whenFinished: { (error, newEntries, updatedEntries, removedEntries) in debugPrint("Number of entries in dictionary before import: " + String(dictionary.numberOfEntries())) }) }) } catch let error { debugPrint(error) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
f5e3b2c881394ef1a7cf176d61ca51a4
35.096154
120
0.581247
5.740061
false
false
false
false
quangpc/HQPagerViewController
HQPagerViewController/Sources/HQPagerMenuView.swift
1
7896
// // HQPagerMenuView.swift // HQPagerViewController // // Created by robert pham on 11/10/16. // Copyright © 2016 quangpc. All rights reserved. // import UIKit private let switchAnimationDuration: TimeInterval = 0.3 private let highlighterAnimationDuration: TimeInterval = switchAnimationDuration / 2 public struct HQPagerMenuViewItemProvider { public var title: String public var normalImage: UIImage? public var selectedImage: UIImage? public var selectedBackgroundColor: UIColor? public init(title: String, normalImage: UIImage?, selectedImage: UIImage?, selectedBackgroundColor: UIColor?) { self.title = title self.normalImage = normalImage self.selectedImage = selectedImage self.selectedBackgroundColor = selectedBackgroundColor } } public protocol HQPagerMenuViewDataSource: class { func numberOfItems(inPagerMenu menuView: HQPagerMenuView)-> Int func pagerMenuView(_ menuView: HQPagerMenuView, itemAt index: Int)-> HQPagerMenuViewItemProvider? } public protocol HQPagerMenuViewDelegate: class { func menuView(_ menuView: HQPagerMenuView, didChangeToIndex index: Int) } open class HQPagerMenuView: UIView { open var titleFont: UIFont = .systemFont(ofSize: 14) { didSet { for label in labels { label.font = titleFont } updateHighlightViewPosition() } } open var titleTextColor: UIColor = .white { didSet { for label in labels { label.textColor = titleTextColor } } } open var edgeFrameStretchable = true { didSet { updateHighlightViewPosition() } } public var selectedIndex: Int = 0 fileprivate let stackView = UIStackView() fileprivate var highlightView = HQRoundCornerView(frame: CGRect.zero) fileprivate var buttons: [UIButton] = [] fileprivate var labels: [UILabel] = [] open weak var dataSource: HQPagerMenuViewDataSource? { didSet { reloadData() } } open weak var delegate: HQPagerMenuViewDelegate? override public init(frame: CGRect) { super.init(frame: frame) setupView() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setupView() } private func setupView() { translatesAutoresizingMaskIntoConstraints = false addSubview(highlightView) stackView.frame = self.bounds stackView.backgroundColor = UIColor.clear addSubview(stackView) stackView.distribution = .fillEqually self.layoutIfNeeded() } open override func layoutSubviews() { super.layoutSubviews() stackView.frame = bounds stackView.layoutIfNeeded() if selectedIndex >= 0 { updateHighlightViewPosition() } } public func reloadData() { guard let dataSource = dataSource else { return } buttons.removeAll() labels.removeAll() for subView in stackView.subviews { subView.removeFromSuperview() } let numberOfItems = dataSource.numberOfItems(inPagerMenu: self) for i in 0..<numberOfItems { let button = createButton(atIndex: i) buttons.append(button) stackView.addArrangedSubview(button) let label = createLabel(atIndex: i) labels.append(label) stackView.addArrangedSubview(label) } stackView.layoutIfNeeded() updateHighlightViewPosition() } fileprivate func updateHighlightViewPosition() { showSelectedLabel() moveHighlightView(toIndex: selectedIndex) } public func setSelectedIndex(index: Int, animated: Bool) { let oldIndex = selectedIndex selectedIndex = index self.showSelectedLabel() if animated { if index != oldIndex { transitionAnimated(to: index) } } else { moveHighlightView(toIndex: index) } } fileprivate func transitionAnimated(to toIndex: Int) { let animation = { self.moveHighlightView(toIndex: toIndex) } UIView.animate( withDuration: switchAnimationDuration, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 3, options: [], animations: animation, completion: nil ) } fileprivate func showSelectedLabel() { for i in 0..<buttons.count { let button = buttons[i] let label = labels[i] label.isHidden = (i != selectedIndex) label.alpha = (i != selectedIndex) ? 0 : 1 button.isSelected = (i == selectedIndex) } self.stackView.layoutIfNeeded() } fileprivate func moveHighlightView(toIndex index:Int) { guard let dataSource = dataSource else { return } let numberOfItems = dataSource.numberOfItems(inPagerMenu: self) if index > labels.count-1 || index < 0 { return } let toLabel = labels[index] let toButton = buttons[index] let labelFrame = convert(toLabel.frame, to: self) let buttonFrame = convert(toButton.frame, to: self) var targetFrame = CGRect(x: buttonFrame.minX, y: 0, width: labelFrame.maxX - buttonFrame.minX, height: bounds.size.height) let delta = bounds.size.height/2 if edgeFrameStretchable { if index == 0 { targetFrame = CGRect(x: -delta, y: 0, width: labelFrame.maxX + delta, height: bounds.size.height) } if index == numberOfItems-1 { targetFrame = CGRect(x: buttonFrame.minX, y: 0, width: bounds.size.width - buttonFrame.minX + delta, height: bounds.size.height) } } highlightView.frame = targetFrame if let item = dataSource.pagerMenuView(self, itemAt: index) { highlightView.backgroundColor = item.selectedBackgroundColor } } private func createLabel(atIndex index:Int)-> UILabel { guard let dataSource = dataSource, let item = dataSource.pagerMenuView(self, itemAt: index) else { return UILabel(frame: .zero) } let label = UILabel(frame: CGRect.zero) label.textAlignment = .left label.font = titleFont label.adjustsFontSizeToFitWidth = true label.isHidden = true label.textColor = titleTextColor label.text = item.title return label } private func createButton(atIndex index: Int)-> UIButton { guard let dataSource = dataSource, let item = dataSource.pagerMenuView(self, itemAt: index) else { return UIButton(frame: .zero) } let button = UIButton() button.tag = index button.setImage(item.normalImage, for: .normal) button.setImage(item.selectedImage, for: .selected) button.addTarget(self, action: #selector(HQPagerMenuView.buttonPressed(button:)), for: .touchUpInside) return button } @objc fileprivate func buttonPressed(button: UIButton) { let oldIndex = selectedIndex let newIndex = button.tag setSelectedIndex(index: newIndex, animated: true) if oldIndex != newIndex { delegate?.menuView(self, didChangeToIndex: newIndex) } } } open class HQRoundCornerView: UIView { open override func layoutSubviews() { super.layoutSubviews() self.layer.cornerRadius = bounds.size.height/2 } }
mit
dfa5ce595bbeb3b4625264ea590eecb1
30.205534
144
0.608613
5.086985
false
false
false
false
touchopia/HackingWithSwift
project33/Project33/ResultsViewController.swift
1
6047
// // ResultsViewController.swift // Project33 // // Created by TwoStraws on 24/08/2016. // Copyright © 2016 Paul Hudson. All rights reserved. // import AVFoundation import CloudKit import UIKit class ResultsViewController: UITableViewController { var whistle: Whistle! var suggestions = [String]() var whistlePlayer: AVAudioPlayer! override func viewDidLoad() { super.viewDidLoad() title = "Genre: \(whistle.genre!)" navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Download", style: .plain, target: self, action: #selector(downloadTapped)) tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell") let reference = CKReference(recordID: whistle.recordID, action: .deleteSelf) let pred = NSPredicate(format: "owningWhistle == %@", reference) let sort = NSSortDescriptor(key: "creationDate", ascending: true) let query = CKQuery(recordType: "Suggestions", predicate: pred) query.sortDescriptors = [sort] CKContainer.default().publicCloudDatabase.perform(query, inZoneWith: nil) { [unowned self] results, error in if let error = error { print(error.localizedDescription) } else { if let results = results { self.parseResults(records: results) } } } } override func numberOfSections(in tableView: UITableView) -> Int { return 2 } override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { if section == 1 { return "Suggested songs" } return nil } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if section == 0 { return 1 } else { return max(1, suggestions.count + 1) } } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) cell.selectionStyle = .none cell.textLabel?.numberOfLines = 0 if indexPath.section == 0 { // the user's comments about this whistle cell.textLabel?.font = UIFont.preferredFont(forTextStyle: UIFontTextStyle.title1) if whistle.comments.characters.count == 0 { cell.textLabel?.text = "Comments: None" } else { cell.textLabel?.text = whistle.comments } } else { cell.textLabel?.font = UIFont.preferredFont(forTextStyle: UIFontTextStyle.body) if indexPath.row == suggestions.count { // this is our extra row cell.textLabel?.text = "Add suggestion" cell.selectionStyle = .gray } else { cell.textLabel?.text = suggestions[indexPath.row] } } return cell } override func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat { return UITableViewAutomaticDimension } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return UITableViewAutomaticDimension } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { guard indexPath.section == 1 && indexPath.row == suggestions.count else { return } tableView.deselectRow(at: indexPath, animated: true) let ac = UIAlertController(title: "Suggest a song…", message: nil, preferredStyle: .alert) ac.addTextField() ac.addAction(UIAlertAction(title: "Submit", style: .default) { [unowned self, ac] action in if let textField = ac.textFields?[0] { if textField.text!.characters.count > 0 { self.add(suggestion: textField.text!) } } }) ac.addAction(UIAlertAction(title: "Cancel", style: .cancel)) present(ac, animated: true) } func add(suggestion: String) { let whistleRecord = CKRecord(recordType: "Suggestions") let reference = CKReference(recordID: whistle.recordID, action: .deleteSelf) whistleRecord["text"] = suggestion as CKRecordValue whistleRecord["owningWhistle"] = reference as CKRecordValue CKContainer.default().publicCloudDatabase.save(whistleRecord) { [unowned self] record, error in DispatchQueue.main.async { if error == nil { self.suggestions.append(suggestion) self.tableView.reloadData() } else { let ac = UIAlertController(title: "Error", message: "There was a problem submitting your suggestion: \(error!.localizedDescription)", preferredStyle: .alert) ac.addAction(UIAlertAction(title: "OK", style: .default)) self.present(ac, animated: true) } } } } func parseResults(records: [CKRecord]) { var newSuggestions = [String]() for record in records { newSuggestions.append(record["text"] as! String) } DispatchQueue.main.async { [unowned self] in self.suggestions = newSuggestions self.tableView.reloadData() } } func downloadTapped() { let spinner = UIActivityIndicatorView(activityIndicatorStyle: .gray) spinner.tintColor = UIColor.black spinner.startAnimating() navigationItem.rightBarButtonItem = UIBarButtonItem(customView: spinner) CKContainer.default().publicCloudDatabase.fetch(withRecordID: whistle.recordID) { [unowned self] record, error in if let error = error { DispatchQueue.main.async { // meaningful error message here! print(error.localizedDescription) self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Download", style: .plain, target: self, action: #selector(self.downloadTapped)) } } else { if let record = record { if let asset = record["audio"] as? CKAsset { self.whistle.audio = asset.fileURL DispatchQueue.main.async { self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Listen", style: .plain, target: self, action: #selector(self.listenTapped)) } } } } } } func listenTapped() { do { whistlePlayer = try AVAudioPlayer(contentsOf: whistle.audio) whistlePlayer.play() } catch { let ac = UIAlertController(title: "Playback failed", message: "There was a problem playing your whistle; please try re-recording.", preferredStyle: .alert) ac.addAction(UIAlertAction(title: "OK", style: .default)) present(ac, animated: true) } } }
unlicense
f56b9e1df4fc3c8cd7172468c180ce87
30.643979
162
0.716413
3.965879
false
false
false
false
BelowTheHorizon/Mocaccino
Mocaccino/CardDetailPageViewController.swift
1
3774
// // CardDetailPageViewController.swift // Mocaccino // // Created by Cirno MainasuK on 2016-2-9. // Copyright © 2016年 Cirno MainasuK. All rights reserved. // import UIKit class CardDetailPageViewController: UIPageViewController { var cards = [Card]() var pageContentViewControllerIdentifier = "PageCardReviewViewController" var pageViewControllers = [UIViewController]() override func viewDidLoad() { super.viewDidLoad() self.dataSource = self // Create the first walkthrough screen if !cards.isEmpty { pageViewControllers.append(self.initViewControllerAIndex(0)!) setViewControllers([pageViewControllers.first!], direction: .Forward, animated: true, completion: nil) } else { let controller = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier(pageContentViewControllerIdentifier) as! PageCardReviewViewController controller.index = 0 setViewControllers([controller], direction: .Forward, animated: true, completion: nil) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func reloadCards(cards: [Card]) { self.cards = cards // save context pageViewControllers.removeAll() pageViewControllers.append(self.initViewControllerAIndex(0)!) setViewControllers([pageViewControllers.first!], direction: .Forward, animated: true, completion: nil) } private func initViewControllerAIndex(index: Int) -> UIViewController? { guard index != NSNotFound && index >= 0 && index < cards.count else { return nil } let controller = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier(pageContentViewControllerIdentifier) as! PageCardReviewViewController controller.index = index controller.card = cards[index] return controller } } extension CardDetailPageViewController: UIPageViewControllerDataSource { func pageViewController(pageViewController: UIPageViewController, viewControllerBeforeViewController viewController: UIViewController) -> UIViewController? { guard pageViewControllers.isEmpty == false else { return nil } let index = (viewController as? PageCardReviewViewController)!.pageIndex() - 1 if index <= -1 || index >= cards.count { return nil } guard index >= 0 && index < pageViewControllers.count else { return initViewControllerAIndex(index) } if let controller = pageViewControllers[index] as? PageCardReviewViewController { return controller } else { return initViewControllerAIndex(index) } } func pageViewController(pageViewController: UIPageViewController, viewControllerAfterViewController viewController: UIViewController) -> UIViewController? { guard pageViewControllers.isEmpty == false else { return nil } let index = (viewController as? PageCardReviewViewController)!.pageIndex() + 1 if index <= -1 || index >= cards.count { return nil } guard index >= 0 && index < pageViewControllers.count else { return initViewControllerAIndex(index) } if let controller = pageViewControllers[index] as? PageCardReviewViewController { return controller } else { return nil } } } protocol UIPageContentViewController { func pageIndex() -> Int }
mit
304b62dc9c4653d69c75c9c65b84909b
33.925926
178
0.654468
5.731003
false
false
false
false
ludoded/ReceiptBot
ReceiptBot/Scene/Inbox/DataSource/InboxDataSourceWorker.swift
1
1657
// // InboxDataSourceWorker.swift // ReceiptBot // // Created by Haik Ampardjian on 4/7/17. // Copyright (c) 2017 receiptbot. All rights reserved. // // This file was generated by the Clean Swift Xcode Templates so you can apply // clean architecture to your iOS and Mac projects, see http://clean-swift.com // import UIKit class InboxDataSourceWorker { let entityId: Int init(entityId: Int) { self.entityId = entityId } func fetchInvoices(callback: @escaping (RebotValueWrapper<[SyncConvertedInvoiceResponse]>) -> ()) { SyncConvertedInvoiceResponse.load(request: API.syncData(with: entityId)) { [unowned self] (invoicesResp, message) in guard message == nil else { callback(.none(message: message!)); return } guard let invoices = invoicesResp else { callback(.none(message: "Can't parse Sync Invoices Data!")); return } let filteredInvoices = self.removeExported(from: invoices) callback(.value(filteredInvoices)) } } private func removeExported(from invoices: [SyncConvertedInvoiceResponse]) -> [SyncConvertedInvoiceResponse] { let filteredInvoices = invoices.filter({ !($0.type.contains("Exported") || $0.type.contains("Split") || $0.type.contains("Modified")) }) /// Remove duplicates var exportedInvoices: [SyncConvertedInvoiceResponse] = [] for invoice in filteredInvoices where exportedInvoices.index(where: { $0.originalInvoiceId == invoice.originalInvoiceId }) == nil { exportedInvoices.append(invoice) } return exportedInvoices } }
lgpl-3.0
9db4ebe884746785c56d16976aa6d639
38.452381
144
0.664454
4.315104
false
false
false
false
gcmcnutt/Sensor2
sensor2/AppDelegate.swift
1
15005
// // AppDelegate.swift // sensor2 // // Created by Greg McNutt on 11/21/15. // Copyright © 2015 Greg McNutt. All rights reserved. // import UIKit import WatchConnectivity import Fabric import TwitterKit import Foundation @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, GIDSignInDelegate, WCSessionDelegate, AIAuthenticationDelegate { static let AMZN_TOKEN_VALID_ESTIMATE_SEC = 3000.0 var window: UIWindow? var viewController : ViewController! var infoPlist : NSDictionary! let wcsession = WCSession.default() // AWS plumbing var credentialsProvider : AWSCognitoCredentialsProvider! var auths : [ String : Any ] = [:] class AWSAuth { var token: String var expires: Date init(token : String, expires : Date) { self.token = token self.expires = expires } } var awsSem = DispatchSemaphore(value: 0) // some google sync... var googleSem = DispatchSemaphore(value: 0) func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool { // Override point for customization after application launch. let path = Bundle.main.path(forResource: "Info", ofType: "plist")! infoPlist = NSDictionary(contentsOfFile: path) viewController = self.window?.rootViewController as! ViewController // set up Cognito //AWSLogger.defaultLogger().logLevel = .Verbose credentialsProvider = AWSCognitoCredentialsProvider( regionType: AWSRegionType.usEast1, identityPoolId: infoPlist[AppGlobals.IDENTITY_POOL_ID_KEY] as! String) let defaultServiceConfiguration = AWSServiceConfiguration( region: AWSRegionType.usEast1, credentialsProvider: credentialsProvider) AWSServiceManager.default().defaultServiceConfiguration = defaultServiceConfiguration // amazon setup let delegate = AuthorizeUserDelegate(delegate: self) delegate.launchGetAccessToken() // google setup var configureError: NSError? GGLContext.sharedInstance().configureWithError(&configureError) assert(configureError == nil, "Error configuring Google services: \(configureError)") GIDSignIn.sharedInstance().delegate = self GIDSignIn.sharedInstance().signInSilently() // twitter setup Fabric.with([AWSCognito.self, Twitter.self]) let store = Twitter.sharedInstance().sessionStore auths[AWSIdentityProviderTwitter] = store.session() // facebook setup FBSDKApplicationDelegate.sharedInstance().application(application, didFinishLaunchingWithOptions: launchOptions) // wake up session to watch wcsession.delegate = self wcsession.activate() NSLog("application initialized") return true } func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool { // TODO seems a little clunky of a dispatcher... if (url.absoluteString.hasPrefix("amzn")) { return AIMobileLib.handleOpen(url, sourceApplication: options[UIApplicationOpenURLOptionsKey.sourceApplication] as! String!) } else if (url.absoluteString.hasPrefix("fb")) { return FBSDKApplicationDelegate.sharedInstance().application(app, open: url, sourceApplication: options[UIApplicationOpenURLOptionsKey.sourceApplication] as! String!, annotation: options[UIApplicationOpenURLOptionsKey.annotation]) } else { return GIDSignIn.sharedInstance().handle(url, sourceApplication: options[UIApplicationOpenURLOptionsKey.sourceApplication] as! String, annotation: options[UIApplicationOpenURLOptionsKey.annotation]) } } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } // amazon @objc func requestDidSucceed(_ apiResult: APIResult!) { NSLog("amazon: connect token") let token = apiResult.result as! String auths[AWSIdentityProviderLoginWithAmazon] = AWSAuth(token : token, expires : Date().addingTimeInterval(AppDelegate.AMZN_TOKEN_VALID_ESTIMATE_SEC)) // a little less than an hour awsSem.signal() genDisplay() } @objc func requestDidFail(_ errorResponse: APIError) { NSLog("amazon: connect failed=\(errorResponse.error.message)") auths.removeValue(forKey: AWSIdentityProviderLoginWithAmazon) awsSem.signal() // let alertController = UIAlertController(title: "", // message: "AccessToken:" + errorResponse.error.message, // preferredStyle: .Alert) // let defaultAction = UIAlertAction(title: "OK", style: .Default, handler: nil) // alertController.addAction(defaultAction) // viewController.presentViewController(alertController, animated: true, completion: nil) genDisplay() } // google func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error!) { if (error == nil) { NSLog("google: connect for \(user.userID)") auths[AWSIdentityProviderGoogle] = user.authentication googleSem.signal() } else { NSLog("\(error.localizedDescription)") auths.removeValue(forKey: AWSIdentityProviderGoogle) googleSem.signal() } genDisplay() } // google func sign(_ signIn: GIDSignIn!, didDisconnectWith user:GIDGoogleUser!, withError error: Error!) { NSLog("google disconnect for \(user.userID)") auths.removeValue(forKey: AWSIdentityProviderGoogle) genDisplay() } // twitter func twitterLogin(_ session : TWTRSession) { NSLog("twitter: connect for \(session.userID)") auths[AWSIdentityProviderTwitter] = session genDisplay() } func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) { NSLog(String(format: "state=%d", activationState.rawValue)) } func sessionDidBecomeInactive(_ session: WCSession) { NSLog("session did become inactive") } func sessionDidDeactivate(_ session: WCSession) { NSLog("session did deactivate") } // message from watch func session(_ session: WCSession, didReceiveMessage message: [String : Any], replyHandler: @escaping ([String : Any]) -> Void) { NSLog("session message " + message.description) if (message[AppGlobals.SESSION_ACTION] as! String == AppGlobals.GET_CREDENTIALS) { var taskResult : AWSTask<AWSCredentials>! let sem = DispatchSemaphore(value: 0) let now = Date() var logins : [ String : Any ] = [:] // amazon do { let auth = auths[AWSIdentityProviderLoginWithAmazon] as? AWSAuth if (auth == nil || auth!.expires.compare(now) == ComparisonResult.orderedAscending) { NSLog("amazon: trigger refresh...") auths[AWSIdentityProviderLoginWithAmazon] = nil awsSem = DispatchSemaphore(value: 0) let delegate = AuthorizeUserDelegate(delegate: self) delegate.launchGetAccessToken() // wait up to 15 seconds _ = awsSem.wait(timeout: DispatchTime.now() + Double(Int64(15 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)) } // load amazon auth if let authNew = auths[AWSIdentityProviderLoginWithAmazon] as? AWSAuth { NSLog("amazon: refresh found token=\(authNew.token), expires=\(authNew.expires)") logins[AWSIdentityProviderLoginWithAmazon] = authNew.token } else { NSLog("amazon: refresh found no token") } } // google do { let auth = auths[AWSIdentityProviderGoogle] as? GIDAuthentication if (auth == nil || auth!.accessTokenExpirationDate.compare(now) == ComparisonResult.orderedAscending) { // sync get google token NSLog("google: trigger refresh...") auths[AWSIdentityProviderGoogle] = nil googleSem = DispatchSemaphore(value: 0) DispatchQueue.main.async { GIDSignIn.sharedInstance().signInSilently() } // wait up to 15 seconds _ = googleSem.wait(timeout: DispatchTime.now() + Double(Int64(15 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)) } // load google login if let authNew = auths[AWSIdentityProviderGoogle] as? GIDAuthentication { NSLog("google: refresh found token=\(authNew.idToken), expires=\(authNew.idTokenExpirationDate)") logins[AWSIdentityProviderGoogle] = authNew.idToken } else { NSLog("google: refresh found no token") } } // twitter -- no expire do { // load twitter login if let authNew = auths[AWSIdentityProviderTwitter] as? TWTRSession { NSLog("twitter: refresh found token=\(authNew.authToken)") let value = authNew.authToken + ";" + authNew.authTokenSecret logins[AWSIdentityProviderTwitter] = value } else { NSLog("twitter: no authToken found") } } // facebook -- no expire do { if let token = FBSDKAccessToken.current()?.tokenString { NSLog("facebook: refresh found token=\(token)") logins[AWSIdentityProviderFacebook] = token } else { NSLog("facebook: refresh found no token") } } // updated list of logins let providerManager = CognitoCustomProviderManager(tokens: logins) credentialsProvider.setIdentityProviderManagerOnce(providerManager) credentialsProvider.credentials().continue({ (task:AWSTask<AWSCredentials>) -> AnyObject? in taskResult = task sem.signal() return task }) _ = sem.wait(timeout: DispatchTime.distantFuture) if (taskResult.error == nil) { let credentials = taskResult.result! NSLog("logins[\(logins)], expiration[\(credentials.expiration)], accessKey[\(credentials.accessKey)], secretKey[\(credentials.secretKey)], sessionKey[\(credentials.sessionKey)]") let reply = [AppGlobals.CRED_COGNITO_KEY : credentialsProvider.identityId!, AppGlobals.CRED_ACCESS_KEY : credentials.accessKey, AppGlobals.CRED_SECRET_KEY : credentials.secretKey, AppGlobals.CRED_SESSION_KEY : credentials.sessionKey!, AppGlobals.CRED_EXPIRATION_KEY : credentials.expiration!] as [String : Any] replyHandler(reply) } else { NSLog("error fetching credentials: \(taskResult.error!.localizedDescription)") viewController.updateErrorState(taskResult.error!.localizedDescription) replyHandler([:]) } } } func clearCredentials() { NSLog("clear credentials...") credentialsProvider.clearKeychain() auths = [:] wcsession.sendMessage([AppGlobals.SESSION_ACTION : AppGlobals.CLEAR_CREDENTIALS], replyHandler: nil, errorHandler: nil) genDisplay() } func genDisplay() { var amznTime = "" var googTime = "" var twtrTime = "" var fbTime = "" if let amzn = auths[AWSIdentityProviderLoginWithAmazon] as? AWSAuth { amznTime = amzn.expires.description } if let goog = auths[AWSIdentityProviderGoogle] as? GIDAuthentication { googTime = goog.accessTokenExpirationDate.description } if auths[AWSIdentityProviderTwitter] != nil { twtrTime = "valid" } if FBSDKAccessToken.current()?.tokenString != nil { fbTime = FBSDKAccessToken.current().expirationDate.description } viewController.updateLoginState(amznTime, goog: googTime, twtr: twtrTime, fb: fbTime) } }
apache-2.0
ddc8ba8e10313c87f3421a324735f87d
44.329305
285
0.603906
5.590164
false
false
false
false
HarrisLee/Utils
MySampleCode-master/CustomTransition/CustomTransition-Swift/CustomTransition-Swift/Interactivity/InteractivityTransitionAnimator.swift
1
3338
// // InteractivityTransitionAnimator.swift // CustomTransition-Swift // // Created by 张星宇 on 16/2/8. // Copyright © 2016年 zxy. All rights reserved. // import UIKit class InteractivityTransitionAnimator: NSObject, UIViewControllerAnimatedTransitioning { let targetEdge: UIRectEdge init(targetEdge: UIRectEdge) { self.targetEdge = targetEdge } func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval { return 0.35 } func animateTransition(transitionContext: UIViewControllerContextTransitioning) { let fromViewController = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey) let toViewController = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey) let containerView = transitionContext.containerView() var fromView = fromViewController?.view var toView = toViewController?.view if transitionContext.respondsToSelector(Selector("viewForKey:")) { fromView = transitionContext.viewForKey(UITransitionContextFromViewKey) toView = transitionContext.viewForKey(UITransitionContextToViewKey) } /// isPresenting用于判断当前是present还是dismiss let isPresenting = (toViewController?.presentingViewController == fromViewController) let fromFrame = transitionContext.initialFrameForViewController(fromViewController!) let toFrame = transitionContext.finalFrameForViewController(toViewController!) /// offset结构体将用于计算toView的位置 let offset: CGVector switch self.targetEdge { case UIRectEdge.Top: offset = CGVectorMake(0, 1) case UIRectEdge.Bottom: offset = CGVectorMake(0, -1) case UIRectEdge.Left: offset = CGVectorMake(1, 0) case UIRectEdge.Right: offset = CGVectorMake(-1, 0) default:fatalError("targetEdge must be one of UIRectEdgeTop, UIRectEdgeBottom, UIRectEdgeLeft, or UIRectEdgeRight.") } /// 根据当前是dismiss还是present,横屏还是竖屏,计算好toView的初始位置以及结束位置 if isPresenting { fromView?.frame = fromFrame toView?.frame = CGRectOffset(toFrame, toFrame.size.width * offset.dx * -1, toFrame.size.height * offset.dy * -1) containerView?.addSubview(toView!) } else { fromView?.frame = fromFrame toView?.frame = toFrame containerView?.insertSubview(toView!, belowSubview: fromView!) } UIView.animateWithDuration(self.transitionDuration(transitionContext), animations: { () -> Void in if isPresenting { toView?.frame = toFrame } else { fromView?.frame = CGRectOffset(fromFrame, fromFrame.size.width * offset.dx, fromFrame.size.height * offset.dy) } }) { (finished: Bool) -> Void in let wasCanceled = transitionContext.transitionWasCancelled() if wasCanceled {toView?.removeFromSuperview()} transitionContext.completeTransition(!wasCanceled) } } }
mit
24490050bb201452ef8292d182e8bf29
42.08
124
0.661715
6.005576
false
false
false
false
hulinSun/Better
better/better/Classes/Home/Tool/HomeModel.swift
1
4471
// // Topic.swift // better // // Created by Hony on 2016/10/26. // Copyright © 2016年 Hony. All rights reserved. // import UIKit import HandyJSON import ObjectMapper /// 话题的 账号模型 class User: Mappable , HandyJSON { var user_id: String? /// 用户id var nickname: String? /// 用户昵称 var avatar: String? /// 用户头像 var is_official: Bool = false /// 是否签约? var article_topic_count: String? /// 话题个数 var post_count: String?/// 转发数 required init?(map: Map){} func mapping(map: Map) { user_id <- map["user_id"] nickname <- map["nickname"] avatar <- map["avatar"] is_official <- map["is_official"] article_topic_count <- map["article_topic_count"] post_count <- map["post_count"] } required init() {} /// 如果是结构体,这个都可以不写 } /// 话题模型 class Topic: Mappable , HandyJSON { var id: String? var type: String? var type_id: String? var title: String? var subtitle: String? var pic: String? var desc: String? var is_show_like: Bool = false var is_recommend: Bool = false var create_time_str: String? var islike: Bool = false var likes: String? var views: String? var comments: String? var update_time: String? var order_time_str: String? var user: User? var pics: [Pics] = [Pics]() var channel: [String: AnyObject]? var video: [String: AnyObject]? required init?(map: Map){} func mapping(map: Map) { id <- map["id"] type <- map["type"] type_id <- map["type_id"] title <- map["title"] subtitle <- map["subtitle"] pic <- map["pic"] is_show_like <- map["is_show_like"] is_recommend <- map["is_recommend"] create_time_str <- map["create_time_str"] islike <- map["islike"] likes <- map["likes"] views <- map["views"] comments <- map["comments"] update_time <- map["update_time"] user <- map["user"] pics <- map["pics"] channel <- map["channel"] video <- map["video"] } required init() {} } /// 首页轮播图对应的模型 class Banner: Mappable , HandyJSON { var id: String? var title: String? var sub_title: String? var type: String? var topic_type: String? var photo: String? var extend: String? var browser_url: String? var index: String? var parent_id: String? var photo_width: String? var photo_height: String? var is_show_icon: Bool = false required init?(map: Map){} func mapping(map: Map) { id <- map["id"] title <- map["title"] sub_title <- map["sub_title"] type <- map["type"] topic_type <- map["topic_type"] photo <- map["photo"] extend <- map["extend"] browser_url <- map["browser_url"] index <- map["index"] parent_id <- map["parent_id"] photo_width <- map["photo_width"] photo_height <- map["photo_height"] is_show_icon <- map["is_show_icon"] } required init() {} } class HomeData: Mappable , HandyJSON { class InsertElement: Mappable , HandyJSON{ var index: Double = 0 var element_list: [Banner]? required init?(map: Map){} func mapping(map: Map) { index <- map["index"] element_list <- map["element_list"] } required init() {} } var topic: [Topic]? var append_extend: [String: AnyObject]? var banner : [Banner]? var category_element: [Banner]? var insert_element: [InsertElement]? required init?(map: Map){} func mapping(map: Map) { topic <- map["topic"] append_extend <- map["append_extend"] banner <- map["banner"] category_element <- map["category_element"] insert_element <- map["insert_element"] } required init() {} } /// 最终的大模型 class HomePageModel: Mappable , HandyJSON { var status: String? var msg: String? var ts: Double = 0 var data :HomeData? required init?(map: Map){} func mapping(map: Map) { status <- map["status"] msg <- map["msg"] ts <- map["ts"] data <- map["data"] } required init() {} }
mit
dd6b05d11d84230dca7795a176ce0d45
21.497409
57
0.540534
3.79214
false
false
false
false
kstaring/swift
validation-test/compiler_crashers_fixed/00969-swift-diagnosticengine-flushactivediagnostic.swift
11
1048
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -parse return ""a<T>) + seq: T>(n: d = F>() class func a extension Array { } func e() typealias F = Int]) A>(Any) { () -> Any in typealias F>] = b<T -> () -> V>(b> { class func f() } func a<c]() func g() -> (#object1, Any) func g: A, a struct c == 0.C(Range(a") class B { import Foundation public class d<T { typealias e, g<T -> { } func call(t: B? { protocol d where h, f(A, Any, k : B>) { let a { print(a(true { } print(Any, let v: [B func d>(a) func b(") } } struct c<T where B : a { class A : C { protocol P {} extension NSSet { enum S<U -> { return self.h : A, range.B } } return true func e: d where H) { private class func a: Sequence> { } } } } } } retur
apache-2.0
28d65df889f26fd1071f276794ef7377
17.714286
78
0.635496
2.787234
false
false
false
false
geasscode/TodoList
ToDoListApp/ToDoListApp/ViewController.swift
1
3730
// // ViewController.swift // ToDoListApp // // Created by desmond on 10/28/14. // Copyright (c) 2014 Phoenix. All rights reserved. // import UIKit class MyViewController: UITabBarController { override func viewDidLoad() { super.viewDidLoad() var todoList: UIStoryboard! todoList = UIStoryboard(name: "Main", bundle: nil) // let todolistNav: UINavigationController = todoList.instantiateViewControllerWithIdentifier("todoListTask") as UINavigationController let todolistVC = TodoListTableViewController() let headerVC = HeaderVC() let addVC = UserAddVC() let dateVC = DatePickerController() // var contactsVC = OrderFood(nibName: "OrderFood", bundle:NSBundle.mainBundle()) // var orderVC = OrderViewController(nibName: "OrderViewController", bundle: NSBundle .mainBundle()) // var threeView = FinishContactsVC() let firstImage = UIImage(named: "icon-calendar.png") let secondImage = UIImage(named: "icon-contacts.png") var oneTabBarItem: UITabBarItem = UITabBarItem(title: "todo", image: firstImage, tag: 0) var twoTabBarItem: UITabBarItem = UITabBarItem(title: "addvc", image: secondImage, tag: 1) var threeTabBarItem: UITabBarItem = UITabBarItem(tabBarSystemItem: UITabBarSystemItem.Contacts, tag: 2) var fouthTabBarItem: UITabBarItem = UITabBarItem(tabBarSystemItem: UITabBarSystemItem.Favorites, tag: 3) threeTabBarItem.badgeValue = "2" fouthTabBarItem.badgeValue = "3" todolistVC.tabBarItem = oneTabBarItem addVC.tabBarItem = twoTabBarItem headerVC.tabBarItem = threeTabBarItem dateVC.tabBarItem = fouthTabBarItem // todolistNav.viewControllers = [todolistVC,addVC,headerVC,dateVC] // self.viewControllers = todolistNav.viewControllers // orderVC.tabBarItem = twoTabBarItem // threeView.tabBarItem = threeTabBarItem var todoListNav: UINavigationController = UINavigationController(rootViewController: todolistVC) var useraddVCNav: UINavigationController = UINavigationController(rootViewController: addVC) var headerNav: UINavigationController = UINavigationController(rootViewController: headerVC) var dateNav: UINavigationController = UINavigationController(rootViewController: dateVC) self.viewControllers = [todoListNav,useraddVCNav,headerVC,dateNav] //self.selectedViewController = self.viewControllers?[2] as HeaderVC self.selectedIndex = 1 // self.navigationController?.pushViewController(self.tabBarController!, animated: true) // self.selectedViewController = self.viewControllers?.count // self.tabBarController?.selectedIndex = 2 // Do any additional setup after loading the view, typically from a nib. } override func viewDidAppear(animated: Bool) { // var selectedImage0 : UIImage = UIImage(named:"selectedImage0.png").imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal) // self.navigationController.tabBarItem.selectedImage = selectedImage0 // let firstImage = UIImage(named: "icon-calendar.png") // // let tabBar = self.tabBar // // // UITabBar Items are an array in order (0 is the first item) // let tabItems = tabBar.items as [UITabBarItem] // tabItems[0].title = "geass" // tabItems[0].selectedImage = firstImage } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
ff1745ad39aacd2e904d4ea73044058f
37.453608
143
0.682038
4.986631
false
false
false
false
SunshineYG888/YG_NetEaseOpenCourse
YG_NetEaseOpenCourse/YG_NetEaseOpenCourse/Classes/View/YGSearchKeyWordsTableViewController.swift
1
3994
// // YGSearchKeyWordsTableViewController.swift // YG_NetEaseOpenCourse // // Created by male on 16/4/20. // Copyright © 2016年 yg. All rights reserved. // import UIKit let KeyWorddCell = "KeyWorddCell" let HotKeyWordViewHeight: CGFloat = 30 let HotKeyWordViewMargin: CGFloat = 10 class YGSearchKeyWordsTableViewController: UITableViewController { var hotKeyWords: [YGHotKeyWord]? override func viewDidLoad() { super.viewDidLoad() tableView.frame.origin.y += NavBarHeight tableView.registerClass(YGHotKeyWordCell.self, forCellReuseIdentifier: KeyWorddCell) tableView.rowHeight = 35 loadData() } /* 动画出场, tableView 添加到 window 上 */ func show() { YGSearchHistoryManager.sharedSearchHistoryManager.loadSearchedKeyWords() if YGSearchHistoryManager.sharedSearchHistoryManager.searchedKeyWords.count > 0 { let headerView = YGSearchHistoryView() tableView.tableHeaderView = headerView headerView.ClearBtnDidClick = { let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel, handler: { (_) -> Void in }) let sureAction = UIAlertAction(title: "Sure", style: .Destructive, handler: { (_) -> Void in YGSearchHistoryManager.sharedSearchHistoryManager.clearAllWords() self.tableView.tableHeaderView = nil }) let alertVC = UIAlertController(title: "Warning", message: "Sure to clear all words?", preferredStyle: .Alert) alertVC.addAction(cancelAction) alertVC.addAction(sureAction) self.presentViewController(alertVC, animated: true, completion: nil) } } UIApplication.sharedApplication().keyWindow?.addSubview(tableView) // 动画出场 tableView.frame.origin.x = ScreenWidth UIView.animateWithDuration(0.3) { () -> Void in self.tableView.frame.origin.x = 0 } } /* 动画离开 */ func dismiss() { UIView.animateWithDuration(0.3, animations: { () -> Void in self.tableView.frame.origin.x = ScreenWidth }) { (_) -> Void in self.tableView.removeFromSuperview() self.tableView.tableHeaderView?.removeFromSuperview() } } } /* tableView's dataSource && delegate */ extension YGSearchKeyWordsTableViewController { override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return hotKeyWords?.count ?? 0 } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(KeyWorddCell, forIndexPath: indexPath) as! YGHotKeyWordCell if let hotKeyWords = hotKeyWords { cell.hotKeyWord = hotKeyWords[indexPath.row] } return cell } override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { return YGHotKeyWordsSectionHeaderView() } override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { print("--------------->>>") return HotKeyWordViewMargin + HotKeyWordViewHeight } } /* 加载数据 */ extension YGSearchKeyWordsTableViewController { private func loadData() { // 读取"热搜关键字"的数据并更新界面 YGHotKeyWordsViewModel.sharedHotKeyWordViewModel.loadHotKeyWordsData { (isSuccess) -> () in if !isSuccess { print("error") } self.hotKeyWords = YGHotKeyWordsViewModel.sharedHotKeyWordViewModel.hotKeyWords self.tableView.reloadData() } } }
mit
62fc7bd290dd1e0df293018a57a71fd4
34.972477
126
0.642693
5.001276
false
false
false
false
mightydeveloper/swift
test/Generics/associated_types.swift
10
2493
// RUN: %target-parse-verify-swift // Deduction of associated types. protocol Fooable { typealias AssocType func foo(x : AssocType) } struct X : Fooable { func foo(x: Float) {} } struct Y<T> : Fooable { func foo(x: T) {} } struct Z : Fooable { func foo(x: Float) {} func blah() { var a : AssocType // expected-warning {{variable 'a' was never used; consider replacing with '_' or removing it}} {{9-10=_}} } // FIXME: We should be able to find this. func blarg() -> AssocType {} // expected-error{{use of undeclared type 'AssocType'}} func wonka() -> Z.AssocType {} } var xa : X.AssocType = Float() var yf : Y<Float>.AssocType = Float() var yd : Y<Double>.AssocType = Double() var f : Float f = xa f = yf var d : Double d = yd protocol P1 { typealias Assoc1 func foo() -> Assoc1 } struct S1 : P1 { func foo() -> X {} } prefix operator % {} protocol P2 { typealias Assoc2 prefix func %(target: Self) -> Assoc2 } prefix func % <P:P1>(target: P) -> P.Assoc1 { } extension S1 : P2 { typealias Assoc2 = X } // <rdar://problem/14418181> protocol P3 { typealias Assoc3 func foo() -> Assoc3 } protocol P4 : P3 { typealias Assoc4 func bar() -> Assoc4 } func takeP4<T : P4>(x: T) { } struct S4<T> : P3, P4 { func foo() -> Int {} func bar() -> Double {} } takeP4(S4<Int>()) // <rdar://problem/14680393> infix operator ~> { precedence 255 } protocol P5 { } struct S7a {} protocol P6 { func foo<Target: P5>(inout target: Target) } protocol P7 : P6 { typealias Assoc : P6 func ~> (x: Self, _: S7a) -> Assoc } func ~> <T:P6>(x: T, _: S7a) -> S7b { return S7b() } struct S7b : P7 { typealias Assoc = S7b func foo<Target: P5>(inout target: Target) {} } // <rdar://problem/14685674> struct zip<A: GeneratorType, B: GeneratorType> : GeneratorType, SequenceType { func next() -> (A.Element, B.Element)? { } typealias Generator = zip func generate() -> zip { } } protocol P8 { } protocol P9 { typealias A1 : P8 } protocol P10 { typealias A1b : P8 typealias A2 : P9 func f() func g(a: A1b) func h(a: A2) } struct X8 : P8 { } struct Y9 : P9 { typealias A1 = X8 } struct Z10 : P10 { func f() { } func g(a: X8) { } func h(a: Y9) { } } struct W : Fooable { func foo(x: String) {} } struct V<T> : Fooable { func foo(x: T) {} } // FIXME: <rdar://problem/16123805> Inferred associated types can't be used in expression contexts var w = W.AssocType() var v = V<String>.AssocType()
apache-2.0
0596b982c90eea2de93de14921e409cd
15.294118
128
0.606899
2.832955
false
false
false
false
Moon1102/Swift-Server
Sources/Extension.swift
1
1204
// // Extension.swift // PerfectTemplate // // Created by Cheer on 16/11/16. // // import MongoDB #if os(Linux) import SwiftGlibc import Foundation #else import Cocoa #endif extension String { func trim() -> String { return self == "" ? self : trimmingCharacters(in: CharacterSet(charactersIn: ", \n")) } } func doMongoDB(code:(_ collection:MongoCollection) throws -> Void) { do { let client = try! MongoClient(uri: "mongodb://localhost:27017") guard client.databaseNames().count > 0 else{throw crawlerError(msg:"数据库缺少表")} let db = client.getDatabase(name: "test") guard let collection = db.getCollection(name: "movie-data") else { return } try code(collection) defer { collection.close() db.close() client.close() } } catch { print(error) } } //func timerTask(with timeInterval:UInt32,code:@escaping ()->Void) //{ // DispatchQueue.global().asyncAfter(deadline: .now() + 5) { // code() // sleep(timeInterval) // timerTask(with: timeInterval, code: code) // } // //}
apache-2.0
139fb9afb9ae3c47d3c1f09e11a1c903
19.20339
93
0.567114
3.772152
false
false
false
false
debugsquad/nubecero
nubecero/Controller/Photos/CPhotosAlbumSelection.swift
1
933
import UIKit class CPhotosAlbumSelection:CController { private weak var viewSelect:VPhotosAlbumSelection! private weak var delegate:CPhotosAlbumSelectionDelegate? weak var currentAlbum:MPhotosItem? convenience init(currentAlbum:MPhotosItem?, delegate:CPhotosAlbumSelectionDelegate) { self.init() self.currentAlbum = currentAlbum self.delegate = delegate } override func loadView() { let viewSelect:VPhotosAlbumSelection = VPhotosAlbumSelection(controller:self) self.viewSelect = viewSelect view = viewSelect } //MARK: public func selected(album:MPhotosItem) { parentController.dismiss(centered:true) { [weak delegate] in delegate?.albumSelected(album:album) } } func cancel() { parentController.dismiss(centered:true, completion:nil) } }
mit
d259c2d5f57ef5b0f1e5249798f2a4ca
23.552632
87
0.651661
4.834197
false
false
false
false
JimCampagno/Marvel-iOS
Marvel/MarvelAPIManager.swift
1
993
// // MarvelAPIManager.swift // Marvel // // Created by Jim Campagno on 12/1/16. // Copyright © 2016 Jim Campagno. All rights reserved. // import Foundation typealias JSON = [String : Any] final class MarvelAPIManager { static let shared = MarvelAPIManager() private init() { } func get(request: MarvelRequest, handler: @escaping (Bool, JSON?) -> Void) { guard let url = request.url else { handler(false, nil); return } let request = URLRequest(url: url) URLSession.shared.dataTask(with: request) { data, response, error in DispatchQueue.main.async { guard let rawData = data else { handler(false, nil); return } let json = try! JSONSerialization.jsonObject(with: rawData, options: .allowFragments) as! JSON print("We have data from internet, returning JSON.") handler(true, json) } }.resume() } }
mit
2353a1a84af1238fea32ebf432faea4b
27.342857
110
0.587702
4.44843
false
false
false
false
atrick/swift
SwiftCompilerSources/Sources/Optimizer/Analysis/AliasAnalysis.swift
2
2398
//===--- AliasAnalysis.swift - the alias analysis -------------------------===// // // 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 OptimizerBridging import SIL struct AliasAnalysis { let bridged: BridgedAliasAnalysis func mayRead(_ inst: Instruction, fromAddress: Value) -> Bool { switch AliasAnalysis_getMemBehavior(bridged, inst.bridged, fromAddress.bridged) { case MayReadBehavior, MayReadWriteBehavior, MayHaveSideEffectsBehavior: return true default: return false } } func mayWrite(_ inst: Instruction, toAddress: Value) -> Bool { switch AliasAnalysis_getMemBehavior(bridged, inst.bridged, toAddress.bridged) { case MayWriteBehavior, MayReadWriteBehavior, MayHaveSideEffectsBehavior: return true default: return false } } func mayReadOrWrite(_ inst: Instruction, address: Value) -> Bool { switch AliasAnalysis_getMemBehavior(bridged, inst.bridged, address.bridged) { case MayReadBehavior, MayWriteBehavior, MayReadWriteBehavior, MayHaveSideEffectsBehavior: return true default: return false } } /// Returns the correct path for address-alias functions. static func getPtrOrAddressPath(for value: Value) -> EscapeInfo.Path { let ty = value.type if ty.isAddress { // This is the regular case: the path selects any sub-fields of an address. return EscapeInfo.Path(.anyValueFields) } // Some optimizations use the address-alias APIs with non-address SIL values. // TODO: this is non-intuitive and we should eliminate those API uses. if ty.isClass { // If the value is a (non-address) reference it means: all addresses within the class instance. return EscapeInfo.Path(.anyValueFields).push(.anyClassField) } // Any other non-address value means: all addresses of any referenced class instances within the value. return EscapeInfo.Path(.anyValueFields).push(.anyClassField).push(.anyValueFields) } }
apache-2.0
ee2b9a47fe2925b4331fcf42571ea74d
37.063492
107
0.683903
4.611538
false
false
false
false
breadwallet/breadwallet-ios
breadwallet/src/ViewModels/TxListViewModel.swift
1
2033
// // TxListViewModel.swift // breadwallet // // Created by Ehsan Rezaie on 2018-01-13. // Copyright © 2018-2019 Breadwinner AG. All rights reserved. // import UIKit /// View model of a transaction in list view struct TxListViewModel: TxViewModel { // MARK: - Properties let tx: Transaction var shortDescription: String { let isComplete = tx.status == .complete if let comment = comment, !comment.isEmpty { return comment } else if let tokenCode = tokenTransferCode { return String(format: S.Transaction.tokenTransfer, tokenCode.uppercased()) } else { var address = tx.toAddress var format: String switch tx.direction { case .sent, .recovered: format = isComplete ? S.Transaction.sentTo : S.Transaction.sendingTo case .received: if !tx.currency.isBitcoinCompatible { format = isComplete ? S.Transaction.receivedFrom : S.Transaction.receivingFrom address = tx.fromAddress } else { format = isComplete ? S.Transaction.receivedVia : S.Transaction.receivingVia } } return String(format: format, address) } } func amount(showFiatAmounts: Bool, rate: Rate) -> NSAttributedString { var amount = tx.amount if tokenTransferCode != nil { // this is the originating tx of a token transfer, so the amount is 0 but we want to show the fee amount = tx.fee } let text = Amount(amount: amount, rate: showFiatAmounts ? rate : nil, negative: (tx.direction == .sent)).description let color: UIColor = (tx.direction == .received) ? .receivedGreen : .darkGray return NSMutableAttributedString(string: text, attributes: [.foregroundColor: color]) } }
mit
a0a4cc580e1df36709a7d6aad8107e05
33.440678
109
0.568406
4.944039
false
false
false
false
breadwallet/breadwallet-ios
breadwallet/src/Views/AnimatedIcons/CheckView.swift
1
4061
// // CheckView.swift // breadwallet // // Created by Adrian Corscadden on 2016-11-22. // Copyright © 2016-2019 Breadwinner AG. All rights reserved. // import UIKit class CheckView: UIView, AnimatableIcon { func startAnimating() { let check = UIBezierPath() check.move(to: CGPoint(x: 32.5, y: 47.0)) check.addLine(to: CGPoint(x: 43.0, y: 57.0)) check.addLine(to: CGPoint(x: 63, y: 37.4)) let shape = CAShapeLayer() shape.path = check.cgPath shape.lineWidth = 9.0 shape.strokeColor = UIColor.white.cgColor shape.fillColor = UIColor.clear.cgColor shape.strokeStart = 0.0 shape.strokeEnd = 0.0 shape.lineCap = CAShapeLayerLineCap.round shape.lineJoin = CAShapeLayerLineJoin.round layer.addSublayer(shape) let animation = CABasicAnimation(keyPath: "strokeEnd") animation.toValue = 1.0 animation.isRemovedOnCompletion = false animation.fillMode = CAMediaTimingFillMode.forwards animation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.default) animation.duration = 0.3 shape.add(animation, forKey: nil) } func stopAnimating() { } override func draw(_ rect: CGRect) { let checkcircle = UIBezierPath() checkcircle.move(to: CGPoint(x: 47.76, y: -0)) checkcircle.addCurve(to: CGPoint(x: 0, y: 47.76), controlPoint1: CGPoint(x: 21.38, y: -0), controlPoint2: CGPoint(x: 0, y: 21.38)) checkcircle.addCurve(to: CGPoint(x: 47.76, y: 95.52), controlPoint1: CGPoint(x: 0, y: 74.13), controlPoint2: CGPoint(x: 21.38, y: 95.52)) checkcircle.addCurve(to: CGPoint(x: 95.52, y: 47.76), controlPoint1: CGPoint(x: 74.14, y: 95.52), controlPoint2: CGPoint(x: 95.52, y: 74.13)) checkcircle.addCurve(to: CGPoint(x: 47.76, y: -0), controlPoint1: CGPoint(x: 95.52, y: 21.38), controlPoint2: CGPoint(x: 74.14, y: -0)) checkcircle.addLine(to: CGPoint(x: 47.76, y: -0)) checkcircle.close() checkcircle.move(to: CGPoint(x: 47.99, y: 85.97)) checkcircle.addCurve(to: CGPoint(x: 9.79, y: 47.76), controlPoint1: CGPoint(x: 26.89, y: 85.97), controlPoint2: CGPoint(x: 9.79, y: 68.86)) checkcircle.addCurve(to: CGPoint(x: 47.99, y: 9.55), controlPoint1: CGPoint(x: 9.79, y: 26.66), controlPoint2: CGPoint(x: 26.89, y: 9.55)) checkcircle.addCurve(to: CGPoint(x: 86.2, y: 47.76), controlPoint1: CGPoint(x: 69.1, y: 9.55), controlPoint2: CGPoint(x: 86.2, y: 26.66)) checkcircle.addCurve(to: CGPoint(x: 47.99, y: 85.97), controlPoint1: CGPoint(x: 86.2, y: 68.86), controlPoint2: CGPoint(x: 69.1, y: 85.97)) checkcircle.close() UIColor.white.setFill() checkcircle.fill() //This is the non-animated check left here for now as a reference // let check = UIBezierPath() // check.move(to: CGPoint(x: 30.06, y: 51.34)) // check.addCurve(to: CGPoint(x: 30.06, y: 44.75), controlPoint1: CGPoint(x: 28.19, y: 49.52), controlPoint2: CGPoint(x: 28.19, y: 46.57)) // check.addCurve(to: CGPoint(x: 36.9, y: 44.69), controlPoint1: CGPoint(x: 32, y: 42.87), controlPoint2: CGPoint(x: 35.03, y: 42.87)) // check.addLine(to: CGPoint(x: 42.67, y: 50.3)) // check.addLine(to: CGPoint(x: 58.62, y: 34.79)) // check.addCurve(to: CGPoint(x: 65.39, y: 34.8), controlPoint1: CGPoint(x: 60.49, y: 32.98), controlPoint2: CGPoint(x: 63.53, y: 32.98)) // check.addCurve(to: CGPoint(x: 65.46, y: 41.45), controlPoint1: CGPoint(x: 67.33, y: 36.68), controlPoint2: CGPoint(x: 67.33, y: 39.63)) // check.addLine(to: CGPoint(x: 45.33, y: 61.02)) // check.addCurve(to: CGPoint(x: 40.01, y: 61.02), controlPoint1: CGPoint(x: 43.86, y: 62.44), controlPoint2: CGPoint(x: 41.48, y: 62.44)) // check.addLine(to: CGPoint(x: 30.06, y: 51.34)) // check.close() // check.move(to: CGPoint(x: 30.06, y: 51.34)) // // UIColor.green.setFill() // check.fill() } }
mit
ceb4ea37de127f489c43a6d46323e3fd
48.512195
149
0.622414
3.10635
false
false
false
false
WickedColdfront/Slide-iOS
Slide for Reddit/CaptionView.swift
1
1071
// // ImageCounterView.swift // Money // // Created by Kristian Angyal on 07/03/2016. // Copyright © 2016 Mail Online. All rights reserved. // import UIKit class CaptionView: UIView { let captionLabel = UILabel() var text: String { didSet { updateLabel() } } override init(frame: CGRect) { text = "" super.init(frame: frame) configureLabel() updateLabel() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func configureLabel() { self.addSubview(captionLabel) } func updateLabel() { captionLabel.numberOfLines = 0 captionLabel.attributedText = NSAttributedString(string: text, attributes: [NSFontAttributeName: FontGenerator.fontOfSize(size: 15, submission: false), NSForegroundColorAttributeName: UIColor.white]) } override func layoutSubviews() { super.layoutSubviews() captionLabel.frame = self.bounds } }
apache-2.0
f91c558fb4bf549f6cf8b839d4b91939
22.777778
207
0.61028
4.885845
false
false
false
false
bumpersfm/handy
Handy/UICollectionView.swift
1
2025
// // UICollectionView.swift // Pods // // Created by Dani Postigo on 8/31/16. // // import Foundation extension UICollectionView { public func scrollToItemAtIndexPath(indexPath: NSIndexPath, atScrollPosition scrollPosition: UICollectionViewScrollPosition, completion: ((Bool) -> Void)? = nil) { if let cell = self.cellForItemAtIndexPath(indexPath) { let point = self.pointForRect(CGRectOffset(cell.frame, -self.contentInset.left, -self.contentInset.top), atScrollPosition: scrollPosition) UIView.animateWithDuration(0.4, animations: { self.contentOffset = point }, completion: completion) } } private func pointForRect(rect: CGRect, atScrollPosition scrollPosition: UICollectionViewScrollPosition) -> CGPoint { switch scrollPosition { case UICollectionViewScrollPosition.Top: return CGPoint(x: rect.minX, y: rect.minY) case UICollectionViewScrollPosition.CenteredVertically: return CGPoint(x: rect.minX, y: rect.midY) case UICollectionViewScrollPosition.Bottom: return CGPoint(x: rect.minX, y: rect.maxY) case UICollectionViewScrollPosition.Left: return CGPoint(x: rect.minX, y: rect.minY) case UICollectionViewScrollPosition.CenteredHorizontally: return CGPoint(x: rect.midX, y: rect.minY) case UICollectionViewScrollPosition.Right: return CGPoint(x: rect.maxX, y: rect.minY) default: return self.contentOffset } } } extension UICollectionReusableView { public static var identifier: String { return String(self) } } extension UICollectionViewFlowLayout { public convenience init(scrollDirection: UICollectionViewScrollDirection) { self.init() self.scrollDirection = scrollDirection } public convenience init(scrollDirection: UICollectionViewScrollDirection, estimatedItemSize: CGSize) { self.init() self.scrollDirection = scrollDirection self.estimatedItemSize = estimatedItemSize } }
mit
51df752753e33475cb0a4b46db5a5878
39.52
167
0.718025
5.152672
false
false
false
false
nikHowlett/Attend-O
attendo1/XMCCamera.swift
2
5589
// // XMCCamera.swift // dojo-custom-camera // // Created by David McGraw on 11/13/14. // Copyright (c) 2014 David McGraw. All rights reserved. // import UIKit import AVFoundation @objc protocol XMCCameraDelegate { func cameraSessionConfigurationDidComplete() func cameraSessionDidBegin() func cameraSessionDidStop() } class XMCCamera: NSObject { weak var delegate: XMCCameraDelegate? var session: AVCaptureSession! var sessionQueue: dispatch_queue_t! var stillImageOutput: AVCaptureStillImageOutput? init(sender: AnyObject) { super.init() self.delegate = sender as? XMCCameraDelegate self.setObservers() self.initializeSession() } deinit { self.removeObservers() } // MARK: Session func initializeSession() { self.session = AVCaptureSession() self.session.sessionPreset = AVCaptureSessionPresetPhoto self.sessionQueue = dispatch_queue_create("camera session", DISPATCH_QUEUE_SERIAL) dispatch_async(self.sessionQueue) { self.session.beginConfiguration() self.addVideoInput() self.addStillImageOutput() self.session.commitConfiguration() dispatch_async(dispatch_get_main_queue()) { NSLog("Session initialization did complete") self.delegate?.cameraSessionConfigurationDidComplete() } } } func startCamera() { dispatch_async(self.sessionQueue) { self.session.startRunning() } } func stopCamera() { dispatch_async(self.sessionQueue) { self.session.stopRunning() } } func captureStillImage(completed: (image: UIImage?) -> Void) { if let imageOutput = self.stillImageOutput { dispatch_async(self.sessionQueue, { () -> Void in var videoConnection: AVCaptureConnection? for connection in imageOutput.connections { let c = connection as! AVCaptureConnection for port in c.inputPorts { let p = port as! AVCaptureInputPort if p.mediaType == AVMediaTypeVideo { videoConnection = c; break } } if videoConnection != nil { break } } if videoConnection != nil { imageOutput.captureStillImageAsynchronouslyFromConnection(videoConnection, completionHandler: { (imageSampleBuffer: CMSampleBufferRef!, error) -> Void in let imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(imageSampleBuffer) let image: UIImage? = UIImage(data: imageData!)! dispatch_async(dispatch_get_main_queue()) { completed(image: image) } }) } else { dispatch_async(dispatch_get_main_queue()) { completed(image: nil) } } }) } else { completed(image: nil) } } // MARK: Configuration func addVideoInput() { let device: AVCaptureDevice = self.deviceWithMediaTypeWithPosition(AVMediaTypeVideo, position: AVCaptureDevicePosition.Back) let input = AVCaptureDeviceInput(device: device) if self.session.canAddInput(input) { self.session.addInput(input) } } func addStillImageOutput() { stillImageOutput = AVCaptureStillImageOutput() stillImageOutput?.outputSettings = [AVVideoCodecKey: AVVideoCodecJPEG] if self.session.canAddOutput(stillImageOutput) { session.addOutput(stillImageOutput) } } func deviceWithMediaTypeWithPosition(mediaType: NSString, position: AVCaptureDevicePosition) -> AVCaptureDevice { let devices: NSArray = AVCaptureDevice.devicesWithMediaType(mediaType as String) var captureDevice: AVCaptureDevice = devices.firstObject as! AVCaptureDevice for device in devices { let d = device as! AVCaptureDevice if d.position == position { captureDevice = d break; } } return captureDevice } // MARK: Observers func setObservers() { NSNotificationCenter.defaultCenter().addObserver(self, selector: "sessionDidStart:", name: AVCaptureSessionDidStartRunningNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "sessionDidStop:", name: AVCaptureSessionDidStopRunningNotification, object: nil) } func removeObservers() { NSNotificationCenter.defaultCenter().removeObserver(self) } func sessionDidStart(notification: NSNotification) { dispatch_async(dispatch_get_main_queue()) { NSLog("Session did start") self.delegate?.cameraSessionDidBegin() } } func sessionDidStop(notification: NSNotification) { dispatch_async(dispatch_get_main_queue()) { NSLog("Session did stop") self.delegate?.cameraSessionDidStop() } } }
mit
3fb9f30b8d034d166e8ab99a30149692
32.267857
173
0.575237
6.009677
false
false
false
false
larcus94/Sweets
Sweets/UIControlExtensions.swift
1
1173
// // UIControlExtensions.swift // Sweets // // Created by Laurin Brandner on 20/05/15. // Copyright (c) 2015 Laurin Brandner. All rights reserved. // import UIKit import ObjectiveC private let actionsKey = "actions" private let selector: Selector = "fire:" extension UIControl { private var actions: [UInt: Action] { get { return objc_getAssociatedObject(self, actionsKey) as? [UInt: Action] ?? [:] } set(value) { objc_setAssociatedObject(self, actionsKey, value, objc_AssociationPolicy(OBJC_ASSOCIATION_RETAIN_NONATOMIC)) } } public func setAction(function: (UIControl) -> (), forControlEvents controlEvents: UIControlEvents) { let action = Action(function, controlEvents: controlEvents) actions[controlEvents.rawValue] = action addTarget(action, action: selector, forControlEvents: controlEvents) } public func removeAction(forControlEvents controlEvents: UIControlEvents) { let action = actions.removeValueForKey(controlEvents.rawValue) removeTarget(action, action: selector, forControlEvents: controlEvents) } }
mit
541e114285f747246bf92cc61fe6919f
29.868421
120
0.678602
4.787755
false
false
false
false
yongxu/InfiniteScrollingScene
InfiniteScrollingScene/GameScene.swift
1
3720
// // GameScene.swift // InfiniteScrollingScene // // Created by Yongxu Ren on 8/13/14. // Copyright (c) 2014 Yongxu Ren. All rights reserved. // import SpriteKit class GameScene: SKScene, InfiniteScrollingNodeDelegate { var cn1,cn2,cn3,cn4:SKSpriteNode! var spaceshipRotateSpeed:CGFloat=0 var spaceship:SKSpriteNode! var world=SKNode() var scrollingNode:InfiniteScrollingNode! var spaceshipSpeed:CGFloat = 700 override func didMoveToView(view: SKView) { /* Setup your scene here */ anchorPoint=CGPointMake(0.5, 0.5) physicsWorld.gravity=CGVectorMake(0, 0) var size2x=CGSizeMake(size.width*2, size.height*2) cn1=SKSpriteNode(color: UIColor.redColor(), size: size2x) cn2=SKSpriteNode(color: UIColor.greenColor(), size: size2x) cn3=SKSpriteNode(color: UIColor.blueColor(), size: size2x) cn4=SKSpriteNode(color: UIColor.yellowColor(), size: size2x) cn1.name="red" cn2.name="green" cn3.name="blue" cn4.name="yellow" scrollingNode=InfiniteScrollingNode(topLeftNode: cn1, topRightNode: cn2, bottomLeftNode: cn3, bottomRightNode: cn4, nodesSize: size2x) scrollingNode.delegate=self world.addChild(scrollingNode) spaceship = SKSpriteNode(imageNamed: "Spaceship") spaceship.zPosition=1 spaceship.name="spaceship" spaceship.xScale=0.5 spaceship.yScale=0.5 let body=SKPhysicsBody(texture: spaceship.texture, size: CGSize(width: spaceship.size.width*0.5,height: spaceship.size.height*0.5)) body.velocity=CGVectorMake(0, 1000) body.mass=10 body.dynamic=true spaceship.physicsBody=body spaceship.position=CGPointMake(0, 0) spaceship.zPosition=1000 world.addChild(spaceship) addChild(world) } override func touchesBegan(touches: NSSet, withEvent event: UIEvent) { /* Called when a touch begins */ for touch: AnyObject in touches { let location = touch.locationInNode(self) spaceshipPhysicsUsingTouchLocation(location) } } override func touchesEnded(touches: NSSet!, withEvent event: UIEvent!) { for touch: AnyObject in touches { spaceshipRotateSpeed=0 } } func spaceshipPhysicsUsingTouchLocation(location:CGPoint){ if location.x<0{ //turnLeft spaceshipRotateSpeed = 2 }else{ //turnRight spaceshipRotateSpeed = -2 } } override func update(currentTime: CFTimeInterval) { /* Called before each frame is rendered */ var rotation = spaceship.zRotation spaceship.physicsBody.velocity=CGVectorMake(spaceshipSpeed*CGFloat(sinf(-Float(rotation))), spaceshipSpeed*CGFloat(cosf(Float(rotation)))) spaceship.physicsBody.angularVelocity=spaceshipRotateSpeed } override func didSimulatePhysics() { centerOnNode(spaceship) scrollingNode.update(spaceship.position) } func nodeInDisplay(node:SKNode){ println("\(node.name) IN.") } func nodeOutDisplay(node:SKNode){ println("\(node.name) OUT.") } /*this function is optional*/ func nodeWillMove(node:SKNode,toPosition pos:CGPoint){ } func centerOnNode(node:SKNode!){ let cameraPositionInScene=node.scene.convertPoint(node.position,fromNode:node.parent) node.parent.position=CGPointMake(node.parent.position.x - cameraPositionInScene.x, node.parent.position.y - cameraPositionInScene.y) } }
mit
0fb93514189ffa64bae0b1c98a3446c7
34.09434
178
0.645968
4.266055
false
false
false
false
Ares42/Portfolio
HackerRankMobile/Helpers/NetworkHelper.swift
1
1090
// // NetworkHelper.swift // HackerRankMobile // // Created by Luke Solomon on 4/1/17. // Copyright © 2017 Solomon Stuff. All rights reserved. // import Foundation import Alamofire import CoreData import SwiftyJSON struct NetworkHelper { static let sharedInstance = NetworkHelper() static func getUserProfileInfo(completion: @escaping() -> Void ) { Alamofire.request("https://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=662FAD1E88064DA3142482D9E452EBAE&steamids=76561197965805643").responseJSON { response in switch response.result { case .success: if let value = response.result.value { let result = JSON(value) let json = result["response"]["players"][0] CoreDataHelper.saveUser(withJson: json) completion() } case .failure(let error): print(error) } } } }
mit
4fe27b9cd95492c7b4c59effca553029
25.560976
185
0.552801
4.714286
false
false
false
false
mluedke2/snowshoe-swift
Example/SnowShoe-Swift/ViewController.swift
1
947
// // ViewController.swift // SnowShoe-Swift // // Created by mluedke2 on 08/25/2015. // Copyright (c) 2015 mluedke2. All rights reserved. // import UIKit import SnowShoe_Swift class ViewController: UIViewController { @IBOutlet var snowShoeView: SnowShoeView! override func viewDidLoad() { super.viewDidLoad() snowShoeView.appKey = "YOUR_APP_KEY" snowShoeView.appSecret = "YOUR_APP_SECRET" snowShoeView.delegate = self } } extension ViewController: SnowShoeDelegate { func onStampRequestMade() { // start activity indicator, etc } func onStampResult(result: SnowShoeResult?) { if let result = result { if let stamp = result.stamp { // handle stamp print("stamp found! serial: \(stamp.serial)") } else if let error = result.error { // handle snowshoe error print("\(error.message)") } } else { // handle request error } } }
mit
aa13de95ddfa43e28efe195b73350b3b
20.522727
53
0.644139
3.834008
false
false
false
false
augmify/Eureka
Tests/HelperMethodTests.swift
3
4252
// HelperMethodTests.swift // Eureka ( https://github.com/xmartlabs/Eureka ) // // Copyright (c) 2015 Xmartlabs ( http://xmartlabs.com ) // // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import XCTest @testable import Eureka class HelperMethodTests: BaseEurekaTests { func testRowByTag(){ // Tests rowByTag() method let urlRow : URLRow? = fieldForm.rowByTag("UrlRow_f1") XCTAssertNotNil(urlRow) let phoneRow : PhoneRow? = fieldForm.rowByTag("phone") XCTAssertNil(phoneRow) } func testRowSequenceMethods(){ // Tests the nextRowForRow() and the previousRowForRow() methods let form = fieldForm + shortForm + dateForm let row6 = form.nextRowForRow(form[0][5]) XCTAssertEqual(row6, form[0][6]) XCTAssertEqual(row6, form.rowByTag("IntRow_f1") as? IntRow) let row_5_and_6: MutableSlice<Section> = form[0][5...6] XCTAssertEqual(row_5_and_6[5], form[0][5]) XCTAssertEqual(row_5_and_6[6], form[0][6]) let row10n = form.nextRowForRow(form[0][9]) let rownil = form.nextRowForRow(form[2][7]) XCTAssertEqual(row10n, form[1][0]) XCTAssertNil(rownil) let row10p = form.previousRowForRow(form[1][1]) let rowNilP = form.previousRowForRow(form[0][0]) XCTAssertEqual(row10n, row10p) XCTAssertNil(rowNilP) XCTAssertNotNil(form.nextRowForRow(form[1][1])) XCTAssertEqual(form[1][1], form.previousRowForRow(form.nextRowForRow(form[1][1])!)) } func testAllRowsMethod(){ // Tests the allRows() method let form = fieldForm + shortForm + dateForm XCTAssertEqual(form.rows.count, 20) XCTAssertEqual(form.rows[11], shortForm[0][1]) XCTAssertEqual(form.rows[19], form.rowByTag("IntervalDateRow_d1") as? DateRow) } func testAllRowsWrappedByTagMethod(){ // Tests the allRows() method let form = fieldForm + shortForm + dateForm let rows = form.dictionaryValuesToEvaluatePredicate() XCTAssertEqual(rows.count, 20) } func testDisabledRows(){ // Tests that a row set up as disabled can not become firstResponder let checkRow = CheckRow("check"){ $0.disabled = true } let switchRow = SwitchRow("switch"){ $0.disabled = true } let segmentedRow = SegmentedRow<String>("segments"){ $0.disabled = true; $0.options = ["a", "b"] } let intRow = IntRow("int"){ $0.disabled = true } formVC.form +++ checkRow <<< switchRow <<< segmentedRow <<< intRow checkRow.updateCell() XCTAssertTrue(checkRow.cell.selectionStyle == .None) switchRow.updateCell() XCTAssertNotNil(switchRow.cell.switchControl) XCTAssertFalse(switchRow.cell.switchControl!.enabled) segmentedRow.updateCell() XCTAssertFalse(segmentedRow.cell.segmentedControl.enabled) intRow.updateCell() XCTAssertFalse(intRow.cell.cellCanBecomeFirstResponder()) } }
mit
3bfabe70bc8468e0e43cb51bbcbd5c24
35.973913
106
0.644638
4.499471
false
true
false
false
chinlam91/edx-app-ios
Source/CourseHandoutsViewController.swift
2
4445
// // CourseHandoutsViewController.swift // edX // // Created by Ehmad Zubair Chughtai on 26/06/2015. // Copyright (c) 2015 edX. All rights reserved. // import UIKit public class CourseHandoutsViewController: UIViewController, UIWebViewDelegate { public class Environment : NSObject { let dataManager : DataManager let networkManager : NetworkManager let styles : OEXStyles init(dataManager : DataManager, networkManager : NetworkManager, styles : OEXStyles) { self.dataManager = dataManager self.networkManager = networkManager self.styles = styles } } let courseID : String let environment : Environment let webView : UIWebView let loadController : LoadStateViewController let handouts : BackedStream<String> = BackedStream() init(environment : Environment, courseID : String) { self.environment = environment self.courseID = courseID self.webView = UIWebView() self.loadController = LoadStateViewController(styles: self.environment.styles) super.init(nibName: nil, bundle: nil) } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override public func viewDidLoad() { super.viewDidLoad() loadController.setupInController(self, contentView: webView) addSubviews() setConstraints() setStyles() webView.delegate = self loadHandouts() } private func addSubviews() { view.addSubview(webView) } private func setConstraints() { webView.snp_makeConstraints { (make) -> Void in make.edges.equalTo(self.view) } } private func setStyles() { self.view.backgroundColor = OEXStyles.sharedStyles().standardBackgroundColor() self.navigationItem.title = OEXLocalizedString("COURSE_HANDOUTS", nil) } private func streamForCourse(course : OEXCourse) -> Stream<String>? { if let access = course.courseware_access where !access.has_access { return Stream<String>(error: OEXCoursewareAccessError(coursewareAccess: access, displayInfo: course.start_display_info)) } else { let request = CourseInfoAPI.getHandoutsForCourseWithID(courseID, overrideURL: course.course_handouts) let loader = self.environment.networkManager.streamForRequest(request, persistResponse: true) return loader } } private func loadHandouts() { if let courseStream = self.environment.dataManager.interface?.courseStreamWithID(courseID) { let handoutStream = courseStream.transform {[weak self] course in return self?.streamForCourse(course) ?? Stream<String>(error : NSError.oex_courseContentLoadError()) } self.handouts.backWithStream(handoutStream) } addListener() } private func addListener() { handouts.listenOnce(self, fireIfAlreadyLoaded: true, success: { [weak self] courseHandouts in if let displayHTML = OEXStyles.sharedStyles().styleHTMLContent(courseHandouts), apiHostUrl = OEXConfig.sharedConfig().apiHostURL() { self?.webView.loadHTMLString(displayHTML, baseURL: NSURL(string: apiHostUrl)) self?.loadController.state = .Loaded } else { self?.loadController.state = LoadState.failed() } }, failure: {[weak self] error in self?.loadController.state = LoadState.failed(error) } ) } override public func updateViewConstraints() { loadController.insets = UIEdgeInsets(top: self.topLayoutGuide.length, left: 0, bottom: self.bottomLayoutGuide.length, right: 0) super.updateViewConstraints() } //MARK: UIWebView delegate public func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool { if (navigationType != UIWebViewNavigationType.Other) { if let URL = request.URL { UIApplication.sharedApplication().openURL(URL) return false } } return true } }
apache-2.0
7b83adcd67cc6c0eab84a37b7f8483df
33.726563
144
0.631721
5.374849
false
false
false
false
nitrado/NitrAPI-Swift
Pod/Classes/order/DimensionPricing.swift
1
3335
open class DimensionPricing: Pricing { var dimensions: [String: String] public override init(nitrapi: Nitrapi, locationId: Int) { self.dimensions = [:] super.init(nitrapi: nitrapi, locationId: locationId) } open func addDimension(_ dimension: String, value: String) { dimensions[dimension] = value } open func getSelectedDimension(_ dimension: String) -> String { return dimensions[dimension]! } open func removeDimension(_ dimension: String) { dimensions.removeValue(forKey: dimension) } open func reset() { dimensions = [:] } open override func getPrice(_ service: Service?, rentalTime: Int) throws -> Int { let information = try getPrices(service) let prices = information.prices var dims: [String?] = [] let realDims = information.dimensions for dim in realDims! { if let id = dim.id { if dimensions.keys.contains(id) { dims.append(dimensions[id]!) } } } dims.append("\(rentalTime)") if !(prices?.keys.contains(calcPath(dims)))! { throw NitrapiError.nitrapiException(message: "Can't find price with dimensions \(calcPath(dims))", errorId: nil) } let price = prices![calcPath(dims)] if let price = price as? PriceDimensionValue { return Int(calcAdvicePrice(price: Double(price.value), advice: Double(information.advice!), service: service)) } throw NitrapiError.nitrapiException(message: "Misformated json for dimension \(calcPath(dims))", errorId: nil) } open override func orderService(_ rentalTime: Int) throws -> Int? { var params = [ "price": "\(try getPrice(rentalTime))", "rental_time": "\(rentalTime)", "location": "\(locationId)" ] for (key, value) in self.dimensions { params["dimensions[\(key)"] = value } for (key, value) in self.additionals { params["additionals[\(key)"] = value } let data = try nitrapi.client.dataPost("order/order/\(product as String)", parameters: params) if let obj = data?["order"] as? Dictionary<String, AnyObject> { return obj["service_id"] as? Int } return nil } open override func switchService(_ service: Service, rentalTime: Int) throws -> Int? { var params = [ "price": "\(try getSwitchPrice(service, rentalTime: rentalTime))", "rental_time": "\(rentalTime)", "location": "\(locationId)", "method": "switch", "service_id": "\(service.id as Int)" ] for (key, value) in self.dimensions { params["dimensions[\(key)"] = value } for (key, value) in self.additionals { params["additionals[\(key)"] = value } let data = try nitrapi.client.dataPost("order/order/\(product as String)", parameters: params) if let obj = data?["order"] as? Dictionary<String, AnyObject> { return obj["service_id"] as? Int } return nil } }
mit
af739d94a1a2fe8ebfee4b330ad04c9e
33.381443
124
0.552624
4.568493
false
false
false
false
timelessg/TLStoryCamera
TLStoryCameraFramework/TLStoryCameraFramework/Class/Tools/Extension/UIDevice+TLStory.swift
1
491
// // UIDevice+TLStory.swift // TLStoryCameraFramework // // Created by garry on 2018/2/7. // Copyright © 2018年 com.garry. All rights reserved. // import Foundation extension UIDevice { static public var isX:Bool { get { return UIScreen.main.bounds.height == 812 } } static let isSimulator: Bool = { var isSim = false #if arch(i386) || arch(x86_64) isSim = true #endif return isSim }() }
mit
97fbb731fa81c0d998e2a95c8c41e0bf
17.769231
53
0.563525
3.8125
false
false
false
false
gurenupet/hah-auth-ios-swift
hah-auth-ios-swift/Pods/Mixpanel-swift/Mixpanel/InAppButton.swift
4
2486
// // InAppButton.swift // Mixpanel // // Created by Yarden Eitan on 1/24/17. // Copyright © 2017 Mixpanel. All rights reserved. // import Foundation class InAppButton { enum PayloadKey { static let text = "text" static let textColor = "text_color" static let backgroundColor = "bg_color" static let borderColor = "border_color" static let callToActionURL = "cta_url" } let text: String let textColor: UInt let backgroundColor: UInt let borderColor: UInt let callToActionURL: URL? init?(JSONObject: [String: Any]?) { guard let object = JSONObject else { Logger.error(message: "notification button json object should not be nil") return nil } guard let text = object[PayloadKey.text] as? String else { Logger.error(message: "invalid notification button text") return nil } guard let textColor = object[PayloadKey.textColor] as? UInt else { Logger.error(message: "invalid notification button text color") return nil } guard let backgroundColor = object[PayloadKey.backgroundColor] as? UInt else { Logger.error(message: "invalid notification button background color") return nil } guard let borderColor = object[PayloadKey.borderColor] as? UInt else { Logger.error(message: "invalid notification button border color") return nil } var callToActionURL: URL? if let URLString = object[PayloadKey.callToActionURL] as? String { callToActionURL = URL(string: URLString) } self.text = text self.textColor = textColor self.backgroundColor = backgroundColor self.borderColor = borderColor self.callToActionURL = callToActionURL } func payload() -> [String: AnyObject] { var payload = [String: AnyObject]() payload[PayloadKey.text] = text as AnyObject payload[PayloadKey.textColor] = textColor as AnyObject payload[PayloadKey.backgroundColor] = backgroundColor as AnyObject payload[PayloadKey.borderColor] = borderColor as AnyObject if let callToActionURLString = callToActionURL?.absoluteString { payload[PayloadKey.callToActionURL] = callToActionURLString as AnyObject } return payload } }
mit
d45cde94b0c9f840caf8bab0711bc843
31.272727
86
0.624547
4.96008
false
false
false
false
suzp1984/IOS-ApiDemo
ApiDemo-Swift/ApiDemo-Swift/SnapshotViewController.swift
1
3389
// // SnapshotViewController.swift // ApiDemo-Swift // // Created by Jacob su on 5/17/16. // Copyright © 2016 [email protected]. All rights reserved. // import UIKit class SnapshotViewController: UIViewController { var snapshot: UIView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.view.backgroundColor = UIColor.white let v1 = UIView() v1.backgroundColor = UIColor.blue self.view.addSubview(v1) v1.translatesAutoresizingMaskIntoConstraints = false v1.widthAnchor.constraint(equalToConstant: 100).isActive = true v1.heightAnchor.constraint(equalToConstant: 100).isActive = true v1.topAnchor.constraint(equalTo: self.topLayoutGuide.bottomAnchor, constant: 10).isActive = true v1.leftAnchor.constraint(equalTo: self.view.leftAnchor, constant: 10).isActive = true let iv = UIImageView(image: UIImage(named: "Mars")) // get snapshot // let iv = self.view.snapshotViewAfterScreenUpdates(false) iv.translatesAutoresizingMaskIntoConstraints = false self.view.addSubview(iv) NSLayoutConstraint.activate([ iv.widthAnchor.constraint(equalToConstant: 100), iv.heightAnchor.constraint(equalToConstant: 100), iv.rightAnchor.constraint(equalTo: self.view.rightAnchor, constant: -10), iv.bottomAnchor.constraint(equalTo: self.bottomLayoutGuide.topAnchor, constant: -10) ]) let button = UIButton(type: .system) button.translatesAutoresizingMaskIntoConstraints = false button.setTitle("Snapshot", for: UIControlState()) button.addTarget(self, action: #selector(SnapshotViewController.takeSnapshot), for: .touchUpInside) self.view.addSubview(button) NSLayoutConstraint.activate([ button.topAnchor.constraint(equalTo: self.topLayoutGuide.bottomAnchor, constant: 20), button.rightAnchor.constraint(equalTo: self.view.rightAnchor, constant: -20) ]) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func takeSnapshot() { if (snapshot != nil) { snapshot.removeFromSuperview() } snapshot = self.view.snapshotView(afterScreenUpdates: false) snapshot.translatesAutoresizingMaskIntoConstraints = false self.view.addSubview(snapshot) NSLayoutConstraint.activate([ snapshot.widthAnchor.constraint(equalToConstant: 100), snapshot.heightAnchor.constraint(equalToConstant: 200), snapshot.leftAnchor.constraint(equalTo: self.view.leftAnchor, constant: 10), snapshot.bottomAnchor.constraint(equalTo: self.bottomLayoutGuide.topAnchor, constant: -10) ]) } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
apache-2.0
fcada90620187062d8905f9d2a910d04
37.067416
107
0.66588
5.204301
false
false
false
false
overtake/TelegramSwift
Telegram-Mac/ArchiverContext.swift
1
6744
// // ArchiverContext.swift // Telegram // // Created by Mikhail Filimonov on 23/10/2018. // Copyright © 2018 Telegram. All rights reserved. // import Zip import SwiftSignalKit enum ArchiveStatus : Equatable { case none case waiting case done(URL) case fail(ZipError) case progress(Double) } enum ArchiveSource : Hashable { static func == (lhs: ArchiveSource, rhs: ArchiveSource) -> Bool { switch lhs { case let .resource(lhsResource): if case let .resource(rhsResource) = rhs { return lhsResource.isEqual(to: rhsResource) } else { return false } } } var contents:[URL] { switch self { case let .resource(resource): if resource.path.contains("tg_temp_archive_") { let files = try? FileManager.default.contentsOfDirectory(at: URL(fileURLWithPath: resource.path), includingPropertiesForKeys: nil, options: FileManager.DirectoryEnumerationOptions.skipsHiddenFiles) return files ?? [URL(fileURLWithPath: resource.path)] } return [URL(fileURLWithPath: resource.path)] } } var hashValue: Int { switch self { case let .resource(resource): return resource.id.hashValue } } var destinationURL: URL { return URL(fileURLWithPath: NSTemporaryDirectory() + "tarchive-\(self.uniqueId).zip") } var uniqueId: Int64 { switch self { case .resource(let resource): return resource.randomId } } case resource(LocalFileArchiveMediaResource) } private final class Archiver { private let status: ValuePromise<ArchiveStatus> = ValuePromise(.waiting, ignoreRepeated: true) var statusSignal:Signal<ArchiveStatus, NoError> { return status.get() } let destination: URL private let source: ArchiveSource private let queue: Queue init(source : ArchiveSource, queue: Queue) { self.queue = queue self.source = source self.destination = source.destinationURL } func start(cancelToken:@escaping()->Bool) { let destination = self.destination let source = self.source queue.async { [weak status] in guard let status = status else {return} let contents = source.contents if !contents.isEmpty { do { try Zip.zipFiles(paths: contents, zipFilePath: destination, password: nil, compression: ZipCompression.BestCompression, progress: { progress in status.set(.progress(progress)) }, cancel: cancelToken) status.set(.done(destination)) } catch { if let error = error as? ZipError { status.set(.fail(error)) } } } } } } // добавить отмену архивирования если разлонигиваемся private final class ArchiveStatusContext { var status: ArchiveStatus = .none let subscribers = Bag<(ArchiveStatus) -> Void>() } class ArchiverContext { var statuses:[ArchiveSource : ArchiveStatus] = [:] private let queue = Queue(name: "ArchiverContext") private var contexts: [ArchiveSource: Archiver] = [:] private let archiveQueue: Queue = Queue.concurrentDefaultQueue() private var statusContexts: [ArchiveSource: ArchiveStatusContext] = [:] private var statusesDisposable:[ArchiveSource : Disposable] = [:] private var cancelledTokens:[ArchiveSource : Any] = [:] init() { } deinit { self.queue.sync { self.contexts.removeAll() for status in statusesDisposable { status.value.dispose() } } } func remove(_ source: ArchiveSource) { queue.async { self.contexts.removeValue(forKey: source) self.statusesDisposable[source]?.dispose() self.statuses.removeValue(forKey: source) self.cancelledTokens[source] = true } } func archive(_ source: ArchiveSource, startIfNeeded: Bool = false) -> Signal<ArchiveStatus, NoError> { let queue = self.queue return Signal { [weak self] subscriber in guard let `self` = self else { return EmptyDisposable } if self.statusContexts[source] == nil { self.statusContexts[source] = ArchiveStatusContext() } let statusContext = self.statusContexts[source]! let index = statusContext.subscribers.add({ status in subscriber.putNext(status) }) if let _ = self.contexts[source] { if let statusContext = self.statusContexts[source] { for subscriber in statusContext.subscribers.copyItems() { subscriber(statusContext.status) } } } else { if startIfNeeded { let archiver = Archiver(source: source, queue: self.archiveQueue) self.contexts[source] = archiver self.statusesDisposable[source] = (archiver.statusSignal |> deliverOn(queue)).start(next: { status in statusContext.status = status for subscriber in statusContext.subscribers.copyItems() { subscriber(statusContext.status) } }, completed: { subscriber.putCompletion() }) archiver.start(cancelToken: { var cancelled: Bool = false queue.sync { cancelled = self.cancelledTokens[source] != nil self.cancelledTokens.removeValue(forKey: source) } return cancelled }) } else { for subscriber in statusContext.subscribers.copyItems() { subscriber(statusContext.status) } } } return ActionDisposable { self.queue.async { if let current = self.statusContexts[source] { current.subscribers.remove(index) } } } } |> runOn(queue) } }
gpl-2.0
25e4b962ca2f38261145f748e6b7e767
32.653266
213
0.541287
5.248433
false
false
false
false
overtake/TelegramSwift
Telegram-Mac/ChatHistoryViewForLocation.swift
1
26732
// // ChatHistoryViewForLocation.swift // Telegram-Mac // // Created by keepcoder on 10/10/2016. // Copyright © 2016 Telegram. All rights reserved. // import Cocoa import Postbox import TelegramCore import InAppSettings import SwiftSignalKit import TGUIKit enum ChatHistoryInitialSearchLocation { case index(MessageIndex) case id(MessageId) } struct ChatHistoryLocationInput: Equatable { var content: ChatHistoryLocation var id: Int32 init(content: ChatHistoryLocation, id: Int32) { self.content = content self.id = id } } enum ChatHistoryLocation: Equatable { case Initial(count: Int) case InitialSearch(location: ChatHistoryInitialSearchLocation, count: Int) case Navigation(index: MessageHistoryAnchorIndex, anchorIndex: MessageHistoryAnchorIndex, count: Int, side: TableSavingSide) case Scroll(index: MessageHistoryAnchorIndex, anchorIndex: MessageHistoryAnchorIndex, sourceIndex: MessageHistoryAnchorIndex, scrollPosition: TableScrollState, count: Int, animated: Bool) var count: Int { switch self { case let .Initial(count): return count case let .InitialSearch(_, count): return count case let .Navigation(_, _, count, _): return count case let .Scroll(_, _, _, _, count, _): return count } } var side: TableSavingSide? { switch self { case let .Navigation(_, _, _, side): return side default: return nil } } } func ==(lhs: ChatHistoryLocation, rhs: ChatHistoryLocation) -> Bool { switch lhs { case let .Navigation(lhsIndex, lhsAnchorIndex, lhsCount, lhsSide): switch rhs { case let .Navigation(rhsIndex, rhsAnchorIndex, rhsCount, rhsSide) where lhsIndex == rhsIndex && lhsAnchorIndex == rhsAnchorIndex && lhsCount == rhsCount && lhsSide == rhsSide: return true default: return false } default: return false } } enum ChatHistoryViewScrollPosition : Equatable { case unread(index: MessageIndex) case positionRestoration(index: MessageIndex, relativeOffset: CGFloat) case index(index: MessageHistoryAnchorIndex, position: TableScrollState, directionHint: ListViewScrollToItemDirectionHint, animated: Bool) } func ==(lhs: ChatHistoryViewScrollPosition, rhs: ChatHistoryViewScrollPosition) -> Bool { switch lhs { case let .unread(index): if case .unread(index: index) = rhs { return true } else { return false } case let .positionRestoration(index, relativeOffset): if case .positionRestoration(index: index, relativeOffset: relativeOffset) = rhs { return true } else { return false } case let .index(index, position, directionHint, animated): if case .index(index: index, position: position, directionHint: directionHint, animated: animated) = rhs { return true } else { return false } } } public struct ChatHistoryCombinedInitialData { let initialData: InitialMessageHistoryData? let buttonKeyboardMessage: Message? let cachedData: CachedPeerData? let cachedDataMessages:[MessageId: [Message]]? let readStateData: [PeerId: ChatHistoryCombinedInitialReadStateData]? let limitsConfiguration: LimitsConfiguration let autoplayMedia: AutoplayMediaPreferences let autodownloadSettings: AutomaticMediaDownloadSettings } enum ChatHistoryViewUpdateType : Equatable { case Initial(fadeIn: Bool) case Generic(type: ViewUpdateType) } public struct ChatHistoryCombinedInitialReadStateData { public let unreadCount: Int32 public let totalUnreadCount: Int32 public let notificationSettings: PeerNotificationSettings? } enum ChatHistoryViewUpdate { case Loading(initialData: ChatHistoryCombinedInitialData, type: ChatHistoryViewUpdateType) case HistoryView(view: MessageHistoryView, type: ChatHistoryViewUpdateType, scrollPosition: ChatHistoryViewScrollPosition?, initialData: ChatHistoryCombinedInitialData) } func chatHistoryViewForLocation(_ location: ChatHistoryLocation, context: AccountContext, chatLocation _chatLocation: ChatLocation, fixedCombinedReadStates: (()->MessageHistoryViewReadState?)?, tagMask: MessageTags?, mode: ChatMode = .history, additionalData: [AdditionalMessageHistoryViewData] = [], orderStatistics: MessageHistoryViewOrderStatistics = [], chatLocationContextHolder: Atomic<ChatLocationContextHolder?> = Atomic(value: nil), chatLocationInput: ChatLocationInput? = nil) -> Signal<ChatHistoryViewUpdate, NoError> { let account = context.account let chatLocationInput = chatLocationInput ?? context.chatLocationInput(for: _chatLocation, contextHolder: chatLocationContextHolder) switch location { case let .Initial(count): var preloaded = false var fadeIn = false let signal: Signal<(MessageHistoryView, ViewUpdateType, InitialMessageHistoryData?), NoError> switch mode { case .history, .thread, .pinned: if let tagMask = tagMask { signal = account.viewTracker.aroundMessageHistoryViewForLocation(chatLocationInput, index: .upperBound, anchorIndex: .upperBound, count: count, fixedCombinedReadStates: nil, tagMask: tagMask, orderStatistics: orderStatistics) } else { //aroundMessageHistoryViewForLocation signal = account.viewTracker.aroundMessageOfInterestHistoryViewForLocation(chatLocationInput, count: count, tagMask: tagMask, orderStatistics: orderStatistics, additionalData: additionalData) } case .scheduled: signal = account.viewTracker.scheduledMessagesViewForLocation(chatLocationInput) } return signal |> map { view, updateType, initialData -> ChatHistoryViewUpdate in let (cachedData, cachedDataMessages, readStateData, limitsConfiguration, autoplayMedia, autodownloadSettings) = extractAdditionalData(view: view, chatLocation: _chatLocation) let combinedInitialData = ChatHistoryCombinedInitialData(initialData: initialData, buttonKeyboardMessage: view.topTaggedMessages.first, cachedData: cachedData, cachedDataMessages: cachedDataMessages, readStateData: readStateData, limitsConfiguration: limitsConfiguration, autoplayMedia: autoplayMedia, autodownloadSettings: autodownloadSettings) if preloaded { //NSLog("entriescount: \(view.entries.count)") return .HistoryView(view: view, type: .Generic(type: updateType), scrollPosition: nil, initialData: combinedInitialData) } else { var scrollPosition: ChatHistoryViewScrollPosition? if let maxReadIndex = view.maxReadIndex, tagMask == nil { let aroundIndex = maxReadIndex scrollPosition = .unread(index: maxReadIndex) var targetIndex = 0 for i in 0 ..< view.entries.count { if view.entries[i].index >= aroundIndex { targetIndex = i break } } let maxIndex = targetIndex + count / 2 let minIndex = targetIndex - count / 2 if minIndex <= 0 && view.holeEarlier { fadeIn = true return .Loading(initialData: combinedInitialData, type: .Generic(type: updateType)) } if maxIndex >= targetIndex { if view.holeLater { fadeIn = true return .Loading(initialData: combinedInitialData, type: .Generic(type: updateType)) } if view.holeEarlier { var incomingCount: Int32 = 0 inner: for entry in view.entries.reversed() { if entry.message.flags.contains(.Incoming) { incomingCount += 1 } } if case let .peer(peerId) = _chatLocation, let combinedReadStates = view.fixedReadStates, case let .peer(readStates) = combinedReadStates, let readState = readStates[peerId], readState.count == incomingCount { } else { fadeIn = true return .Loading(initialData: combinedInitialData, type: .Generic(type: updateType)) } } } } else if let opaqueState = (initialData?.storedInterfaceState).flatMap(_internal_decodeStoredChatInterfaceState) { let interfaceState = ChatInterfaceState.parse(opaqueState, peerId: _chatLocation.peerId, context: context) if let historyScrollState = interfaceState?.historyScrollState { scrollPosition = .positionRestoration(index: historyScrollState.messageIndex, relativeOffset: CGFloat(historyScrollState.relativeOffset)) } } else { if view.entries.isEmpty && (view.holeEarlier || view.holeLater) { fadeIn = true return .Loading(initialData: combinedInitialData, type: .Generic(type: updateType)) } } preloaded = true return .HistoryView(view: view, type: .Initial(fadeIn: fadeIn), scrollPosition: scrollPosition, initialData: combinedInitialData) } } case let .InitialSearch(searchLocation, count): var preloaded = false var fadeIn = false let signal: Signal<(MessageHistoryView, ViewUpdateType, InitialMessageHistoryData?), NoError> switch mode { case .history, .thread, .pinned: switch searchLocation { case let .index(index): signal = account.viewTracker.aroundMessageHistoryViewForLocation(chatLocationInput, index: MessageHistoryAnchorIndex.message(index), anchorIndex: MessageHistoryAnchorIndex.message(index), count: count, fixedCombinedReadStates: nil, tagMask: tagMask, orderStatistics: orderStatistics, additionalData: additionalData) case let .id(id): signal = account.viewTracker.aroundIdMessageHistoryViewForLocation(chatLocationInput, count: count, ignoreRelatedChats: false, messageId: id, tagMask: tagMask, orderStatistics: orderStatistics, additionalData: additionalData) } case .scheduled: signal = account.viewTracker.scheduledMessagesViewForLocation(chatLocationInput) } return signal |> map { view, updateType, initialData -> ChatHistoryViewUpdate in let (cachedData, cachedDataMessages, readStateData, limitsConfiguration, autoplayMedia, autodownloadSettings) = extractAdditionalData(view: view, chatLocation: _chatLocation) let combinedInitialData = ChatHistoryCombinedInitialData(initialData: initialData, buttonKeyboardMessage: view.topTaggedMessages.first, cachedData: cachedData, cachedDataMessages: cachedDataMessages, readStateData: readStateData, limitsConfiguration: limitsConfiguration, autoplayMedia: autoplayMedia, autodownloadSettings: autodownloadSettings) if preloaded { return .HistoryView(view: view, type: .Generic(type: updateType), scrollPosition: nil, initialData: combinedInitialData) } else { let anchorIndex = view.anchorIndex var targetIndex = 0 for i in 0 ..< view.entries.count { //if view.entries[i].index >= anchorIndex if anchorIndex.isLessOrEqual(to: view.entries[i].index) { targetIndex = i break } } if !view.entries.isEmpty { let minIndex = max(0, targetIndex - count / 2) let maxIndex = min(view.entries.count, targetIndex + count / 2) if minIndex == 0 && view.holeEarlier { fadeIn = true return .Loading(initialData: combinedInitialData, type: .Generic(type: updateType)) } if maxIndex == view.entries.count && view.holeLater { fadeIn = true return .Loading(initialData: combinedInitialData, type: .Generic(type: updateType)) } } else if view.holeEarlier || view.holeLater { fadeIn = true return .Loading(initialData: combinedInitialData, type: .Generic(type: updateType)) } var reportUpdateType: ChatHistoryViewUpdateType = .Initial(fadeIn: fadeIn) if case .FillHole = updateType { reportUpdateType = .Generic(type: updateType) } preloaded = true var scroll: TableScrollState if view.entries.count > targetIndex { let focusMessage = view.entries[targetIndex].message let mustToFocus: Bool switch searchLocation { case let .index(index): mustToFocus = view.entries[targetIndex].index == index case let .id(id): mustToFocus = view.entries[targetIndex].message.id == id } scroll = .center(id: ChatHistoryEntryId.message(focusMessage), innerId: nil, animated: false, focus: .init(focus: mustToFocus), inset: 0) } else { scroll = .none(nil) } return .HistoryView(view: view, type: reportUpdateType, scrollPosition: .index(index: anchorIndex, position: scroll, directionHint: .Down, animated: false), initialData: combinedInitialData) } } case let .Navigation(index, anchorIndex, count, _): var first = true let signal:Signal<(MessageHistoryView, ViewUpdateType, InitialMessageHistoryData?), NoError> switch mode { case .history, .thread, .pinned: signal = account.viewTracker.aroundMessageHistoryViewForLocation(chatLocationInput, index: index, anchorIndex: anchorIndex, count: count, fixedCombinedReadStates: fixedCombinedReadStates?(), tagMask: tagMask, orderStatistics: orderStatistics, additionalData: additionalData) case .scheduled: signal = account.viewTracker.scheduledMessagesViewForLocation(chatLocationInput) } return signal |> map { view, updateType, initialData -> ChatHistoryViewUpdate in let (cachedData, cachedDataMessages, readStateData, limitsConfiguration, autoplayMedia, autodownloadSettings) = extractAdditionalData(view: view, chatLocation: _chatLocation) let combinedInitialData = ChatHistoryCombinedInitialData(initialData: initialData, buttonKeyboardMessage: view.topTaggedMessages.first, cachedData: cachedData, cachedDataMessages: cachedDataMessages, readStateData: readStateData, limitsConfiguration: limitsConfiguration, autoplayMedia: autoplayMedia, autodownloadSettings: autodownloadSettings) let genericType: ViewUpdateType if first { first = false genericType = ViewUpdateType.UpdateVisible } else { genericType = updateType } return .HistoryView(view: view, type: .Generic(type: genericType), scrollPosition: nil, initialData: combinedInitialData) } case let .Scroll(index, anchorIndex, sourceIndex, scrollPosition, count, animated): let directionHint: ListViewScrollToItemDirectionHint = sourceIndex > index ? .Down : .Up let chatScrollPosition = ChatHistoryViewScrollPosition.index(index: index, position: scrollPosition, directionHint: directionHint, animated: animated) var first = true let signal:Signal<(MessageHistoryView, ViewUpdateType, InitialMessageHistoryData?), NoError> switch mode { case .history, .thread, .pinned: signal = account.viewTracker.aroundMessageHistoryViewForLocation(chatLocationInput, index: index, anchorIndex: anchorIndex, count: count, fixedCombinedReadStates: fixedCombinedReadStates?(), tagMask: tagMask, orderStatistics: orderStatistics, additionalData: additionalData) case .scheduled: signal = account.viewTracker.scheduledMessagesViewForLocation(chatLocationInput) } return signal |> map { view, updateType, initialData -> ChatHistoryViewUpdate in let (cachedData, cachedDataMessages, readStateData, limitsConfiguration, autoplayMedia, autodownloadSettings) = extractAdditionalData(view: view, chatLocation: _chatLocation) let combinedInitialData = ChatHistoryCombinedInitialData(initialData: initialData, buttonKeyboardMessage: view.topTaggedMessages.first, cachedData: cachedData, cachedDataMessages: cachedDataMessages, readStateData: readStateData, limitsConfiguration: limitsConfiguration, autoplayMedia: autoplayMedia, autodownloadSettings: autodownloadSettings) let genericType: ViewUpdateType let scrollPosition: ChatHistoryViewScrollPosition? = first ? chatScrollPosition : nil if first { first = false genericType = ViewUpdateType.UpdateVisible } else { genericType = updateType } return .HistoryView(view: view, type: .Generic(type: genericType), scrollPosition: scrollPosition, initialData: combinedInitialData) } } } private func extractAdditionalData(view: MessageHistoryView, chatLocation: ChatLocation) -> ( cachedData: CachedPeerData?, cachedDataMessages: [MessageId: [Message]]?, readStateData: [PeerId: ChatHistoryCombinedInitialReadStateData]?, limitsConfiguration: LimitsConfiguration, autoplayMedia: AutoplayMediaPreferences, autodownloadSettings: AutomaticMediaDownloadSettings ) { var cachedData: CachedPeerData? var cachedDataMessages: [MessageId: [Message]]? var readStateData: [PeerId: ChatHistoryCombinedInitialReadStateData] = [:] var notificationSettings: PeerNotificationSettings? var limitsConfiguration: LimitsConfiguration = LimitsConfiguration.defaultValue var autoplayMedia: AutoplayMediaPreferences = AutoplayMediaPreferences.defaultSettings var autodownloadSettings: AutomaticMediaDownloadSettings = AutomaticMediaDownloadSettings.defaultSettings loop: for data in view.additionalData { switch data { case let .peerNotificationSettings(value): notificationSettings = value break loop default: break } } for data in view.additionalData { switch data { case let .peerNotificationSettings(value): notificationSettings = value case let .cachedPeerData(peerIdValue, value): if case .peer(peerIdValue) = chatLocation { cachedData = value } case let .cachedPeerDataMessages(peerIdValue, value): if case .peer(peerIdValue) = chatLocation { cachedDataMessages = value?.mapValues { [$0] } } case let .message(messageId, messages): cachedDataMessages = [messageId : messages] case let .preferencesEntry(key, value): if key == PreferencesKeys.limitsConfiguration { limitsConfiguration = value?.get(LimitsConfiguration.self) ?? .defaultValue } if key == ApplicationSpecificPreferencesKeys.autoplayMedia { autoplayMedia = value?.get(AutoplayMediaPreferences.self) ?? .defaultSettings } if key == ApplicationSpecificPreferencesKeys.automaticMediaDownloadSettings { autodownloadSettings = value?.get(AutomaticMediaDownloadSettings.self) ?? .defaultSettings } case let .totalUnreadState(unreadState): if let combinedReadStates = view.fixedReadStates { if case let .peer(peerId) = chatLocation, case let .peer(readStates) = combinedReadStates, let readState = readStates[peerId] { readStateData[peerId] = ChatHistoryCombinedInitialReadStateData(unreadCount: readState.count, totalUnreadCount: 0, notificationSettings: notificationSettings) } } default: break } } autoplayMedia = autoplayMedia.withUpdatedAutoplayPreloadVideos(autoplayMedia.preloadVideos && autodownloadSettings.automaticDownload && (autodownloadSettings.categories.video.fileSize ?? 0) >= 5 * 1024 * 1024) return (cachedData, cachedDataMessages, readStateData, limitsConfiguration, autoplayMedia, autodownloadSettings) } func preloadedChatHistoryViewForLocation(_ location: ChatHistoryLocation, context: AccountContext, chatLocation: ChatLocation, chatLocationContextHolder: Atomic<ChatLocationContextHolder?>, tagMask: MessageTags?, additionalData: [AdditionalMessageHistoryViewData]) -> Signal<ChatHistoryViewUpdate, NoError> { return (chatHistoryViewForLocation(location, context: context, chatLocation: chatLocation, fixedCombinedReadStates: nil, tagMask: tagMask, additionalData: additionalData, chatLocationContextHolder: chatLocationContextHolder) |> castError(Bool.self) |> mapToSignal { update -> Signal<ChatHistoryViewUpdate, Bool> in switch update { case let .Loading(_, value): if case .Generic(.FillHole) = value { return .fail(true) } case let .HistoryView(_, value, _, _): if case .Generic(.FillHole) = value { return .fail(true) } } return .single(update) }) |> restartIfError } struct ThreadInfo { var message: ChatReplyThreadMessage var isChannelPost: Bool var isEmpty: Bool var scrollToLowerBoundMessage: MessageIndex? var contextHolder: Atomic<ChatLocationContextHolder?> } enum ThreadSubject { case channelPost(MessageId) case groupMessage(MessageId) } func fetchAndPreloadReplyThreadInfo(context: AccountContext, subject: ThreadSubject, atMessageId: MessageId? = nil, preload: Bool = true) -> Signal<ThreadInfo, FetchChannelReplyThreadMessageError> { let message: Signal<ChatReplyThreadMessage, FetchChannelReplyThreadMessageError> switch subject { case .channelPost(let messageId), .groupMessage(let messageId): message = context.engine.messages.fetchChannelReplyThreadMessage(messageId: messageId, atMessageId: atMessageId) } return message |> mapToSignal { replyThreadMessage -> Signal<ThreadInfo, FetchChannelReplyThreadMessageError> in let chatLocationContextHolder = Atomic<ChatLocationContextHolder?>(value: nil) let input: ChatHistoryLocation var scrollToLowerBoundMessage: MessageIndex? switch replyThreadMessage.initialAnchor { case .automatic: if let atMessageId = atMessageId { input = .InitialSearch(location: .id(atMessageId), count: 40) } else { input = .Initial(count: 40) } case let .lowerBoundMessage(index): input = .Navigation(index: .message(index), anchorIndex: .message(index), count: 40, side: .upper) scrollToLowerBoundMessage = index } if replyThreadMessage.isNotAvailable { return .single(ThreadInfo( message: replyThreadMessage, isChannelPost: replyThreadMessage.isChannelPost, isEmpty: false, scrollToLowerBoundMessage: nil, contextHolder: chatLocationContextHolder )) } if preload { let preloadSignal = preloadedChatHistoryViewForLocation( input, context: context, chatLocation: .thread(replyThreadMessage), chatLocationContextHolder: chatLocationContextHolder, tagMask: nil, additionalData: [] ) return preloadSignal |> map { historyView -> Bool? in switch historyView { case .Loading: return nil case let .HistoryView(view, _, _, _): return view.entries.isEmpty } } |> mapToSignal { value -> Signal<Bool, NoError> in if let value = value { return .single(value) } else { return .complete() } } |> take(1) |> map { isEmpty -> ThreadInfo in return ThreadInfo( message: replyThreadMessage, isChannelPost: replyThreadMessage.isChannelPost, isEmpty: isEmpty, scrollToLowerBoundMessage: scrollToLowerBoundMessage, contextHolder: chatLocationContextHolder ) } |> castError(FetchChannelReplyThreadMessageError.self) } else { return .single(ThreadInfo( message: replyThreadMessage, isChannelPost: replyThreadMessage.isChannelPost, isEmpty: false, scrollToLowerBoundMessage: scrollToLowerBoundMessage, contextHolder: chatLocationContextHolder )) } } }
gpl-2.0
d5d4ada6e352b55733a38def5d94a185
47.250903
530
0.628746
5.445305
false
false
false
false
hellogaojun/Swift-coding
swift学习教材案例/Swifter.playground/Pages/lazy.xcplaygroundpage/Contents.swift
1
739
import Foundation class ClassA { lazy var str: String = { let str = "Hello" print("只在首次访问输出") return str }() } print("Creating object") let obj = ClassA() print("Accessing str") obj.str print("Accessing str again") obj.str let data1 = 1...3 let result1 = data1.map { (i: Int) -> Int in print("正在处理 \(i)") return i * 2 } print("准备访问结果") for i in result1 { print("操作后结果为 \(i)") } print("操作完毕") let data2 = 1...3 let result2 = lazy(data2).map { (i: Int) -> Int in print("正在处理 \(i)") return i * 2 } print("准备访问结果") for i in result2 { print("操作后结果为 \(i)") } print("操作完毕")
apache-2.0
f7d8ab4aff1bfe9e643c9f9a78f02017
12.395833
31
0.562986
2.80786
false
false
false
false
foretagsplatsen/ios-app
Monitor/LoginController.swift
1
2740
// // LoginController.swift // Monitor // // Created by Benjamin on 25/11/15. // Copyright (c) 2015 Företagsplatsen AB. All rights reserved. // class LoginController: UIViewController { @IBOutlet var name: UITextField? @IBOutlet var password: UITextField? @IBAction func submit() { self.post(["username":name!.text!, "password":password!.text!], url: ForetagsplatsenController.baseUrl + "/External/Authenticate/Login") { (succeeded: Bool, data: JSON) -> () in if(succeeded) { NSOperationQueue.mainQueue().addOperationWithBlock { self.performSegueWithIdentifier("login", sender: nil) } } else { let alert = UIAlertView(title: "Success!", message: "", delegate: nil, cancelButtonTitle: "Okay.") alert.title = "Failed : (" alert.message = ":(" // Move to the UI thread dispatch_async(dispatch_get_main_queue(), { () -> Void in // Show the alert alert.show() }) } } } func post(params : Dictionary<String, String>, url : String, postCompleted : (succeeded: Bool, data: JSON) -> ()) { let request = NSMutableURLRequest(URL: NSURL(string: url)!) let session = NSURLSession.sharedSession() request.HTTPMethod = "POST" var err: Bool = false do { request.HTTPBody = try NSJSONSerialization.dataWithJSONObject(params, options: .PrettyPrinted) } catch { err = true } request.addValue("application/json", forHTTPHeaderField: "Content-Type") request.addValue("application/json", forHTTPHeaderField: "Accept") let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in let json = JSON(data: data!) // Did the JSONObjectWithData constructor return an error? If so, log the error to the console if(err || response == nil) { postCompleted(succeeded: false, data: "Error") } else { let statusCode = (response as! NSHTTPURLResponse).statusCode if statusCode == 200 { postCompleted(succeeded: true, data: json) return } else { // Woa, okay the json object was nil, something went worng. Maybe the server isn't running? postCompleted(succeeded: false, data: json) } } }) task.resume() } }
mit
5c4d09185e3f6440451e3e24a00bf7dd
37.055556
185
0.538153
5.1875
false
false
false
false
siemensikkema/Fairness
FairnessTests/ParticipantControllerTests.swift
1
3194
import XCTest import UIKit class ParticipantsControllerTests: XCTestCase { class ParticipantsStoreForTesting: ParticipantsStoreInterface { var argumentPassedToApplyAmounts: [Double] = [] var participantTransactionModels = ["name1", "name2"].map { ParticipantTransactionModel(participant: Participant(name: $0)) } func addParticipant() { participantTransactionModels.append(ParticipantTransactionModel(participant: Participant(name: "name3"))) } func applyAmounts(amounts: [Double]) { argumentPassedToApplyAmounts = amounts } func removeParticipantAtIndex(index: Int) { participantTransactionModels.removeAtIndex(index) } } var sut: ParticipantsController! var participantTransactionModelsFromCallback: [ParticipantTransactionModel]! var participantsStore: ParticipantsStoreForTesting! var tableView: UITableViewForTesting! let indexPath = NSIndexPath(forRow: 0, inSection: 0) var participantTransactionModelDataSource: TableViewDataSourceObjC! override func setUp() { tableView = UITableViewForTesting() participantsStore = ParticipantsStoreForTesting() sut = ParticipantsController(participantsStore: participantsStore) sut.participantTransactionModelUpdateCallbackOrNil = { participantTransactionModels in self.participantTransactionModelsFromCallback = participantTransactionModels } sut.tableView = tableView participantTransactionModelDataSource = tableView.dataSource as TableViewDataSourceObjC sut.participantTransactionModelUpdateCallbackOrNil = { participantTransactionModels in self.participantTransactionModelsFromCallback = participantTransactionModels } } func testApplyAmountsAddsSuppliedNumbersToParticipantsBalance() { let amounts = [0, 1.23] sut.applyAmounts(amounts) XCTAssertEqual(participantsStore.argumentPassedToApplyAmounts, amounts) } func testDataSourceIsSet() { XCTAssertNotNil(participantTransactionModelDataSource) } func testParticipantTransactionModelUpdateCallbackAfterSettingIt() { XCTAssertEqual(participantTransactionModelsFromCallback!.count, 2) XCTAssertEqual(participantTransactionModelDataSource.items.count, 2) } func testParticipantTransactionModelsFromCallbackAndDataSourceAreSameInstances() { XCTAssertEqual( ObjectIdentifier(participantTransactionModelsFromCallback.first!), ObjectIdentifier(participantTransactionModelDataSource.items.first! as ParticipantTransactionModel)) } func testAddParticipantUpdatesDataSource() { sut.addParticipant() XCTAssertEqual(participantTransactionModelDataSource.items.count, 3) } func testAddParticipantReloadsTableView() { sut.addParticipant() XCTAssertTrue(tableView.didCallReloadData) } func testDeletionCallbackCallsDeleteOnParticipantsController() { participantTransactionModelDataSource.deletionCallback?(tableView, indexPath) XCTAssertEqual(participantTransactionModelsFromCallback.first!.nameOrNil!, "name2") } }
mit
1adda79ed7981f931fb383ca851937cb
40.493506
133
0.760802
5.839122
false
true
false
false
dasdom/DDHCustomTransition
DDHCustomTransition/ViewController.swift
1
994
// // ViewController.swift // DDHCustomTransition // // Created by dasdom on 21.02.15. // Copyright (c) 2015 Dominik Hauser. All rights reserved. // import UIKit class ViewController: UIViewController, TransitionInfoProtocol { @IBOutlet weak var imageView: UIImageView! @IBOutlet weak var label: UILabel! func viewsToAnimate() -> [UIView] { return [imageView, label] } func copyForView(_ subView: UIView) -> UIView { if subView == imageView { let imageViewCopy = UIImageView(image: imageView.image) imageViewCopy.contentMode = imageView.contentMode imageViewCopy.clipsToBounds = true return imageViewCopy } else if subView == label { let labelCopy = UILabel() labelCopy.text = label.text labelCopy.font = label.font labelCopy.backgroundColor = view.backgroundColor return labelCopy } return UIView() } }
mit
ba52b0b22c3bed3156934ee184fc186f
26.611111
67
0.624748
4.825243
false
false
false
false
scootpl/Na4lapyAPI
Sources/Na4LapyCore/Shelter.swift
1
5556
// // Shelter.swift // Na4lapyAPI // // Created by Andrzej Butkiewicz on 23.12.2016. // Copyright © 2016 Stowarzyszenie Na4Łapy. All rights reserved. // import SwiftyJSON import Foundation import PostgreSQL struct Shelter { //TODO: Obsługa statusu active? private(set) var id: Int private var name: String private var street: String? private var buildingNumber: Int? private var city: String? private var postalCode: String? private var voivodeship: String? private var email: String? private var phoneNumber: String? private var website: String? private var facebookProfile: String? private var accountNumber: String? private var adoptionRules: String? init?(dictionary: DBEntry) { guard let id = dictionary[ShelterDBKey.id]?.int, let name = dictionary[ShelterDBKey.name]?.string else { return nil } self.id = id self.name = name self.street = dictionary[ShelterDBKey.street]?.string self.buildingNumber = dictionary[ShelterDBKey.building_number]?.int self.city = dictionary[ShelterDBKey.city]?.string self.postalCode = dictionary[ShelterDBKey.postal_code]?.string self.voivodeship = dictionary[ShelterDBKey.voivodeship]?.string self.email = dictionary[ShelterDBKey.email]?.string self.phoneNumber = dictionary[ShelterDBKey.phone_number]?.string self.website = dictionary[ShelterDBKey.website]?.string self.facebookProfile = dictionary[ShelterDBKey.facebook_profile]?.string self.accountNumber = dictionary[ShelterDBKey.account_number]?.string self.adoptionRules = dictionary[ShelterDBKey.adoption_rules]?.string } init?(withJSON json: JSONDictionary) { guard let id = json[ShelterJSON.id] as? Int, let name = json[ShelterJSON.name] as? String else { return nil } self.id = id self.name = name self.street = json[ShelterJSON.street] as? String self.buildingNumber = json[ShelterJSON.building_number] as? Int self.city = json[ShelterJSON.city] as? String self.postalCode = json[ShelterJSON.postal_code] as? String self.voivodeship = json[ShelterJSON.voivodeship] as? String self.email = json[ShelterJSON.email] as? String self.phoneNumber = json[ShelterJSON.phone_number] as? String self.website = json[ShelterJSON.website] as? String self.facebookProfile = json[ShelterJSON.facebook_profile] as? String self.accountNumber = json[ShelterJSON.account_number] as? String self.adoptionRules = json[ShelterJSON.adoption_rules] as? String } func dictionaryRepresentation() -> JSONDictionary { let street = self.street ?? "" let buildingNumber = self.buildingNumber ?? -1 let city = self.city ?? "" let postalCode = self.postalCode ?? "" let voivodeship = self.voivodeship ?? "" let email = self.email ?? "" let phoneNumber = self.phoneNumber ?? "" let website = self.website ?? "" let facebookProfile = self.facebookProfile ?? "" let accountNumber = self.accountNumber ?? "" let adoptionRules = self.adoptionRules ?? "" let dict: JSONDictionary = [ ShelterJSON.id : self.id, ShelterJSON.name : self.name, ShelterJSON.street : street, ShelterJSON.building_number : buildingNumber, ShelterJSON.city : city, ShelterJSON.postal_code : postalCode, ShelterJSON.voivodeship : voivodeship, ShelterJSON.email : email, ShelterJSON.phone_number : phoneNumber, ShelterJSON.website : website, ShelterJSON.facebook_profile : facebookProfile, ShelterJSON.account_number : accountNumber, ShelterJSON.adoption_rules : adoptionRules ] return dict } func dbRepresentation() -> DBEntry { let name = self.name.makeNode() let street = self.street?.makeNode() ?? Node.null let buildingNumber = try? self.buildingNumber?.makeNode() ?? Node.null let city = self.city?.makeNode() ?? Node.null let postalCode = self.postalCode?.makeNode() ?? Node.null let voivodeship = self.voivodeship?.makeNode() ?? Node.null let email = self.email?.makeNode() ?? Node.null let phoneNumber = self.phoneNumber?.makeNode() ?? Node.null let website = self.website?.makeNode() ?? Node.null let facebookProfile = self.facebookProfile?.makeNode() ?? Node.null let accountNumber = self.accountNumber?.makeNode() ?? Node.null let adoptionRules = self.adoptionRules?.makeNode() ?? Node.null let dbEntry: DBEntry = [ ShelterDBKey.id : Node(self.id), ShelterDBKey.name : name, ShelterDBKey.street : street, ShelterDBKey.building_number : buildingNumber ?? Node.null, ShelterDBKey.city : city, ShelterDBKey.postal_code : postalCode, ShelterDBKey.voivodeship : voivodeship, ShelterDBKey.email : email, ShelterDBKey.phone_number : phoneNumber, ShelterDBKey.website : website, ShelterDBKey.facebook_profile : facebookProfile, ShelterDBKey.account_number : accountNumber, ShelterDBKey.adoption_rules : adoptionRules ] return dbEntry } }
apache-2.0
2d41b97a799ab402664322703d86cd66
37.832168
80
0.640735
4.341673
false
false
false
false
bitjammer/swift
validation-test/compiler_crashers_fixed/01427-swift-typebase-getcanonicaltype.swift
65
599
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck S(h: Sequence, x in c == b() { typealias B.A<D> [") func g<B == c<T : Any) { protocol d { class c] { enum S() in x } let end = [c() { enum A { protocol d where H) { } } class B { } } func d<T: d where
apache-2.0
b813741f0bd48de466c7619d8a4cd8d0
25.043478
79
0.679466
3.169312
false
false
false
false
aotian16/Blog
Study/Dev/Swift/SwiftDesignPatterns/SwiftDesignPatterns_Iterator.playground/Contents.swift
1
875
// 迭代器模式 // 百度百科:提供一种方法顺序访问一个聚合对象中的各种元素,而又不暴露该对象的内部表示 // 设计模式分类:行为型模式 /** * 小说集类 */ struct NovellasCollection<T> { let novellas: [T] } // 实现SequenceType接口 extension NovellasCollection: SequenceType { typealias Generator = AnyGenerator<T> func generate() -> AnyGenerator<T> { var i = 0 return AnyGenerator{ if i >= self.novellas.count { return nil } else { let r = self.novellas[i] i += 1 return r } } } } let greatNovellas = NovellasCollection(novellas:["三国演义", "水浒", "红楼梦", "西游记"]) // 可以迭代 for novella in greatNovellas { print("I've read: \(novella)") }
cc0-1.0
288d63c0b2e7ea4aa356eb0a3f1068ad
19.314286
77
0.54993
3.291667
false
false
false
false
Sage-Bionetworks/BridgeAppSDK
BridgeAppSDK/SBAOnboardingSection.swift
1
7335
// // SBAOnboardingSection.swift // BridgeAppSDK // // Copyright © 2016 Sage Bionetworks. All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation and/or // other materials provided with the distribution. // // 3. Neither the name of the copyright holder(s) nor the names of any contributors // may be used to endorse or promote products derived from this software without // specific prior written permission. No license is granted to the trademarks of // the copyright holders even if such marks are included in this software. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // import Foundation import ResearchKit /** Onboarding can be broken into different sections. Which section is required depends upon the type of onboarding. */ public enum SBAOnboardingSectionBaseType: String { /** Section to include for login with a previously registered account. Included with `SBAOnboardingTaskType.login` */ case login = "login" /** Section to include for checking a potential participant's eligibility. Included with `SBAOnboardingTaskType.registration` */ case eligibility = "eligibility" /** Section to include for consenting a user. Either because the user is registering a new account or because there is a new consent document that the user must accept to continue participating in the study. Included with all onboarding types. */ case consent = "consent" /** Section to include to register a new account. Included with `SBAOnboardingTaskType.registration` */ case registration = "registration" /** Section to include if a passcode is to be set up for the app to lock the screen. Included with all types if there isn't already a passcode set up. */ case passcode = "passcode" /** Section to include during registration to allow the user to acknowledge that they have verified their email address. Included with `SBAOnboardingTaskType.registration` */ case emailVerification = "emailVerification" /** Section to include to set up any permissions that are included with either login or registration. */ case permissions = "permissions" /** Additional profile information is included if this is a new user. Included with `SBAOnboardingTaskType.registration` */ case profile = "profile" /** An optional completion section that is included with either login or registration. */ case completion = "completion" /** The sort order for the sections. */ func ordinal() -> Int { let order:[SBAOnboardingSectionBaseType] = SBAOnboardingSectionBaseType.all guard let ret = order.firstIndex(of: self) else { assertionFailure("\(self) ordinal value is unknown") return (order.firstIndex(of: .completion)! - 1) } return ret } /** List of all the sections include in the base types */ public static var all: [SBAOnboardingSectionBaseType] { return [.login, .eligibility, .consent, .registration, .passcode, .emailVerification, .permissions, .profile, .completion] } } /** Enum for extending the base sections defined in this SDK. */ public enum SBAOnboardingSectionType { case base(SBAOnboardingSectionBaseType) case custom(String) public init(rawValue: String) { if let baseType = SBAOnboardingSectionBaseType(rawValue: rawValue) { self = .base(baseType) } else { self = .custom(rawValue) } } public func baseType() -> SBAOnboardingSectionBaseType? { if case .base(let baseType) = self { return baseType } return nil } public var identifier: String { switch (self) { case .base(let baseType): return baseType.rawValue case .custom(let customType): return customType } } } extension SBAOnboardingSectionType: Equatable { } public func ==(lhs: SBAOnboardingSectionType, rhs: SBAOnboardingSectionType) -> Bool { switch (lhs, rhs) { case (.base(let lhsValue), .base(let rhsValue)): return lhsValue == rhsValue; case (.custom(let lhsValue), .custom(let rhsValue)): return lhsValue == rhsValue; default: return false } } extension SBAOnboardingSectionType: Hashable { public func hash(into hasher: inout Hasher) { switch (self) { case (.base(let value)): hasher.combine(value) case (.custom(let value)): hasher.combine(value) } } } /** Protocol for defining an onboarding section. */ public protocol SBAOnboardingSection: NSSecureCoding { /** The onboarding section type for this section. Determines into which types of onboarding this section should be included. */ var onboardingSectionType: SBAOnboardingSectionType? { get } /** The survey factory to be used by default with this section. */ func defaultOnboardingSurveyFactory() -> SBASurveyFactory /** A dictionary representation for this class that can be used to encode it */ func dictionaryRepresentation() -> [AnyHashable: Any] } extension NSDictionary: SBAOnboardingSection { public var onboardingSectionType: SBAOnboardingSectionType? { guard let onboardingType = self["onboardingType"] as? String else { return nil } return SBAOnboardingSectionType(rawValue: onboardingType); } public func defaultOnboardingSurveyFactory() -> SBASurveyFactory { let dictionary = self.objectWithResourceDictionary() as? NSDictionary ?? self return SBASurveyFactory(dictionary: dictionary) } public func dictionaryRepresentation() -> [AnyHashable: Any] { return self as! [AnyHashable: Any] } }
bsd-3-clause
045ae3d5ead3b035df47f282df2512ff
31.741071
94
0.664849
5.157525
false
false
false
false
danielsaidi/KeyboardKit
Demo/Keyboard/DemoKeyboardActionHandler.swift
1
3764
// // DemoKeyboardActionHandler.swift // KeyboardKit // // Created by Daniel Saidi on 2020-07-02. // Copyright © 2021 Daniel Saidi. All rights reserved. // import KeyboardKit import UIKit /** This action handler inherits `DemoKeyboardActionHandlerBase` and adds `SwiftUI` demo-specific functionality to it. */ class DemoKeyboardActionHandler: StandardKeyboardActionHandler { public init( inputViewController: KeyboardInputViewController, toastContext: KeyboardToastContext) { self.toastContext = toastContext super.init(inputViewController: inputViewController) } private let toastContext: KeyboardToastContext override func action(for gesture: KeyboardGesture, on action: KeyboardAction) -> GestureAction? { if gesture == .longPress, let action = longPressAction(for: action) { return action } if gesture == .tap, let action = tapAction(for: action) { return action } return super.action(for: gesture, on: action) } func longPressAction(for action: KeyboardAction) -> GestureAction? { switch action { case .image(_, _, let imageName): return { [weak self] _ in self?.saveImage(UIImage(named: imageName)!) } default: return nil } } func tapAction(for action: KeyboardAction) -> GestureAction? { switch action { case .image(_, _, let imageName): return { [weak self] _ in self?.copyImage(UIImage(named: imageName)!) } default: return nil } } // MARK: - Functions /** Override this function to implement a way to alert text messages in the keyboard extension. You can't use logic that you use in real apps, e.g. `UIAlertController`. */ func alert(_ message: String) { toastContext.present(message) } func copyImage(_ image: UIImage) { guard keyboardContext.hasFullAccess else { return alert("You must enable full access to copy images.") } guard image.copyToPasteboard() else { return alert("The image could not be copied.") } alert("Copied to pasteboard!") } func saveImage(_ image: UIImage) { guard keyboardContext.hasFullAccess else { return alert("You must enable full access to save images.") } image.saveToPhotos(completion: handleImageDidSave) } } private extension DemoKeyboardActionHandler { func handleImageDidSave(WithError error: Error?) { if error == nil { alert("Saved!") } else { alert("Failed!") } } } private extension UIImage { func copyToPasteboard(_ pasteboard: UIPasteboard = .general) -> Bool { guard let data = pngData() else { return false } pasteboard.setData(data, forPasteboardType: "public.png") return true } } private extension UIImage { func saveToPhotos(completion: @escaping (Error?) -> Void) { ImageService.default.saveImageToPhotos(self, completion: completion) } } /** This class is used as a target/selector holder by the image extension above. */ private class ImageService: NSObject { public typealias Completion = (Error?) -> Void public static private(set) var `default` = ImageService() private var completions = [Completion]() public func saveImageToPhotos(_ image: UIImage, completion: @escaping (Error?) -> Void) { completions.append(completion) UIImageWriteToSavedPhotosAlbum(image, self, #selector(saveImageToPhotosDidComplete), nil) } @objc func saveImageToPhotosDidComplete(_ image: UIImage, error: NSError?, contextInfo: UnsafeRawPointer) { guard completions.count > 0 else { return } completions.removeFirst()(error) } }
mit
a4877a044793cda73204f2a65da91a08
30.621849
113
0.664364
4.70375
false
false
false
false
KiiPlatform/thing-if-iOSSample
SampleProject/TriggerServerCodeEditViewController.swift
1
7250
import UIKit import ThingIFSDK protocol TriggerServerCodeEditViewControllerDelegate { func saveServerCode(serverCode: ServerCode) } struct ParameterStruct { var key: String var value: AnyObject var isString: Bool { return value is NSString } var isBool: Bool { if let num = value as? NSNumber { return num.isBool() } return false } var isInt: Bool { if let num = value as? NSNumber { return num.isInt() } return false } } class TriggerServerCodeEditViewController: KiiBaseTableViewController, TriggerServerCodeParameterEditViewControllerDelegate { var serverCode: ServerCode? = nil var delegate: TriggerServerCodeEditViewControllerDelegate? var parameters: [ParameterStruct] = [] override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) if parameters.isEmpty { if let params = serverCode?.parameters { for (key, value) in params { parameters.append(ParameterStruct(key: key, value: value)) } } } } @IBAction func tapNewParameter(sender: AnyObject) { var fields = Dictionary<String, String>() for rowIndex in 0...self.tableView.numberOfRowsInSection(0) { let indexPath : NSIndexPath = NSIndexPath(forItem: rowIndex, inSection: 0); let cell : UITableViewCell? = self.tableView.cellForRowAtIndexPath(indexPath); if let textField = cell?.viewWithTag(200) as? UITextField { fields[cell!.reuseIdentifier!] = textField.text! } } self.serverCode = ServerCode( endpoint: fields["EndpointCell"]!, executorAccessToken: fields["ExecutorAccessTokenCell"], targetAppID: fields["TargetAppIDCell"], parameters: nil) self.performSegueWithIdentifier("editServerCodeParameter", sender: self) } @IBAction func tapSaveServerCode(sender: AnyObject) { var fields = Dictionary<String, String>() for rowIndex in 0...self.tableView.numberOfRowsInSection(0) { let indexPath : NSIndexPath = NSIndexPath(forItem: rowIndex, inSection: 0); let cell : UITableViewCell? = self.tableView.cellForRowAtIndexPath(indexPath); if let textField = cell?.viewWithTag(200) as? UITextField { fields[cell!.reuseIdentifier!] = textField.text! } } let parameters = TriggerServerCodeEditViewController.parametersToDictionary( self.parameters) self.serverCode = ServerCode( endpoint: fields["EndpointCell"]!, executorAccessToken: fields["ExecutorAccessTokenCell"], targetAppID: fields["TargetAppIDCell"], parameters: parameters) if self.delegate != nil { self.delegate!.saveServerCode(self.serverCode!) } self.navigationController?.popViewControllerAnimated(true) } //MARK: Table view delegation methods override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 4 + (parameters.count ?? 0) } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var cell: UITableViewCell? if indexPath.row == 0 { // endpoint cell = tableView.dequeueReusableCellWithIdentifier("EndpointCell") if cell == nil { cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "EndpointCell") } if let textField = cell!.viewWithTag(200) as? UITextField { textField.text = serverCode!.endpoint } } else if indexPath.row == 1 { // executor access token cell = tableView.dequeueReusableCellWithIdentifier("ExecutorAccessTokenCell") if cell == nil { cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "ExecutorAccessTokenCell") } if let textField = cell!.viewWithTag(200) as? UITextField { textField.text = serverCode!.executorAccessToken } } else if indexPath.row == 2 { // target app id cell = tableView.dequeueReusableCellWithIdentifier("TargetAppIDCell") if cell == nil { cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "TargetAppIDCell") } if let textField = cell!.viewWithTag(200) as? UITextField { textField.text = serverCode!.targetAppID } } else if indexPath.row == 3 { // add new parameter button cell = tableView.dequeueReusableCellWithIdentifier("NewParameterButtonCell") if cell == nil { cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "NewParameterButtonCell") } } else { cell = tableView.dequeueReusableCellWithIdentifier("NewParameterCell") if cell == nil { cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "NewParameterCell") } let parameter = parameters[indexPath.row - 4] var parameterString = parameter.key + " = " if parameter.isString { parameterString += parameter.value as! String } else if parameter.isInt { parameterString += String(parameter.value as! NSNumber) } else if parameter.isBool { parameterString += String(parameter.value as! Bool) } cell?.textLabel?.text = parameterString } return cell! } override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { return true } func saveParameter(parameters: [ParameterStruct]) { self.parameters = parameters self.serverCode = ServerCode( endpoint: self.serverCode!.endpoint, executorAccessToken: self.serverCode!.executorAccessToken, targetAppID: self.serverCode!.targetAppID, parameters: TriggerServerCodeEditViewController.parametersToDictionary( parameters)) tableView.reloadData() self.refreshControl?.endRefreshing() } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "editServerCodeParameter" { if let editParameterVC = segue.destinationViewController as? TriggerServerCodeParameterEditViewController { editParameterVC.parameters = self.parameters editParameterVC.delegate = self } } } private static func parametersToDictionary( parameters: [ParameterStruct]) -> Dictionary<String, AnyObject> { var retval: Dictionary<String, AnyObject> = [ : ] for parameter in parameters { retval[parameter.key] = parameter.value } return retval } }
mit
d4693db84327bc2d763a5e69909b3393
39.277778
125
0.624
5.513308
false
false
false
false
AnneBlair/Aphrodite
Aphrodite/UIViewAttribute.swift
1
2875
// // UIViewAttribute.swift // Aphrodite // // Created by AnneBlair on 2017/9/9. // Copyright © 2017年 blog.aiyinyu.com. All rights reserved. // import Foundation /// 加载 xib 内的 UIView /// /// - Parameters: /// - name: the UIStoryboard Name /// - indentifier: UIStoryboard Indentifier /// - Returns: UIViewController func xibLoad(name: String) -> View? { let view = Bundle.main.loadNibNamed(name, owner: nil, options: nil)?.last as? UIView return view } /// <#Description#> /// /// - Returns: <#return value description#> func screenSize() -> CGSize { return UIScreen.main.bounds.size } /// 加载 StoryBoard 内的 UIViewController /// /// - Parameters: /// - name: UIStoryboard Name /// - indentifier: StoryBoard Indentifier /// - Returns: UIViewController func storyBoard(name: String, indentifier: String) -> UIViewController { return UIStoryboard(name: name, bundle: nil).instantiateViewController(withIdentifier: indentifier) } /// 直接加载 StoryBoard /// /// - Parameter forStoryboardName: StoryBoard Name /// - Returns: StoryBoard VC public func viewController(forStoryboardName: String) -> UIViewController { return UIStoryboard(name: forStoryboardName, bundle: nil).instantiateInitialViewController()! } /// image 安全不崩溃的命名原则 class TemplateImageView: ImageView { @IBInspectable var templateImage: Image? { didSet { image = templateImage?.withRenderingMode(.alwaysTemplate) } } } /// 设置顶部电池栏的颜色 /// /// - Parameter black: 黑色或者白色 public func viewTopStaus(black: Bool) { var barStyle: UIStatusBarStyle = .default switch black { case true: barStyle = .default default: barStyle = .lightContent } UIApplication.shared.statusBarStyle = barStyle } /// 设置背景渐变 /// /// - Parameters: /// - begin: 开始的颜色 0x123456 /// - end: 结束的颜色 0X123456 /// - frame: 所加的背景的范围 /// - Returns: CAGradientLayer public func bkShadeColor(begin: Int,end: Int, frame: CGRect) -> CAGradientLayer { let layer = CAGradientLayer() layer.colors = [Color(hex: begin).cgColor,Color(hex: end).cgColor] layer.frame = frame return layer } /// 设置透明导航栏 /// /// - Parameter nav: public func navigationLayerShade(nav: UINavigationController) { nav.navigationBar.setBackgroundImage(UIImage(), for: .default) nav.navigationBar.shadowImage = UIImage() } /// 设置导航栏的颜色 /// /// - Parameters: /// - nav: 导航栏控制器 /// - color: 颜色 public func setNavigationColor(nav: UINavigationController,color: Color) { let image = Image(color: Color(hex: 0x58101D), size: CGSize(width: UIScreeWidth, height: 64)) nav.navigationBar.setBackgroundImage(image, for: .default) nav.navigationBar.shadowImage = Image() }
mit
e5943e837d7a524c371c0844985c98f0
25.752475
103
0.688749
3.915942
false
false
false
false
gottesmm/swift
stdlib/public/SDK/Intents/INIntegerResolutionResult.swift
3
878
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// @_exported import Intents import Foundation #if os(iOS) @available(iOS 10.0, *) extension INIntegerResolutionResult { @nonobjc public static func confirmationRequired(with valueToConfirm: Int?) -> Self { let number = valueToConfirm.map { NSNumber(value: $0) } return __confirmationRequiredWithValue(toConfirm: number) } } #endif
apache-2.0
5e12d904395dafa41e788efb6b8c9a23
34.12
80
0.594533
4.824176
false
false
false
false
ppwwyyxx/tensorflow
tensorflow/lite/experimental/swift/TestApp/TestApp/ViewController.swift
9
10492
// Copyright 2019 Google Inc. 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 TensorFlowLite import UIKit class ViewController: UIViewController { // MARK: - Properties /// TensorFlow Lite interpreter object for performing inference from a given model. private var interpreter: Interpreter? /// Serial dispatch queue for managing `Interpreter` calls. private let interpreterQueue = DispatchQueue( label: Constant.dispatchQueueLabel, qos: .userInitiated ) /// The currently selected model. private var currentModel: Model { guard let currentModel = Model(rawValue: modelControl.selectedSegmentIndex) else { preconditionFailure("Invalid model for selected segment index.") } return currentModel } /// A description of the current model. private var modelDescription: String { guard let interpreter = interpreter else { return "" } let inputCount = interpreter.inputTensorCount let outputCount = interpreter.outputTensorCount let inputTensors = (0..<inputCount).map { index in var tensorInfo = " Input \(index + 1): " do { let tensor = try interpreter.input(at: index) tensorInfo += "\(tensor)" } catch let error { tensorInfo += "\(error.localizedDescription)" } return tensorInfo }.joined(separator: "\n") let outputTensors = (0..<outputCount).map { index in var tensorInfo = " Output \(index + 1): " do { let tensor = try interpreter.output(at: index) tensorInfo += "\(tensor)" } catch let error { tensorInfo += "\(error.localizedDescription)" } return tensorInfo }.joined(separator: "\n") return "Model Description:\n" + " Input Tensor Count = \(inputCount)\n\(inputTensors)\n\n" + " Output Tensor Count = \(outputCount)\n\(outputTensors)" } // MARK: - IBOutlets /// A segmented control for changing models. See the `Model` enum for available models. @IBOutlet private var modelControl: UISegmentedControl! @IBOutlet private var resultsTextView: UITextView! @IBOutlet private var invokeButton: UIBarButtonItem! // MARK: - UIViewController override func viewDidLoad() { super.viewDidLoad() invokeButton.isEnabled = false updateResultsText("Using TensorFlow Lite runtime version \(TensorFlowLite.Runtime.version).") loadModel() } // MARK: - IBActions @IBAction func modelChanged(_ sender: Any) { invokeButton.isEnabled = false updateResultsText("Switched to the \(currentModel.description) model.") loadModel() } @IBAction func invokeInterpreter(_ sender: Any) { switch currentModel { case .add: invokeAdd() case .addQuantized: invokeAddQuantized() case .multiAdd: invokeMultiAdd() } } // MARK: - Private private func loadModel() { let fileInfo = currentModel.fileInfo guard let modelPath = Bundle.main.path(forResource: fileInfo.name, ofType: fileInfo.extension) else { updateResultsText("Failed to load the \(currentModel.description) model.") return } setUpInterpreter(withModelPath: modelPath) } private func setUpInterpreter(withModelPath modelPath: String) { interpreterQueue.async { do { var options = Interpreter.Options() options.threadCount = 2 self.interpreter = try Interpreter(modelPath: modelPath, options: options) } catch let error { self.updateResultsText( "Failed to create the interpreter with error: \(error.localizedDescription)" ) return } safeDispatchOnMain { self.invokeButton.isEnabled = true } } } private func invokeAdd() { interpreterQueue.async { guard let interpreter = self.interpreter else { self.updateResultsText(Constant.nilInterpreterErrorMessage) return } do { try interpreter.resizeInput(at: 0, to: [2]) try interpreter.allocateTensors() let input: [Float32] = [1, 3] let resultsText = self.modelDescription + "\n\n" + "Performing 2 add operations on input \(input.description) equals: " self.updateResultsText(resultsText) let data = Data(copyingBufferOf: input) try interpreter.copy(data, toInputAt: 0) try interpreter.invoke() let outputTensor = try interpreter.output(at: 0) let results: () -> String = { guard let results = [Float32](unsafeData: outputTensor.data) else { return "No results." } return resultsText + results.description } self.updateResultsText(results()) } catch let error { self.updateResultsText( "Failed to invoke the interpreter with error: \(error.localizedDescription)" ) return } } } private func invokeAddQuantized() { interpreterQueue.async { guard let interpreter = self.interpreter else { self.updateResultsText(Constant.nilInterpreterErrorMessage) return } do { try interpreter.resizeInput(at: 0, to: [2]) try interpreter.allocateTensors() let input: [UInt8] = [1, 3] let resultsText = self.modelDescription + "\n\n" + "Performing 2 add operations on quantized input \(input.description) equals: " self.updateResultsText(resultsText) let data = Data(input) try interpreter.copy(data, toInputAt: 0) try interpreter.invoke() let outputTensor = try interpreter.output(at: 0) let results: () -> String = { guard let quantizationParameters = outputTensor.quantizationParameters else { return "No results." } let quantizedResults = [UInt8](outputTensor.data) let dequantizedResults = quantizedResults.map { quantizationParameters.scale * Float(Int($0) - quantizationParameters.zeroPoint) } return resultsText + quantizedResults.description + ", dequantized results: " + dequantizedResults.description } self.updateResultsText(results()) } catch let error { self.updateResultsText( "Failed to invoke the interpreter with error: \(error.localizedDescription)" ) return } } } private func invokeMultiAdd() { interpreterQueue.async { guard let interpreter = self.interpreter else { self.updateResultsText(Constant.nilInterpreterErrorMessage) return } do { let shape = Tensor.Shape(2) try (0..<interpreter.inputTensorCount).forEach { index in try interpreter.resizeInput(at: index, to: shape) } try interpreter.allocateTensors() let inputs = try (0..<interpreter.inputTensorCount).map { index -> [Float32] in let input = [Float32(index + 1), Float32(index + 2)] let data = Data(copyingBufferOf: input) try interpreter.copy(data, toInputAt: index) return input } let resultsText = self.modelDescription + "\n\n" + "Performing 3 add operations on inputs \(inputs.description) equals: " self.updateResultsText(resultsText) try interpreter.invoke() let results = try (0..<interpreter.outputTensorCount).map { index -> [Float32] in let tensor = try interpreter.output(at: index) return [Float32](unsafeData: tensor.data) ?? [] } self.updateResultsText(resultsText + results.description) } catch let error { self.updateResultsText( "Failed to invoke the interpreter with error: \(error.localizedDescription)" ) return } } } private func updateResultsText(_ text: String? = nil) { safeDispatchOnMain { self.resultsTextView.text = text } } } // MARK: - Constants private enum Constant { static let dispatchQueueLabel = "TensorFlowLiteInterpreterQueue" static let nilInterpreterErrorMessage = "Failed to invoke the interpreter because the interpreter was nil." } /// Models that can be loaded by the TensorFlow Lite `Interpreter`. private enum Model: Int, CustomStringConvertible { /// A float model that performs two add operations on one input tensor and returns the result in /// one output tensor. case add = 0 /// A quantized model that performs two add operations on one input tensor and returns the result /// in one output tensor. case addQuantized = 1 /// A float model that performs three add operations on four input tensors and returns the results /// in 2 output tensors. case multiAdd = 2 var fileInfo: (name: String, extension: String) { switch self { case .add: return Add.fileInfo case .addQuantized: return AddQuantized.fileInfo case .multiAdd: return MultiAdd.fileInfo } } // MARK: - CustomStringConvertible var description: String { switch self { case .add: return Add.name case .addQuantized: return AddQuantized.name case .multiAdd: return MultiAdd.name } } } /// Values for the `Add` model. private enum Add { static let name = "Add" static let fileInfo = (name: "add", extension: "bin") } /// Values for the `AddQuantized` model. private enum AddQuantized { static let name = "AddQuantized" static let fileInfo = (name: "add_quantized", extension: "bin") } /// Values for the `MultiAdd` model. private enum MultiAdd { static let name = "MultiAdd" static let fileInfo = (name: "multi_add", extension: "bin") } // MARK: - Fileprivate /// Safely dispatches the given block on the main queue. If the current thread is `main`, the block /// is executed synchronously; otherwise, the block is executed asynchronously on the main thread. fileprivate func safeDispatchOnMain(_ block: @escaping () -> Void) { if Thread.isMainThread { block(); return } DispatchQueue.main.async { block() } }
apache-2.0
67e8e23da62fe1980007b57e6c530bbf
32.414013
100
0.662314
4.460884
false
false
false
false
zhixingxi/JJA_Swift
JJA_Swift/Pods/TimedSilver/Sources/UIKit/UIScreen+TSExtension.swift
1
2376
// // UIScreen+TSExtension.swift // TimedSilver // Source: https://github.com/hilen/TimedSilver // // Created by Hilen on 11/3/15. // Copyright © 2015 Hilen. All rights reserved. // import Foundation import UIKit public extension UIScreen { /// The screen size class var ts_size: CGSize { return UIScreen.main.bounds.size } /// The screen's width class var ts_width: CGFloat { return UIScreen.main.bounds.size.width } /// The screen's height class var ts_height: CGFloat { return UIScreen.main.bounds.size.height } /// The screen's orientation size @available(iOS 8.0, *) class var ts_orientationSize: CGSize { guard let app = UIApplication.ts_sharedApplication() else { return CGSize.zero } let systemVersion = (UIDevice.current.systemVersion as NSString).floatValue let isLand: Bool = UIInterfaceOrientationIsLandscape(app.statusBarOrientation) return (systemVersion > 8.0 && isLand) ? UIScreen.ts_swapSize(self.ts_size) : self.ts_size } /// The screen's orientation width class var ts_orientationWidth: CGFloat { return self.ts_orientationSize.width } /// The screen's orientation height class var ts_orientationHeight: CGFloat { return self.ts_orientationSize.height } /// The screen's DPI size class var ts_DPISize: CGSize { let size: CGSize = UIScreen.main.bounds.size let scale: CGFloat = UIScreen.main.scale return CGSize(width: size.width * scale, height: size.height * scale) } /** Swap size - parameter size: The target size - returns: CGSize */ class func ts_swapSize(_ size: CGSize) -> CGSize { return CGSize(width: size.height, height: size.width) } /// The screen's height without status bar's height @available(iOS 8.0, *) class var ts_screenHeightWithoutStatusBar: CGFloat { guard let app = UIApplication.ts_sharedApplication() else { return 0 } if UIInterfaceOrientationIsPortrait(app.statusBarOrientation) { return UIScreen.main.bounds.size.height - app.statusBarFrame.height } else { return UIScreen.main.bounds.size.width - app.statusBarFrame.height } } }
mit
931dbdcaeeaa55b614e7e5f21d54deb6
27.614458
98
0.634105
4.390018
false
false
false
false
yahua/YAHCharts
Source/Charts/Renderers/XAxisRendererHorizontalBarChart.swift
1
13511
// // XAxisRendererHorizontalBarChart.swift // Charts // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/Charts // import Foundation import CoreGraphics #if !os(OSX) import UIKit #endif open class XAxisRendererHorizontalBarChart: XAxisRenderer { internal var chart: BarChartView? public init(viewPortHandler: ViewPortHandler?, xAxis: XAxis?, transformer: Transformer?, chart: BarChartView?) { super.init(viewPortHandler: viewPortHandler, xAxis: xAxis, transformer: transformer) self.chart = chart } open override func computeAxis(min: Double, max: Double, inverted: Bool) { guard let viewPortHandler = self.viewPortHandler else { return } var min = min, max = max if let transformer = self.transformer { // calculate the starting and entry point of the y-labels (depending on // zoom / contentrect bounds) if viewPortHandler.contentWidth > 10 && !viewPortHandler.isFullyZoomedOutX { let p1 = transformer.valueForTouchPoint(CGPoint(x: viewPortHandler.contentLeft, y: viewPortHandler.contentBottom)) let p2 = transformer.valueForTouchPoint(CGPoint(x: viewPortHandler.contentLeft, y: viewPortHandler.contentTop)) if inverted { min = Double(p2.y) max = Double(p1.y) } else { min = Double(p1.y) max = Double(p2.y) } } } computeAxisValues(min: min, max: max) } open override func computeSize() { guard let xAxis = self.axis as? XAxis else { return } let longest = xAxis.getLongestLabel() as NSString let labelSize = longest.size(attributes: [NSFontAttributeName: xAxis.labelFont]) let labelWidth = floor(labelSize.width + xAxis.xOffset * 3.5) let labelHeight = labelSize.height let labelRotatedSize = ChartUtils.sizeOfRotatedRectangle(rectangleWidth: labelSize.width, rectangleHeight: labelHeight, degrees: xAxis.labelRotationAngle) xAxis.labelWidth = labelWidth xAxis.labelHeight = labelHeight xAxis.labelRotatedWidth = round(labelRotatedSize.width + xAxis.xOffset * 3.5) xAxis.labelRotatedHeight = round(labelRotatedSize.height) } open override func renderAxisLabels(context: CGContext) { guard let xAxis = self.axis as? XAxis, let viewPortHandler = self.viewPortHandler else { return } if !xAxis.isEnabled || !xAxis.isDrawLabelsEnabled || chart?.data === nil { return } let xoffset = xAxis.xOffset if xAxis.labelPosition == .top { drawLabels(context: context, pos: viewPortHandler.contentRight + xoffset, anchor: CGPoint(x: 0.0, y: 0.5)) } else if xAxis.labelPosition == .topInside { drawLabels(context: context, pos: viewPortHandler.contentRight - xoffset, anchor: CGPoint(x: 1.0, y: 0.5)) } else if xAxis.labelPosition == .bottom { drawLabels(context: context, pos: viewPortHandler.contentLeft - xoffset, anchor: CGPoint(x: 1.0, y: 0.5)) } else if xAxis.labelPosition == .bottomInside { drawLabels(context: context, pos: viewPortHandler.contentLeft + xoffset, anchor: CGPoint(x: 0.0, y: 0.5)) } else { // BOTH SIDED drawLabels(context: context, pos: viewPortHandler.contentRight + xoffset, anchor: CGPoint(x: 0.0, y: 0.5)) drawLabels(context: context, pos: viewPortHandler.contentLeft - xoffset, anchor: CGPoint(x: 1.0, y: 0.5)) } } /// draws the x-labels on the specified y-position open override func drawLabels(context: CGContext, pos: CGFloat, anchor: CGPoint) { guard let xAxis = self.axis as? XAxis, let transformer = self.transformer, let viewPortHandler = self.viewPortHandler else { return } let labelRotationAngleRadians = xAxis.labelRotationAngle * ChartUtils.Math.FDEG2RAD let centeringEnabled = xAxis.isCenterAxisLabelsEnabled // pre allocate to save performance (dont allocate in loop) var position = CGPoint(x: 0.0, y: 0.0) for i in stride(from: 0, to: xAxis.entryCount, by: 1) { // only fill x values position.x = 0.0 if centeringEnabled { position.y = CGFloat(xAxis.centeredEntries[i]) } else { position.y = CGFloat(xAxis.entries[i]) } transformer.pointValueToPixel(&position) //x轴每一个显示一种字体和颜色 var labelFont = xAxis.labelFont if i<xAxis.labelFonts.count { labelFont = xAxis.labelFonts[i] } var labelTextColor = xAxis.labelTextColor if i<xAxis.labelTextColors.count { labelTextColor = xAxis.labelTextColors[i] } if viewPortHandler.isInBoundsY(position.y) { if let label = xAxis.valueFormatter?.stringForValue(xAxis.entries[i], axis: xAxis) { drawLabel( context: context, formattedLabel: label, x: pos, y: position.y, attributes: [NSFontAttributeName: labelFont, NSForegroundColorAttributeName: labelTextColor], anchor: anchor, angleRadians: labelRotationAngleRadians) } } } } open func drawLabel( context: CGContext, formattedLabel: String, x: CGFloat, y: CGFloat, attributes: [String: NSObject], anchor: CGPoint, angleRadians: CGFloat) { ChartUtils.drawText( context: context, text: formattedLabel, point: CGPoint(x: x, y: y), attributes: attributes, anchor: anchor, angleRadians: angleRadians) } open override var gridClippingRect: CGRect { var contentRect = viewPortHandler?.contentRect ?? CGRect.zero let dy = self.axis?.gridLineWidth ?? 0.0 contentRect.origin.y -= dy / 2.0 contentRect.size.height += dy return contentRect } fileprivate var _gridLineSegmentsBuffer = [CGPoint](repeating: CGPoint(), count: 2) open override func drawGridLine(context: CGContext, x: CGFloat, y: CGFloat) { guard let viewPortHandler = self.viewPortHandler else { return } if viewPortHandler.isInBoundsY(y) { context.beginPath() context.move(to: CGPoint(x: viewPortHandler.contentLeft, y: y)) context.addLine(to: CGPoint(x: viewPortHandler.contentRight, y: y)) context.strokePath() } } open override func renderAxisLine(context: CGContext) { guard let xAxis = self.axis as? XAxis, let viewPortHandler = self.viewPortHandler else { return } if !xAxis.isEnabled || !xAxis.isDrawAxisLineEnabled { return } context.saveGState() context.setStrokeColor(xAxis.axisLineColor.cgColor) context.setLineWidth(xAxis.axisLineWidth) if xAxis.axisLineDashLengths != nil { context.setLineDash(phase: xAxis.axisLineDashPhase, lengths: xAxis.axisLineDashLengths) } else { context.setLineDash(phase: 0.0, lengths: []) } if xAxis.labelPosition == .top || xAxis.labelPosition == .topInside || xAxis.labelPosition == .bothSided { context.beginPath() context.move(to: CGPoint(x: viewPortHandler.contentRight, y: viewPortHandler.contentTop)) context.addLine(to: CGPoint(x: viewPortHandler.contentRight, y: viewPortHandler.contentBottom)) context.strokePath() } if xAxis.labelPosition == .bottom || xAxis.labelPosition == .bottomInside || xAxis.labelPosition == .bothSided { context.beginPath() context.move(to: CGPoint(x: viewPortHandler.contentLeft, y: viewPortHandler.contentTop)) context.addLine(to: CGPoint(x: viewPortHandler.contentLeft, y: viewPortHandler.contentBottom)) context.strokePath() } context.restoreGState() } open override func renderLimitLines(context: CGContext) { guard let xAxis = self.axis as? XAxis, let viewPortHandler = self.viewPortHandler, let transformer = self.transformer else { return } var limitLines = xAxis.limitLines if limitLines.count == 0 { return } let trans = transformer.valueToPixelMatrix var position = CGPoint(x: 0.0, y: 0.0) for i in 0 ..< limitLines.count { let l = limitLines[i] if !l.isEnabled { continue } context.saveGState() defer { context.restoreGState() } var clippingRect = viewPortHandler.contentRect clippingRect.origin.y -= l.lineWidth / 2.0 clippingRect.size.height += l.lineWidth context.clip(to: clippingRect) position.x = 0.0 position.y = CGFloat(l.limit) position = position.applying(trans) context.beginPath() context.move(to: CGPoint(x: viewPortHandler.contentLeft, y: position.y)) context.addLine(to: CGPoint(x: viewPortHandler.contentRight, y: position.y)) context.setStrokeColor(l.lineColor.cgColor) context.setLineWidth(l.lineWidth) if l.lineDashLengths != nil { context.setLineDash(phase: l.lineDashPhase, lengths: l.lineDashLengths!) } else { context.setLineDash(phase: 0.0, lengths: []) } context.strokePath() let label = l.label // if drawing the limit-value label is enabled if l.drawLabelEnabled && label.characters.count > 0 { let labelLineHeight = l.valueFont.lineHeight let xOffset: CGFloat = 4.0 + l.xOffset let yOffset: CGFloat = l.lineWidth + labelLineHeight + l.yOffset if l.labelPosition == .rightTop { ChartUtils.drawText(context: context, text: label, point: CGPoint( x: viewPortHandler.contentRight - xOffset, y: position.y - yOffset), align: .right, attributes: [NSFontAttributeName: l.valueFont, NSForegroundColorAttributeName: l.valueTextColor]) } else if l.labelPosition == .rightBottom { ChartUtils.drawText(context: context, text: label, point: CGPoint( x: viewPortHandler.contentRight - xOffset, y: position.y + yOffset - labelLineHeight), align: .right, attributes: [NSFontAttributeName: l.valueFont, NSForegroundColorAttributeName: l.valueTextColor]) } else if l.labelPosition == .leftTop { ChartUtils.drawText(context: context, text: label, point: CGPoint( x: viewPortHandler.contentLeft + xOffset, y: position.y - yOffset), align: .left, attributes: [NSFontAttributeName: l.valueFont, NSForegroundColorAttributeName: l.valueTextColor]) } else { ChartUtils.drawText(context: context, text: label, point: CGPoint( x: viewPortHandler.contentLeft + xOffset, y: position.y + yOffset - labelLineHeight), align: .left, attributes: [NSFontAttributeName: l.valueFont, NSForegroundColorAttributeName: l.valueTextColor]) } } } } }
mit
4d71e023daaa9976baedd7e2470a9731
34.208877
163
0.534742
5.583851
false
false
false
false
DaftMobile/ios4beginners_2017
Class 5/Class5.playground/Pages/TableViews.xcplaygroundpage/Contents.swift
1
1384
//: A UIKit based Playground for presenting user interface import UIKit import PlaygroundSupport class MyViewController : UIViewController, UITableViewDataSource, UITableViewDelegate { var tableView: UITableView! override func loadView() { self.view = UIView() view.backgroundColor = .white tableView = UITableView(frame: .zero, style: .plain) view.addSubview(tableView) view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "|[tableView]|", options: [], metrics: nil, views: ["tableView": tableView])) view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[tableView]|", options: [], metrics: nil, views: ["tableView": tableView])) tableView.translatesAutoresizingMaskIntoConstraints = false } override func viewDidLoad() { super.viewDidLoad() tableView.delegate = self tableView.dataSource = self tableView.register(UITableViewCell.self, forCellReuseIdentifier: "CELL") } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 0 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let cell = tableView.dequeueReusableCell(withIdentifier: "CELL") else { fatalError() } return cell } } // Present the view controller in the Live View window PlaygroundPage.current.liveView = MyViewController()
apache-2.0
40c2425d3038c861eaa467b066db215c
35.421053
150
0.757225
4.890459
false
false
false
false
Luavis/Kasa
Kasa.swift/LyricWindow.swift
1
1446
// // LyricWindow.swift // Kasa.swift // // Created by Luavis Kang on 12/2/15. // Copyright © 2015 Luavis. All rights reserved. // import Foundation class LyricWindow: OverlayWindow{ @IBOutlet weak var lyricLabel: ShadowLabel! @IBOutlet weak var informationLabel: ShadowLabel! override func awakeFromNib() { self.backgroundColor = NSColor.blackColor().colorWithAlphaComponent(0.00) self.collectionBehavior.insert(.CanJoinAllSpaces) super.awakeFromNib() } override func mouseEntered(theEvent: NSEvent) { self.backgroundColor = NSColor.blackColor().colorWithAlphaComponent(0.15) self.informationLabel.hidden = false; NSAnimationContext.runAnimationGroup({ (context) -> Void in self.informationLabel.alphaValue = 1.0; }) { () -> Void in super.mouseEntered(theEvent) } } override func mouseExited(theEvent: NSEvent) { self.backgroundColor = NSColor.blackColor().colorWithAlphaComponent(0.00) NSAnimationContext.runAnimationGroup({ (context) -> Void in self.informationLabel.alphaValue = 0.0; }) { () -> Void in self.informationLabel.hidden = true; super.mouseExited(theEvent) } } func setLyricText(value: String) { dispatch_async(dispatch_get_main_queue()) { self.lyricLabel.stringValue = value } } }
mit
f1525871861d85031aff88a387e5ba83
29.104167
81
0.643599
4.601911
false
false
false
false
JoeLago/MHGDB-iOS
MHGDB/Screens/Weapon/WeaponDetails.swift
1
1368
// // MIT License // Copyright (c) Gathering Hall Studios // import UIKit class WeaponDetails: DetailController, DetailScreen { var id: Int convenience init(id: Int) { self.init(Database.shared.weapon(id: id)) } init(_ weapon: Weapon) { id = weapon.id super.init() title = weapon.name addCustomSection(data: [weapon], cellType: WeaponCell.self) add(section: WeaponDetailSection(weapon: weapon)) if weapon.ammo != nil { addCustomSection(title: "Ammo", data: [weapon], cellType: AmmoCell.self) } addSimpleSection(data: weapon.components, title: "Components") { ItemDetails(id: $0.id) } let result = Database.shared.weaponTree(weaponId: weapon.id) let path = TreeSection<Weapon, WeaponView>(tree: result.1) { self.push(WeaponDetails(id: $0.id)) } path.selectedNode = result.0 path.title = "Path" add(section: path) } required init?(coder aDecoder: NSCoder) { fatalError("I don't want to use storyboards Apple") } } extension Component: DetailCellModel { var primary: String? { return name } var subtitle: String? { return type } var secondary: String? { return "x \(quantity)" } var imageName: String? { return icon } }
mit
0379fa735a68da66356194e0f9823f9e
26.918367
97
0.600877
4.035398
false
false
false
false
pmlbrito/cookiecutter-ios-template
{{ cookiecutter.project_name | replace(' ', '') }}/app/{{ cookiecutter.project_name | replace(' ', '') }}/Domain/Models/Common/ProcessResult.swift
1
837
// // ProcessResult.swift // {{ cookiecutter.project_name | replace(' ', '') }} // // Created by {{ cookiecutter.lead_dev }} on 28/06/2017. // Copyright © 2017 {{ cookiecutter.company_name }}. All rights reserved. // import Foundation open class ProcessResult { enum Status: Int { case ok = 1 case error = 2 case unknown = -1 } var statusCode: Status var message: String? init(status: Status) { self.statusCode = status self.message = nil } convenience init(resultCode: Int) { self.init(status: Status(rawValue: resultCode) ?? .unknown) } init(status: Status, resultMessage: String?) { self.statusCode = status self.message = resultMessage } func hasError() -> Bool { return self.statusCode == .error } }
mit
03813e3fac307f408d2539100ed32ee8
21
74
0.594498
4.038647
false
false
false
false
haskellswift/swift-package-manager
Tests/FunctionalTests/ClangModuleTests.swift
2
6161
/* This source file is part of the Swift.org open source project Copyright 2015 - 2016 Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for Swift project authors */ import XCTest import TestSupport import Basic import PackageModel import Utility extension String { // FIXME: It doesn't seem right for this to be an extension on String; it isn't inherent "string behavior". fileprivate var soname: String { return "lib\(self).\(Product.dynamicLibraryExtension)" } } class ClangModulesTestCase: XCTestCase { func testSingleModuleFlatCLibrary() { fixture(name: "ClangModules/CLibraryFlat") { prefix in XCTAssertBuilds(prefix) let debugPath = prefix.appending(components: ".build", "debug") XCTAssertFileExists(debugPath.appending(components: "CLibraryFlat".soname)) } } func testSingleModuleCLibraryInSources() { fixture(name: "ClangModules/CLibrarySources") { prefix in XCTAssertBuilds(prefix) let debugPath = prefix.appending(components: ".build", "debug") XCTAssertFileExists(debugPath.appending(component: "CLibrarySources".soname)) } } func testMixedSwiftAndC() { fixture(name: "ClangModules/SwiftCMixed") { prefix in XCTAssertBuilds(prefix) let debugPath = prefix.appending(components: ".build", "debug") XCTAssertFileExists(debugPath.appending(component: "SeaLib".soname)) XCTAssertFileExists(debugPath.appending(component: "SeaExec")) var output = try popen([debugPath.appending(component: "SeaExec").asString]) XCTAssertEqual(output, "a = 5\n") output = try popen([debugPath.appending(component: "CExec").asString]) XCTAssertEqual(output, "5") } } func testExternalSimpleCDep() { fixture(name: "DependencyResolution/External/SimpleCDep") { prefix in XCTAssertBuilds(prefix.appending(component: "Bar")) let debugPath = prefix.appending(components: "Bar", ".build", "debug") XCTAssertFileExists(debugPath.appending(component: "Bar")) XCTAssertFileExists(debugPath.appending(component: "Foo".soname)) XCTAssertDirectoryExists(prefix.appending(components: "Bar", "Packages", "Foo-1.2.3")) } } func testiquoteDep() { fixture(name: "ClangModules/CLibraryiquote") { prefix in XCTAssertBuilds(prefix) let debugPath = prefix.appending(components: ".build", "debug") XCTAssertFileExists(debugPath.appending(component: "Foo".soname)) XCTAssertFileExists(debugPath.appending(component: "Bar".soname)) XCTAssertFileExists(debugPath.appending(component: "Bar with spaces".soname)) } } func testCUsingCDep() { fixture(name: "DependencyResolution/External/CUsingCDep") { prefix in XCTAssertBuilds(prefix.appending(component: "Bar")) let debugPath = prefix.appending(components: "Bar", ".build", "debug") XCTAssertFileExists(debugPath.appending(component: "Foo".soname)) XCTAssertDirectoryExists(prefix.appending(components: "Bar", "Packages", "Foo-1.2.3")) } } func testCExecutable() { fixture(name: "ValidLayouts/SingleModule/CExecutable") { prefix in XCTAssertBuilds(prefix) let debugPath = prefix.appending(components: ".build", "debug") XCTAssertFileExists(debugPath.appending(component: "CExecutable")) let output = try popen([debugPath.appending(component: "CExecutable").asString]) XCTAssertEqual(output, "hello 5") } } func testCUsingCDep2() { //The C dependency "Foo" has different layout fixture(name: "DependencyResolution/External/CUsingCDep2") { prefix in XCTAssertBuilds(prefix.appending(component: "Bar")) let debugPath = prefix.appending(components: "Bar", ".build", "debug") XCTAssertFileExists(debugPath.appending(component: "Foo".soname)) XCTAssertDirectoryExists(prefix.appending(components: "Bar", "Packages", "Foo-1.2.3")) } } func testModuleMapGenerationCases() { fixture(name: "ClangModules/ModuleMapGenerationCases") { prefix in XCTAssertBuilds(prefix) let debugPath = prefix.appending(components: ".build", "debug") XCTAssertFileExists(debugPath.appending(component: "UmbrellaHeader".soname)) XCTAssertFileExists(debugPath.appending(component: "FlatInclude".soname)) XCTAssertFileExists(debugPath.appending(component: "UmbellaModuleNameInclude".soname)) XCTAssertFileExists(debugPath.appending(component: "NoIncludeDir".soname)) XCTAssertFileExists(debugPath.appending(component: "Baz")) } } func testCanForwardExtraFlagsToClang() { // Try building a fixture which needs extra flags to be able to build. fixture(name: "ClangModules/CDynamicLookup") { prefix in XCTAssertBuilds(prefix, Xld: ["-undefined", "dynamic_lookup"]) let debugPath = prefix.appending(components: ".build", "debug") XCTAssertFileExists(debugPath.appending(component: "CDynamicLookup".soname)) } } static var allTests = [ ("testSingleModuleFlatCLibrary", testSingleModuleFlatCLibrary), ("testSingleModuleCLibraryInSources", testSingleModuleCLibraryInSources), ("testMixedSwiftAndC", testMixedSwiftAndC), ("testExternalSimpleCDep", testExternalSimpleCDep), ("testiquoteDep", testiquoteDep), ("testCUsingCDep", testCUsingCDep), ("testCUsingCDep2", testCUsingCDep2), ("testCExecutable", testCExecutable), ("testModuleMapGenerationCases", testModuleMapGenerationCases), ("testCanForwardExtraFlagsToClang", testCanForwardExtraFlagsToClang), ] }
apache-2.0
83beb9e3d14240b43b6e8036fe493c04
43.970803
111
0.668236
4.660363
false
true
false
false
creatubbles/ctb-api-swift
CreatubblesAPIClient/Sources/Requests/Creation/NewCreationUploadRequest.swift
1
3648
// // NewCreationUploadRequest.swift // CreatubblesAPIClient // // Copyright (c) 2017 Creatubbles Pte. 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 UIKit @objc public enum UploadExtension: Int { case png case jpg case jpeg case h264 case gif case mpeg4 case wmv case webm case flv case ogg case ogv case mp4 case m4V case mov case uzpb case zip public var stringValue: String { switch self { case .png: return "png" case .jpg: return "jpg" case .jpeg: return "jpeg" case .h264: return "h264" case .gif: return "gif" case .mpeg4: return "mpeg4" case .wmv: return "wmv" case .webm: return "webm" case .flv: return "flv" case .ogg: return "ogg" case .ogv: return "ogv" case .mp4: return "mp4" case .m4V: return "m4v" case .mov: return "mov" case .uzpb: return "uzpb" case .zip: return "zip" } } public static func fromString(_ stringValue: String) -> UploadExtension? { if stringValue == "png" { return .png } if stringValue == "jpg" { return .jpg } if stringValue == "jpeg" { return .jpeg } if stringValue == "h264" { return .h264 } if stringValue == "gif" { return .gif } if stringValue == "mpeg4" { return .mpeg4 } if stringValue == "wmv" { return .wmv } if stringValue == "webm" { return .webm } if stringValue == "flv" { return .flv } if stringValue == "ogg" { return .ogg } if stringValue == "ogv" { return .ogv } if stringValue == "mp4" { return .mp4 } if stringValue == "m4v" { return .m4V } if stringValue == "mov" { return .mov } if stringValue == "uzpb" { return .uzpb } return nil } } class NewCreationUploadRequest: Request { override var method: RequestMethod { return .post } override var endpoint: String { return "creations/"+creationId+"/uploads" } override var parameters: Dictionary<String, AnyObject> { if let ext = creationExtension { return ["extension": ext.stringValue as AnyObject] } return Dictionary<String, AnyObject>() } fileprivate let creationId: String fileprivate let creationExtension: UploadExtension? init(creationId: String, creationExtension: UploadExtension? = nil) { self.creationId = creationId self.creationExtension = creationExtension } }
mit
1e38ac9be5aa51c5198c58f64dad38bd
34.417476
81
0.628564
4.183486
false
false
false
false
louisdh/lioness
Sources/Lioness/AST/ASTChildNode.swift
1
538
// // ASTChildNode.swift // Lioness // // Created by Louis D'hauwe on 04/11/2016. // Copyright © 2016 - 2017 Silver Fox. All rights reserved. // import Foundation public struct ASTChildNode { public let connectionToParent: String? public let isConnectionConditional: Bool public let node: ASTNode init(connectionToParent: String? = nil, isConnectionConditional: Bool = false, node: ASTNode) { self.connectionToParent = connectionToParent self.node = node self.isConnectionConditional = isConnectionConditional } }
mit
4a3abf55c67fe395e00ed234733cf792
19.653846
96
0.748603
3.808511
false
false
false
false
codeliling/HXDYWH
dywh/dywh/views/MapArticlePanelView.swift
1
1790
// // MapArticlePanelView.swift // dywh // // Created by lotusprize on 15/6/8. // Copyright (c) 2015年 geekTeam. All rights reserved. // import Foundation class MapArticlePanelView: UIView { var imageLayer:CALayer = CALayer() var titleLayer:CATextLayer = CATextLayer() var descriptionLayer:CATextLayer = CATextLayer() var title:String? var articleDescription:String? init(frame: CGRect, title:String, articleDescription:String) { super.init(frame: frame) self.title = title self.articleDescription = articleDescription } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func drawRect(rect: CGRect) { imageLayer.frame = CGRectMake(3, 3, self.frame.width / 7 * 3, self.frame.height - 6) self.layer.addSublayer(imageLayer) titleLayer.frame = CGRectMake(self.frame.width / 7 * 3 + 10, 10, self.frame.width / 7 * 3, self.frame.height / 3) titleLayer.foregroundColor = UIColor.darkGrayColor().CGColor titleLayer.fontSize = 22.0 titleLayer.string = title titleLayer.contentsScale = 2.0 titleLayer.wrapped = true titleLayer.truncationMode = kCATruncationEnd self.layer.addSublayer(titleLayer) descriptionLayer.frame = CGRectMake(self.frame.width / 7 * 3 + 10, 10 + self.frame.height / 3, self.frame.width / 7 * 3, self.frame.height / 3 * 2 - 5) descriptionLayer.foregroundColor = UIColor .darkGrayColor().CGColor descriptionLayer.string = articleDescription descriptionLayer.fontSize = 16.0 descriptionLayer.contentsScale = 2.0 self.layer.addSublayer(descriptionLayer) } }
apache-2.0
7078290444789374fdd8ffcb6923cf9b
33.403846
159
0.658277
4.329298
false
false
false
false
Trevi-Swift/Trevi
Sources/IncomingMessage.swift
1
1397
// // IncomingMessage.swift // Trevi // // Created by LeeYoseob on 2016. 3. 3.. // Copyright © 2016 Trevi Community. All rights reserved. // import Foundation // Class we use to handle a request. public class IncomingMessage: StreamReadable{ public var socket: Socket! public var connection: Socket! // HTTP header public var header: [ String: String ]! public var httpVersionMajor: String = "1" public var httpVersionMinor: String = "1" public var version : String{ return "\(httpVersionMajor).\(httpVersionMinor)" } public var method: HTTPMethodType! // Seperated path by component from the requested url public var pathComponent: [String] = [ String ] () // Qeury string from requested url // ex) /url?id="123" public var query = [ String: String ] () public var path = "" public var hasBody: Bool! //server only public var url: String! //response only public var statusCode: String! public var client: AnyObject! public init(socket: Socket){ super.init() self.socket = socket self.connection = socket self.client = socket } deinit{ socket = nil connection = nil client = nil } public override func _read(n: Int) { } }
apache-2.0
b0a90be9dcefae721130c58648027a81
19.835821
58
0.588109
4.517799
false
false
false
false
orj/Manoeuvre
Manoeuvre/Steerable.swift
1
3748
// Copyright (c) 2014 Oliver Jones. All rights reserved. // import UIKit public struct SteeringForce<T> { let value : T } public protocol Positionable { typealias PositionType var position: PositionType { get set } } public protocol Steerable : Positionable { typealias VectorType typealias PositionType = VectorType var velocity: VectorType { get set } /// A normalized vector pointing in the direction the entity is heading. var heading : VectorType { get set } /// A vector perpendicular to the heading vector. var side : VectorType { get } var mass: Mass { get } /// The maximum speed at which this entity may travel. var maxSpeed : CGFloat { get } /// The maximum force this entity can produce to power itself (thrust). var maxForce : CGFloat { get } /// The maximum rate (radians per second) at which this vehicle can rotate. var maxTurnRate : RadiansPerSecond { get } } //func steer<T:Vector2DType, S:Steerable where S.VectorType == T, S.PositionType == T>(steerable: S, force : SteeringForce<T>, timeElapsed: NSTimeInterval) -> (position:T, heading:T, velocity:T) { // var acceleration = force.value / steerable.mass.value // // var velocity = truncate(steerable.velocity + (acceleration * timeElapsed), steerable.maxSpeed) // var position = steerable.position + (velocity * timeElapsed) // var heading = steerable.heading // // if (velocity.lengthSquared > 0.000000001) { // heading = normalize(velocity) // } // // return (position, heading, velocity) //// steerable.position = position //// steerable.velocity = velocity //// steerable.heading = heading //} public protocol SteeringBehaviour { typealias SteerableType: Steerable func calculate(steerable:SteerableType) -> SteeringForce<SteerableType.VectorType> } public class SeekBehaviour : SteeringBehaviour { public typealias SteerableType = Vehicle public let target:Target init(target:Target) { self.target = target } public func calculate(steerable:Vehicle) -> SteeringForce<Vehicle.VectorType> { var s = self.target.position - steerable.position var headingToTarget = s.normalized var desiredVelocity = headingToTarget * steerable.maxSpeed var velocity = desiredVelocity - steerable.velocity return SteeringForce<Vehicle.VectorType>(value: velocity) } } public class Target : Positionable { public typealias PositionType = Vector2 public var position: Vector2 public init() { self.position = Vector2.zeroVector } } public class Vehicle : Target, Steerable { public typealias VectorType = Vector2 public typealias PositionType = VectorType public var heading:VectorType public var velocity:VectorType /// A vector perpendicular to the heading vector. public var side : VectorType { return perpendicular(heading) } public var mass: Mass { return Mass(value: 1.0) } /// The maximum speed at which this entity may travel. public var maxSpeed : CGFloat { return 10.0 } /// The maximum force this entity can produce to power itself (thrust). public var maxForce : CGFloat { return 1.0 } /// The maximum rate (radians per second) at which this vehicle can rotate. public var maxTurnRate : RadiansPerSecond { return RadiansPerSecond(value: 1.0) } public override init() { self.heading = Vector2(1, 0) self.velocity = Vector2.zeroVector super.init() } } func doIt() { let t = Target() let v = Vehicle() var b = SeekBehaviour(target: t) b.calculate(v) }
mit
54cf5030ea46b11c31f7e12e75b3879e
27.830769
196
0.670491
4.249433
false
false
false
false
flypaper0/ethereum-wallet
ethereum-wallet/Classes/PresentationLayer/Wallet/Transactions/View/TransactionsViewController.swift
1
3754
// Copyright © 2018 Conicoin LLC. All rights reserved. // Created by Artur Guseinov import UIKit import SafariServices import Dwifft class TransactionsViewController: UIViewController { @IBOutlet var tableView: UITableView! var output: TransactionsViewOutput! var diffCalculator: TableViewDiffCalculator<Date, TransactionDisplayer>! private var transactions = [TransactionDisplayer]() private var refresh = UIRefreshControl() // MARK: Life cycle override func viewDidLoad() { super.viewDidLoad() localize() setupDiffCalculator() setupTableView() output.viewIsReady() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) output.viewIsAppear() } // MARK: Privates private func localize() { navigationItem.title = Localized.transactionsTitle() } private func setupTableView() { tableView.setupBorder() tableView.refreshControl = refresh tableView.registerNib(TransactionCell.self) tableView.setEmptyView(with: Localized.transactionsEmptyTitle()) refresh.addTarget(self, action: #selector(refresh(_:)), for: .valueChanged) } private func setupDiffCalculator() { diffCalculator = TableViewDiffCalculator(tableView: tableView) diffCalculator.deletionAnimation = .fade diffCalculator.insertionAnimation = .fade } @objc func refresh(_ sender: UIRefreshControl) { sender.setFallbackTime(3) output.didRefresh() } } // MARK: - TransactionsViewInput extension TransactionsViewController: TransactionsViewInput { func setTransactions(_ transactions: [TransactionDisplayer]) { self.transactions = transactions diffCalculator.sectionedValues = { return SectionedValues<Date, TransactionDisplayer>(values: transactions, valueToSection: { tx in return Calendar.current.startOfDay(for: tx.time) }, sortSections: { $0 > $1 }, sortValues: { $0.time > $1.time }) }() } func setupInitialState() { } func stopRefreshing() { refresh.endRefreshing() } } // MARK: - Table View extension TransactionsViewController: UITableViewDataSource, UITableViewDelegate { func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeue(TransactionCell.self, for: indexPath) let transaction = diffCalculator.value(atIndexPath: indexPath) cell.configure(with: transaction) return cell } func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let header = tableView.dequeue(TransactionHeaderCell.self) let sectionKey = diffCalculator.value(forSection: section) header.timeLabel.text = sectionKey.dayDifference() // returning contentView is a workaround: section headers disappear when using -performBatchUpdates // https://stackoverflow.com/questions/30149551/tableview-section-headers-disappear-swift return header.contentView } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return diffCalculator.numberOfObjects(inSection: section) } func numberOfSections(in tableView: UITableView) -> Int { return diffCalculator.numberOfSections() } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 76 } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 52 } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) let transaction = diffCalculator.value(atIndexPath: indexPath) output.didTransactionPressed(transaction) } }
gpl-3.0
090e1d3e1f6f2c58dede8531a684e230
28.320313
103
0.732214
4.912304
false
false
false
false
RobinRH/family-history-booklet
GlobalData.swift
1
1704
// // GlobalData.swift // Copyright © 2017 Robin Reynolds. All rights reserved. // import Foundation class GlobalData { static var oneTree = FamilyTree() static var selectedFamily = Family() static var selectedParent = Person() static var selectedFather = Person() static var selectedMother = Person() static var selectedChild = Person() static var selectedPerson = Person() static func readFamilyTree() { let defaults: UserDefaults = UserDefaults.standard if (defaults.object(forKey: "data") == nil) { GlobalData.oneTree = FamilyTree() GlobalData.writeFamilyTree() } else { let dataString = defaults.object(forKey: "data") as! String let jd = JSONDecoder() var tree : FamilyTree? = nil do { try tree = jd.decode(FamilyTree.self, from: dataString.data(using: .utf8)!) GlobalData.oneTree = tree! } catch { GlobalData.oneTree = FamilyTree() GlobalData.writeFamilyTree() } } } static func readFamilyTree(json : Data) { let jd = JSONDecoder() let tree = try? jd.decode(FamilyTree.self, from: json) GlobalData.oneTree = tree! } static func writeFamilyTree() { let defaults: UserDefaults = UserDefaults.standard let je = JSONEncoder() je.outputFormatting = .prettyPrinted let data = try? je.encode(GlobalData.oneTree) let dataString = String(data: data!, encoding: .utf8)! defaults.set(dataString as String, forKey: "data") defaults.synchronize() } }
apache-2.0
7011b4a3555a89aa452ad9afc2158f76
30.537037
91
0.594833
4.517241
false
false
false
false
akuraru/MuscleAssert-Objective-C
MuscleAssert/Swift/MuscleAssert.swift
1
1727
// // MuscleAssert.swift // MuscleAssert // // Created by akuraru on 2016/12/17. // // class MuscleAssert: MUSDeepDiffProtocol { var formatter: MUSFormatterProtocol let optionalDiffer = MUSOptionalDiffer() var differ: [MUSCustomDiffer] var lastDiffer: [MUSCustomDiffer] init() { differ = [ MUSStringDiffer(), MUSDateDiffer(), MUSURLDiffer(), MUSNumberDiffer(), MUSDictionaryDiffer(), MUSArrayDiffer() ] lastDiffer = [ MUSSameAnyObjectDiff(), MUSSameTypeDiffer(), MUSDifferentTypeDiffer(), ] formatter = MUSStandardFormatter() } func deepStricEqual(left: Any?, right: Any?) -> String? { return deepStricEqual(left:left, right:right, message:nil) } func deepStricEqual(left :Any?, right: Any?, message: String?) -> String? { let differences = diff(left:left, right:right, path:nil) return formatter.format(message:message, differences:differences) } func diff(left: Any?, right: Any?, path: String?) -> [MUSDifference] { guard let l = left, let r = right else { return optionalDiffer.diff(left: left, right: right, path: path, delegatge: self) } let allDiffer = differ + lastDiffer for diff in allDiffer { if diff.match(left:l, right:r) { return diff.diff(left:l, right:r, path:path, delegatge:self) } } return [] } func cons(custom: MUSCustomDiffer) { differ.insert(custom, at: 0) } func add(custom: MUSCustomDiffer) { differ.append(custom) } }
mit
117f779ee223aeb1bd443161c5426ef1
26.854839
93
0.576144
3.9161
false
false
false
false
TucoBZ/GitHub_APi_Test
GitHub_API/UserViewController.swift
1
5901
// // UserViewController.swift // GitHub_API // // Created by Túlio Bazan da Silva on 11/01/16. // Copyright © 2016 TulioBZ. All rights reserved. // import UIKit import PINRemoteImage final class UserViewController: UIViewController{ // MARK: - Variables var users : Array<User>? var filteredArray : Array<User>? var connection : APIConnection? var searchController : UISearchController! var shouldShowSearchResults = false @IBOutlet var tableView: UITableView! // MARK: - Initialization override func viewDidLoad() { super.viewDidLoad() users = [] filteredArray = [] configureSearchController() configureConnection() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) { if (segue.identifier == "detailSegue") { if let detailViewController: DetailViewController = segue.destinationViewController as? DetailViewController { detailViewController.repo = sender as? Array<Repository> } } } func configureSearchController() { // Initialize and perform a minimum configuration to the search controller. searchController = UISearchController(searchResultsController: nil) searchController.searchResultsUpdater = self searchController.dimsBackgroundDuringPresentation = false searchController.searchBar.placeholder = "Search here..." searchController.searchBar.delegate = self searchController.searchBar.sizeToFit() // Place the search bar view to the tableview headerview. tableView.tableHeaderView = searchController.searchBar } func configureConnection(){ connection = APIConnection.init(connectionDelegate: self, currentView: self.view) connection?.getUsers(0) } } // MARK: - UITableViewDelegate extension UserViewController: UITableViewDelegate { func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { if shouldShowSearchResults { if searchController.active { searchController.searchBar.resignFirstResponder() searchController.active = false } if let name = filteredArray?[indexPath.row].login{ connection?.getRepositoriesFromUser(name) } }else{ if let name = users?[indexPath.row].login{ connection?.getRepositoriesFromUser(name) } } } } // MARK: - UITableViewDataSource extension UserViewController: UITableViewDataSource { func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if shouldShowSearchResults { return filteredArray?.count ?? 0 } return users?.count ?? 0 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var cell = UITableViewCell() if let reuseblecell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as? UITableViewCell { if shouldShowSearchResults { //User Name if let name = filteredArray?[indexPath.row].login{ reuseblecell.textLabel?.text = name } //Image if let imageURL = filteredArray?[indexPath.row].avatar_url{ reuseblecell.imageView?.pin_setImageFromURL(NSURL(string:imageURL), placeholderImage: UIImage(named: "githubPlaceHolder")) } } else { //User Name if let name = users?[indexPath.row].login, let id = users?[indexPath.row].id{ reuseblecell.textLabel?.text = "\(name) - ID: \(id)" if users!.count-1 == indexPath.row{ connection?.getUsers(id) } } //Image if let imageURL = users?[indexPath.row].avatar_url{ reuseblecell.imageView?.pin_setImageFromURL(NSURL(string:imageURL), placeholderImage: UIImage(named: "githubPlaceHolder")) } } cell = reuseblecell } return cell } } // MARK: - UISearchBarDelegate extension UserViewController: UISearchBarDelegate { func updateSearchResultsForSearchController(searchController: UISearchController) {} } // MARK: - UISearchResultsUpdating extension UserViewController: UISearchResultsUpdating { func searchBarTextDidBeginEditing(searchBar: UISearchBar) { shouldShowSearchResults = false filteredArray = [] } func searchBarCancelButtonClicked(searchBar: UISearchBar) { shouldShowSearchResults = false filteredArray = [] tableView.reloadData() } func searchBarSearchButtonClicked(searchBar: UISearchBar) { if !shouldShowSearchResults { shouldShowSearchResults = true connection?.searchForUser(searchBar.text!) } searchController.searchBar.resignFirstResponder() } } // MARK: - ConnectionDelegate extension UserViewController: ConnectionDelegate { func updatedUsers(users: Array<User>) { self.users?.appendAll(users) tableView?.reloadData() } func updatedSearchUsers(users: Array<User>) { filteredArray = users tableView?.reloadData() } func updatedRepositories(repositories: Array<Repository>) { performSegueWithIdentifier("detailSegue", sender: repositories) } func updatedSearchRepositories(repositories: Array<Repository>){} }
mit
b19372d72bdd2a137f46e6ed928313b5
33.296512
142
0.63943
5.834817
false
false
false
false
ustwo/videoplayback-ios
VideoPlaybackKit/View/Video/VPKPlaybackControlView.swift
1
9144
// // VPKVideoToolBarView.swift // VideoPlaybackKit // // Created by Sonam on 4/21/17. // Copyright © 2017 ustwo. All rights reserved. // import Foundation import UIKit import MediaPlayer import ASValueTrackingSlider public class VPKPlaybackControlView: UIView { //Protocol weak var presenter: VPKVideoPlaybackPresenterProtocol? var theme: ToolBarTheme = .normal var progressValue: Float = 0.0 { didSet { DispatchQueue.main.async { self.playbackProgressSlider.value = self.progressValue } } } var maximumSeconds: Float = 0.0 { didSet { playbackProgressSlider.maximumValue = maximumSeconds } } //Private fileprivate var playPauseButton = UIButton(frame: .zero) private let fullScreen = UIButton(frame: .zero) private let volumeCtrl = MPVolumeView() private let expandButton = UIButton(frame: .zero) fileprivate let timeProgressLabel = UILabel(frame: .zero) fileprivate let durationLabel = UILabel(frame: .zero) private let skipBackButton = UIButton(frame: .zero) private let skipForwardButton = UIButton(frame: .zero) private let bottomControlContainer = UIView(frame: .zero) fileprivate let playbackProgressSlider = ASValueTrackingSlider(frame: .zero) convenience init(theme: ToolBarTheme) { self.init(frame: .zero) self.theme = theme setup() } override init(frame: CGRect) { super.init(frame: frame) playbackProgressSlider.dataSource = self } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func setup() { switch theme { case .normal: setupNormalColorTheme() setupNormalLayout() case .custom(bottomBackgroundColor: _, sliderBackgroundColor: _, sliderIndicatorColor: _, sliderCalloutColors: _): setupNormalLayout() setupCustomColorWith(theme: theme) } } private func setupNormalColorTheme() { bottomControlContainer.backgroundColor = VPKColor.backgroundiOS11Default.rgbColor playbackProgressSlider.textColor = VPKColor.borderiOS11Default.rgbColor playbackProgressSlider.backgroundColor = VPKColor.timeSliderBackground.rgbColor playbackProgressSlider.popUpViewColor = .white } private func setupCustomColorWith(theme: ToolBarTheme) { switch theme { case let .custom(bottomBackgroundColor: bottomBGColor, sliderBackgroundColor: sliderBGColor, sliderIndicatorColor: sliderIndicatorColor, sliderCalloutColors: calloutColors): self.bottomControlContainer.backgroundColor = bottomBGColor self.playbackProgressSlider.backgroundColor = sliderBGColor self.playbackProgressSlider.textColor = sliderIndicatorColor self.playbackProgressSlider.popUpViewAnimatedColors = calloutColors default: break } } private func setupNormalLayout() { isUserInteractionEnabled = true addSubview(bottomControlContainer) bottomControlContainer.snp.makeConstraints { (make) in make.left.equalTo(self).offset(6.5) make.right.equalTo(self).offset(-6.5) make.height.equalTo(47) make.bottom.equalTo(self.snp.bottom).offset(-6.5) } bottomControlContainer.layer.cornerRadius = 16.0 bottomControlContainer.layer.borderColor = VPKColor.borderiOS11Default.rgbColor.cgColor bottomControlContainer.layer.borderWidth = 0.5 let blurContainer = UIView(frame: .zero) bottomControlContainer.addSubview(blurContainer) blurContainer.snp.makeConstraints { (make) in make.edges.equalTo(bottomControlContainer) } blurContainer.backgroundColor = .clear blurContainer.isUserInteractionEnabled = true blurContainer.clipsToBounds = true let blurEffect = self.defaultBlurEffect() blurContainer.addSubview(blurEffect) blurEffect.snp.makeConstraints { (make) in make.edges.equalToSuperview() } blurContainer.layer.cornerRadius = bottomControlContainer.layer.cornerRadius bottomControlContainer.addSubview(playPauseButton) playPauseButton.snp.makeConstraints { (make) in make.left.equalTo(bottomControlContainer).offset(8.0) make.centerY.equalTo(bottomControlContainer) make.height.width.equalTo(28) } playPauseButton.setBackgroundImage(UIImage(named: PlayerState.paused.buttonImageName), for: .normal) playPauseButton.contentMode = .scaleAspectFit playPauseButton.addTarget(self, action: #selector(didTapPlayPause), for: .touchUpInside) bottomControlContainer.addSubview(timeProgressLabel) bottomControlContainer.addSubview(playbackProgressSlider) timeProgressLabel.snp.makeConstraints { (make) in make.left.equalTo(playPauseButton.snp.right).offset(8.0) make.centerY.equalTo(bottomControlContainer) make.right.equalTo(playbackProgressSlider.snp.left).offset(-6.0) } timeProgressLabel.textColor = UIColor(white: 1.0, alpha: 0.75) timeProgressLabel.text = "0:00" bottomControlContainer.addSubview(durationLabel) playbackProgressSlider.snp.makeConstraints { (make) in make.left.equalTo(timeProgressLabel.snp.right).offset(5.0) make.right.equalTo(durationLabel.snp.left).offset(-5.0).priority(1000) make.centerY.equalTo(bottomControlContainer) make.height.equalTo(5.0) } playbackProgressSlider.addTarget(self, action: #selector(didScrub), for: .valueChanged) playbackProgressSlider.setContentCompressionResistancePriority(UILayoutPriorityDefaultLow, for: .horizontal) playbackProgressSlider.setContentHuggingPriority(UILayoutPriorityDefaultHigh, for: .horizontal) bottomControlContainer.addSubview(durationLabel) durationLabel.snp.makeConstraints { (make) in make.right.equalTo(bottomControlContainer.snp.right).offset(-8.0) make.centerY.equalTo(bottomControlContainer) } durationLabel.textColor = UIColor(white: 1.0, alpha: 0.75) durationLabel.text = "0:00" durationLabel.setContentCompressionResistancePriority(UILayoutPriorityDefaultHigh, for: .horizontal) durationLabel.setContentHuggingPriority(UILayoutPriorityFittingSizeLevel, for: .horizontal) addSubview(expandButton) expandButton.layer.cornerRadius = 16.0 expandButton.backgroundColor = VPKColor.backgroundiOS11Default.rgbColor expandButton.snp.makeConstraints { (make) in make.left.equalTo(self).offset(8.0) make.width.equalTo(30) make.height.equalTo(30) make.top.equalTo(self).offset(8.0) } expandButton.setBackgroundImage(#imageLiteral(resourceName: "defaultExpand"), for: .normal) expandButton.addTarget(self, action: #selector(didTapExpandView), for: .touchUpInside) bottomControlContainer.setContentHuggingPriority(UILayoutPriorityDefaultHigh, for: .horizontal) } } extension VPKPlaybackControlView: ASValueTrackingSliderDataSource { public func slider(_ slider: ASValueTrackingSlider!, stringForValue value: Float) -> String! { return presenter?.formattedProgressTime(from: TimeInterval(value)) } } extension VPKPlaybackControlView: VPKPlaybackControlViewProtocol { func showDurationWith(_ time: String) { durationLabel.text = time layoutIfNeeded() } func didSkipBack(_ seconds: Float = 15.0) { presenter?.didSkipBack(seconds) } func didSkipForward(_ seconds: Float = 15.0) { presenter?.didSkipForward(seconds) } func updateTimePlayingCompletedTo(_ time: String) { timeProgressLabel.text = time } func didScrub() { #if DEBUG print("USER SCRUBBED TO \(playbackProgressSlider.value)") #endif presenter?.didScrubTo(TimeInterval(playbackProgressSlider.value)) } func didTapExpandView() { presenter?.didExpand() } func toggleActionButton(_ imageName: String) { playPauseButton.setBackgroundImage(UIImage(named: imageName), for: .normal) } func didTapPlayPause() { presenter?.didTapVideoView() } } extension VPKPlaybackControlView { func defaultBlurEffect() -> UIVisualEffectView { let blurEffect = UIBlurEffect(style: .dark) let blurEffectView = UIVisualEffectView(effect: blurEffect) blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight] blurEffectView.clipsToBounds = true return blurEffectView } }
mit
4318614e73452131cdbc64cf8b1773fa
36.166667
181
0.675599
5.040243
false
false
false
false
crossroadlabs/Swirl
Sources/Swirl/Limit.swift
1
1035
//===--- Limit.swift ------------------------------------------------------===// //Copyright (c) 2017 Crossroad Labs s.r.o. // //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. //===----------------------------------------------------------------------===// public enum Limit { case limit(Int) case offset(Int, limit:Int) } extension Limit { init(limit:Int, offset:Int? = nil) { if let offset = offset { self = .offset(offset, limit: limit) } else { self = .limit(limit) } } }
apache-2.0
9686ffc3418a665379de30bb4d9b225d
33.5
80
0.582609
4.404255
false
false
false
false
jpush/aurora-imui
iOS/IMUIMessageCollectionView/Controllers/IMUIVideoFileLoader.swift
1
3791
// // IMUIVideoFileLoader.swift // IMUIChat // // Created by oshumini on 2017/3/24. // Copyright © 2017年 HXHG. All rights reserved. // import UIKit import AVFoundation typealias ReadFrameCallBack = (CGImage) -> () class IMUIVideoFileLoader: NSObject { var readFrameCallback: ReadFrameCallBack? static let queue = OperationQueue() var videoReadOperation: IMUIVideFileLoaderOperation? var isNeedToStopVideo: Bool { set { self.videoReadOperation?.isNeedToStop = newValue } get { return true } } func loadVideoFile(with url: URL, callback: @escaping ReadFrameCallBack) { self.readFrameCallback = callback videoReadOperation?.isNeedToStop = true videoReadOperation = IMUIVideFileLoaderOperation(url: url, callback: callback) IMUIVideoFileLoader.queue.addOperation(videoReadOperation!) return } } class IMUIVideFileLoaderOperation: Operation { var isNeedToStop = false var previousFrameTime: CMTime? var url: URL var readFrameCallback: ReadFrameCallBack init(url: URL, callback: @escaping ReadFrameCallBack) { self.url = url self.readFrameCallback = callback super.init() } override func main() { self.isNeedToStop = false do { while !self.isNeedToStop { let videoAsset = AVAsset(url: url) let reader = try AVAssetReader(asset: videoAsset) let videoTracks = videoAsset.tracks(withMediaType: AVMediaType.video) let videoTrack = videoTracks[0] let options = [String(kCVPixelBufferPixelFormatTypeKey): kCVPixelFormatType_32BGRA] let videoReaderOutput = AVAssetReaderTrackOutput(track: videoTrack, outputSettings: options) reader.add(videoReaderOutput) reader.startReading() while reader.status == .reading && videoTrack.nominalFrameRate > 0 { let videoBuffer = videoReaderOutput.copyNextSampleBuffer() if videoBuffer == nil { if reader.status != .cancelled { reader.cancelReading() } break } let image = self.imageFromSampleBuffer(sampleBuffer: videoBuffer!) if self.isNeedToStop != true { self.readFrameCallback(image) } else { break } usleep(41666) if reader.status == .completed { reader.cancelReading() } } } } catch { print("can not load video file") return } } fileprivate func imageFromSampleBuffer(sampleBuffer: CMSampleBuffer) -> CGImage { let imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) CVPixelBufferLockBaseAddress(imageBuffer!, CVPixelBufferLockFlags(rawValue: 0)) let baseAddress = CVPixelBufferGetBaseAddress(imageBuffer!) let bytesPerRow = CVPixelBufferGetBytesPerRow(imageBuffer!) let width = CVPixelBufferGetWidth(imageBuffer!) let height = CVPixelBufferGetHeight(imageBuffer!) // Create a device-dependent RGB color space let colorSpace = CGColorSpaceCreateDeviceRGB() let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.noneSkipFirst.rawValue | CGBitmapInfo.byteOrder32Little.rawValue) let context = CGContext(data: baseAddress, width: width, height: height, bitsPerComponent: 8, bytesPerRow: bytesPerRow, space: colorSpace, bitmapInfo: bitmapInfo.rawValue) let quartzImage = context!.makeImage(); CVPixelBufferUnlockBaseAddress(imageBuffer!,CVPixelBufferLockFlags(rawValue: 0)); return quartzImage! } fileprivate func ciImageFromSampleBuffer(sampleBuffer: CMSampleBuffer) -> CIImage { return CIImage(cvPixelBuffer: CMSampleBufferGetImageBuffer(sampleBuffer)!) } }
mit
e0626412fe6d389043483cfcf520bf6b
28.138462
175
0.68189
4.951634
false
false
false
false
hirohisa/Shelf
Shelf/HeaderView.swift
1
1346
// // HeaderView.swift // Shelf // // Created by Hirohisa Kawasaki on 8/10/15. // Copyright (c) 2015 Hirohisa Kawasaki. All rights reserved. // import UIKit enum Position { case Left case Center case Right } class HeaderView: UIView { @IBOutlet weak var scrollView: UIScrollView! var index = 0 { didSet { updateData() } } var views: [UIView] = [] { didSet { index = 0 } } override func awakeFromNib() { super.awakeFromNib() scrollView.backgroundColor = UIColor.redColor() } func updateData() { // if unnecessary views exist, remove them. // necessary views exist, change their frame. // necessary views dont exist, add subview with frame } func frameForPosition(position: Position) -> CGRect { var frame = scrollView.bounds switch position { case .Left: frame.origin.x = frame.origin.x - frame.width case .Right: frame.origin.x = frame.origin.x + frame.width default: break } return frame } } extension HeaderView: UIScrollViewDelegate { func scrollViewDidEndDecelerating(scrollView: UIScrollView) { // TODO: Change index by current view // index = next index } }
mit
0ff1cecc4621e2e00e0fdf00259753cb
20.046875
65
0.583952
4.62543
false
false
false
false
wordpress-mobile/WordPress-iOS
WordPress/Classes/Utility/FormattableContent/FormattableContentFormatter.swift
2
4160
import Foundation class FormattableContentFormatter { /// Helper used by the +Interface Extension. /// fileprivate var dynamicAttributesCache = [String: AnyObject]() func render(content: FormattableContent, with styles: FormattableContentStyles) -> NSAttributedString { let attributedText = memoize { let snippet = self.text(from: content, with: styles) return snippet.trimNewlines() } return attributedText(styles.key) } func resetCache() { dynamicAttributesCache.removeAll() } /// This method is meant to aid cache-implementation into all of the AttributedString getters introduced /// in this extension. /// /// - Parameter fn: A Closure that, on execution, returns an attributed string. /// /// - Returns: A new Closure that on execution will either hit the cache, or execute the closure `fn` /// and store its return value in the cache. /// fileprivate func memoize(_ fn: @escaping () -> NSAttributedString) -> (String) -> NSAttributedString { return { cacheKey in if let cachedSubject = self.cacheValueForKey(cacheKey) as? NSAttributedString { return cachedSubject } let newValue = fn() self.setCacheValue(newValue, forKey: cacheKey) return newValue } } // Dynamic Attribute Cache: Used internally by the Interface Extension, as an optimization. /// func cacheValueForKey(_ key: String) -> AnyObject? { return dynamicAttributesCache[key] } /// Stores a specified value within the Dynamic Attributes Cache. /// func setCacheValue(_ value: AnyObject?, forKey key: String) { guard let value = value else { dynamicAttributesCache.removeValue(forKey: key) return } dynamicAttributesCache[key] = value } private func text(from content: FormattableContent, with styles: FormattableContentStyles) -> NSAttributedString { guard let text = content.text else { return NSAttributedString() } let tightenedText = replaceCommonWhitespaceIssues(in: text) let theString = NSMutableAttributedString(string: tightenedText, attributes: styles.attributes) if let quoteStyles = styles.quoteStyles { theString.applyAttributes(toQuotes: quoteStyles) } // Apply the Ranges var lengthShift = 0 for range in content.ranges { lengthShift += range.apply(styles, to: theString, withShift: lengthShift) } return theString } /// Replaces some common extra whitespace with hairline spaces so that comments display better /// /// - Parameter baseString: string of the comment body before attributes are added /// - Returns: string of same length /// - Note: the length must be maintained or the formatting will break private func replaceCommonWhitespaceIssues(in baseString: String) -> String { var newString: String // \u{200A} = hairline space (very skinny space). // we use these so that the ranges are still in the right position, but the extra space basically disappears newString = baseString.replacingOccurrences(of: "\t ", with: "\u{200A}\u{200A}") // tabs before a space newString = newString.replacingOccurrences(of: " \t", with: " \u{200A}") // tabs after a space newString = newString.replacingOccurrences(of: "\t@", with: "\u{200A}@") // tabs before @mentions newString = newString.replacingOccurrences(of: "\t.", with: "\u{200A}.") // tabs before a space newString = newString.replacingOccurrences(of: "\t,", with: "\u{200A},") // tabs cefore a comman newString = newString.replacingOccurrences(of: "\n\t\n\t", with: "\u{200A}\u{200A}\n\t") // extra newline-with-tab before a newline-with-tab // if the length of the string changes the range-based formatting will break guard newString.count == baseString.count else { return baseString } return newString } }
gpl-2.0
e45b56bfdfebbf54e1ffa018255eea77
37.878505
148
0.649279
4.882629
false
false
false
false
bsmith11/ScoreReporter
ScoreReporter/Teams/TeamsViewModel.swift
1
664
// // TeamsViewModel.swift // ScoreReporter // // Created by Bradley Smith on 11/22/16. // Copyright © 2016 Brad Smith. All rights reserved. // import Foundation import ScoreReporterCore class TeamsViewModel: NSObject { fileprivate let teamService = TeamService(client: APIClient.sharedInstance) fileprivate(set) dynamic var loading = false fileprivate(set) dynamic var error: NSError? = nil } // MARK: - Public extension TeamsViewModel { func downloadTeams() { loading = true teamService.downloadTeamList { [weak self] result in self?.loading = false self?.error = result.error } } }
mit
53e44d805fe24f9ed4ac59b449811b2a
21.1
79
0.6727
4.169811
false
false
false
false
congncif/SiFUtilities
Example/Pods/Boardy/Boardy/Core/BoardType/BoardInputModel.swift
1
1398
// // BoardInputModel.swift // Boardy // // Created by NGUYEN CHI CONG on 12/14/20. // import Foundation public protocol BoardInputModel { var identifier: BoardID { get } var option: Any? { get } } public struct BoardInput<Input>: BoardInputModel { public let identifier: BoardID public let input: Input public var option: Any? { input } public init(target: BoardID, input: Input) { identifier = target self.input = input } } extension BoardInput { public static func target<Input>(_ id: BoardID, _ input: Input) -> BoardInput<Input> { BoardInput<Input>(target: id, input: input) } } extension BoardInput where Input == Void { public init(target: BoardID) { identifier = target input = () } public static func target(_ id: BoardID) -> BoardInput<Void> { BoardInput<Void>(target: id) } } extension BoardInput where Input: ExpressibleByNilLiteral { public init(target: BoardID) { identifier = target input = nil } public static func target(_ id: BoardID) -> BoardInput<Input> { BoardInput<Input>(target: id) } } public extension BoardID { func with<Input>(input: Input) -> BoardInput<Input> { BoardInput<Input>(target: self, input: input) } var withoutInput: BoardInput<Void> { BoardInput<Void>(target: self) } }
mit
e099e4f3f788aa33482ef281bc6389c9
21.190476
90
0.633047
3.788618
false
false
false
false
jindulys/GitPocket
GitPocket/OldAPIViewControllers/WebViewController.swift
1
1371
// // WebViewController.swift // GitPocket // // Created by yansong li on 2015-07-26. // Copyright © 2015 yansong li. All rights reserved. // import Foundation import UIKit open class WebViewController: UIViewController { open let webView: UIWebView = UIWebView() open var webURL: URLLiteralConvertible? override open func viewDidLoad() { super.viewDidLoad() setupViews() let urlRequest = URLRequest(url: (webURL?.URL)! as URL) webView.loadRequest(urlRequest) } func setupViews() { self.view.addSubview(webView) webView.translatesAutoresizingMaskIntoConstraints = false if #available(iOS 9.0, *) { // webView constraints let webViewLeadingConstraint = webView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor) let webViewTrailingConstraint = webView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor) let webViewTopConstraint = webView.topAnchor.constraint(equalTo: self.view.topAnchor) let webViewBottomConstraint = webView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor) NSLayoutConstraint.activate([webViewLeadingConstraint, webViewTopConstraint, webViewBottomConstraint, webViewTrailingConstraint]) } } }
mit
5745d2ff52442810ebe96fdff1bce884
33.25
141
0.675912
5.524194
false
false
false
false
tryswift/TryParsec
excludedTests/TryParsec/Specs/ParserSpec.swift
1
8711
import TryParsec import Runes import Quick import Nimble class ParserSpec: QuickSpec { override func spec() { // MARK: Functor describe("Functor") { describe("`<^>` (fmap)") { it("`f <^> p` succeeds when `p` succeeds") { let p: Parser<String, Int> = { $0 + 1 } <^> pure(1) let r = parse(p, "hello")._done expect(r?.input) == "hello" expect(r?.output) == 2 } it("`f <^> p` fails when `p` fails") { let p: Parser<String, Int> = { $0 + 1 } <^> fail("oops") let r = parse(p, "hello")._fail expect(r?.input) == "hello" expect(r?.contexts) == [] expect(r?.message) == "oops" } } describe("`<&>` (flip fmap)") { it("`p <&> f` succeeds when `p` succeeds") { let p: Parser<String, Int> = pure(1) <&> { $0 + 1 } let r = parse(p, "hello")._done expect(r?.input) == "hello" expect(r?.output) == 2 } it("`p <&> f` fails when `p` fails") { let p: Parser<String, Int> = fail("oops") <&> { $0 + 1 } let r = parse(p, "hello")._fail expect(r?.input) == "hello" expect(r?.contexts) == [] expect(r?.message) == "oops" } } } // MARK: Applicative describe("Applicative") { describe("`<*>` (ap)") { it("`f <*> p` succeeds when both `f` and `p` succeed") { let p: Parser<String, Int> = pure({ $0 + 1 }) <*> pure(1) let r = parse(p, "hello")._done expect(r?.input) == "hello" expect(r?.output) == 2 } it("`f <*> p` fails when `f` succeeds but `p` fails") { let p: Parser<String, Int> = pure({ $0 + 1 }) <*> fail("oops") let r = parse(p, "hello")._fail expect(r?.input) == "hello" expect(r?.contexts) == [] expect(r?.message) == "oops" } it("`f <*> p` fails when `f` fails") { let p: Parser<String, Int> = fail("oops") <*> pure(1) let r = parse(p, "hello")._fail expect(r?.input) == "hello" expect(r?.contexts) == [] expect(r?.message) == "oops" } it("`f <^> p1 <*> p2` (applicative style) succeeds when `f`, `p1`, and `p2` succeed") { let p = { a in { b in (a, b) } } <^> char("h") <*> char("e") let r = parse(p, "hello")._done expect(r?.input) == "llo" expect(r?.output.0) == "h" expect(r?.output.1) == "e" } } describe("`*>` (sequence, discarding left)") { it("`p *> q` succeeds when both `p` and `q` succeed") { let p = char("h") *> char("e") let r = parse(p, "hello")._done expect(r?.input) == "llo" expect(r?.output) == "e" } it("`p *> q` fails when `p` succeeds but `q` fails") { let p = char("h") *> char("x") let r = parse(p, "hello")._fail expect(r?.input) == "ello" expect(r?.contexts) == [] expect(r?.message) == "satisfy" } it("`p *> q` fails when `p` fails") { let p = char("x") *> char("h") let r = parse(p, "hello")._fail expect(r?.input) == "hello" expect(r?.contexts) == [] expect(r?.message) == "satisfy" } } describe("`<*` (sequence, discarding right)") { it("`p <* q` succeeds when both `p` and `q` succeed") { let p = char("h") <* char("e") let r = parse(p, "hello")._done expect(r?.input) == "llo" expect(r?.output) == "h" } it("`p <* q` fails when `p` succeeds but `q` fails") { let p = char("h") <* char("x") let r = parse(p, "hello")._fail expect(r?.input) == "ello" expect(r?.contexts) == [] expect(r?.message) == "satisfy" } it("`p <* q` fails when `p` fails") { let p = char("x") <* char("h") let r = parse(p, "hello")._fail expect(r?.input) == "hello" expect(r?.contexts) == [] expect(r?.message) == "satisfy" } } } // MARK: Alternative describe("Alternative") { describe("`<|>` (choice, alternation)") { it("`p <|> q` succeeds when both `p` and `q` succeed") { let p = string("he") <|> string("hell") let r = parse(p, "hello")._done expect(r?.input) == "llo" expect(r?.output) == "he" } it("`p <|> q` succeeds when `p` succeeds but `q` fails") { let p = string("hell") <|> string("x") let r = parse(p, "hello")._done expect(r?.input) == "o" expect(r?.output) == "hell" } it("`p <|> q` succeeds when `p` fails but `q` succeeds") { let p = string("x") <|> string("hell") let r = parse(p, "hello")._done expect(r?.input) == "o" expect(r?.output) == "hell" } it("`p <|> q` fails when both `p` and `q` fail") { let p = string("x") <|> string("y") let r = parse(p, "hello")._fail expect(r?.input) == "hello" expect(r?.contexts) == [] expect(r?.message) == "satisfy" } } } // MARK: Monad describe("Monad") { describe(">>- (bind, flatMap)") { it("`p >>- f` succeeds when both `p` and `f()` succeeds") { let p = string("he") >>- { pure($0 + ["y"]) } let r = parse(p, "hello")._done expect(r?.input) == "llo" expect(r?.output) == "hey" } it("`p >>- f` fails when `p` succeeds but `f()` fails") { let p: Parser<USV, USV> = string("he") >>- { _ in fail("oops") } let r = parse(p, "hello")._fail expect(r?.input) == "llo" expect(r?.contexts) == [] expect(r?.message) == "oops" } it("`p >>- f` fails when `p` fails") { let p: Parser<USV, USV> = string("x") >>- { _ in pure("I made it!!!") } let r = parse(p, "hello")._fail expect(r?.input) == "hello" expect(r?.contexts) == [] expect(r?.message) == "satisfy" } } } // MARK: Peek describe("peek") { let p: Parser<USV, UnicodeScalar> = peek() it("succeeds") { let r = parse(p, "abc")._done expect(r?.input) == "abc" expect(r?.output) == "a" } it("fails") { let r = parse(p, "")._fail expect(r?.input) == "" expect(r?.contexts) == [] expect(r?.message) == "peek" } } describe("endOfInput") { let p: Parser<USV, ()> = endOfInput() it("succeeds") { let r = parse(p, "")._done expect(r?.input) == "" expect(r?.output) == () } it("fails") { let r = parse(p, "abc")._fail expect(r?.input) == "abc" expect(r?.contexts) == [] expect(r?.message) == "endOfInput" } } } }
mit
4a392b59a9c04063c3d3c584dcb71676
32.248092
103
0.349214
4.253418
false
false
false
false
HabitRPG/habitrpg-ios
HabitRPG/Utilities/SoundManager.swift
1
7364
// // SoundManager.swift // Habitica // // Created by Phillip Thelen on 11.06.18. // Copyright © 2018 HabitRPG Inc. All rights reserved. // import Foundation import AVFoundation import Habitica_Models enum SoundEffect: String { case achievementUnlocked = "Achievement_Unlocked" case chat = "Chat" case dailyCompleted = "Daily" case death = "Death" case itemDropped = "Item_Drop" case levelUp = "Level_Up" case habitNegative = "Minus_Habit" case habitPositive = "Plus_Habit" case rewardBought = "Reward" case todoCompleted = "Todo" static var allEffects: [SoundEffect] { return [ SoundEffect.achievementUnlocked, SoundEffect.chat, SoundEffect.dailyCompleted, SoundEffect.death, SoundEffect.itemDropped, SoundEffect.levelUp, SoundEffect.habitPositive, SoundEffect.habitNegative, SoundEffect.rewardBought, SoundEffect.todoCompleted ] } } enum SoundTheme: String, EquatableStringEnumProtocol { case none = "off" case airu = "airuTheme" case arashi = "arashiTheme" case beatScribeNes = "beatscribeNesTheme" case danielTheBard = "danielTheBard" case dewin = "dewinTheme" case farvoid = "farvoidTheme" case gokul = "gokulTheme" case lunasol = "lunasolTheme" case luneFox = "luneFoxTheme" case mafl = "maflTheme" case pizilden = "pizildenTheme" case rosstavo = "rosstavoTheme" case spacePengiun = "spacePengiunTheme" case triumph = "triumphTheme" case watts = "wattsTheme" static var allThemes: [SoundTheme] { return [ SoundTheme.none, SoundTheme.airu, SoundTheme.arashi, SoundTheme.beatScribeNes, SoundTheme.danielTheBard, SoundTheme.dewin, SoundTheme.farvoid, SoundTheme.gokul, SoundTheme.lunasol, SoundTheme.luneFox, SoundTheme.mafl, SoundTheme.pizilden, SoundTheme.rosstavo, SoundTheme.spacePengiun, SoundTheme.triumph, SoundTheme.watts ] } var niceName: String { switch self { case .none: return "Off" case .airu: return "Airu's Theme" case .arashi: return "Arashi's Theme" case .beatScribeNes: return "Beatscribe's NES Theme" case .danielTheBard: return "Daniel The Bard" case .dewin: return "Dewin's Theme" case .farvoid: return "Farvoid Theme" case .gokul: return "Gokul's Theme" case .lunasol: return "Lunasol Theme" case .luneFox: return "LuneFox's Theme" case .mafl: return "MAFL Theme" case .pizilden: return "Pizilden's Theme" case .rosstavo: return "Rosstavo's Theme" case .spacePengiun: return "SpacePenguin's Theme" case .triumph: return "Triumph's Theme" case .watts: return "Watts' Theme" } } } class SoundManager { public static let shared = SoundManager() var currentTheme = SoundTheme.none { didSet { if currentTheme != oldValue { loadAllFiles() } } } private var player: AVAudioPlayer? private var soundsDirectory: URL? { let documentDirectory = FileManager.SearchPathDirectory.documentDirectory let userDomainMask = FileManager.SearchPathDomainMask.userDomainMask let paths = NSSearchPathForDirectoriesInDomains(documentDirectory, userDomainMask, true) if paths.isEmpty == false { let folderPath = String(paths[0]) var folder = URL(fileURLWithPath: folderPath) folder = folder.appendingPathComponent("sounds", isDirectory: true) return folder } return nil } private init() { let defaults = UserDefaults.standard currentTheme = SoundTheme(rawValue: defaults.string(forKey: "soundTheme") ?? "") ?? SoundTheme.none } func play(effect: SoundEffect) { if currentTheme == SoundTheme.none { return } guard let url = soundsDirectory?.appendingPathComponent("\(currentTheme.rawValue)/\(effect.rawValue).mp3") else { return } if !FileManager.default.fileExists(atPath: url.path) { return } do { try AVAudioSession.sharedInstance().setCategory(.ambient, mode: .default) try AVAudioSession.sharedInstance().setActive(true) /* The following line is required for the player to work on iOS 11. Change the file type accordingly*/ player = try? AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileType.mp3.rawValue) /* iOS 10 and earlier require the following line: player = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileTypeMPEGLayer3) */ guard let player = player else { return } player.play() } catch let error { print(error.localizedDescription) } } private func loadAllFiles() { if currentTheme == SoundTheme.none { return } if let soundThemeDirectory = self.soundsDirectory?.appendingPathComponent("\(currentTheme.rawValue)") { if !FileManager.default.fileExists(atPath: soundThemeDirectory.path, isDirectory: nil) { try? FileManager.default.createDirectory(at: soundThemeDirectory, withIntermediateDirectories: true, attributes: nil) } SoundEffect.allEffects.forEach {[weak self] (effect) in self?.load(soundEffect: effect) } } } private func load(soundEffect: SoundEffect) { let effectPath = "\(currentTheme.rawValue)/\(soundEffect.rawValue).mp3" guard let url = URL(string: "https://s3.amazonaws.com/habitica-assets/mobileApp/sounds/\(effectPath)") else { return } guard let soundsDirectory = self.soundsDirectory else { return } let localUrl = soundsDirectory.appendingPathComponent(effectPath) if FileManager.default.fileExists(atPath: localUrl.path) { return } let sessionConfig = URLSessionConfiguration.default let session = URLSession(configuration: sessionConfig) let request = URLRequest(url: url, cachePolicy: .returnCacheDataElseLoad) let task = session.downloadTask(with: request) { (tempLocalUrl, _, error) in if let tempLocalUrl = tempLocalUrl, error == nil { do { try FileManager.default.moveItem(at: tempLocalUrl, to: localUrl) } catch let writeError { print("error writing file \(localUrl) : \(writeError)") } } else { print("Failure: %@", error?.localizedDescription ?? "") } } task.resume() } }
gpl-3.0
140e2b71721b62806251fc0b6b80a224
31.724444
133
0.585088
4.573292
false
false
false
false
alisidd/iOS-WeJ
Pods/NVActivityIndicatorView/Source/NVActivityIndicatorView/Animations/NVActivityIndicatorAnimationTriangleSkewSpin.swift
4
3469
// // NVActivityIndicatorAnimationTriangleSkewSpin.swift // NVActivityIndicatorView // // The MIT License (MIT) // Copyright (c) 2016 Vinh Nguyen // 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 NVActivityIndicatorAnimationTriangleSkewSpin: NVActivityIndicatorAnimationDelegate { func setUpAnimation(in layer: CALayer, size: CGSize, color: UIColor) { let x = (layer.bounds.size.width - size.width) / 2 let y = (layer.bounds.size.height - size.height) / 2 let duration: CFTimeInterval = 3 let timingFunction = CAMediaTimingFunction(controlPoints: 0.09, 0.57, 0.49, 0.9) // Animation let animation = CAKeyframeAnimation(keyPath: "transform") animation.keyTimes = [0, 0.25, 0.5, 0.75, 1] animation.timingFunctions = [timingFunction, timingFunction, timingFunction, timingFunction] animation.values = [ NSValue(caTransform3D: CATransform3DConcat(createRotateXTransform(angle: 0), createRotateYTransform(angle: 0))), NSValue(caTransform3D: CATransform3DConcat(createRotateXTransform(angle: CGFloat(Double.pi)), createRotateYTransform(angle: 0))), NSValue(caTransform3D: CATransform3DConcat(createRotateXTransform(angle: CGFloat(Double.pi)), createRotateYTransform(angle: CGFloat(Double.pi)))), NSValue(caTransform3D: CATransform3DConcat(createRotateXTransform(angle: 0), createRotateYTransform(angle: CGFloat(Double.pi)))), NSValue(caTransform3D: CATransform3DConcat(createRotateXTransform(angle: 0), createRotateYTransform(angle: 0))) ] animation.duration = duration animation.repeatCount = HUGE animation.isRemovedOnCompletion = false // Draw triangle let triangle = NVActivityIndicatorShape.triangle.layerWith(size: size, color: color) triangle.frame = CGRect(x: x, y: y, width: size.width, height: size.height) triangle.add(animation, forKey: "animation") layer.addSublayer(triangle) } func createRotateXTransform(angle: CGFloat) -> CATransform3D { var transform = CATransform3DMakeRotation(angle, 1, 0, 0) transform.m34 = CGFloat(-1) / 100 return transform } func createRotateYTransform(angle: CGFloat) -> CATransform3D { var transform = CATransform3DMakeRotation(angle, 0, 1, 0) transform.m34 = CGFloat(-1) / 100 return transform } }
gpl-3.0
dac1fe3e8ae83a355077ae6a31f32b5c
44.051948
158
0.720957
4.681511
false
false
false
false
onekiloparsec/SwiftAA
Sources/SwiftAA/PlanetaryPhenomena.swift
1
3741
// // Planet.swift // SwiftAA // // Created by Cédric Foellmi on 18/06/16. // MIT Licence. See LICENCE file. // import Foundation import ObjCAA /** * The PlanetaryPhenomena protocol encompass all methods associated with planetary phenomena in the solar system: * conjunction, oppotisions, etc. */ public protocol PlanetaryPhenomena: PlanetaryBase { /** Compute the julian day of the inferior conjunction of the planet after the given julian day. - parameter mean: The 'mean' configuration here means that it is calculated from circular orbits and uniform planetary motions. See AA. pp 250. if false, the true inferior conjunction is computed. That is, calculated by adding corrections to computations made from circular orbits and uniform planetary motions. See AA. pp 251. - returns: A julian day. */ func inferiorConjunction(mean: Bool) -> JulianDay /** Compute the julian day of the superior conjunction of the planet after the given julian day. - parameter mean: The 'mean' configuration here means that it is calculated from circular orbits and uniform planetary motions. See AA. pp 250. if false, the true inferior conjunction is computed. That is, calculated by adding corrections to computations made from circular orbits and uniform planetary motions. See AA. pp 251. - returns: A julian day. */ func superiorConjunction(mean: Bool) -> JulianDay func opposition(mean: Bool) -> JulianDay func conjunction(mean: Bool) -> JulianDay func easternElongation(mean: Bool) -> JulianDay func westernElongation(mean: Bool) -> JulianDay func station1(mean: Bool) -> JulianDay func station2(mean: Bool) -> JulianDay func elongationValue(eastern: Bool) -> Degree } public extension PlanetaryPhenomena { func inferiorConjunction(mean: Bool = true) -> JulianDay { return JulianDay(KPCAAPlanetaryPhenomena(mean, self.julianDay.date.fractionalYear, self.planetaryObject, .INFERIOR_CONJUNCTION)) } func superiorConjunction(mean: Bool = true) -> JulianDay { return JulianDay(KPCAAPlanetaryPhenomena(mean, self.julianDay.date.fractionalYear, self.planetaryObject, .SUPERIOR_CONJUNCTION)) } func opposition(mean: Bool = true) -> JulianDay { return JulianDay(KPCAAPlanetaryPhenomena(mean, self.julianDay.date.fractionalYear, self.planetaryObject, .OPPOSITION)) } func conjunction(mean: Bool = true) -> JulianDay { return JulianDay(KPCAAPlanetaryPhenomena(mean, self.julianDay.date.fractionalYear, self.planetaryObject, .CONJUNCTION)) } func easternElongation(mean: Bool = true) -> JulianDay { return JulianDay(KPCAAPlanetaryPhenomena(mean, self.julianDay.date.fractionalYear, self.planetaryObject, .EASTERN_ELONGATION)) } func westernElongation(mean: Bool = true) -> JulianDay { return JulianDay(KPCAAPlanetaryPhenomena(mean, self.julianDay.date.fractionalYear, self.planetaryObject, .WESTERN_ELONGATION)) } func station1(mean: Bool = true) -> JulianDay { return JulianDay(KPCAAPlanetaryPhenomena(mean, self.julianDay.date.fractionalYear, self.planetaryObject, .STATION1)) } func station2(mean: Bool = true) -> JulianDay { return JulianDay(KPCAAPlanetaryPhenomena(mean, self.julianDay.date.fractionalYear, self.planetaryObject, .STATION2)) } func elongationValue(eastern: Bool = true) -> Degree { let k = KPCAAPlanetaryPhenomena_K(self.julianDay.date.fractionalYear, self.planetaryObject, .EASTERN_ELONGATION) return Degree(KPCAAPlanetaryPhenomena_ElongationValue(k.rounded(), self.planetaryObject, eastern)) } }
mit
2d8ac19064f9bcafbcc20649b694712e
39.215054
136
0.721658
4.096386
false
false
false
false
necrowman/CRLAlamofireFuture
Examples/SimpleTvOSCarthage/Carthage/Checkouts/Future/Future/MutableFuture.swift
111
2318
//===--- MutableFuture.swift ------------------------------------------------------===// //Copyright (c) 2016 Daniel Leping (dileping) // //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 import Result import Boilerplate import ExecutionContext public protocol MutableFutureType { associatedtype Value func tryComplete<E : ErrorProtocol>(result:Result<Value, E>) -> Bool } internal class MutableFuture<V> : Future<V>, MutableFutureType { internal override init(context:ExecutionContextType) { super.init(context: context) } internal func tryComplete<E : ErrorProtocol>(result:Result<Value, E>) -> Bool { if self.result != nil { return false } self.result = result.asAnyError() return true } } public extension MutableFutureType { func complete<E : ErrorProtocol>(result:Result<Value, E>) throws { if !tryComplete(result) { throw Error.AlreadyCompleted } } func trySuccess(value:Value) -> Bool { return tryComplete(Result<Value, AnyError>(value:value)) } func success(value:Value) throws { if !trySuccess(value) { throw Error.AlreadyCompleted } } func tryFail(error:ErrorProtocol) -> Bool { return tryComplete(Result(error: anyError(error))) } func fail(error:ErrorProtocol) throws { if !tryFail(error) { throw Error.AlreadyCompleted } } /// safe to be called several times func completeWith<F: FutureType where F.Value == Value>(f:F) { f.onComplete { (result:Result<Value, AnyError>) in self.tryComplete(result) } } }
mit
7b24db52de3f84157d247782865c8ff6
28.730769
88
0.614754
4.663984
false
false
false
false
PerfectServers/Perfect-Authentication-Server
Sources/PerfectAuthServer/handlers/applications/ApplicationList.swift
1
1082
// // ApplicationList.swift // PerfectAuthServer // // Created by Jonathan Guthrie on 2017-08-04. // import PerfectHTTP import PerfectLogger import PerfectLocalAuthentication extension Handlers { static func applicationList(data: [String:Any]) throws -> RequestHandler { return { request, response in let contextAccountID = request.session?.userid ?? "" let contextAuthenticated = !(request.session?.userid ?? "").isEmpty if !contextAuthenticated { response.redirect(path: "/login") } // Verify Admin Account.adminBounce(request, response) let list = Application.list() var context: [String : Any] = [ "accountID": contextAccountID, "authenticated": contextAuthenticated, "islist?":"true", "list": list ] if contextAuthenticated { for i in Handlers.extras(request) { context[i.0] = i.1 } } // add app config vars for i in Handlers.appExtras(request) { context[i.0] = i.1 } response.renderMustache(template: request.documentRoot + "/views/applications.mustache", context: context) } } }
apache-2.0
3a854158a05bd42b8cf14cd16e304a74
22.021277
109
0.682994
3.618729
false
false
false
false
practicalswift/swift
test/Generics/function_defs.swift
4
12130
// RUN: %target-typecheck-verify-swift //===----------------------------------------------------------------------===// // Type-check function definitions //===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===// // Basic type checking //===----------------------------------------------------------------------===// protocol EqualComparable { func isEqual(_ other: Self) -> Bool } func doCompare<T : EqualComparable, U : EqualComparable>(_ t1: T, t2: T, u: U) -> Bool { var b1 = t1.isEqual(t2) if b1 { return true } return t1.isEqual(u) // expected-error {{cannot invoke 'isEqual' with an argument list of type '(U)'}} expected-note {{expected an argument list of type '(T)'}} } protocol MethodLessComparable { func isLess(_ other: Self) -> Bool } func min<T : MethodLessComparable>(_ x: T, y: T) -> T { if (y.isLess(x)) { return y } return x } //===----------------------------------------------------------------------===// // Interaction with existential types //===----------------------------------------------------------------------===// func existential<T : EqualComparable, U : EqualComparable>(_ t1: T, t2: T, u: U) { var eqComp : EqualComparable = t1 // expected-error{{protocol 'EqualComparable' can only be used as a generic constraint}} eqComp = u if t1.isEqual(eqComp) {} // expected-error{{cannot invoke 'isEqual' with an argument list of type '(EqualComparable)'}} // expected-note @-1 {{expected an argument list of type '(T)'}} if eqComp.isEqual(t2) {} // expected-error{{member 'isEqual' cannot be used on value of protocol type 'EqualComparable'; use a generic constraint instead}} } protocol OtherEqualComparable { func isEqual(_ other: Self) -> Bool } func otherExistential<T : EqualComparable>(_ t1: T) { var otherEqComp : OtherEqualComparable = t1 // expected-error{{value of type 'T' does not conform to specified type 'OtherEqualComparable'}} otherEqComp = t1 // expected-error{{value of type 'T' does not conform to 'OtherEqualComparable' in assignment}} _ = otherEqComp var otherEqComp2 : OtherEqualComparable // expected-error{{protocol 'OtherEqualComparable' can only be used as a generic constraint}} otherEqComp2 = t1 // expected-error{{value of type 'T' does not conform to 'OtherEqualComparable' in assignment}} _ = otherEqComp2 _ = t1 as EqualComparable & OtherEqualComparable // expected-error{{'T' is not convertible to 'EqualComparable & OtherEqualComparable'; did you mean to use 'as!' to force downcast?}} {{10-12=as!}} expected-error{{protocol 'OtherEqualComparable' can only be used as a generic constraint}} expected-error{{protocol 'EqualComparable' can only be used as a generic constraint}} } protocol Runcible { func runce<A>(_ x: A) func spoon(_ x: Self) } func testRuncible(_ x: Runcible) { // expected-error{{protocol 'Runcible' can only be used as a generic constraint}} x.runce(5) } //===----------------------------------------------------------------------===// // Overloading //===----------------------------------------------------------------------===// protocol Overload { associatedtype A associatedtype B func getA() -> A func getB() -> B func f1(_: A) -> A func f1(_: B) -> B func f2(_: Int) -> A // expected-note{{found this candidate}} func f2(_: Int) -> B // expected-note{{found this candidate}} func f3(_: Int) -> Int // expected-note {{found this candidate}} func f3(_: Float) -> Float // expected-note {{found this candidate}} func f3(_: Self) -> Self // expected-note {{found this candidate}} var prop : Self { get } } func testOverload<Ovl : Overload, OtherOvl : Overload>(_ ovl: Ovl, ovl2: Ovl, other: OtherOvl) { var a = ovl.getA() var b = ovl.getB() // Overloading based on arguments _ = ovl.f1(a) a = ovl.f1(a) _ = ovl.f1(b) b = ovl.f1(b) // Overloading based on return type a = ovl.f2(17) b = ovl.f2(17) ovl.f2(17) // expected-error{{ambiguous use of 'f2'}} // Check associated types from different objects/different types. a = ovl2.f2(17) a = ovl2.f1(a) other.f1(a) // expected-error{{cannot invoke 'f1' with an argument list of type '(Ovl.A)'}} // expected-note @-1 {{overloads for 'f1' exist with these partially matching parameter lists: (Self.A), (Self.B)}} // Overloading based on context var f3i : (Int) -> Int = ovl.f3 var f3f : (Float) -> Float = ovl.f3 var f3ovl_1 : (Ovl) -> Ovl = ovl.f3 var f3ovl_2 : (Ovl) -> Ovl = ovl2.f3 var f3ovl_3 : (Ovl) -> Ovl = other.f3 // expected-error{{ambiguous reference to member 'f3'}} var f3i_unbound : (Ovl) -> (Int) -> Int = Ovl.f3 var f3f_unbound : (Ovl) -> (Float) -> Float = Ovl.f3 var f3f_unbound2 : (OtherOvl) -> (Float) -> Float = OtherOvl.f3 var f3ovl_unbound_1 : (Ovl) -> (Ovl) -> Ovl = Ovl.f3 var f3ovl_unbound_2 : (OtherOvl) -> (OtherOvl) -> OtherOvl = OtherOvl.f3 } //===----------------------------------------------------------------------===// // Subscripting //===----------------------------------------------------------------------===// protocol Subscriptable { associatedtype Index associatedtype Value func getIndex() -> Index func getValue() -> Value subscript (index : Index) -> Value { get set } } protocol IntSubscriptable { associatedtype ElementType func getElement() -> ElementType subscript (index : Int) -> ElementType { get } } func subscripting<T : Subscriptable & IntSubscriptable>(_ t: T) { var index = t.getIndex() var value = t.getValue() var element = t.getElement() value = t[index] t[index] = value // expected-error{{cannot assign through subscript: 't' is a 'let' constant}} element = t[17] t[42] = element // expected-error{{cannot assign through subscript: subscript is get-only}} // Suggests the Int form because we prefer concrete matches to generic matches in diagnosis. t[value] = 17 // expected-error{{cannot convert value of type 'T.Value' to expected argument type 'Int'}} } //===----------------------------------------------------------------------===// // Static functions //===----------------------------------------------------------------------===// protocol StaticEq { static func isEqual(_ x: Self, y: Self) -> Bool } func staticEqCheck<T : StaticEq, U : StaticEq>(_ t: T, u: U) { if t.isEqual(t, t) { return } // expected-error{{static member 'isEqual' cannot be used on instance of type 'T'}} // expected-error {{missing argument label 'y:' in call}} if T.isEqual(t, y: t) { return } if U.isEqual(u, y: u) { return } T.isEqual(t, y: u) // expected-error{{cannot invoke 'isEqual' with an argument list of type '(T, y: U)'}} expected-note {{expected an argument list of type '(T, y: T)'}} } //===----------------------------------------------------------------------===// // Operators //===----------------------------------------------------------------------===// protocol Ordered { static func <(lhs: Self, rhs: Self) -> Bool } func testOrdered<T : Ordered>(_ x: T, y: Int) { if y < 100 || 500 < y { return } if x < x { return } } //===----------------------------------------------------------------------===// // Requires clauses //===----------------------------------------------------------------------===// func conformanceViaRequires<T>(_ t1: T, t2: T) -> Bool where T : EqualComparable, T : MethodLessComparable { let b1 = t1.isEqual(t2) if b1 || t1.isLess(t2) { return true } } protocol GeneratesAnElement { associatedtype Element : EqualComparable func makeIterator() -> Element } protocol AcceptsAnElement { associatedtype Element : MethodLessComparable func accept(_ e : Element) } func impliedSameType<T : GeneratesAnElement>(_ t: T) where T : AcceptsAnElement { t.accept(t.makeIterator()) let e = t.makeIterator(), e2 = t.makeIterator() if e.isEqual(e2) || e.isLess(e2) { return } } protocol GeneratesAssoc1 { associatedtype Assoc1 : EqualComparable func get() -> Assoc1 } protocol GeneratesAssoc2 { associatedtype Assoc2 : MethodLessComparable func get() -> Assoc2 } func simpleSameType<T : GeneratesAssoc1, U : GeneratesAssoc2> (_ t: T, u: U) -> Bool where T.Assoc1 == U.Assoc2 { return t.get().isEqual(u.get()) || u.get().isLess(t.get()) } protocol GeneratesMetaAssoc1 { associatedtype MetaAssoc1 : GeneratesAnElement func get() -> MetaAssoc1 } protocol GeneratesMetaAssoc2 { associatedtype MetaAssoc2 : AcceptsAnElement func get() -> MetaAssoc2 } func recursiveSameType <T : GeneratesMetaAssoc1, U : GeneratesMetaAssoc2, V : GeneratesAssoc1> (_ t: T, u: U, v: V) where T.MetaAssoc1 == V.Assoc1, V.Assoc1 == U.MetaAssoc2 { t.get().accept(t.get().makeIterator()) let e = t.get().makeIterator(), e2 = t.get().makeIterator() if e.isEqual(e2) || e.isLess(e2) { return } } // <rdar://problem/13985164> protocol P1 { associatedtype Element } protocol P2 { associatedtype AssocP1 : P1 func getAssocP1() -> AssocP1 } func beginsWith2<E0: P1, E1: P1>(_ e0: E0, _ e1: E1) -> Bool where E0.Element == E1.Element, E0.Element : EqualComparable { } func beginsWith3<S0: P2, S1: P2>(_ seq1: S0, _ seq2: S1) -> Bool where S0.AssocP1.Element == S1.AssocP1.Element, S1.AssocP1.Element : EqualComparable { return beginsWith2(seq1.getAssocP1(), seq2.getAssocP1()) } // FIXME: Test same-type constraints that try to equate things we // don't want to equate, e.g., T == U. //===----------------------------------------------------------------------===// // Bogus requirements //===----------------------------------------------------------------------===// func nonTypeReq<T>(_: T) where T : Wibble {} // expected-error{{use of undeclared type 'Wibble'}} func badProtocolReq<T>(_: T) where T : Int {} // expected-error{{type 'T' constrained to non-protocol, non-class type 'Int'}} func nonTypeSameType<T>(_: T) where T == Wibble {} // expected-error{{use of undeclared type 'Wibble'}} func nonTypeSameType2<T>(_: T) where Wibble == T {} // expected-error{{use of undeclared type 'Wibble'}} func sameTypeEq<T>(_: T) where T = T {} // expected-error{{use '==' for same-type requirements rather than '='}} {{34-35===}} // expected-warning@-1{{redundant same-type constraint 'T' == 'T'}} func badTypeConformance1<T>(_: T) where Int : EqualComparable {} // expected-error{{type 'Int' in conformance requirement does not refer to a generic parameter or associated type}} func badTypeConformance2<T>(_: T) where T.Blarg : EqualComparable { } // expected-error{{'Blarg' is not a member type of 'T'}} func badTypeConformance3<T>(_: T) where (T) -> () : EqualComparable { } // expected-error@-1{{type '(T) -> ()' in conformance requirement does not refer to a generic parameter or associated type}} func badTypeConformance4<T>(_: T) where @escaping (inout T) throws -> () : EqualComparable { } // expected-error@-1{{type '(inout T) throws -> ()' in conformance requirement does not refer to a generic parameter or associated type}} // expected-error@-2 2 {{@escaping attribute may only be used in function parameter position}} // FIXME: Error emitted twice. func badTypeConformance5<T>(_: T) where T & Sequence : EqualComparable { } // expected-error@-1 2 {{non-protocol, non-class type 'T' cannot be used within a protocol-constrained type}} // expected-error@-2{{type 'Sequence' in conformance requirement does not refer to a generic parameter or associated type}} func badTypeConformance6<T>(_: T) where [T] : Collection { } // expected-error@-1{{type '[T]' in conformance requirement does not refer to a generic parameter or associated type}} func badTypeConformance7<T, U>(_: T, _: U) where T? : U { } // expected-error@-1{{type 'T?' constrained to non-protocol, non-class type 'U'}} func badSameType<T, U : GeneratesAnElement, V>(_ : T, _ : U) where T == U.Element, U.Element == V {} // expected-error{{same-type requirement makes generic parameters 'T' and 'V' equivalent}}
apache-2.0
59433181d5ebc5ac5e4d796f4d1d5f6d
37.264984
375
0.590602
3.990132
false
false
false
false
SwiftApps/SwiftAlgo
SwiftAlgo/BinaryTree.swift
2
897
// // BinaryTree.swift // SwiftAlgo // // Created by Harshad Kale on 10/10/15. // Copyright © 2015 Harshad Kale. All rights reserved. // import Foundation class BinaryTree <T where T: Comparable, T: Equatable> { var root: BinaryTreeNode<T> init(root: BinaryTreeNode<T>) { self.root = root } func isPresent(node: BinaryTreeNode<T>) -> Bool { var runner: BinaryTreeNode<T>? = self.root while runner != nil { if runner?.data < node.data { runner = runner?.left } else if runner?.data > node.data { runner = runner?.right } else { return true } } return false } func recursivelyTraversFromNode(node: BinaryTreeNode<T>?) { if node != nil { } } }
mit
7b81c091dacada928dd7c3379c4b9def
20.878049
63
0.502232
4.457711
false
false
false
false
maxim-pervushin/HyperHabit
HyperHabit/HyperHabit/Scenes/EditHabit/EditHabitViewController.swift
1
9185
// // Created by Maxim Pervushin on 24/11/15. // Copyright (c) 2015 Maxim Pervushin. All rights reserved. // import UIKit class EditHabitViewController: UIViewController { // MARK: EditHabitViewController @IB @IBOutlet weak var tintView: UIView! @IBOutlet weak var headerTopView: UIView! @IBOutlet weak var headerView: UIView! @IBOutlet weak var headerTopConstraint: NSLayoutConstraint! @IBOutlet weak var headerHeightConstraint: NSLayoutConstraint! @IBOutlet weak var contentTopView: UIView! @IBOutlet weak var contentView: UIView! @IBOutlet weak var contentViewTopConstraint: NSLayoutConstraint! @IBOutlet weak var contentViewHeightConstraint: NSLayoutConstraint! @IBOutlet weak var nameTextField: UITextField! @IBOutlet weak var definitionTextField: UITextField! @IBOutlet weak var saveButton: UIButton! @IBAction func nameTextFieldEditingChanged(sender: AnyObject) { editor.name = nameTextField.text } @IBAction func definitionTextFieldEditingChanged(sender: AnyObject) { editor.definition = definitionTextField.text } @IBAction func saveButtonAction(sender: AnyObject) { guard let habit = self.editor.updatedHabit else { return } if dataSource.saveHabit(habit) { dismissViewControllerAnimated(true, completion: nil) } } @IBAction func cancelButtonAction(sender: AnyObject) { dismissViewControllerAnimated(true, completion: nil) } // MARK: EditHabitViewController let editor = HabitEditor() let dataSource = EditHabitDataSource(dataProvider: App.dataProvider) private func updateUI() { dispatch_async(dispatch_get_main_queue()) { self.nameTextField.text = self.editor.name self.definitionTextField.text = self.editor.definition self.saveButton.enabled = self.editor.canSave } } private func subscribe() { NSNotificationCenter.defaultCenter().addObserverForName(ThemeManager.changedNotification, object: nil, queue: NSOperationQueue.mainQueue(), usingBlock: { _ in self.setNeedsStatusBarAppearanceUpdate() }) } private func unsubscribe() { NSNotificationCenter.defaultCenter().removeObserver(self, name: ThemeManager.changedNotification, object: nil) } override func viewDidLoad() { super.viewDidLoad() editor.changesObserver = self } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) nameTextField?.becomeFirstResponder() updateUI() view.layoutIfNeeded() } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) nameTextField?.resignFirstResponder() } private func commonInit() { transitioningDelegate = self modalPresentationStyle = .Custom modalPresentationCapturesStatusBarAppearance = true subscribe() } deinit { unsubscribe() } override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) commonInit() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } override func preferredStatusBarStyle() -> UIStatusBarStyle { return App.themeManager.theme.statusBarStyle } } extension EditHabitViewController: ChangesObserver { func observableChanged(observable: AnyObject) { updateUI() } } extension EditHabitViewController { // TODO: Would be great to move all this transition-related stuff somewhere. Somehow... private func prepareForPresentation() { view.bringSubviewToFront(tintView) view.bringSubviewToFront(contentView) view.bringSubviewToFront(contentTopView) view.bringSubviewToFront(headerView) view.bringSubviewToFront(headerTopView) headerTopConstraint.constant = -headerHeightConstraint.constant * 2 contentViewTopConstraint.constant = (-headerHeightConstraint.constant - contentViewHeightConstraint.constant) * 2 view.layoutIfNeeded() } private func performPresentationWithDuration(duration: NSTimeInterval, completion: ((Bool) -> Void)?) { view.layoutIfNeeded() headerTopConstraint.constant = 0 view.setNeedsUpdateConstraints() tintView.alpha = 0 UIView.animateWithDuration(duration / 2, delay: 0, usingSpringWithDamping: 0.85, initialSpringVelocity: 0.5, options: [.CurveEaseInOut, .TransitionNone], animations: { // Layout header self.view.layoutIfNeeded() self.tintView.alpha = 1 }, completion: { _ in self.contentViewTopConstraint.constant = self.headerHeightConstraint.constant self.view.setNeedsUpdateConstraints() UIView.animateWithDuration(duration / 2, delay: 0, usingSpringWithDamping: 0.85, initialSpringVelocity: 0.5, options: [.CurveEaseInOut, .TransitionNone], animations: { // Layout content self.view.layoutIfNeeded() }, completion: completion) }) } private func prepareForDismissal() { view.bringSubviewToFront(tintView) view.bringSubviewToFront(contentView) view.bringSubviewToFront(contentTopView) view.bringSubviewToFront(headerView) view.bringSubviewToFront(headerTopView) headerTopConstraint.constant = 0 contentViewTopConstraint.constant = headerHeightConstraint.constant view.layoutIfNeeded() } private func performDismissalWithDuration(duration: NSTimeInterval, completion: ((Bool) -> Void)?) { view.layoutIfNeeded() contentViewTopConstraint.constant = (-headerHeightConstraint.constant - contentViewHeightConstraint.constant) * 2 view.setNeedsUpdateConstraints() tintView.alpha = 1 UIView.animateWithDuration(duration / 2, delay: 0, usingSpringWithDamping: 0.85, initialSpringVelocity: 0.5, options: [.CurveEaseInOut, .TransitionNone], animations: { // Layout content self.view.layoutIfNeeded() }, completion: { _ in self.headerTopConstraint.constant = -self.headerHeightConstraint.constant * 2 self.view.setNeedsUpdateConstraints() UIView.animateWithDuration(duration / 2, delay: 0, usingSpringWithDamping: 0.85, initialSpringVelocity: 0.5, options: [.CurveEaseInOut, .TransitionNone], animations: { // Layout header self.view.layoutIfNeeded() self.tintView.alpha = 0 }, completion: completion) }) } } extension EditHabitViewController: UIViewControllerTransitioningDelegate { func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? { return self } func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { return self } } extension EditHabitViewController: UIViewControllerAnimatedTransitioning { func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval { return 0.5 } func animateTransition(transitionContext: UIViewControllerContextTransitioning) { guard let fromViewController = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey) else { print("Invalid fromViewController") return } guard let toViewController = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey) else { print("Invalid toViewController") return } guard let contentView = transitionContext.containerView() else { print("Invalid containerView") return } if let editHabitViewController = toViewController as? EditHabitViewController { editHabitViewController.prepareForPresentation() contentView.insertSubview(toViewController.view, belowSubview: fromViewController.view) editHabitViewController.performPresentationWithDuration(transitionDuration(transitionContext), completion: { _ in transitionContext.completeTransition(!transitionContext.transitionWasCancelled()) }) } if let editHabitViewController = fromViewController as? EditHabitViewController { editHabitViewController.prepareForDismissal() editHabitViewController.performDismissalWithDuration(transitionDuration(transitionContext), completion: { _ in fromViewController.view.removeFromSuperview() transitionContext.completeTransition(!transitionContext.transitionWasCancelled()) }) } } func animationEnded(transitionCompleted: Bool) { } }
mit
3b7c9db171258af2144698fa0632d8cf
35.88755
217
0.694937
5.995431
false
false
false
false
moked/iuob
iUOB 2/MenuController.swift
1
1720
// // MenuController.swift // Example // // Created by Teodor Patras on 16/06/16. // Copyright © 2016 teodorpatras. All rights reserved. // import UIKit class MenuController: UITableViewController { @IBOutlet weak var logoImageView: UIImageView! let segues = ["showCenterController", "showStudentScheduleController", "showScheduleBuilderController", "showMapController", "showUsefulLinksController", "showAboutController"]; let names = ["Semester Schedule", "My Schedule", "Schedule Builder", "UOB Map", "Useful Links", "About"] fileprivate var previousIndex: IndexPath? override func viewDidLoad() { super.viewDidLoad() logoImageView.layer.cornerRadius = 16 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return segues.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "menuCell")! cell.textLabel?.font = UIFont(name: "HelveticaNeue-Regular", size: 17) cell.textLabel?.text = names[(indexPath as NSIndexPath).row] cell.imageView?.image = UIImage(named: names[(indexPath as NSIndexPath).row]) return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if let index = previousIndex { tableView.deselectRow(at: index, animated: true) } sideMenuController?.performSegue(withIdentifier: segues[(indexPath as NSIndexPath).row], sender: nil) previousIndex = indexPath } }
mit
d92843a8cba537c2ff932ba1cf389451
34.081633
181
0.674229
5.116071
false
false
false
false