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
vector-im/vector-ios
Riot/Modules/Call/Dialpad/Views/DialpadButton.swift
1
3397
// // Copyright 2020 New Vector Ltd // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import UIKit /// Digit button class for Dialpad screen class DialpadButton: UIButton { struct ViewData { let title: String let tone: SystemSoundID let subtitle: String? let showsSubtitleSpace: Bool init(title: String, tone: SystemSoundID, subtitle: String? = nil, showsSubtitleSpace: Bool = false) { self.title = title self.tone = tone self.subtitle = subtitle self.showsSubtitleSpace = showsSubtitleSpace } } private var viewData: ViewData? private var theme: Theme = ThemeService.shared().theme private enum Constants { static let size: CGSize = CGSize(width: 68, height: 68) static let titleFont: UIFont = .boldSystemFont(ofSize: 32) static let subtitleFont: UIFont = .boldSystemFont(ofSize: 12) } init() { super.init(frame: CGRect(origin: .zero, size: Constants.size)) } override init(frame: CGRect) { super.init(frame: frame) setup() } required init?(coder: NSCoder) { super.init(coder: coder) setup() } private func setup() { clipsToBounds = true layer.cornerRadius = Constants.size.width/2 vc_enableMultiLinesTitle() } func render(withViewData viewData: ViewData) { self.viewData = viewData let totalAttributedString = NSMutableAttributedString(string: viewData.title, attributes: [ .font: Constants.titleFont, .foregroundColor: theme.textPrimaryColor ]) if let subtitle = viewData.subtitle { totalAttributedString.append(NSAttributedString(string: "\n" + subtitle, attributes: [ .font: Constants.subtitleFont, .foregroundColor: theme.textPrimaryColor ])) } else if viewData.showsSubtitleSpace { totalAttributedString.append(NSAttributedString(string: "\n ", attributes: [ .font: Constants.subtitleFont, .foregroundColor: theme.textPrimaryColor ])) } setAttributedTitle(totalAttributedString, for: .normal) } } // MARK: - Themable extension DialpadButton: Themable { func update(theme: Theme) { self.theme = theme backgroundColor = theme.headerBackgroundColor // re-render view data if set if let viewData = self.viewData { render(withViewData: viewData) } } }
apache-2.0
e7a4642f46b27f430ec5a6b359690c9a
31.04717
109
0.579923
5.226154
false
false
false
false
JohnCoates/Aerial
Aerial/Source/Views/Layers/Music/MusicLayer.swift
1
4784
// // MusicLayer.swift // Aerial // // Created by Guillaume Louel on 11/06/2021. // Copyright © 2021 Guillaume Louel. All rights reserved. // import Foundation import AVKit class MusicLayer: AnimationLayer { var config: PrefsInfo.Music? var wasSetup = false var timer: Timer? var startTime: Date? var endTime: Date? let artworkLayer = ArtworkLayer() let nameLayer = CATextLayer() let artistLayer = CATextLayer() override init(layer: Any) { super.init(layer: layer) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } // Our inits override init(withLayer: CALayer, isPreview: Bool, offsets: LayerOffsets, manager: LayerManager) { super.init(withLayer: withLayer, isPreview: isPreview, offsets: offsets, manager: manager) self.opacity = 0 } convenience init(withLayer: CALayer, isPreview: Bool, offsets: LayerOffsets, manager: LayerManager, config: PrefsInfo.Music) { self.init(withLayer: withLayer, isPreview: isPreview, offsets: offsets, manager: manager) self.config = config // Set our layer's font & corner now /*(self.font, self.fontSize) = getFont(name: config.fontName, size: config.fontSize)*/ self.corner = config.corner } // Called at each new video, we only setup once though ! override func setupForVideo(video: AerialVideo, player: AVPlayer) { // Only run this once if !wasSetup { setupLayer() // This is where the magic happens, we get notified if we need to display something Music.instance.addCallback { [self] songInfo in updateStatus(songInfo: songInfo) update() } wasSetup = true update() /* let fadeAnimation = self.createFadeInAnimation() add(fadeAnimation, forKey: "textfade")*/ } } func setupLayer() { addSublayer(artworkLayer) // Song name on top nameLayer.string = "" (nameLayer.font, nameLayer.fontSize) = nameLayer.makeFont(name: PrefsInfo.music.fontName, size: PrefsInfo.music.fontSize) addSublayer(nameLayer) // Artist name below artistLayer.string = "" (artistLayer.font, artistLayer.fontSize) = artistLayer.makeFont(name: PrefsInfo.music.fontName, size: PrefsInfo.music.fontSize) addSublayer(artistLayer) // frame/position stuff reframe() } func reframe() { // ReRect the name & artist let rect = nameLayer.calculateRect(string: nameLayer.string as! String, font: nameLayer.font as! NSFont, maxWidth: Double(layerManager.frame!.size.width)) nameLayer.frame = rect nameLayer.contentsScale = self.contentsScale let rect2 = artistLayer.calculateRect(string: artistLayer.string as! String, font: artistLayer.font as! NSFont, maxWidth: Double(layerManager.frame!.size.width)) artistLayer.frame = rect2 artistLayer.contentsScale = self.contentsScale artworkLayer.contentsScale = self.contentsScale // Then calc our parent frame size let textHeight = nameLayer.frame.height + artistLayer.frame.height let textWidth = max(nameLayer.frame.width, artistLayer.frame.width) let artworkOffset = textHeight + 20 frame.size = CGSize(width: textWidth + artworkOffset, height: textHeight) // If we don't have any song playing, we change the height to 0 if (nameLayer.string as! String == "") && (artistLayer.string as! String == "") { frame.size.height = 0 } // Position the things nameLayer.anchorPoint = CGPoint(x: 0, y: 0) nameLayer.position = CGPoint(x: artworkOffset, y: 0) artistLayer.anchorPoint = CGPoint(x: 0, y: 0) artistLayer.position = CGPoint(x: artworkOffset, y: nameLayer.frame.height - 6) artworkLayer.anchorPoint = CGPoint(x: 0, y: 0) artworkLayer.position = CGPoint(x: 0, y: 0) artworkLayer.frame.size = CGSize(width: frame.size.height, height: frame.size.height) } func updateStatus(songInfo: SongInfo) { guard songInfo.name != "", songInfo.id != "" else { opacity = 0 frame.size.height = 0 return } opacity = 1 nameLayer.string = songInfo.name artistLayer.string = songInfo.artist artworkLayer.updateArtwork(id: songInfo.id) // frame/position stuff reframe() } }
mit
151eca81fe712e64d7a47eed1f9e0836
32.921986
135
0.61175
4.63469
false
false
false
false
glyuck/GlyuckDataGrid
Example/Tests/CollectionViewDelegateSpec.swift
1
7088
// // CollectionViewDelegateSpec.swift // // Created by Vladimir Lyukov on 17/08/15. // import Foundation import Quick import Nimble import GlyuckDataGrid class CollectionViewDelegateSpec: QuickSpec { override func spec() { var dataGridView: DataGridView! var stubDataSource: StubDataGridViewDataSource! var stubDelegate: StubDataGridViewDelegate! var sut: CollectionViewDelegate! beforeEach { dataGridView = DataGridView(frame: CGRect(x: 0, y: 0, width: 400, height: 400)) stubDataSource = StubDataGridViewDataSource() stubDelegate = StubDataGridViewDelegate() dataGridView.dataSource = stubDataSource dataGridView.delegate = stubDelegate sut = dataGridView.collectionViewDelegate } describe("collectionView:didTapHeaderForColumn:") { it("should change dataGridView.sortColumn and sortAscending when sorting enabled") { stubDelegate.shouldSortByColumnBlock = { (column) in return true } expect(dataGridView.sortColumn).to(beNil()) // when sut.collectionView(dataGridView.collectionView, didTapHeaderForColumn: 0) // then expect(dataGridView.sortColumn) == 0 expect(dataGridView.sortAscending).to(beTrue()) // when sut.collectionView(dataGridView.collectionView, didTapHeaderForColumn: 1) // then expect(dataGridView.sortColumn) == 1 expect(dataGridView.sortAscending).to(beTrue()) // when sut.collectionView(dataGridView.collectionView, didTapHeaderForColumn: 1) // then expect(dataGridView.sortColumn) == 1 expect(dataGridView.sortAscending).to(beFalse()) } it("should do nothing when sorting is disabled") { expect(dataGridView.sortColumn).to(beNil()) // given stubDelegate.shouldSortByColumnBlock = { (column) in return false } // when sut.collectionView(dataGridView.collectionView, didTapHeaderForColumn: 0) // then expect(dataGridView.sortColumn).to(beNil()) } it("should do nothing when delegate doesnt implement shouldSortByColumn:") { // given dataGridView.delegate = nil // when sut.collectionView(dataGridView.collectionView, didTapHeaderForColumn: 0) // then expect(dataGridView.sortColumn).to(beNil()) } } describe("collectionView:didHighlightItemAtIndexPath:") { it("should highlight whole row") { let row = 1 let indexPath = IndexPath(item: 2, section: row + 1) let collectionView = dataGridView.collectionView collectionView.layoutSubviews() // Otherwise collectionView.cellForItemAtIndexPath won't work // when sut.collectionView(collectionView, didHighlightItemAt: indexPath) // then for i in 0..<stubDataSource.numberOfColumns { let indexPath = IndexPath(item: i, section: row + 1) if let cell = collectionView.cellForItem(at: indexPath) { expect(cell.isHighlighted).to(beTrue()) } } } } describe("collectionView:didUnhighlightItemAtIndexPath:") { it("should unhighlight whole row") { let row = 1 let indexPath = IndexPath(item: 2, section: row + 1) let collectionView = dataGridView.collectionView collectionView.layoutSubviews() // Otherwise collectionView.cellForItemAtIndexPath won't work // given sut.collectionView(collectionView, didHighlightItemAt: indexPath) // when sut.collectionView(collectionView, didUnhighlightItemAt: indexPath) // then for i in 0..<stubDataSource.numberOfColumns { let indexPath = IndexPath(item: i, section: row + 1) if let cell = collectionView.cellForItem(at: indexPath) { expect(cell.isHighlighted).to(beFalse()) } } } } describe("collectionView:shouldSelectItemAtIndexPath:") { it("should return delegate's dataGridView:shouldSelectRow:") { // when stubDelegate.shouldSelectRowBlock = { row in row % 2 == 0 } // then expect(sut.collectionView(dataGridView.collectionView, shouldSelectItemAt: IndexPath(item: 0, section: 0))).to(beTrue()) expect(sut.collectionView(dataGridView.collectionView, shouldSelectItemAt: IndexPath(item: 0, section: 1))).to(beFalse()) } it("should return true if delegate doesn't implement dataGridView:shouldSelectRow:") { // when dataGridView.delegate = StubMinimumDataGridViewDelegate() // then expect(sut.collectionView(dataGridView.collectionView, shouldSelectItemAt: IndexPath(item: 0, section: 0))).to(beTrue()) expect(sut.collectionView(dataGridView.collectionView, shouldSelectItemAt: IndexPath(item: 0, section: 1))).to(beTrue()) } } describe("collectionView:didSelectItemAtIndexPath:") { it("should select whole row") { let row = 1 let indexPath = IndexPath(item: 2, section: row) let collectionView = dataGridView.collectionView collectionView.layoutSubviews() // when sut.collectionView(collectionView, didSelectItemAt: indexPath) let selectedIndexes = collectionView.indexPathsForSelectedItems // then expect(selectedIndexes?.count) == stubDataSource.numberOfColumns for i in 0..<stubDataSource.numberOfColumns { let indexPath = IndexPath(item: i, section: row) expect(selectedIndexes).to(contain(indexPath)) } } it("should call delegate's dataGridView:didSelectRow:") { let row = 1 let indexPath = IndexPath(item: 2, section: row) let collectionView = dataGridView.collectionView var selectedRow: Int? // given stubDelegate.didSelectRowBlock = { row in selectedRow = row } // when sut.collectionView(collectionView, didSelectItemAt: indexPath) // then expect(selectedRow) == row } } } }
mit
591ce516f24a6d7b8dd1121712cd2116
39.971098
137
0.568284
6.131488
false
false
false
false
shergin/PeterParker
Sources/PeterParker/Socket Address/SocketAddressFamily.swift
1
2215
// // SocketAddressFamily.swift // PeterParker // // Created by Valentin Shergin on 5/16/16. // Copyright © 2016 The PeterParker Authors. All rights reserved. // import Foundation import PeterParkerPrivate.ifaddrs public enum SocketAddressFamily: sa_family_t { case Unspecified = 0 // AF_UNSPEC case Unix = 1 // AF_UNIX case IPv4 = 2 // AF_INET case ImpLink = 3 // AF_IMPLINK case Pup = 4 // AF_PUP case CHAOS = 5 // AF_CHAOS case NS = 6 // AF_NS case ISO = 7 // AF_ISO case ECMA = 8 // AF_ECMA case DataKit = 9 // AF_DATAKIT case CCITT = 10 // AF_CCITT case SNA = 11 // AF_SNA case DECnet = 12 // AF_DECnet case DLI = 13 // AF_DLI case LAT = 14 // AF_LAT case HYLINK = 15 // AF_HYLINK case AppleTalk = 16 // AF_APPLETALK case Routing = 17 // AF_ROUTE case Link = 18 // AF_LINK case PseudoXTP = 19 // pseudo_AF_XTP case COIP = 20 // AF_COIP case CNT = 21 // AF_CNT case PseudoRTIP = 22 // pseudo_AF_RTIP case IPX = 23 // AF_IPX case SIP = 24 // AF_SIP case PIP = 25 // pseudo_AF_PIP case Blue = 26 // pseudo_AF_BLUE case NDRV = 27 // AF_NDRV case ISDN = 28 // AF_ISDN case PseudoKey = 29 // pseudo_AF_KEY case IPv6 = 30 // AF_INET6 case NATM = 31 // AF_NATM case System = 32 // AF_SYSTEM case NetBIOS = 33 // AF_NETBIOS case PPP = 34 // AF_PPP case PseudoHDRCMPLT = 35 // pseudo_AF_HDRCMPLT case Reserved36 = 36 // AF_RESERVED_36 case IEEE80211 = 37 // AF_IEEE80211 case UTUN = 38 // AF_UTUN } extension SocketAddressFamily { public init(_ sa_family: sa_family_t) { self = SocketAddressFamily(rawValue: sa_family) ?? .Unspecified } }
mit
fa9f37cd1e60ff444261559e07b02422
35.9
71
0.47019
3.804124
false
false
false
false
sgr-ksmt/PullToDismiss
Demo/Demo/SampleTableViewController.swift
1
2535
// // SampleTableViewController.swift // PullToDismiss // // Created by Suguru Kishimoto on 11/13/16. // Copyright © 2016 Suguru Kishimoto. All rights reserved. // import UIKit import PullToDismiss class SampleTableViewController: UITableViewController { private lazy var dataSource: [String] = { () -> [String] in return (0..<100).map { "Item : \($0)" } }() private var pullToDismiss: PullToDismiss? override func viewDidLoad() { super.viewDidLoad() tableView.register(UITableViewCell.classForCoder(), forCellReuseIdentifier: "Cell") let button = UIBarButtonItem(title: "Close", style: .plain, target: self, action: #selector(dismiss(_:))) navigationItem.rightBarButtonItem = button navigationItem.title = "Sample Table View" navigationController?.navigationBar.isTranslucent = false navigationController?.navigationBar.barTintColor = .orange navigationController?.navigationBar.setValue(UIBarPosition.topAttached.rawValue, forKey: "barPosition") pullToDismiss = PullToDismiss(scrollView: tableView) Config.shared.adaptSetting(pullToDismiss: pullToDismiss) pullToDismiss?.dismissAction = { [weak self] in self?.dismiss(nil) } pullToDismiss?.delegate = self } var disissBlock: (() -> Void)? // MARK: - Table view data source override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return dataSource.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) cell.textLabel?.text = dataSource[indexPath.row] return cell } @objc func dismiss(_: AnyObject?) { dismiss(animated: true) { [weak self] in self?.disissBlock?() } } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) let alert = UIAlertController(title: "test", message: "\(indexPath.section)-\(indexPath.row) touch!", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "ok", style: .default, handler: nil)) self.present(alert, animated: true, completion: nil) } override func scrollViewDidScroll(_ scrollView: UIScrollView) { print("\(scrollView.contentOffset.y)") } }
mit
086ab7008634f4413e7a2ce3dff40a2a
37.984615
133
0.672849
5.027778
false
false
false
false
iOSDevLog/iOSDevLog
201. UI Test/Swift/Lister WatchKit Extension/ListInterfaceController.swift
1
8389
/* Copyright (C) 2015 Apple Inc. All Rights Reserved. See LICENSE.txt for this sample’s licensing information Abstract: The `ListInterfaceController` interface controller that presents a single list managed by a `ListPresenterType` object. */ import WatchKit import ListerKit /** The interface controller that presents a list. The interface controller listens for changes to how the list should be presented by the list presenter. */ class ListInterfaceController: WKInterfaceController, ListPresenterDelegate { // MARK: Types struct Storyboard { static let interfaceControllerName = "ListInterfaceController" struct RowTypes { static let item = "ListControllerItemRowType" static let noItems = "ListControllerNoItemsRowType" } } // MARK: Properties @IBOutlet weak var interfaceTable: WKInterfaceTable! var listDocument: ListDocument! var listPresenter: IncompleteListItemsPresenter? { return listDocument?.listPresenter as? IncompleteListItemsPresenter } // MARK: Interface Table Selection override func table(table: WKInterfaceTable, didSelectRowAtIndex rowIndex: Int) { guard let listPresenter = listPresenter else { return } let listItem = listPresenter.presentedListItems[rowIndex] listPresenter.toggleListItem(listItem) } // MARK: Actions @IBAction func markAllListItemsAsComplete() { guard let listPresenter = listPresenter else { return } listPresenter.updatePresentedListItemsToCompletionState(true) } @IBAction func markAllListItemsAsIncomplete() { guard let listPresenter = listPresenter else { return } listPresenter.updatePresentedListItemsToCompletionState(false) } func refreshAllData() { guard let listPresenter = listPresenter else { return } let listItemCount = listPresenter.count if listItemCount > 0 { interfaceTable.setNumberOfRows(listItemCount, withRowType: Storyboard.RowTypes.item) for idx in 0..<listItemCount { configureRowControllerAtIndex(idx) } } else { let indexSet = NSIndexSet(index: 0) interfaceTable.insertRowsAtIndexes(indexSet, withRowType: Storyboard.RowTypes.noItems) } } // MARK: ListPresenterDelegate func listPresenterDidRefreshCompleteLayout(_: ListPresenterType) { refreshAllData() } func listPresenterWillChangeListLayout(_: ListPresenterType, isInitialLayout: Bool) { // `WKInterfaceTable` objects do not need to be notified of changes to the table, so this is a no op. } func listPresenter(_: ListPresenterType, didInsertListItem listItem: ListItem, atIndex index: Int) { let indexSet = NSIndexSet(index: index) // The list presenter was previously empty. Remove the "no items" row. if index == 0 && listPresenter!.count == 1 { interfaceTable.removeRowsAtIndexes(indexSet) } interfaceTable.insertRowsAtIndexes(indexSet, withRowType: Storyboard.RowTypes.item) } func listPresenter(_: ListPresenterType, didRemoveListItem listItem: ListItem, atIndex index: Int) { let indexSet = NSIndexSet(index: index) interfaceTable.removeRowsAtIndexes(indexSet) // The list presenter is now empty. Add the "no items" row. if index == 0 && listPresenter!.isEmpty { interfaceTable.insertRowsAtIndexes(indexSet, withRowType: Storyboard.RowTypes.noItems) } } func listPresenter(_: ListPresenterType, didUpdateListItem listItem: ListItem, atIndex index: Int) { configureRowControllerAtIndex(index) } func listPresenter(_: ListPresenterType, didMoveListItem listItem: ListItem, fromIndex: Int, toIndex: Int) { // Remove the item from the fromIndex straight away. let fromIndexSet = NSIndexSet(index: fromIndex) interfaceTable.removeRowsAtIndexes(fromIndexSet) /* Determine where to insert the moved item. If the `toIndex` was beyond the `fromIndex`, normalize its value. */ var toIndexSet: NSIndexSet if toIndex > fromIndex { toIndexSet = NSIndexSet(index: toIndex - 1) } else { toIndexSet = NSIndexSet(index: toIndex) } interfaceTable.insertRowsAtIndexes(toIndexSet, withRowType: Storyboard.RowTypes.item) } func listPresenter(_: ListPresenterType, didUpdateListColorWithColor color: List.Color) { guard let listPresenter = listPresenter else { return } for idx in 0..<listPresenter.count { configureRowControllerAtIndex(idx) } } func listPresenterDidChangeListLayout(_: ListPresenterType, isInitialLayout: Bool) { if isInitialLayout { // Display all of the list items on the first layout. refreshAllData() } else { /* The underlying document changed because of user interaction (this event only occurs if the list presenter's underlying list presentation changes based on user interaction). */ listDocument.updateChangeCount(.Done) } } // MARK: Convenience func setupInterfaceTable() { listDocument.listPresenter = IncompleteListItemsPresenter() listPresenter!.delegate = self listDocument.openWithCompletionHandler { success in if !success { print("Couldn't open document: \(self.listDocument?.fileURL).") return } /* Once the document for the list has been found and opened, update the user activity with its URL path to enable the container iOS app to start directly in this list document. A URL path is passed instead of a URL because the `userInfo` dictionary of a WatchKit app's user activity does not allow NSURL values. */ let userInfo: [NSObject: AnyObject] = [ AppConfiguration.UserActivity.listURLPathUserInfoKey: self.listDocument.fileURL.path!, AppConfiguration.UserActivity.listColorUserInfoKey: self.listDocument.listPresenter!.color.rawValue ] /* Lister uses a specific user activity name registered in the Info.plist and defined as a constant to separate this action from the built-in UIDocument handoff support. */ self.updateUserActivity(AppConfiguration.UserActivity.watch, userInfo: userInfo, webpageURL: nil) } } func configureRowControllerAtIndex(index: Int) { guard let listPresenter = listPresenter else { return } let listItemRowController = interfaceTable.rowControllerAtIndex(index) as! ListItemRowController let listItem = listPresenter.presentedListItems[index] listItemRowController.setText(listItem.text) let textColor = listItem.isComplete ? UIColor.grayColor() : UIColor.whiteColor() listItemRowController.setTextColor(textColor) // Update the checkbox image. let state = listItem.isComplete ? "checked" : "unchecked" let imageName = "checkbox-\(listPresenter.color.name.lowercaseString)-\(state)" listItemRowController.setCheckBoxImageNamed(imageName) } // MARK: Interface Life Cycle override func awakeWithContext(context: AnyObject?) { precondition(context is ListInfo, "Expected class of `context` to be ListInfo.") let listInfo = context as! ListInfo listDocument = ListDocument(fileURL: listInfo.URL) // Set the title of the interface controller based on the list's name. setTitle(listInfo.name) // Fill the interface table with the current list items. setupInterfaceTable() } override func didDeactivate() { listDocument.closeWithCompletionHandler(nil) } }
mit
b052b6293e2dbf6a664cdb1bc433cb9f
36.110619
123
0.648504
5.873249
false
false
false
false
iOSDevLog/iOSDevLog
171. photo-extensions-Filtster/FiltsterPack/FiltsterFilter.swift
1
2709
/* * Copyright 2015 Sam Davies * * 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 public protocol FiltsterFilterDelegate { func outputImageDidUpdate(outputImage: CIImage) } public class FiltsterFilter { // MARK:- Filter info public let filterIdentifier: String = "com.shinobicontrols.filster" public let filterVersion: String = "1.0" // MARK:- Public properties public var delegate: FiltsterFilterDelegate? public init() { } public var inputImage: CIImage! { didSet { performFilter() } } // MARK:- Filter Parameters public var vignetteIntensity: Double = 1.0 { didSet { performFilter() } } public var vignetteRadius: Double = 0.5 { didSet { performFilter() } } public var sepiaIntensity: Double = 1.0 { didSet { performFilter() } } // MARK:- Output images public var outputImage: CIImage { let filter = vignette(vignetteRadius, intensity: vignetteIntensity) >>> sepia(sepiaIntensity) return filter(inputImage) } // MARK:- Private methods private func performFilter() { delegate?.outputImageDidUpdate(outputImage) } } // MARK:- Filter Serialization extension FiltsterFilter { public func supportsFilterIdentifier(identifier: String, version: String) -> Bool { return identifier == filterIdentifier && version == filterVersion } public func importFilterParameters(data: NSData?) { if let data = data { if let dataDict = NSKeyedUnarchiver.unarchiveObjectWithData(data) as? [String : AnyObject] { vignetteIntensity = dataDict["vignetteIntensity"] as? Double ?? vignetteIntensity vignetteRadius = dataDict["vignetteRadius"] as? Double ?? vignetteRadius sepiaIntensity = dataDict["sepiaIntensity"] as? Double ?? sepiaIntensity } } } public func encodeFilterParameters() -> NSData { var dataDict = [String : AnyObject]() dataDict["vignetteIntensity"] = vignetteIntensity dataDict["vignetteRadius"] = vignetteRadius dataDict["sepiaIntensity"] = sepiaIntensity return NSKeyedArchiver.archivedDataWithRootObject(dataDict) } }
mit
697d16ecbf02d7e775b4f2209e153824
27.526316
98
0.692506
4.492537
false
false
false
false
eljeff/AudioKit
Sources/AudioKit/MIDI/Listeners/MIDIClockListener.swift
2
7415
// Copyright AudioKit. All Rights Reserved. Revision History at http://github.com/AudioKit/AudioKit/ #if !os(tvOS) import Foundation import CoreMIDI import os.log /// This class is used to count midi clock events and inform observers /// every 24 pulses (1 quarter note) /// /// If you wish to observer its events, then add your own MIDIBeatObserver /// public class MIDIClockListener: NSObject { /// Definition of 24 quantums per quarter note let quantumsPerQuarterNote: MIDIByte /// Count of 24 quantums per quarter note public var quarterNoteQuantumCounter: MIDIByte = 0 /// number of all time quantum F8 MIDI Clock messages seen public var quantumCounter: UInt64 = 0 /// 6 F8 MIDI Clock messages = 1 SPP MIDI Beat public var sppMIDIBeatCounter: UInt64 = 0 /// 6 F8 MIDI Clock quantum messages = 1 SPP MIDI Beat public var sppMIDIBeatQuantumCounter: MIDIByte = 0 /// 1, 2, 3, 4 , 1, 2, 3, 4 - quarter note counter public var fourCount: MIDIByte = 0 private var sendStart = false private var sendContinue = false private let srtListener: MIDISystemRealTimeListener private let tempoListener: MIDITempoListener private var observers: [MIDIBeatObserver] = [] /// MIDIClockListener requires to be an observer of both SRT and BPM events /// - Parameters: /// - srt: MIDI System real-time listener /// - count: Quantums per quarter note /// - tempo: Tempo listener init(srtListener srt: MIDISystemRealTimeListener, quantumsPerQuarterNote count: MIDIByte = 24, tempoListener tempo: MIDITempoListener) { quantumsPerQuarterNote = count srtListener = srt tempoListener = tempo super.init() // self is now initialized srtListener.addObserver(self) tempoListener.addObserver(self) } deinit { srtListener.removeObserver(self) tempoListener.removeObserver(self) observers = [] } func sppChange(_ positionPointer: UInt16) { sppMIDIBeatCounter = UInt64(positionPointer) quantumCounter = UInt64(6 * sppMIDIBeatCounter) quarterNoteQuantumCounter = MIDIByte(quantumCounter % 24) } func midiClockBeat(time: MIDITimeStamp) { self.quantumCounter += 1 // quarter notes can only increment when we are playing guard srtListener.state == .playing else { sendQuantumUpdateToObservers(time: time) return } // increment quantum counter used for counting quarter notes self.quarterNoteQuantumCounter += 1 // ever first quantum we will count as a quarter note event if quarterNoteQuantumCounter == 1 { // ever four quarter notes we reset if fourCount >= 4 { fourCount = 0 } fourCount += 1 let spaces = " " let prefix = spaces.prefix( Int(fourCount) ) Log("\(prefix) \(fourCount)", log: OSLog.midi) if sendStart || sendContinue { sendStartContinueToObservers() sendContinue = false sendStart = false } sendQuarterNoteMessageToObservers() } else if quarterNoteQuantumCounter == quantumsPerQuarterNote { quarterNoteQuantumCounter = 0 } sendQuantumUpdateToObservers(time: time) if sppMIDIBeatQuantumCounter == 6 { sppMIDIBeatQuantumCounter = 0; sppMIDIBeatCounter += 1 } sppMIDIBeatQuantumCounter += 1 if sppMIDIBeatQuantumCounter == 1 { sendMIDIBeatUpdateToObservers() let beat = (sppMIDIBeatCounter % 16) + 1 Log(" \(beat)", log: OSLog.midi) } } func midiClockStopped() { quarterNoteQuantumCounter = 0 quantumCounter = 0 } } // MARK: - Observers extension MIDIClockListener { /// Add MIDI beat observer /// - Parameter observer: MIDI Beat observer to add public func addObserver(_ observer: MIDIBeatObserver) { observers.append(observer) Log("[MIDIClockListener:addObserver] (\(observers.count) observers)", log: OSLog.midi) } /// Remove MIDI beat observer /// - Parameter observer: MIDI Beat observer to remove public func removeObserver(_ observer: MIDIBeatObserver) { observers.removeAll { $0 == observer } Log("[MIDIClockListener:removeObserver] (\(observers.count) observers)", log: OSLog.midi) } /// Remove all MIDI Beat observers public func removeAllObservers() { observers.removeAll() } } // MARK: - Beat Observations extension MIDIClockListener: MIDIBeatObserver { internal func sendMIDIBeatUpdateToObservers() { observers.forEach { (observer) in observer.receivedBeatEvent(beat: sppMIDIBeatCounter) } } internal func sendQuantumUpdateToObservers(time: MIDITimeStamp) { observers.forEach { (observer) in observer.receivedQuantum(time: time, quarterNote: fourCount, beat: sppMIDIBeatCounter, quantum: quantumCounter) } } internal func sendQuarterNoteMessageToObservers() { observers.forEach { (observer) in observer.receivedQuarterNoteBeat(quarterNote: fourCount) } } internal func sendPreparePlayToObservers(continue resume: Bool) { observers.forEach { (observer) in observer.preparePlay(continue: resume) } } internal func sendStartContinueToObservers() { guard sendContinue || sendStart else { return } observers.forEach { (observer) in observer.startFirstBeat(continue: sendContinue) } } internal func sendStopToObservers() { observers.forEach { (observer) in observer.stopSRT() } } } // MARK: - MMC Observations interface extension MIDIClockListener: MIDITempoObserver { /// Resets the quantumc ounter public func midiClockFollowerMode() { Log("MIDI Clock Follower", log: OSLog.midi) quarterNoteQuantumCounter = 0 } /// Resets the quantum counter public func midiClockLeaderEnabled() { Log("MIDI Clock Leader Enabled", log: OSLog.midi) quarterNoteQuantumCounter = 0 } } extension MIDIClockListener: MIDISystemRealTimeObserver { /// Stop MIDI System Real-time listener /// - Parameter listener: MIDI System Real-time Listener public func stopSRT(listener: MIDISystemRealTimeListener) { Log("Beat: [Stop]", log: OSLog.midi) sendStopToObservers() } /// Start MIDI System Real-time listener /// - Parameter listener: MIDI System Real-time Listener public func startSRT(listener: MIDISystemRealTimeListener) { Log("Beat: [Start]", log: OSLog.midi) sppMIDIBeatCounter = 0 quarterNoteQuantumCounter = 0 fourCount = 0 sendStart = true sendPreparePlayToObservers(continue: false) } /// Continue MIDI System Real-time listener /// - Parameter listener: MIDI System Real-time Listener public func continueSRT(listener: MIDISystemRealTimeListener) { Log("Beat: [Continue]", log: OSLog.midi) sendContinue = true sendPreparePlayToObservers(continue: true) } } #endif
mit
e19de37b65b7cadcdaf2afded913778a
31.665198
100
0.646258
5.1386
false
false
false
false
WangCrystal/actor-platform
actor-apps/app-ios/ActorApp/Controllers/Contacts/Cells/ContactActionCell.swift
4
1400
// // Copyright (c) 2014-2015 Actor LLC. <https://actor.im> // import Foundation class ContactActionCell: BasicCell { let titleView = UILabel() let iconView = UIImageView() init(reuseIdentifier:String) { super.init(reuseIdentifier: reuseIdentifier, separatorPadding: 80) titleView.font = UIFont(name: "HelveticaNeue", size: 18); titleView.textColor = MainAppTheme.list.actionColor iconView.contentMode = UIViewContentMode.Center self.contentView.addSubview(titleView) self.contentView.addSubview(iconView) backgroundColor = MainAppTheme.list.bgColor let selectedView = UIView() selectedView.backgroundColor = MainAppTheme.list.bgSelectedColor selectedBackgroundView = selectedView } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func bind(icon: String, actionTitle: String, isLast: Bool){ hideSeparator(isLast) titleView.text = actionTitle iconView.image = UIImage(named: icon)?.tintImage(MainAppTheme.list.actionColor) } override func layoutSubviews() { super.layoutSubviews() let width = self.contentView.frame.width; iconView.frame = CGRectMake(30, 8, 40, 40); titleView.frame = CGRectMake(80, 8, width - 80 - 14, 40); } }
mit
b827f2ee198225ad2163cbf681bb5549
31.581395
87
0.661429
4.912281
false
false
false
false
polkahq/PLKSwift
Sources/polka/utils/PLKHash.swift
1
1304
// // PLKHash.swift // // Created by Alvaro Talavera on 5/12/16. // Copyright © 2016 Polka. All rights reserved. // import Foundation public class PLKHash: NSObject { public static func uuid() -> String! { return NSUUID().uuidString } public static func base64Encode(input:String!) -> String! { let data:Data = input.data(using: String.Encoding.utf8)! return data.base64EncodedString(options: NSData.Base64EncodingOptions(rawValue: 0)) } public static func base64Decode(input:String!) -> String! { let data:Data? = Data(base64Encoded: input, options: Data.Base64DecodingOptions.init(rawValue: 0)) if(data != nil) { var string:String? = String(data: data!, encoding: .utf8) if(string == nil) { string = String(data: data!, encoding: .isoLatin1) } if(string == nil) { string = String(data: data!, encoding: .isoLatin2) } if(string == nil) { string = String(data: data!, encoding: .ascii) } if(string != nil) { return string! } } return "" } }
mit
80b4495c2fd50097aeed8ef51c482633
26.723404
107
0.513431
4.203226
false
false
false
false
Bijiabo/F-Client-iOS
F/Library/FAction.swift
1
6828
// // FAction.swift // F // // Created by huchunbo on 15/11/4. // Copyright © 2015年 TIDELAB. All rights reserved. // import Foundation import Alamofire import SwiftyJSON import UIKit class FAction: NSObject { subscript(request: String) -> AnyObject? { if let value = self.valueForKey(request) { return value } return nil } let _actions = [ "login": { (params: [AnyObject], delegate: UIViewController) in if params.count < 1 {return} guard let userInputData = params[0] as? [String: String] else {return} let parameters = userInputData FNetwork.POST(path: "request_new_token", parameters: parameters, completionHandler: { (reqest, response, json, error) -> Void in if error == nil { if !json["error"].boolValue { print("login success!") }else{ print("login error:(") } print(json) } }) }, "register": { (params: [AnyObject], delegate: UIViewController) in } ] func run (action: String, params: [AnyObject], delegate: UIViewController) { _actions[action]?(params, delegate) } // MARK: // MARK: actions class func checkLogin (completeHandler: (success: Bool, description: String)->Void ) { FNetwork.GET(path: "check_token.json?token=\(FHelper.token)") { (request, response, json, error) -> Void in var success: Bool = false var description: String = error.debugDescription if error == nil { success = json["success"].boolValue if !success { description = json["description"].stringValue } else { description = json["description"].stringValue } FHelper.current_user = User(id: json["user"]["id"].intValue , name: json["user"]["name"].stringValue, email: json["user"]["email"].stringValue, valid: true) } completeHandler(success: success, description: description) } } class func login (email: String, password: String, completeHandler: (success: Bool, description: String)->Void ) { let parameters = [ "email": email, "password": password, "deviceID": FTool.Device.ID(), "deviceName": FTool.Device.Name() ] FNetwork.POST(path: "request_new_token.json", parameters: parameters) { (request, response, json, error) -> Void in var success: Bool = false var description: String = error.debugDescription if error == nil { success = !json["error"].boolValue if !success { description = json["description"].stringValue } //save token FHelper.setToken(id: json["token"]["id"].stringValue, token: json["token"]["token"].stringValue) FHelper.current_user = User(id: json["token"]["user_id"].intValue , name: json["name"].stringValue, email: json["email"].stringValue, valid: true) } completeHandler(success: success, description: description) } } class func register (email: String, name: String, password: String, completeHandler: (success: Bool, description: String)->Void ) { let parameters = [ "email": email, "name": name, "password": password, "password_confirmation": password ] //TODO: finish viewController FNetwork.POST(path: "users.json", parameters: parameters) { (request, response, json, error) -> Void in var success: Bool = false var description: String = String() if error == nil { success = !json["error"].boolValue if !success { description = json["description"].stringValue completeHandler(success: success, description: description) } else { FAction.login(email, password: password, completeHandler: completeHandler) } } else { description = error.debugDescription completeHandler(success: success, description: description) } } } class func logout () { FNetwork.DELETE(path: "tokens/\(FHelper.tokenID).json?token=\(FHelper.token)") { (request, response, json, error) -> Void in print(json) } } // MARK: - Get class func GET(path path: String, completeHandler: (request: NSURLRequest, response: NSHTTPURLResponse?, json: JSON, error: ErrorType?)->Void) { FNetwork.GET(path: "\(path).json?token=\(FHelper.token)") { (request, response, json, error) -> Void in completeHandler(request: request, response: response, json: json, error: error) } } // MARK: class fluxes { class func create(motion motion: String, content: String, image: NSData?, completeHandler: (success: Bool, description: String)->Void) { FNetwork.UPLOAD(path: "fluxes.json?token=\(FHelper.token)", multipartFormData: { (multipartFormData) -> Void in if let imageData = image { multipartFormData.appendBodyPart(data: imageData, name: "flux[picture]", fileName: "xxx.jpg", mimeType: "image/jpeg") }else{ multipartFormData.appendBodyPart(data: "".dataUsingEncoding(NSUTF8StringEncoding)!, name: "flux[picture]") } //multipartFormData.appendBodyPart(fileURL: uploadImageURL, name: "flux[picture]") multipartFormData.appendBodyPart(data: motion.dataUsingEncoding(NSUTF8StringEncoding)!, name: "flux[motion]") multipartFormData.appendBodyPart(data: content.dataUsingEncoding(NSUTF8StringEncoding)!, name: "flux[content]") }, completionHandler: { (request, response, json, error) -> Void in completeHandler(success: json["success"].boolValue, description: json["description"].stringValue) }, failedHandler: {(success: Bool, description: String) in completeHandler(success: success, description: description) } ) } } }
gpl-2.0
a3433a0b2099db4f0b86e9a5ca18a240
38.918129
172
0.537729
5.15873
false
false
false
false
IBM-MIL/IBM-Ready-App-for-Insurance
PerchReadyApp/apps/Perch/iphone/native/Perch/Extensions/UIViewControllerExtension.swift
1
5497
/* Licensed Materials - Property of IBM © Copyright IBM Corporation 2015. All Rights Reserved. */ import Foundation import UIKit /** * Useful methods related to UIViewControllers */ extension UIViewController { /** Find the best candidate for being the current view controller - parameter vc: Initially the root viewcontroller, then passed in recursively as the previous vc's presented view controller - returns: The current view controller */ private class func findBestViewController(vc: UIViewController) -> UIViewController { // If the vc passed in has presented another vc, then dive into that presented vc by calling this method with it recursively if (vc.presentedViewController != nil) { return UIViewController.findBestViewController(vc.presentedViewController!) } // If the vc passed in has not presented another vc, but it is a split view controller, determine the current vc from the split vc else if vc.isKindOfClass(UISplitViewController) { let svc = vc as! UISplitViewController if svc.viewControllers.count > 0 { return UIViewController.findBestViewController(svc.viewControllers.last as UIViewController!) } else { return vc } } // If the vc passed in has not presented another vc, but it is a navigation controller, determine the current vc from the nav controller else if vc.isKindOfClass(UINavigationController) { let nvc = vc as! UINavigationController if nvc.viewControllers.count > 0 { return UIViewController.findBestViewController(nvc.topViewController!) } else { return vc } } // If the vc passed in has not presented another vc, but it is a tab bar controller, determine the current vc from the tab controller else if vc.isKindOfClass(UITabBarController) { let tvc = vc as! UITabBarController if tvc.viewControllers?.count > 0 { return UIViewController.findBestViewController(tvc.selectedViewController!) } else { return vc } } // The view controller passed in has not presented another view controller and is not of a more interesting (complicated) type, so we have found the current vc else { return vc } } /** Public facing method for finding the current view controller by stepping through all view controllers presented since the root view - returns: The current view controller */ class func currentViewController() -> UIViewController { let viewController = UIApplication.sharedApplication().keyWindow?.rootViewController return UIViewController.findBestViewController(viewController!) } /** App specific for digging down through view hierarchy and finding asset overview if it exists. Needed so we can tell the asset overview to reload when a push notification comes in. - parameter vc: The initial view controller, then recursively the previous vc's presented vc - returns: The asset overview reference */ private class func findAssetOverviewReference(vc: UIViewController) -> UIViewController { if vc.isKindOfClass(PageHandlerViewController) { let phvc = vc as! PageHandlerViewController if let navHandlerVC = phvc.navHandlerViewController { if navHandlerVC.assetsViewController != nil { return navHandlerVC.assetsViewController } else { return vc } } else { return vc } } else if vc.presentedViewController != nil { return UIViewController.findAssetOverviewReference(vc.presentedViewController!) } else { return vc } } /** App specific for digging down through view hierarchy and finding pagehandler if it exists. Needed for clearing out a reference this view has to the alert history vc. - parameter vc: The initial view controller, then recursively the previous vc's presented vc - returns: The page handler reference */ private class func findPageHandlerReference(vc: UIViewController) -> UIViewController { if vc.isKindOfClass(PageHandlerViewController) { return vc } else if vc.presentedViewController != nil { return UIViewController.findPageHandlerReference(vc.presentedViewController!) } else { return vc } } /** Public facing method for finding the asset overview reference - returns: The asset overview vc reference */ class func assetOverviewReference() -> UIViewController { let viewController = UIApplication.sharedApplication().keyWindow?.rootViewController return UIViewController.findAssetOverviewReference(viewController!) } /** Public facing method for finding the page handler reference - returns: The page handler vc reference */ class func pageHanderReference() -> UIViewController { let viewController = UIApplication.sharedApplication().keyWindow?.rootViewController return UIViewController.findPageHandlerReference(viewController!) } }
epl-1.0
f1614d504f1de721ddc3a3a036a5a26c
38.833333
167
0.659389
5.928803
false
false
false
false
morizotter/MZRBolts-iOS-Sample
MZRBolts-iOS-Sample/ViewController.swift
1
2323
// // ViewController.swift // MZRBolts-iOS-Sample // // Copyright (c) 2014 molabo. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // PREPARE EMPTY TASK - FOR EXECUTING TASK IN SERIES var task = BFTask(result: nil) // 1. ASYNCRONOUS CONNECTION TO YAHOO task = task.continueWithBlock({ (task: BFTask!) -> BFTask! in // INSTANTIATE TASK COMPLETION let taskCompletion = BFTaskCompletionSource() // ASYNCRONOUS NETWORK let url = "http://yahoo.co.jp" let session = NSURLSession.sharedSession() let sessionTask = session.dataTaskWithURL(NSURL(string: url), completionHandler: { (data: NSData!, response: NSURLResponse!, error: NSError!) -> Void in if let err = error { println("1 ERROR: YAHOO!") taskCompletion.setError(err) } println("1 SUCCESS: YAHOO!") taskCompletion.setResult(data) }) sessionTask.resume() // RETURN TASK return taskCompletion.task }) // 2. ASYNCRONOUS CONNECTION TO GOOGLE task = task.continueWithBlock({ (task: BFTask!) -> BFTask! in // INSTANTIATE TASK COMPLETION let taskCompletion = BFTaskCompletionSource() // ASYNCRONOUS NETWORK let url = "http://google.com" let session = NSURLSession.sharedSession() let sessionTask = session.dataTaskWithURL(NSURL(string: url), completionHandler: { (data: NSData!, response: NSURLResponse!, error: NSError!) -> Void in if let err = error { println("2 ERROR: GOOGLE!") taskCompletion.setError(err) } println("2 SUCCESS: GOOGLE!") taskCompletion.setResult(data) }) sessionTask.resume() // RETURN TASK return taskCompletion.task }) } }
mit
af228986e03935426b13be587b7c53e9
30.821918
164
0.507533
5.517815
false
false
false
false
davecom/ClassicComputerScienceProblemsInSwift
Classic Computer Science Problems in Swift.playground/Pages/Chapter 5.xcplaygroundpage/Contents.swift
1
11747
//: [Previous](@previous) // Classic Computer Science Problems in Swift Chapter 5 Source // Copyright 2017 David Kopec // // 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 // for arc4random_uniform() and drand48() srand48(time(nil)) // seed random number generator for drand48() // A derivative of the Fisher-Yates algorithm to shuffle an array extension Array { public func shuffled() -> Array<Element> { var shuffledArray = self // value semantics (Array is Struct) makes this a copy if count < 2 { return shuffledArray } // already shuffled for i in (1..<count).reversed() { // count backwards let position = Int(arc4random_uniform(UInt32(i + 1))) // random to swap if i != position { // swap with the end, don't bother with self swaps shuffledArray.swapAt(i, position) } } return shuffledArray } } public protocol Chromosome { var fitness: Double { get } // how well does this individual solve the problem? init(from: Self) // must be able to copy itself static func randomInstance() -> Self func crossover(other: Self) -> (child1: Self, child2: Self) // combine with other to form children func mutate() // make a small change somewhere func prettyPrint() } open class GeneticAlgorithm<ChromosomeType: Chromosome> { enum SelectionType { case roulette case tournament(UInt) // the UInt is the number of participants in the tournament } private let threshold: Double // at what fitness level to stop running private let maxGenerations: UInt // number of generations to run private let mutationChance: Double // probability of mutation for each individual in each generation private let crossoverChance: Double // probability of any two children being crossed each generation private let selectionType: SelectionType // which selection method? private var population: [ChromosomeType] // all of the individuals in a generation private var fitnessCache: [Double] // the fitness of each individual in the current generation private var fitnessSum: Double = -Double.greatestFiniteMagnitude // summed generation fitness init(size: UInt, threshold: Double, maxGenerations: UInt = 100, mutationChance: Double = 0.01, crossoverChance: Double = 0.7, selectionType: SelectionType = SelectionType.tournament(4)) { self.threshold = threshold self.maxGenerations = maxGenerations self.mutationChance = mutationChance self.crossoverChance = crossoverChance self.selectionType = selectionType population = [ChromosomeType]() // initialize the population with random chromosomes for _ in 0..<size { population.append(ChromosomeType.randomInstance()) } fitnessCache = [Double](repeating: -Double.greatestFiniteMagnitude, count: Int(size)) } // pick based on the proportion of summed total fitness that each individual represents private func pickRoulette(wheel: [Double]) -> ChromosomeType { var pick = drand48() // chance of picking a particular one for (index, chance) in wheel.enumerated() { pick -= chance if pick <= 0 { // we had one that took us over, leads to a pick return population[index] } } return population[0] } // find k random individuals in the population and pick the best one private func pickTournament(numParticipants: UInt) -> ChromosomeType { var best: ChromosomeType = ChromosomeType.randomInstance() var bestFitness: Double = best.fitness for _ in 0..<numParticipants { // find the best participant let test = Int(arc4random_uniform(UInt32(population.count))) if fitnessCache[test] > bestFitness { bestFitness = fitnessCache[test] best = population[test] } } return best } private func reproduceAndReplace() { var newPopulation: [ChromosomeType] = [ChromosomeType]() // replacement population var chanceEach: [Double] = [Double]() // used for pickRoulette, chance of each individual being picked if case .roulette = selectionType { chanceEach = fitnessCache.map({return $0/fitnessSum}) } while newPopulation.count < population.count { var parents: (parent1: ChromosomeType, parent2: ChromosomeType) switch selectionType { // how to pick parents case let .tournament(k): parents = (parent1: pickTournament(numParticipants: k), parent2: pickTournament(numParticipants: k)) default: // don't have a case for roulette because no other option parents = (parent1: pickRoulette(wheel: chanceEach), parent2: pickRoulette(wheel: chanceEach)) } if drand48() < crossoverChance { // if crossover, produce children let children = parents.parent1.crossover(other: parents.parent2) newPopulation.append(children.child1) newPopulation.append(children.child2) } else { // no crossover, just use parents newPopulation.append(parents.parent1) newPopulation.append(parents.parent2) } } if newPopulation.count > population.count { // in case we had an odd population newPopulation.removeLast() } population = newPopulation } private func mutate() { for individual in population { // every individual could possibly be mutated each generation if drand48() < mutationChance { individual.mutate() } } } public func run() -> ChromosomeType { var best: ChromosomeType = ChromosomeType.randomInstance() // best in any run so far var bestFitness: Double = best.fitness for generation in 1...maxGenerations { // try maxGenerations of the genetic algorithm print("generation \(generation) best \(best.fitness) avg \(fitnessSum / Double(fitnessCache.count))") for (index, individual) in population.enumerated() { fitnessCache[index] = individual.fitness if fitnessCache[index] >= threshold { // early end; found something great return individual } if fitnessCache[index] > bestFitness { // best so far in any iteration bestFitness = fitnessCache[index] best = ChromosomeType(from: individual) } } fitnessSum = fitnessCache.reduce(0, +) reproduceAndReplace() mutate() } return best } } final class SimpleEquation: Chromosome { var x: Int = Int(arc4random_uniform(100)) var y: Int = Int(arc4random_uniform(100)) var fitness: Double { // 6x - x^2 + 4y - y^2 return Double(6 * x - x * x + 4 * y - y * y) } init(from: SimpleEquation) { // like making a copy x = from.x y = from.y } init() {} static func randomInstance() -> SimpleEquation { return SimpleEquation() } func crossover(other: SimpleEquation) -> (child1: SimpleEquation, child2: SimpleEquation) { let child1 = SimpleEquation(from: self) let child2 = SimpleEquation(from: other) child1.y = other.y child2.y = self.y return (child1: child1, child2: child2) } func mutate() { if drand48() > 0.5 { // mutate x if drand48() > 0.5 { x += 1 } else { x -= 1 } } else { // otherwise mutate y if drand48() > 0.5 { y += 1 } else { y -= 1 } } } func prettyPrint() { print("x:\(x) y:\(y) fitness:\(fitness)") } } let se = GeneticAlgorithm<SimpleEquation>(size: 10, threshold: 13.0, maxGenerations: 100, mutationChance: 0.1, crossoverChance: 0.7) let result1 = se.run() result1.fitness result1.prettyPrint() final class SendMoreMoney: Chromosome { var genes: [Character] static let letters: [Character] = ["S", "E", "N", "D", "M", "O", "R", "Y", " ", " "] var fitness: Double { if let s = genes.index(of: "S"), let e = genes.index(of: "E"), let n = genes.index(of: "N"), let d = genes.index(of: "D"), let m = genes.index(of: "M"), let o = genes.index(of: "O"), let r = genes.index(of: "R"), let y = genes.index(of: "Y") { let send: Int = s * 1000 + e * 100 + n * 10 + d let more: Int = m * 1000 + o * 100 + r * 10 + e let money: Int = m * 10000 + o * 1000 + n * 100 + e * 10 + y let difference = abs(money - (send + more)) return 1 / Double(difference + 1) } return 0 } init(from: SendMoreMoney) { genes = from.genes } init(genes: [Character]) { self.genes = genes } static func randomInstance() -> SendMoreMoney { return SendMoreMoney(genes: letters.shuffled()) } func crossover(other: SendMoreMoney) -> (child1: SendMoreMoney, child2: SendMoreMoney) { let crossingPoint = Int(arc4random_uniform(UInt32(genes.count))) let childGenes1 = genes[0..<crossingPoint] + other.genes[crossingPoint..<other.genes.count] let childGenes2 = other.genes[0..<crossingPoint] + genes[crossingPoint..<genes.count] return (child1: SendMoreMoney(genes: Array(childGenes1)), child2: SendMoreMoney(genes: Array(childGenes2))) } func mutate() { // put a random letter in a random place let position1 = Int(arc4random_uniform(UInt32(SendMoreMoney.letters.count))) let position2 = Int(arc4random_uniform(UInt32(genes.count))) if drand48() < 0.5 { // half the time random letter genes[position2] = SendMoreMoney.letters[position1] } else { // half the time random swap if position1 != position2 { genes.swapAt(position1, position2) } } } func prettyPrint() { if let s = genes.index(of: "S"), let e = genes.index(of: "E"), let n = genes.index(of: "N"), let d = genes.index(of: "D"), let m = genes.index(of: "M"), let o = genes.index(of: "O"), let r = genes.index(of: "R"), let y = genes.index(of: "Y") { let send: Int = s * 1000 + e * 100 + n * 10 + d let more: Int = m * 1000 + o * 100 + r * 10 + e let money: Int = m * 10000 + o * 1000 + n * 100 + e * 10 + y print("\(send) + \(more) = \(money) difference:\(money - (send + more))") } else { print("Missing some letters") } } } // experimentally, n=100, mchance=.3, and cchance=.7 seem to work well let smm: GeneticAlgorithm<SendMoreMoney> = GeneticAlgorithm<SendMoreMoney>(size: 100, threshold: 1.0, maxGenerations: 1000, mutationChance: 0.3, crossoverChance: 0.7, selectionType: .tournament(5)) let result2 = smm.run() result2.prettyPrint() //: [Next](@next)
apache-2.0
a6ad6ae084b469d79db8d2e364e17652
40.80427
251
0.61139
4.393044
false
false
false
false
SwiftBond/Bond
Playground-iOS.playground/Pages/UIPickerView+ObservableArray2D.xcplaygroundpage/Contents.swift
2
1328
//: [Previous](@previous) import Foundation import PlaygroundSupport import UIKit import Bond import ReactiveKit let pickerView = UIPickerView() pickerView.frame.size = CGSize(width: 300, height: 300) pickerView.backgroundColor = .white // Note: Open the assistant editor to see the table view PlaygroundPage.current.liveView = pickerView PlaygroundPage.current.needsIndefiniteExecution = true let data = MutableObservableArray2D( Array2D<String, String>( sectionsWithItems: [ ("Feet", ["0 ft", "1 ft", "2 ft", "3 ft", "4 ft", "5 ft", "6 ft", "7 ft", "8 ft", "9 ft"]), ("Inches", ["0 in", "1 in", "2 in", "3 in", "4 in", "5 in", "6 in", "7 in", "8 in", "9 in", "10 in", "11 in", "12 in"]) ] ) ) data.bind(to: pickerView) // Handle cell selection let selectedRow = pickerView.reactive.selectedRow selectedRow.observeNext { (row, component) in print("selected", row, component) } let selectedPair = selectedRow.scan([0, 0]) { (pair, rowAndComponent) -> [Int] in var pair = pair pair[rowAndComponent.1] = rowAndComponent.0 return pair } selectedPair.observeNext { (pair) in print("selected indices", pair) let items = pair.enumerated().map { data[itemAt: [$0.offset, $0.element]] } print("selected items", items) } //: [Next](@next)
mit
8be8ed8c396945947e6d95a5937c4bf0
26.102041
131
0.64759
3.541333
false
false
false
false
sarvex/SwiftRecepies
Concurrency/Handling Network Connections in the Background/Handling Network Connections in the Background/AppDelegate.swift
1
4102
// // AppDelegate.swift // Handling Network Connections in the Background // // Created by Vandad Nahavandipoor on 7/7/14. // Copyright (c) 2014 Pixolity Ltd. All rights reserved. // // These example codes are written for O'Reilly's iOS 8 Swift Programming Cookbook // If you use these solutions in your apps, you can give attribution to // Vandad Nahavandipoor for his work. Feel free to visit my blog // at http://vandadnp.wordpress.com for daily tips and tricks in Swift // and Objective-C and various other programming languages. // // You can purchase "iOS 8 Swift Programming Cookbook" from // the following URL: // http://shop.oreilly.com/product/0636920034254.do // // If you have any questions, you can contact me directly // at [email protected] // Similarly, if you find an error in these sample codes, simply // report them to O'Reilly at the following URL: // http://www.oreilly.com/catalog/errata.csp?isbn=0636920034254 /* 1 */ //import UIKit // //@UIApplicationMain //class AppDelegate: UIResponder, UIApplicationDelegate { // // var window: UIWindow? // // func application(application: UIApplication, // didFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool { // // let urlAsString = "http://www.apple.com" // let url = NSURL(string: urlAsString) // let urlRequest = NSURLRequest(URL: url!) // let queue = NSOperationQueue() // // NSURLConnection.sendAsynchronousRequest(urlRequest, // queue: queue, // completionHandler: {(response: NSURLResponse!, // data: NSData!, // error: NSError!) in // // if data.length > 0 && error == nil{ // /* Date did come back */ // } // else if data.length == 0 && error == nil{ // /* No data came back */ // } // else if error != nil{ // /* Error happened. Make sure you handle this properly */ // } // }) // // return true // } // //} /* 2 */ //import UIKit // //@UIApplicationMain //class AppDelegate: UIResponder, UIApplicationDelegate { // // var window: UIWindow? // // func application(application: UIApplication, // didFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool { // // let urlAsString = "http://www.apple.com" // let url = NSURL(string: urlAsString) // let urlRequest = NSURLRequest(URL: url!) // let queue = NSOperationQueue() // var error: NSError? // // let data = NSURLConnection.sendSynchronousRequest(urlRequest, // returningResponse: nil, // error: &error) // // if data != nil && error == nil{ // /* Date did come back */ // } // else if data!.length == 0 && error == nil{ // /* No data came back */ // } // else if error != nil{ // /* Error happened. Make sure you handle this properly */ // } // // return true // } // //} /* 3 */ import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool { let dispatchQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0) dispatch_async(dispatchQueue, { /* Replace this URL with the URL of a file that is rather big in size */ let urlAsString = "http://www.apple.com" let url = NSURL(string: urlAsString) let urlRequest = NSURLRequest(URL: url!) let queue = NSOperationQueue() var error: NSError? let data = NSURLConnection.sendSynchronousRequest(urlRequest, returningResponse: nil, error: &error) if data != nil && error == nil{ /* Date did come back */ } else if data!.length == 0 && error == nil{ /* No data came back */ } else if error != nil{ /* Error happened. Make sure you handle this properly */ } }) return true } }
isc
567c1553677919b9d1e6779b2c09dcf0
28.517986
85
0.610922
4.198567
false
false
false
false
IvanVorobei/Sparrow
sparrow/ui/controllers/SPConfirmActionViewController.swift
1
16463
// The MIT License (MIT) // Copyright © 2017 Ivan Vorobei ([email protected]) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import UIKit class SPConfirmActionViewController: UIViewController { let navigationBarView = SPConfirmActionNavigationBar.init() let cellsView = SPConfirmActionCellsView.init() let confirmActionView = SPConfirmActionButtonView.init() private var animationDuration: TimeInterval { return 0.5 } override func viewDidLoad() { super.viewDidLoad() self.modalPresentationStyle = .overCurrentContext self.modalTransitionStyle = .crossDissolve self.view.backgroundColor = UIColor.black.withAlphaComponent(0) self.navigationBarView.button.addTarget(self, action: #selector(self.hide), for: .touchUpInside) self.view.addSubview(self.navigationBarView) self.view.addSubview(self.cellsView) self.view.addSubview(self.confirmActionView) self.updateLayout(size: self.view.frame.size) } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) self.updateLayout(size: size) } override func viewSafeAreaInsetsDidChange() { if #available(iOS 11.0, *) { super.viewSafeAreaInsetsDidChange() self.updateLayout(size: self.view.frame.size) } } private func updateLayout(size: CGSize) { self.confirmActionView.setWidth(size.width) self.confirmActionView.sizeToFit() self.confirmActionView.frame.origin.x = 0 self.confirmActionView.frame.origin.y = size.height - self.confirmActionView.frame.height self.cellsView.setWidth(size.width) self.cellsView.sizeToFit() self.cellsView.frame.origin.x = 0 self.cellsView.frame.origin.y = self.confirmActionView.frame.origin.y - self.cellsView.frame.height self.navigationBarView.setWidth(size.width) self.navigationBarView.sizeToFit() self.navigationBarView.frame.origin.x = 0 self.navigationBarView.frame.origin.y = self.cellsView.frame.origin.y - self.navigationBarView.frame.height } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.confirmActionView.frame.origin.y = self.view.frame.size.height self.cellsView.frame.origin.y = self.view.frame.size.height self.navigationBarView.frame.origin.y = self.view.frame.size.height SPAnimationSpring.animate(self.animationDuration, animations: { self.view.backgroundColor = UIColor.black.withAlphaComponent(0.35) self.confirmActionView.frame.origin.y = self.view.frame.height - self.confirmActionView.frame.height self.cellsView.frame.origin.y = self.confirmActionView.frame.origin.y - self.cellsView.frame.height self.navigationBarView.frame.origin.y = self.cellsView.frame.origin.y - self.navigationBarView.frame.height }, spring: 1, velocity: 1, options: .transitionCurlUp) } override func dismiss(animated flag: Bool, completion: (() -> Void)? = nil) { SPAnimationSpring.animate(self.animationDuration, animations: { self.view.backgroundColor = UIColor.black.withAlphaComponent(0) self.confirmActionView.frame.origin.y = self.view.frame.size.height self.cellsView.frame.origin.y = self.view.frame.size.height self.navigationBarView.frame.origin.y = self.view.frame.size.height }, spring: 1, velocity: 1, options: .transitionCurlDown, withComplection: { super.dismiss(animated: false) { completion?() }}) } func addCell(task: String, title: String, subtitle: String? = nil, imageLink: String? = nil, image: UIImage? = nil) { let cell = SPConfirmActionCellView.init( task: task, title: title, subtitle: subtitle, imageLink: imageLink, image: image ) self.cellsView.addSubview(cell) } @objc func hide() { self.dismiss(animated: true) } class SPConfirmActionNavigationBar: UIView { let label: UILabel = UILabel.init() let button: UIButton = UIButton.init() let separatorView = UIView.init() let backgroundView = UIVisualEffectView(effect: UIBlurEffect(style: UIBlurEffectStyle.extraLight)) private var leftAndRightSpace: CGFloat { return 18 } init() { super.init(frame: CGRect.zero) self.addSubview(self.backgroundView) self.separatorView.backgroundColor = UIColor.black.withAlphaComponent(0.15) self.addSubview(self.separatorView) self.label.numberOfLines = 1 self.label.textColor = UIColor.black self.label.text = "SPConfirmAction" self.label.font = UIFont.system(type: .DemiBold, size: 16) self.addSubview(self.label) self.button.setTitle("Сancel", for: .normal) self.button.setTitleColorForNoramlAndHightlightedStates(color: SPNativeStyleKit.Colors.blue) self.button.titleLabel?.font = UIFont.system(type: .DemiBold, size: 16) self.addSubview(self.button) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func sizeToFit() { super.sizeToFit() self.setHeight(45) self.layoutSubviews() } override func layoutSubviews() { super.layoutSubviews() self.backgroundView.setEqualsBoundsFromSuperview() self.label.sizeToFit() self.label.frame.origin.x = self.leftAndRightSpace self.label.center.y = self.frame.height / 2 self.button.sizeToFit() self.button.frame.origin.x = self.frame.width - self.leftAndRightSpace - self.button.frame.width self.button.center.y = self.frame.height / 2 self.separatorView.frame = CGRect.init(x: 0, y: self.frame.height - 1, width: self.frame.width, height: 1) } } class SPConfirmActionCellView: UIView { var taskLabel = UILabel.init() var titleLabel: UILabel = UILabel.init() var subtitleLabel: UILabel? var imageView: SPDownloadingImageView? var separatorView = UIView.init() var yLeftPosition: CGFloat = 0 var baseSpace: CGFloat = 0 init(task: String, title: String, subtitle: String? = nil, imageLink: String? = nil, image: UIImage? = nil) { super.init(frame: CGRect.zero) self.separatorView.backgroundColor = UIColor.lightGray.withAlphaComponent(0.3) self.addSubview(self.separatorView) self.taskLabel.text = task.uppercased() self.taskLabel.font = UIFont.system(type: .Medium, size: 13) self.taskLabel.textColor = SPNativeStyleKit.Colors.gray self.taskLabel.numberOfLines = 1 self.taskLabel.textAlignment = .right self.addSubview(self.taskLabel) self.titleLabel.text = title.uppercased() self.titleLabel.font = UIFont.system(type: .Medium, size: 13) self.titleLabel.textColor = UIColor.black self.titleLabel.numberOfLines = 1 self.titleLabel.textAlignment = .left self.addSubview(self.titleLabel) if subtitle != nil { self.subtitleLabel = UILabel.init() self.subtitleLabel?.text = subtitle?.uppercased() self.subtitleLabel?.font = UIFont.system(type: .Medium, size: 13) self.subtitleLabel?.textColor = SPNativeStyleKit.Colors.gray self.subtitleLabel?.numberOfLines = 0 self.subtitleLabel?.textAlignment = .left self.addSubview(self.subtitleLabel!) } if imageLink != nil { self.imageView = SPDownloadingImageView.init() self.imageView?.setImage(link: imageLink!) self.imageView?.layer.cornerRadius = 12 self.addSubview(self.imageView!) } if image != nil { self.imageView = SPDownloadingImageView.init() self.imageView?.image = image self.imageView?.layer.cornerRadius = 12 self.addSubview(self.imageView!) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func sizeToFit() { super.sizeToFit() self.setHeight(45) if self.imageView != nil { self.setHeight(75) } if self.subtitleLabel != nil { var height = 45 + self.subtitleLabel!.frame.height height.setIfFewer(when: 75) self.setHeight(height) } self.layoutSubviews() } override func layoutSubviews() { super.layoutSubviews() self.taskLabel.sizeToFit() self.taskLabel.center.y = self.frame.height / 2 self.taskLabel.frame.origin.x = self.yLeftPosition - self.taskLabel.frame.width self.titleLabel.sizeToFit() self.titleLabel.center.y = self.frame.height / 2 self.titleLabel.frame.origin.x = self.yLeftPosition + self.baseSpace self.titleLabel.setWidth(self.frame.width - self.titleLabel.frame.origin.x - self.baseSpace) if subtitleLabel != nil { let allContentHeight: CGFloat = self.titleLabel.frame.height + self.subtitleLabel!.frame.height + 3 self.titleLabel.frame.origin.y = (self.frame.height - allContentHeight) / 2 self.subtitleLabel?.frame.origin.x = self.titleLabel.frame.origin.x self.subtitleLabel?.frame.origin.y = self.titleLabel.frame.bottomYPosition + 3 self.subtitleLabel?.sizeToFit() self.subtitleLabel?.setWidth(self.titleLabel.frame.width) } if imageView != nil { self.taskLabel.frame = CGRect.zero var imageSideSize = self.frame.height - 10 * 2 imageSideSize.setIfMore(when: 40) self.imageView?.frame = CGRect.init(x: self.yLeftPosition - imageSideSize, y: 0, width: imageSideSize, height: imageSideSize) self.imageView?.center.y = self.frame.height / 2 } self.separatorView.frame = CGRect.init(x: 18, y: self.frame.height - 1, width: self.frame.width - 18, height: 1) } } class SPConfirmActionCellsView: UIView { let backgroundView = UIVisualEffectView(effect: UIBlurEffect(style: UIBlurEffectStyle.extraLight)) private var baseSpace: CGFloat = 18 init() { super.init(frame: CGRect.zero) self.addSubview(self.backgroundView) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() self.backgroundView.setEqualsBoundsFromSuperview() var maxLabelWidth: CGFloat = 0 for view in self.subviews { if view != self.backgroundView { if let cellView = view as? SPConfirmActionCellView { cellView.sizeToFit() if maxLabelWidth < cellView.taskLabel.frame.width { maxLabelWidth = cellView.taskLabel.frame.width } } } } for view in self.subviews { if view != self.backgroundView { if let cellView = view as? SPConfirmActionCellView { cellView.yLeftPosition = self.baseSpace * 2 + maxLabelWidth cellView.baseSpace = self.baseSpace cellView.layoutSubviews() } } } var yPosition: CGFloat = 0 for view in subviews { if view != self.backgroundView { view.sizeToFit() view.setWidth(self.frame.width) view.frame.origin = CGPoint.init(x: 0, y: yPosition) yPosition += view.frame.height } } self.setHeight(yPosition) } override func sizeToFit() { super.sizeToFit() var height: CGFloat = 0 for view in subviews { if view != self.backgroundView { view.sizeToFit() height += view.frame.height } } self.setHeight(height) self.layoutSubviews() } } class SPConfirmActionButtonView: UIView { let button = UIButton.init() let backgroundView = UIVisualEffectView(effect: UIBlurEffect(style: UIBlurEffectStyle.extraLight)) init() { super.init(frame: CGRect.zero) self.button.setTitle("Execute", for: .normal) self.button.setTitleColorForNoramlAndHightlightedStates(color: SPNativeStyleKit.Colors.blue) self.button.titleLabel?.font = UIFont.system(type: .DemiBold, size: 16) self.addSubview(self.backgroundView) self.addSubview(self.button) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func sizeToFit() { super.sizeToFit() var baseHeight: CGFloat = 80 if #available(iOS 11.0, *) { baseHeight += (self.superview?.safeAreaInsets.bottom ?? 0) } self.setHeight(baseHeight) self.layoutSubviews() } override func layoutSubviews() { super.layoutSubviews() self.backgroundView.setEqualsBoundsFromSuperview() self.button.sizeToFit() var safeAreaInsetsBottom: CGFloat = 0 if #available(iOS 11.0, *) { safeAreaInsetsBottom = (self.superview?.safeAreaInsets.bottom ?? 0) } self.button.frame = CGRect.init( x: 0, y: 0, width: self.frame.width, height: self.frame.height - safeAreaInsetsBottom ) } } }
mit
24ced28ae036bbc048909a14d5f4e67a
39.345588
141
0.586963
5.102604
false
false
false
false
IvanVorobei/Sparrow
sparrow/ui/controllers/SPGradientViewController.swift
2
2258
// The MIT License (MIT) // Copyright © 2017 Ivan Vorobei ([email protected]) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import UIKit public class SPGradientViewControllerDEPRICATED: UIViewController { var gradient: CAGradientLayer? override public func viewDidLoad() { super.viewDidLoad() self.commonInit() } fileprivate func commonInit() { } func setGradient(_ fromColor: UIColor, toColor: UIColor, startPoint: CGPoint = CGPoint(x: 0.0, y: 0.0), endPoint: CGPoint = CGPoint(x: 1.0, y: 1.0)) { self.gradient = CAGradientLayer() self.gradient!.colors = [fromColor.cgColor, toColor.cgColor] self.gradient!.locations = [0.0, 1.0] self.gradient!.startPoint = startPoint self.gradient!.endPoint = endPoint self.gradient!.frame = CGRect(x: 0.0, y: 0.0, width: self.view.frame.size.width, height: self.view.frame.size.height) self.view.layer.insertSublayer(self.gradient!, at: 0) } override public func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() self.gradient?.frame = self.view.bounds } }
mit
27deac8086f0afbd5574a5d8c6e2c39f
40.796296
125
0.688525
4.50499
false
false
false
false
wireapp/wire-ios
Wire-iOS/Sources/UserInterface/Conversation/InputBar/ConversationInputBarViewController+Ephemeral.swift
1
5453
// // Wire // Copyright (C) 2016 Wire Swiss GmbH // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // import Foundation import WireSyncEngine import UIKit extension ConversationInputBarViewController { @discardableResult func createEphemeralKeyboardViewController() -> EphemeralKeyboardViewController { let ephemeralKeyboardViewController = EphemeralKeyboardViewController(conversation: conversation as? ZMConversation) ephemeralKeyboardViewController.delegate = self self.ephemeralKeyboardViewController = ephemeralKeyboardViewController return ephemeralKeyboardViewController } func configureEphemeralKeyboardButton(_ button: IconButton) { button.addTarget(self, action: #selector(ephemeralKeyboardButtonTapped), for: .touchUpInside) } @objc func ephemeralKeyboardButtonTapped(_ sender: IconButton) { toggleEphemeralKeyboardVisibility() } fileprivate func toggleEphemeralKeyboardVisibility() { let isEphemeralControllerPresented = ephemeralKeyboardViewController != nil let isEphemeralKeyboardPresented = mode == .timeoutConfguration if !isEphemeralControllerPresented || !isEphemeralKeyboardPresented { presentEphemeralController() } else { dismissEphemeralController() } } private func presentEphemeralController() { let shouldShowPopover = traitCollection.horizontalSizeClass == .regular if shouldShowPopover { presentEphemeralControllerAsPopover() } else { // we only want to change the mode when we present a custom keyboard mode = .timeoutConfguration inputBar.textView.becomeFirstResponder() } } private func dismissEphemeralController() { let isPopoverPresented = ephemeralKeyboardViewController?.modalPresentationStyle == .popover if isPopoverPresented { ephemeralKeyboardViewController?.dismiss(animated: true, completion: nil) ephemeralKeyboardViewController = nil } else { mode = .textInput } } private func presentEphemeralControllerAsPopover() { createEphemeralKeyboardViewController() ephemeralKeyboardViewController?.modalPresentationStyle = .popover ephemeralKeyboardViewController?.preferredContentSize = CGSize.IPadPopover.pickerSize let pointToView: UIView = ephemeralIndicatorButton.isHidden ? hourglassButton : ephemeralIndicatorButton if let popover = ephemeralKeyboardViewController?.popoverPresentationController, let presentInView = self.parent?.view, let backgroundColor = ephemeralKeyboardViewController?.view.backgroundColor { popover.config(from: self, pointToView: pointToView, sourceView: presentInView) popover.backgroundColor = backgroundColor popover.permittedArrowDirections = .down } guard let controller = ephemeralKeyboardViewController else { return } self.parent?.present(controller, animated: true) } func updateEphemeralIndicatorButtonTitle(_ button: ButtonWithLargerHitArea) { let title = conversation.activeMessageDestructionTimeoutValue?.shortDisplayString button.setTitle(title, for: .normal) } } extension ConversationInputBarViewController: EphemeralKeyboardViewControllerDelegate { func ephemeralKeyboardWantsToBeDismissed(_ keyboard: EphemeralKeyboardViewController) { toggleEphemeralKeyboardVisibility() } func ephemeralKeyboard(_ keyboard: EphemeralKeyboardViewController, didSelectMessageTimeout timeout: TimeInterval) { guard let conversation = conversation as? ZMConversation else { return } inputBar.setInputBarState(.writing(ephemeral: timeout != 0 ? .message : .none), animated: true) updateMarkdownButton() ZMUserSession.shared()?.enqueue { conversation.setMessageDestructionTimeoutValue(.init(rawValue: timeout), for: .selfUser) self.updateRightAccessoryView() } } } extension ConversationInputBarViewController { var ephemeralState: EphemeralState { var state = EphemeralState.none if !sendButtonState.ephemeral { state = .none } else if self.conversation.hasSyncedMessageDestructionTimeout { state = .conversation } else { state = .message } return state } func updateViewsForSelfDeletingMessageChanges() { updateAccessoryViews() updateInputBarButtons() inputBar.changeEphemeralState(to: ephemeralState) if conversation.hasSyncedMessageDestructionTimeout { dismissEphemeralController() } } }
gpl-3.0
314e465332d8fc634589b3901c58c16b
35.112583
124
0.709151
6.018764
false
false
false
false
wireapp/wire-ios
Wire-iOS/Sources/UserInterface/Calling/Thumbnail/PinnableThumbnailViewController.swift
1
9935
// // Wire // Copyright (C) 2018 Wire Swiss GmbH // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // import UIKit final class PinnableThumbnailViewController: UIViewController { private let thumbnailView = RoundedView() private let thumbnailContainerView = PassthroughTouchesView() private(set) var contentView: OrientableView? // MARK: - Dynamics fileprivate let edgeInsets = CGPoint(x: 16, y: 16) fileprivate var originalCenter: CGPoint = .zero fileprivate var hasDoneInitialLayout = false fileprivate var hasEnabledPinningBehavior = false fileprivate lazy var pinningBehavior: ThumbnailCornerPinningBehavior = { return ThumbnailCornerPinningBehavior(item: self.thumbnailView, edgeInsets: self.edgeInsets) }() fileprivate lazy var animator: UIDynamicAnimator = { return UIDynamicAnimator(referenceView: self.thumbnailContainerView) }() // MARK: - Changing the Previewed Content fileprivate(set) var thumbnailContentSize = CGSize(width: 100, height: 100) func removeCurrentThumbnailContentView() { contentView?.removeFromSuperview() contentView = nil thumbnailView.accessibilityIdentifier = nil } func setThumbnailContentView(_ contentView: OrientableView, contentSize: CGSize) { removeCurrentThumbnailContentView() thumbnailView.addSubview(contentView) thumbnailView.accessibilityIdentifier = "ThumbnailView" self.contentView = contentView self.thumbnailContentSize = contentSize updateThumbnailFrame(animated: false, parentSize: thumbnailContainerView.frame.size) } func updateThumbnailContentSize(_ newSize: CGSize, animated: Bool) { self.thumbnailContentSize = newSize updateThumbnailFrame(animated: false, parentSize: thumbnailContainerView.frame.size) } // MARK: - Configuration override func loadView() { view = PassthroughTouchesView() } override func viewDidLoad() { super.viewDidLoad() configureViews() configureConstraints() let panGestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(handlePanGesture)) thumbnailView.addGestureRecognizer(panGestureRecognizer) NotificationCenter.default.addObserver(self, selector: #selector(orientationDidChange), name: UIDevice.orientationDidChangeNotification, object: nil) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) if !hasDoneInitialLayout { view.layoutIfNeeded() view.backgroundColor = .clear updateThumbnailAfterLayoutUpdate() hasDoneInitialLayout = true } } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) if !hasEnabledPinningBehavior { animator.addBehavior(self.pinningBehavior) hasEnabledPinningBehavior = true } } private func configureViews() { view.addSubview(thumbnailContainerView) thumbnailContainerView.addSubview(thumbnailView) thumbnailView.autoresizingMask = [] thumbnailView.clipsToBounds = true thumbnailView.shape = .rounded(radius: 12) thumbnailContainerView.layer.shadowRadius = 30 thumbnailContainerView.layer.shadowOpacity = 0.32 thumbnailContainerView.layer.shadowColor = UIColor.black.cgColor thumbnailContainerView.layer.shadowOffset = CGSize(width: 0, height: 8) thumbnailContainerView.layer.masksToBounds = false } private func configureConstraints() { thumbnailContainerView.translatesAutoresizingMaskIntoConstraints = false thumbnailContainerView.leadingAnchor.constraint(equalTo: view.safeLeadingAnchor).isActive = true thumbnailContainerView.trailingAnchor.constraint(equalTo: view.safeTrailingAnchor).isActive = true thumbnailContainerView.topAnchor.constraint(equalTo: safeTopAnchor).isActive = true thumbnailContainerView.bottomAnchor.constraint(equalTo: safeBottomAnchor).isActive = true } // MARK: - Orientation @objc func orientationDidChange() { contentView?.layoutForOrientation() } // MARK: - Size override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) pinningBehavior.isEnabled = false // Calculate the new size of the container let insets = view.safeAreaInsetsOrFallback let safeSize = CGSize(width: size.width - insets.left - insets.right, height: size.height - insets.top - insets.bottom) let bounds = CGRect(origin: CGPoint.zero, size: safeSize) pinningBehavior.updateFields(in: bounds) coordinator.animate(alongsideTransition: { _ in self.updateThumbnailFrame(animated: false, parentSize: safeSize) }, completion: { _ in self.pinningBehavior.isEnabled = true }) } @available(iOS 11, *) override func viewSafeAreaInsetsDidChange() { super.viewSafeAreaInsetsDidChange() view.layoutIfNeeded() updateThumbnailAfterLayoutUpdate() } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() updateThumbnailAfterLayoutUpdate() } private func updateThumbnailFrame(animated: Bool, parentSize: CGSize) { guard thumbnailContentSize != .zero else { return } let size = thumbnailContentSize.withOrientation(UIDevice.current.orientation) let position = thumbnailPosition(for: size, parentSize: parentSize) let changesBlock = { [contentView, thumbnailView, view] in thumbnailView.frame = CGRect( x: position.x - size.width / 2, y: position.y - size.height / 2, width: size.width, height: size.height ) view?.layoutIfNeeded() contentView?.layoutForOrientation() } if animated { UIView.animate(withDuration: 0.2, animations: changesBlock) } else { changesBlock() } } private func updateThumbnailAfterLayoutUpdate() { updateThumbnailFrame(animated: false, parentSize: thumbnailContainerView.frame.size) pinningBehavior.updateFields(in: thumbnailContainerView.bounds) } private func thumbnailPosition(for size: CGSize, parentSize: CGSize) -> CGPoint { if let center = pinningBehavior.positionForCurrentCorner() { return center } let frame: CGRect if UIApplication.isLeftToRightLayout { frame = CGRect(x: parentSize.width - size.width - edgeInsets.x, y: edgeInsets.y, width: size.width, height: size.height) } else { frame = CGRect(x: edgeInsets.x, y: edgeInsets.y, width: size.width, height: size.height) } return CGPoint(x: frame.midX, y: frame.midY) } // MARK: - Panning @objc private func handlePanGesture(_ recognizer: UIPanGestureRecognizer) { switch recognizer.state { case .began: // Disable the pinning while the user moves the thumbnail pinningBehavior.isEnabled = false originalCenter = thumbnailView.center case .changed: // Calculate the target center let originalFrame = thumbnailView.frame let containerBounds = thumbnailContainerView.bounds let translation = recognizer.translation(in: thumbnailContainerView) let transform = CGAffineTransform(translationX: translation.x, y: translation.y) let transformedPoint = originalCenter.applying(transform) // Calculate the appropriate horizontal origin let x: CGFloat let halfWidth = originalFrame.width / 2 if (transformedPoint.x - halfWidth) < containerBounds.minX { x = containerBounds.minX } else if (transformedPoint.x + halfWidth) > containerBounds.maxX { x = containerBounds.maxX - originalFrame.width } else { x = transformedPoint.x - halfWidth } // Calculate the appropriate vertical origin let y: CGFloat let halfHeight = originalFrame.height / 2 if (transformedPoint.y - halfHeight) < containerBounds.minY { y = containerBounds.minY } else if (transformedPoint.y + halfHeight) > containerBounds.maxY { y = containerBounds.maxY - originalFrame.height } else { y = transformedPoint.y - halfHeight } // Do not move the thumbnail outside the container thumbnailView.frame = CGRect(x: x, y: y, width: originalFrame.width, height: originalFrame.height) case .cancelled, .ended: // Snap the thumbnail to the closest edge let velocity = recognizer.velocity(in: self.thumbnailContainerView) pinningBehavior.isEnabled = true pinningBehavior.addLinearVelocity(velocity) default: break } } }
gpl-3.0
73fd4dde9f51b1ec698f56da74bf097f
34.609319
157
0.669552
5.525584
false
false
false
false
jakarmy/swift-summary
The Swift Summary Book.playground/Pages/06 Functions.xcplaygroundpage/Contents.swift
1
2610
// |=------------------------------------------------------=| // Copyright (c) 2016 Juan Antonio Karmy. // Licensed under MIT License // // See https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/ for Swift Language Reference // // See Juan Antonio Karmy - http://karmy.co | http://twitter.com/jkarmy // // |=------------------------------------------------------=| func sayHello(personName: String) -> String{ return "Hello \(personName)!" } //In this case we return a tuple func minMax(array: [Int]) -> (min: Int, max:Int)? { if array.isEmpty {return nil} return (0,1) } //Note: returning void translates in returning an empty tuple: () //Here we are using external and local params names. //Also, note how the last param is predefined. This means we can omit it when calling the function. //Also note that an external name will be provided automatically to every predefined param. func join(string s1: String, toString s2: String, withJoiner joiner: String = " ") -> String { return s1 + joiner + s2 } //A variadic param can take more than one value of a specified type. func arithmeticMean(numbers: Double...) -> Double { var total: Double = 0 for number in numbers { total += number } return total / Double(numbers.count) } //In this example, the inout prefix defines that the passed parameters' values can be modified, //and this will be reflected on the original variables defined outside of the function. func swapTwoInts( a: inout Int, b: inout Int) { let temporaryA = a a = b b = temporaryA } //You can use a function type to pass functions as params to other functions. func printMathResult(mathFunction: (Int, Int) -> Int, a: Int, b: Int) { print("Result: \(mathFunction(a, b))") } //You can use function type to return functions. //Here, we are also defining nested functions. These functions can only be accessed through the parent function. //but can be passed as return values. func chooseStepFunction(backwards: Bool) -> (Int) -> Int { func stepForward(input: Int) -> Int { return input + 1 } func stepBackward(input: Int) -> Int { return input - 1 } return backwards ? stepBackward : stepForward } //Start sayHello(personName: "Juan") minMax(array: []) join(string: "Hello", toString: "World", withJoiner: "New") join(string: "", toString: "") arithmeticMean(numbers: 4,5,6,7) var someInt = 3 var anotherInt = 107 swapTwoInts(a: &someInt, b: &anotherInt) //Here we are defining a var of type function. var mathFunction: (String) -> String = sayHello
mit
59c9ddef1901ea6e8ea8fb85e640ad8e
32.037975
135
0.668966
3.907186
false
false
false
false
toggl/superday
teferi/Models/Entities/TimeSlotEntity.swift
1
1020
import Foundation // This is a business logic here, so all this code has // to make sense business wise and independent of the app code struct TimeSlotEntity { let startTime: Date let endTime: Date? let category: Category let activities: [MotionEventEntity] let edited: Bool } // Computed properties extension TimeSlotEntity { var duration: TimeInterval? { guard let endTime = endTime else { return nil } return endTime.timeIntervalSince(startTime) } var isRunning: Bool { return endTime == nil } } // Methods extension TimeSlotEntity { func with(category: Category? = nil, startTime: Date? = nil, endTime: Date? = nil, editByUser: Bool = false) -> TimeSlotEntity { return TimeSlotEntity( startTime: startTime ?? self.startTime, endTime: endTime ?? self.endTime, category: category ?? self.category, activities: self.activities, edited: editByUser ) } }
bsd-3-clause
386ca9c36e91a12d4b618209cf15da25
22.181818
130
0.638235
4.678899
false
false
false
false
SuperAwesomeLTD/sa-mobile-sdk-ios-demo
AwesomeAdsDemo/AdFormat.swift
1
7914
// // AdFormat.swift // AwesomeAdsDemo // // Created by Gabriel Coman on 25/11/2016. // Copyright © 2016 Gabriel Coman. All rights reserved. // import UIKit import SuperAwesome //Mobile Small Leaderboard 300x50 //Mobile Leaderboard 320x50 //Small Leaderboard 468x60 //Leaderboard 728x90 //Push down 970x90 //Billboard 970x250 //Skinny Skyscraper 120x600 //Skyscraper 160x600 //MPU 300x250 //Double MPU 300x600 //Mobile interstitial portrait 320x480 / 400x600 //Tablet interstitial portrait 768x1024 //Tablet lansdscape interstitial 1024x768 //Mobile interstitial landscape 480x320 / 600x400 //Video //AppWall enum AdFormat { case unknown case smallbanner case banner case smallleaderboard case leaderboard case pushdown case billboard case skinnysky case sky case mpu case doublempu case mobile_portrait_interstitial case mobile_landscape_interstitial case tablet_portrait_interstitial case tablet_landscape_interstitial case video case gamewall func toString() -> String { switch self { case .unknown: return "Unknown" case .smallbanner: return "Mobile Small Leaderboard" case .banner: return "Mobile Leaderboard" case .smallleaderboard: return "Small Leaderboard" case .leaderboard: return "Tablet Leaderboard" case .pushdown: return "Push Down" case .billboard: return "Billboard" case .skinnysky: return "Skinny Skyscraper" case .sky: return "Skyscraper" case .mpu: return "Tablet MPU" case .doublempu: return "Double MPU" case .mobile_portrait_interstitial: return "Mobile Interstitial Portrait" case .mobile_landscape_interstitial: return "Mobile Interstitial Landscape" case .tablet_portrait_interstitial: return "Tablet Interstitial Portrait" case .tablet_landscape_interstitial: return "Tablet Interstitial Landscape" case .video: return "Mobile Video" case .gamewall: return "App Wall" } } static func fromCreative (_ creative: DemoCreative?) -> AdFormat { if let creative = creative, let format = creative.format { switch format { case .video: return .video case .imageWithLink, .tag, .richMedia, .unknown: let width = creative.width let height = creative.height switch (width, height) { case (300, 50): return .smallbanner case (320, 50): return .banner case (468, 60): return .smallleaderboard case (728, 90): return .leaderboard case (970, 90): return .pushdown case (970, 250): return .billboard case (120, 600): return .skinnysky case (160, 600): return .sky case (300, 250): return .mpu case (300, 600): return .doublempu case (320, 480): return .mobile_portrait_interstitial case (400, 600): return .mobile_portrait_interstitial case (768, 1024): return .tablet_portrait_interstitial case (480, 320): return .mobile_landscape_interstitial case (600, 400): return .mobile_landscape_interstitial case (1024, 768): return .tablet_landscape_interstitial default: return .unknown } } } else { return .unknown } } static func fromResponse (_ response: SAResponse?) -> AdFormat { if let response = response { if response.format == .appwall { return .gamewall } else if response.format == .video { return .video } else if response.format == .invalid { return .unknown } else { if response.ads.count > 0, let ad = response.ads.firstObject as? SAAd { let width = ad.creative.details.width let height = ad.creative.details.height switch (width, height) { case (300, 50): return .smallbanner case (320, 50): return .banner case (468, 60): return .smallleaderboard case (728, 90): return .leaderboard case (970, 90): return .pushdown case (970, 250): return .billboard case (120, 600): return .skinnysky case (160, 600): return .sky case (300, 250): return .mpu case (300, 600): return .doublempu case (320, 480): return .mobile_portrait_interstitial case (400, 600): return .mobile_portrait_interstitial case (768, 1024): return .tablet_portrait_interstitial case (480, 320): return .mobile_landscape_interstitial case (600, 400): return .mobile_landscape_interstitial case (1024, 768): return .tablet_landscape_interstitial default: return .unknown } } else { return .unknown } } } else { return .unknown } } static func fromPlacement(placement: Placement) -> AdFormat { if let format = placement.format, format == "video" { return .video } else if let _ = placement.format, let width = placement.width, let height = placement.height { switch (width, height) { case (300, 50): return .smallbanner case (320, 50): return .banner case (468, 60): return .smallleaderboard case (728, 90): return .leaderboard case (970, 90): return .pushdown case (970, 250): return .billboard case (120, 600): return .skinnysky case (160, 600): return .sky case (300, 250): return .mpu case (300, 600): return .doublempu case (320, 480): return .mobile_portrait_interstitial case (400, 600): return .mobile_portrait_interstitial case (768, 1024): return .tablet_portrait_interstitial case (480, 320): return .mobile_landscape_interstitial case (600, 400): return .mobile_landscape_interstitial case (1024, 768): return .tablet_landscape_interstitial default: return .unknown } } else { return .unknown } } func isBannerType () -> Bool { return self == .smallbanner || self == .banner || self == .leaderboard || self == .smallleaderboard || self == .pushdown || self == .billboard || self == .skinnysky || self == .sky || self == .mpu || self == .doublempu } func isInterstitialType () -> Bool { return self == .mobile_portrait_interstitial || self == .mobile_landscape_interstitial || self == .tablet_portrait_interstitial || self == .tablet_landscape_interstitial } func isVideoType () -> Bool { return self == .video } func isAppWallType () -> Bool { return self == .gamewall } func isUnknownType () -> Bool { return self == .unknown } }
apache-2.0
4d90a11dc207ee5cb10eb0630f87a415
32.529661
87
0.530899
5.111757
false
false
false
false
exis-io/swiftRiffleCocoapod
Pod/Classes/CuminicableExtensions.swift
1
16275
// Extensions.swift // SwiftRiffle // // Created by damouse on 12/29/15. // Copyright © 2015 Exis. All rights reserved. // import Foundation #if os(Linux) import SwiftGlibc import Glibc #else import Darwin.C #endif // All properties implement Convertible, but Models react differently // This allows each property to handle its construction differently public protocol Convertible { func serialize() -> Any static func deserialize(from: Any) -> Any func unsafeSerialize() -> Any static func unsafeDeserialize<T>(from: Any, t: T.Type) -> T? // Returns a core representation of this type static func representation() -> Any } public protocol BaseConvertible: Convertible {} extension BaseConvertible { public static func deserialize(from: Any) -> Any { return from } public static func unsafeDeserialize<T>(from: Any, t: T.Type) -> T? { return unsafeBitCast(from, t.self) } public static func representation() -> Any { return "\(Self.self)" } public func serialize() -> Any { return self } public func unsafeSerialize() -> Any { return self } } /// All model properties must conform to this protocol public protocol Property: Convertible {} extension Property { static func size() -> Int { return Int(ceil(Double(sizeof(self))/Double(sizeof(Int)))) } static func type() -> Self.Type.Type { return self.dynamicType } mutating func codeInto(pointer: UnsafePointer<Int>) { (UnsafeMutablePointer(pointer) as UnsafeMutablePointer<Self>).memory = self } mutating func codeOptionalInto(pointer: UnsafePointer<Int>) { (UnsafeMutablePointer(pointer) as UnsafeMutablePointer<Optional<Self>>).memory = self } } protocol OptionalProperty : Property { static func codeNilInto(pointer: UnsafePointer<Int>) static func propertyType() -> Property.Type? func property() -> Property? } extension Optional : OptionalProperty { static func codeNilInto(pointer: UnsafePointer<Int>) { (UnsafeMutablePointer(pointer) as UnsafeMutablePointer<Optional>).memory = nil } static func propertyType() -> Property.Type? { return Wrapped.self as? Property.Type } func property() -> Property? { switch self { case .Some(let property): if let property = property as? Property { return property } else { return nil } default: return nil } } } extension Int: Property, Convertible { public func serialize() -> Any { return self } public func unsafeSerialize() -> Any { return unsafeBitCast(self, Int.self) } public static func deserialize(from: Any) -> Any { if let x = from as? Int { return x } else if let x = from as? String { return Int(x) } else if let x = from as? Double { return Int(x) } print("WARN: Convertible was not able to complete for type \(self) with value \(from)") return from } public static func unsafeDeserialize<T>(from: Any, t: T.Type) -> T? { return recode(deserialize(switchTypes(from)), t.self) } public static func representation() -> Any { return "int" } } extension String: Property, Convertible { public func serialize() -> Any { return self } public func unsafeSerialize() -> Any { return unsafeBitCast(self, String.self) } public static func deserialize(from: Any) -> Any { if let x = from as? String { return x } else if let x = from as? Int { return String(x) } print("WARN: Convertible was not able to complete for type \(self) with value \(from)") return from } public static func unsafeDeserialize<T>(from: Any, t: T.Type) -> T? { if let s = from as? String { return caster!.recode(from as! String, t: t) } return recode(deserialize(switchTypes(from)), t.self) } public static func representation() -> Any { return "str" } } extension Double: Property, Convertible { public func serialize() -> Any { return self } public func unsafeSerialize() -> Any { return unsafeBitCast(self, Double.self) } public static func deserialize(from: Any) -> Any { if let x = from as? Double { return x } else if let x = from as? Int { return Double(x) } print("WARN: Convertible was not able to complete for type \(self) with value \(from)") return from } public static func unsafeDeserialize<T>(from: Any, t: T.Type) -> T? { return recode(deserialize(switchTypes(from)), t.self) } public static func representation() -> Any { return "double" } } extension Float: Property, Convertible { public func serialize() -> Any { return Double(self) } public func unsafeSerialize() -> Any { return unsafeBitCast(self, Float.self) } public static func deserialize(from: Any) -> Any { if let x = from as? Float { return x } else if let x = from as? Double { return Float(x) } else if let x = from as? Int { return Float(x) } print("WARN: Convertible was not able to complete for type \(self) with value \(from)") return from } public static func unsafeDeserialize<T>(from: Any, t: T.Type) -> T? { return recode(deserialize(switchTypes(from)), t.self) } public static func representation() -> Any { return "float" } } extension Bool: Property, Convertible { public func serialize() -> Any { return self } public func unsafeSerialize() -> Any { return unsafeBitCast(self, Bool.self) } public static func deserialize(from: Any) -> Any { if let x = from as? Bool { return x } else if let x = from as? Int { return x == 1 ? true : false } print("WARN: Convertible was not able to complete for type \(self) with value \(from)") return from } public static func unsafeDeserialize<T>(from: Any, t: T.Type) -> T? { // Occasional segfault within recode if let b = from as? Bool { return caster!.recode(b, t: t) } return recode(deserialize(from), t.self) } public static func representation() -> Any { return "bool" } } // TODO: Dictionaries extension Array : Property, BaseConvertible { public static func deserialize(from: Any) -> Any { if let arr = from as? [Any] { var ret: [Element] = [] // Reconstruct values within the array for element in arr { if let child = Generator.Element.self as? Convertible.Type { ret.append(child.deserialize(element) as! Element) } } return ret } Riffle.warn("Array deserialize not given an array!") return from } public func serialize() -> Any { // TODO: Apply recursive serialization here var ret: [Any] = [] for child in self { if let convert = child as? Convertible { ret.append(convert.serialize()) } else if let convert = asConvertible(child) { ret.append(convert.serialize()) } else { Riffle.warn("UNALBE TO SERIALIZE \(child) \(child.dynamicType)") } } return ret } public func unsafeSerialize() -> Any { // TODO: Apply recursive serialization here var ret: [Any] = [] for child in self { var switched = switchTypes(child) if let convert = switched as? Convertible { ret.append(convert.serialize()) } } return ret } public static func unsafeDeserialize<T>(from: Any, t: T.Type) -> T? { if let arr = from as? [Any] { var ret: [Element] = [] // Reconstruct values within the array for element in arr { if let child = Generator.Element.self as? Convertible.Type { ret.append(child.unsafeDeserialize(element, t: Generator.Element.self)!) } else { let switchedType = switchTypeObject(Generator.Element.self) if let child = switchedType as? Convertible.Type { ret.append(child.unsafeDeserialize(element, t: Generator.Element.self)!) } } } return unsafeBitCast(ret, t.self) } Riffle.warn("Array unsafeDeserialize not given an array!") let failsafe: [Generator.Element] = [] return unsafeBitCast(failsafe, T.self) // return from as! T } public static func representation() -> Any { if let child = Generator.Element.self as? Convertible.Type { return [child.representation()] } // OSX hack for primitive arrays, arrays of models not possible var ret = "\(Generator.Element.self)" #if os(OSX) switch ret { case "Int": ret = "int" case "String": ret = "str" case "Double": ret = "double" case "Float": ret = "float" case "Bool": ret = "bool" default: break } #else Riffle.warn("Unable to derive representation of array! Type: \(self), returning \(ret)") #endif return [ret] } } // Structures extension AnyBidirectionalCollection : Property, BaseConvertible {} extension AnyBidirectionalIndex : Property, BaseConvertible {} extension AnyForwardCollection : Property, BaseConvertible {} extension AnyForwardIndex : Property, BaseConvertible {} extension AnyRandomAccessCollection : Property, BaseConvertible {} extension AnyRandomAccessIndex : Property, BaseConvertible {} extension AnySequence : Property, BaseConvertible {} extension ArraySlice : Property, BaseConvertible {} extension COpaquePointer : Property, BaseConvertible {} extension CVaListPointer : Property, BaseConvertible {} extension Character : Property, BaseConvertible {} extension ClosedInterval : Property, BaseConvertible {} extension CollectionOfOne : Property, BaseConvertible {} extension ContiguousArray : Property, BaseConvertible {} extension Dictionary : Property, BaseConvertible {} extension DictionaryGenerator : Property, BaseConvertible {} extension DictionaryIndex : Property, BaseConvertible {} extension DictionaryLiteral : Property, BaseConvertible {} extension EmptyCollection : Property, BaseConvertible {} extension EmptyGenerator : Property, BaseConvertible {} extension EnumerateGenerator : Property, BaseConvertible {} extension EnumerateSequence : Property, BaseConvertible {} extension FlattenBidirectionalCollection : Property, BaseConvertible {} extension FlattenBidirectionalCollectionIndex : Property, BaseConvertible {} extension FlattenCollection : Property, BaseConvertible {} extension FlattenCollectionIndex : Property, BaseConvertible {} extension FlattenGenerator : Property, BaseConvertible {} extension FlattenSequence : Property, BaseConvertible {} extension GeneratorOfOne : Property, BaseConvertible {} extension GeneratorSequence : Property, BaseConvertible {} extension HalfOpenInterval : Property, BaseConvertible {} extension IndexingGenerator : Property, BaseConvertible {} extension Int16 : Property, BaseConvertible {} extension Int32 : Property, BaseConvertible {} extension Int64 : Property, BaseConvertible {} extension Int8 : Property, BaseConvertible {} extension JoinGenerator : Property, BaseConvertible {} extension JoinSequence : Property, BaseConvertible {} extension LazyCollection : Property, BaseConvertible {} extension LazyFilterCollection : Property, BaseConvertible {} extension LazyFilterGenerator : Property, BaseConvertible {} extension LazyFilterIndex : Property, BaseConvertible {} extension LazyFilterSequence : Property, BaseConvertible {} extension LazyMapCollection : Property, BaseConvertible {} extension LazyMapGenerator : Property, BaseConvertible {} extension LazyMapSequence : Property, BaseConvertible {} extension LazySequence : Property, BaseConvertible {} extension ManagedBufferPointer : Property, BaseConvertible {} extension Mirror : Property, BaseConvertible {} extension MutableSlice : Property, BaseConvertible {} extension ObjectIdentifier : Property, BaseConvertible {} extension PermutationGenerator : Property, BaseConvertible {} extension Range : Property, BaseConvertible {} extension RangeGenerator : Property, BaseConvertible {} extension RawByte : Property, BaseConvertible {} extension Repeat : Property, BaseConvertible {} extension ReverseCollection : Property, BaseConvertible {} extension ReverseIndex : Property, BaseConvertible {} extension ReverseRandomAccessCollection : Property, BaseConvertible {} extension ReverseRandomAccessIndex : Property, BaseConvertible {} extension Set : Property, BaseConvertible {} extension SetGenerator : Property, BaseConvertible {} extension SetIndex : Property, BaseConvertible {} extension Slice : Property, BaseConvertible {} extension StaticString : Property, BaseConvertible {} extension StrideThrough : Property, BaseConvertible {} extension StrideThroughGenerator : Property, BaseConvertible {} extension StrideTo : Property, BaseConvertible {} extension StrideToGenerator : Property, BaseConvertible {} extension String.CharacterView : Property, BaseConvertible {} extension String.CharacterView.Index : Property, BaseConvertible {} extension String.UTF16View : Property, BaseConvertible {} extension String.UTF16View.Index : Property, BaseConvertible {} extension String.UTF8View : Property, BaseConvertible {} extension String.UTF8View.Index : Property, BaseConvertible {} extension String.UnicodeScalarView : Property, BaseConvertible {} extension String.UnicodeScalarView.Generator : Property, BaseConvertible {} extension String.UnicodeScalarView.Index : Property, BaseConvertible {} extension UInt : Property, BaseConvertible {} extension UInt16 : Property, BaseConvertible {} extension UInt32 : Property, BaseConvertible {} extension UInt64 : Property, BaseConvertible {} extension UInt8 : Property, BaseConvertible {} extension UTF16 : Property, BaseConvertible {} extension UTF32 : Property, BaseConvertible {} extension UTF8 : Property, BaseConvertible {} extension UnicodeScalar : Property, BaseConvertible {} extension Unmanaged : Property, BaseConvertible {} extension UnsafeBufferPointer : Property, BaseConvertible {} extension UnsafeBufferPointerGenerator : Property, BaseConvertible {} extension UnsafeMutableBufferPointer : Property, BaseConvertible {} extension UnsafeMutablePointer : Property, BaseConvertible {} extension UnsafePointer : Property, BaseConvertible {} extension Zip2Generator : Property, BaseConvertible {} extension Zip2Sequence : Property, BaseConvertible {} /// Enumerations extension Bit : Property, BaseConvertible {} extension FloatingPointClassification : Property, BaseConvertible {} extension ImplicitlyUnwrappedOptional : Property, BaseConvertible {} extension Mirror.AncestorRepresentation : Property, BaseConvertible {} extension Mirror.DisplayStyle : Property, BaseConvertible {} extension Optional : Property, BaseConvertible {} extension PlaygroundQuickLook : Property, BaseConvertible {} extension Process : Property, BaseConvertible {} extension UnicodeDecodingResult : Property, BaseConvertible {} /// Classes extension AnyGenerator : Property, BaseConvertible {} extension NonObjectiveCBase : Property, BaseConvertible {} extension NSObject : Property, BaseConvertible {} extension VaListBuilder : Property, BaseConvertible {}
mit
5a07a2d4713979362a4c995019749342
34.225108
100
0.659703
5.187759
false
false
false
false
jjochen/JJFloatingActionButton
Example/Tests/JJActionItemSpec.swift
1
5489
// // JJActionItemSpec.swift // // Copyright (c) 2017-Present Jochen Pfeiffer // // 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. // @testable import JJFloatingActionButton import Nimble import Nimble_Snapshots import Quick class JJActionItemSpec: QuickSpec { override func spec() { describe("JJActionItem") { var actionItem: JJActionItem! beforeEach { actionItem = JJActionItem(frame: CGRect(x: 0, y: 0, width: 150, height: 100)) actionItem.titleLabel.font = UIFont(name: "Courier", size: 12) actionItem.titleLabel.text = "item" actionItem.imageView.image = #imageLiteral(resourceName: "Owl") actionItem.buttonColor = .red actionItem.buttonImageColor = .white actionItem.circleView.widthAnchor.constraint(equalToConstant: 40).isActive = true actionItem.circleView.heightAnchor.constraint(equalToConstant: 40).isActive = true setNimbleTolerance(0.002) } it("looks correct") { expect(actionItem) == snapshot() } it("looks correct with title position leading") { actionItem.titlePosition = .leading expect(actionItem) == snapshot() } it("looks correct with title position trailing") { actionItem.titlePosition = .trailing expect(actionItem) == snapshot() } it("looks correct with title position left") { actionItem.titlePosition = .left expect(actionItem) == snapshot() } it("looks correct with title position right") { actionItem.titlePosition = .right expect(actionItem) == snapshot() } it("looks correct with title position top") { actionItem.titlePosition = .top expect(actionItem) == snapshot() } it("looks correct with title position bottom") { actionItem.titlePosition = .bottom expect(actionItem) == snapshot() } it("looks correct with title position hidden") { actionItem.titlePosition = .hidden expect(actionItem) == snapshot() } it("looks correct with horizontal title spacing configured") { actionItem.titlePosition = .leading actionItem.titleSpacing = 42 expect(actionItem) == snapshot() } it("looks correct with vertical title spacing configured") { actionItem.titlePosition = .bottom actionItem.titleSpacing = 42 expect(actionItem) == snapshot() } it("looks correct with empty title") { actionItem.titleLabel.text = "" expect(actionItem) == snapshot() } it("looks correct with smaller image size") { setNimbleTolerance(0.005) actionItem.imageSize = CGSize(width: 10, height: 10) expect(actionItem) == snapshot() } it("looks correct with bigger image size") { setNimbleTolerance(0.025) actionItem.imageSize = CGSize(width: 30, height: 30) expect(actionItem) == snapshot() } } describe("JJActionItem loaded from xib") { var actionItem: JJActionItem? beforeEach { let bundle = Bundle(for: type(of: self)) actionItem = bundle.loadNibNamed("JJActionItem", owner: nil)?.first as? JJActionItem actionItem?.titleLabel.font = UIFont(name: "Courier", size: 12) actionItem?.titleLabel.text = "item" actionItem?.imageView.image = #imageLiteral(resourceName: "Owl") actionItem?.buttonColor = .red actionItem?.buttonImageColor = .white actionItem?.circleView.widthAnchor.constraint(equalToConstant: 40).isActive = true actionItem?.circleView.heightAnchor.constraint(equalToConstant: 40).isActive = true setNimbleTolerance(0.002) } it("looks correct") { expect(actionItem) == snapshot() } } } }
mit
fb38d03a333a9ff4d56f29d7e0cb8538
37.65493
100
0.589543
5.370841
false
false
false
false
tbajis/Bop
Pin.swift
1
1283
// // Pin+CoreDataClass.swift // Bop // // Created by Thomas Manos Bajis on 4/24/17. // Copyright © 2017 Thomas Manos Bajis. All rights reserved. // import Foundation import CoreData import MapKit // MARK: - Pin: NSManagedObject, MKAnnotation class Pin: NSManagedObject, MKAnnotation { // Allow Pin class to conform to MKAnnotation var coordinate: CLLocationCoordinate2D { return CLLocationCoordinate2D(latitude: latitude, longitude: longitude) } var title: String? { return name } var subtitle: String? { let count = Int(checkinsCount) return "Check In Count is: \(count)" } // MARK: Initializer convenience init(name: String?, id: String?, latitude: Double, longitude: Double, address: String?, checkinsCount: Double, context: NSManagedObjectContext) { if let ent = NSEntityDescription.entity(forEntityName: "Pin", in: context) { self.init(entity: ent, insertInto: context) self.name = name self.id = id self.latitude = latitude self.longitude = longitude self.address = address self.checkinsCount = checkinsCount } else { fatalError("Unable to find Entity Pin") } } }
apache-2.0
0f0a153168605804d4de7464dbb6f6a2
27.488889
161
0.632605
4.466899
false
false
false
false
gribozavr/swift
test/Driver/Dependencies/chained-private-after-fine.swift
1
1553
/// other --> main ==> yet-another /// other ==>+ main ==> yet-another /// Coarse and fine // RUN: %empty-directory(%t) // RUN: cp -r %S/Inputs/chained-private-after-fine/* %t // RUN: touch -t 201401240005 %t/*.swift // Generate the build record... // RUN: cd %t && %swiftc_driver -enable-fine-grained-dependencies -c -driver-use-frontend-path "%{python};%S/Inputs/update-dependencies.py" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents ./main.swift ./other.swift ./yet-another.swift -module-name main -j1 -v // ...then reset the .swiftdeps files. // RUN: cp -r %S/Inputs/chained-private-after-fine/*.swiftdeps %t // RUN: cd %t && %swiftc_driver -enable-fine-grained-dependencies -c -driver-use-frontend-path "%{python};%S/Inputs/update-dependencies.py" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents ./main.swift ./other.swift ./yet-another.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-FIRST %s // CHECK-FIRST-NOT: warning // CHECK-FIRST-NOT: Handled // RUN: touch -t 201401240006 %t/other.swift // RUN: cd %t && %swiftc_driver -enable-fine-grained-dependencies -c -driver-use-frontend-path "%{python};%S/Inputs/update-dependencies.py" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents ./yet-another.swift ./main.swift ./other.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-SECOND %s // CHECK-SECOND-DAG: Handled other.swift // CHECK-SECOND-DAG: Handled main.swift // CHECK-SECOND: Handled yet-another.swift
apache-2.0
7c233174424f205ac680cfc42dc0746d
63.708333
338
0.71539
3.215321
false
false
true
false
strivingboy/CocoaChinaPlus
Code/CocoaChinaPlus/Application/Business/Util/Helper/CCSqlite/Service/CCArticleCache.swift
1
1164
// // CCArticleCache.swift // CocoaChinaPlus // // Created by zixun on 15/10/4. // Copyright © 2015年 zixun. All rights reserved. // import Foundation let kArticleCache = CCArticleCache.sharedCache //对保存在数据库中的文章做一个简单的cache,提升访问性能 class CCArticleCache: NSObject { static let sharedCache: CCArticleCache = { return CCArticleCache() }() private var model_collection = CCArticleService.queryArticles(.Collection) private var model_uncollection = CCArticleService.queryArticles(.UnCollection) func updateCache() { self.model_collection = CCArticleService.queryArticles(.Collection) self.model_uncollection = CCArticleService.queryArticles(.UnCollection) } func articlesOfType(type:CCArticleType) ->[CCArticleModel] { switch type { case .Collection: return model_collection case .UnCollection: return model_uncollection default: return model_collection + model_uncollection } } }
mit
67a28c108d3d932611c6083f265738fb
24.318182
83
0.629829
4.716102
false
false
false
false
michael-groble/motioncapture
MotionCapture/DataManager.swift
1
5316
// Copyright (c) 2014 Michael Groble // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import Foundation import CoreData class DataManager : NSObject { let bundleName: String? let modelName: String let databaseName: String init(bundleName: String?, modelName: String, databaseName: String) { self.bundleName = bundleName self.modelName = modelName self.databaseName = databaseName } var objectContext: NSManagedObjectContext { get { return clearableObjectContext.getOrCreateOnMainThread() } } var objectModel: NSManagedObjectModel { get { return clearableObjectModel.getOrCreate() } } func truncateDatabase() { let store = persistentStoreCoordinator.persistentStoreForURL(databaseUrl) objectContext.performBlockAndWait() { self.objectContext.rollback() var error: NSError? = nil; if !self.persistentStoreCoordinator.removePersistentStore(store, error:&error) { NSLog("Error trying to truncate database %@", error!) } else if !NSFileManager.defaultManager().removeItemAtPath(self.databaseUrl.path, error:&error) { NSLog("Error trying to delete file %@", error!); } } clearableObjectModel.clear() clearableObjectContext.clear() clearablePersistentStoreCoordinator.clear() } var databaseBytes: CLongLong { get { var size: AnyObject? var error: NSError? self.databaseUrl.getResourceValue(&size, forKey:NSURLFileSizeKey, error:&error) return size == nil ? 0 : (size as NSNumber).longLongValue; } } private lazy var databaseUrl: NSURL = { let directories = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) let directory = directories[directories.endIndex-1] as NSURL return directory.URLByAppendingPathComponent(self.databaseName) }() private var persistentStoreCoordinator: NSPersistentStoreCoordinator { get { return clearablePersistentStoreCoordinator.getOrCreate() } } // Note, we need lazy on the clearables so we can access self in the initializer closures private lazy var clearableObjectContext: ClearableLazy<NSManagedObjectContext> = { return ClearableLazy<NSManagedObjectContext>() { let context = NSManagedObjectContext(concurrencyType: .PrivateQueueConcurrencyType) context.persistentStoreCoordinator = self.persistentStoreCoordinator return context } }() private lazy var clearableObjectModel: ClearableLazy<NSManagedObjectModel> = { return ClearableLazy<NSManagedObjectModel>() { var bundle = NSBundle.mainBundle() if let name = self.bundleName? { if let bundlePath = bundle.pathForResource(name, ofType:"bundle") { bundle = NSBundle(path: bundlePath) } } // TODO load specific version, e.g. // [bundle URLForResource:@"Blah2" withExtension:@"mom" subdirectory:@"Blah.momd"]; if let modelPath = bundle.pathForResource(self.modelName, ofType:"momd") { let modelUrl = NSURL.fileURLWithPath(modelPath) var objectModel = NSManagedObjectModel(contentsOfURL: modelUrl) return objectModel; } NSLog("Unable to read data model %@: ", self.modelName); abort(); } }() private lazy var clearablePersistentStoreCoordinator: ClearableLazy<NSPersistentStoreCoordinator> = { return ClearableLazy<NSPersistentStoreCoordinator>() { var error: NSError?; let persistentStoreCoordinator = NSPersistentStoreCoordinator(managedObjectModel:self.objectModel) if nil == self.createDatabase(persistentStoreCoordinator, error: &error) { NSLog("Fatal error while creating persistent store: %@", error!); abort(); } return persistentStoreCoordinator; } }() private func createDatabase(coordinator: NSPersistentStoreCoordinator, error: NSErrorPointer) -> NSPersistentStore! { let options = [NSMigratePersistentStoresAutomaticallyOption: true, NSInferMappingModelAutomaticallyOption: true] return coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: self.databaseUrl, options: options, error: error) } }
mit
f17e6cc1009c3e95eda7d9df216f59e4
35.662069
117
0.718962
5.242604
false
false
false
false
ahoppen/swift
test/Sema/availability_and_delayed_parsing.swift
5
3351
/// Check for reliable availability checking in inlinable code even when /// skipping some function bodies. rdar://82269657 /// Default build mode reading everything // RUN: %target-swift-frontend -typecheck -dump-type-refinement-contexts %s -target %target-cpu-apple-macos10.10 2>&1 \ // RUN: | %FileCheck %s --check-prefixes TRC-API,TRC-INLINABLE,TRC-WITHTYPES,TRC-FULL /// Emit-module-separately mode / for LLDB // RUN: %target-swift-frontend -typecheck -dump-type-refinement-contexts %s -target %target-cpu-apple-macos10.10 -experimental-skip-non-inlinable-function-bodies-without-types 2>&1 \ // RUN: | %FileCheck %s --check-prefixes TRC-API,TRC-INLINABLE,TRC-WITHTYPES,TRC-FULL-NOT /// InstallAPI mode // RUN: %target-swift-frontend -typecheck -dump-type-refinement-contexts %s -target %target-cpu-apple-macos10.10 -experimental-skip-non-inlinable-function-bodies 2>&1 \ // RUN: | %FileCheck %s --check-prefixes TRC-API,TRC-INLINABLE,TRC-WITHTYPES-NOT,TRC-FULL-NOT /// Index build mode // RUN: %target-swift-frontend -typecheck -dump-type-refinement-contexts %s -target %target-cpu-apple-macos10.10 -experimental-skip-all-function-bodies 2>&1 \ // RUN: | %FileCheck %s --check-prefixes TRC-API,TRC-INLINABLE-NOT,TRC-WITHTYPES-NOT,TRC-FULL-NOT // REQUIRES: OS=macosx @available(macOS 10.12, *) public func foo() { } // TRC-API: (root versions=[10.10.0,+Inf) // TRC-API: (decl versions=[10.12,+Inf) decl=foo() #if canImport(Swift) @available(macOS 10.10, *) extension String { public var computedVariable: String { struct SomeTypeToForceCheckingThis {} if #available(macOS 10.12, *) { foo() } fatalError() } } #endif // TRC-FULL: (decl versions=[10.10,+Inf) decl=extension.String // TRC-WITHTYPES: (condition_following_availability versions=[10.12,+Inf) // TRC-WITHTYPES: (if_then versions=[10.12,+Inf) // TRC-WITHTYPES-NOT-NOT: (condition_following_availability versions=[10.12,+Inf) // TRC-WITHTYPES-NOT-NOT: (if_then versions=[10.12,+Inf) struct S { fileprivate var actual: [String] = [] { didSet { if #available(macOS 10.15, *) { foo() } } } } // TRC-API: (condition_following_availability versions=[10.15,+Inf) // TRC-API: (if_then versions=[10.15,+Inf) @inlinable public func inlinableFunc() { if #available(macOS 10.12, *) { foo() } } // TRC-INLINABLE: (condition_following_availability versions=[10.12,+Inf) // TRC-INLINABLE: (if_then versions=[10.12,+Inf) // TRC-INLINABLE-NOT-NOT: (condition_following_availability versions=[10.12,+Inf) // TRC-INLINABLE-NOT-NOT: (if_then versions=[10.12,+Inf) public func funcWithType() { struct S {} if #available(macOS 10.13, *) { foo() } } // TRC-WITHTYPES: (condition_following_availability versions=[10.13,+Inf) // TRC-WITHTYPES: (if_then versions=[10.13,+Inf) // TRC-WITHTYPES-NOT-NOT: (condition_following_availability versions=[10.13,+Inf) // TRC-WITHTYPES-NOT-NOT: (if_then versions=[10.13,+Inf) public func funcSkippable() { if #available(macOS 10.14, *) { foo() } } // TRC-FULL: (condition_following_availability versions=[10.14,+Inf) // TRC-FULL: (if_then versions=[10.14,+Inf) // TRC-FULL-NOT-NOT: (condition_following_availability versions=[10.14,+Inf) // TRC-FULL-NOT-NOT: (if_then versions=[10.14,+Inf)
apache-2.0
9eb508e4ce5c9a5827fd96b62f6ebeae
37.079545
182
0.682184
3.179317
false
false
false
false
swift-tweets/tweetup-kit
Sources/TweetupKit/Async.swift
1
2631
import Foundation import PromiseK public func sync<T, R>(operation: (@escaping (T, @escaping (() throws -> R) -> ()) -> ())) -> (T) throws -> R { return { value in var resultValue: R! var resultError: Error? var waiting = true operation(value) { getValue in defer { waiting = false } do { resultValue = try getValue() } catch let error { resultError = error } } let runLoop = RunLoop.current while waiting && runLoop.run(mode: .defaultRunLoopMode, before: .distantFuture) { } if let error = resultError { throw error } return resultValue } } internal func repeated<T, R1, R2>(operation: @escaping (T, R1?) -> Promise<() throws -> R2>, convert: @escaping (R2) -> R1, interval: TimeInterval? = nil) -> ([T]) -> Promise<() throws -> [R2]> { return { values in _repeat(operation: operation, for: values[...], convert: convert, interval: interval) } } internal func repeated<T, R>(operation: @escaping (T) -> Promise<() throws -> R>, interval: TimeInterval? = nil) -> ([T]) -> Promise<() throws -> [R]> { return { values in _repeat(operation: { r, _ in operation(r) }, for: values[...], convert: { $0 }, interval: interval) } } private func _repeat<T, R1, R2>(operation: @escaping (T, R1?) -> Promise<() throws -> R2>, for values: ArraySlice<T>, convert: @escaping (R2) -> R1, interval: TimeInterval?, results: [R2] = []) -> Promise<() throws -> [R2]> { let (headOrNil, tail) = values.headAndTail guard let head = headOrNil else { return Promise { results } } let resultPromise: Promise<() throws -> R2> if let interval = interval, !tail.isEmpty { resultPromise = wait(operation(head, results.last.map(convert)), for: interval) } else { resultPromise = operation(head, results.last.map(convert)) } return resultPromise.flatMap { getResult in _repeat(operation: operation, for: tail, convert: convert, interval: interval, results: results + [try getResult()]) } } internal func wait<T>(_ promise: Promise<() throws -> T>, for interval: TimeInterval) -> Promise<() throws -> T> { let waiting = Promise<()> { fulfill in DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(Int(interval * 1000.0))) { fulfill(()) } } return promise.flatMap { getValue in let value = try getValue() return waiting.map { _ in value } } }
mit
6ff867743cab404df29f07004a24d8a0
36.056338
225
0.571266
4.098131
false
false
false
false
informmegp2/inform-me
InformME/OrganizerHomeViewController.swift
1
2890
// // OrganizerHomeViewController.swift // InformME // // Created by Amal Ibrahim on 2/5/16. // Copyright © 2016 King Saud University. All rights reserved. // import Foundation import UIKit class OrganizerHomeViewController: CenterViewController { @IBOutlet weak var menuButton: UIBarButtonItem! /*Hello : ) */ override func viewDidLoad() { super.viewDidLoad() //setup tint color for tha back button. } var window:UIWindow! override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { window = UIWindow(frame: UIScreen.mainScreen().bounds) let containerViewController = ContainerViewController() if(segue.identifier == "orgMain"){ containerViewController.centerViewController = mainStoryboard().instantiateViewControllerWithIdentifier("CenterViewController1") as? CenterViewController print(window!.rootViewController) window!.rootViewController = containerViewController print(window!.rootViewController) window!.makeKeyAndVisible() } else if(segue.identifier == "events"){ containerViewController.centerViewController = mainStoryboard().instantiateViewControllerWithIdentifier("eventsMng") as? CenterViewController print(window!.rootViewController) window!.rootViewController = containerViewController print(window!.rootViewController) window!.makeKeyAndVisible() } else if(segue.identifier == "beacons"){ containerViewController.centerViewController = mainStoryboard().instantiateViewControllerWithIdentifier("beaconsMng") as? CenterViewController print(window!.rootViewController) window!.rootViewController = containerViewController print(window!.rootViewController) window!.makeKeyAndVisible() } else if(segue.identifier == "profile"){ containerViewController.centerViewController = mainStoryboard().instantiateViewControllerWithIdentifier("profileMng") as? CenterViewController print(window!.rootViewController) window!.rootViewController = containerViewController print(window!.rootViewController) window!.makeKeyAndVisible() } if(segue.identifier != "backtologin") { containerViewController.centerViewController.delegate?.collapseSidePanels!() } } func mainStoryboard() -> UIStoryboard { return UIStoryboard(name: "Main", bundle: NSBundle.mainBundle()) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
42655dc790d6325d00b349d503d21709
36.051282
165
0.657667
6.59589
false
false
false
false
MaxHasADHD/TraktKit
Common/Models/Shows/TraktWatchedShow.swift
1
967
// // TraktWatchedShow.swift // TraktKit // // Created by Maximilian Litteral on 4/13/16. // Copyright © 2016 Maximilian Litteral. All rights reserved. // import Foundation public struct TraktWatchedShow: Codable, Hashable { // Extended: Min public let plays: Int // Total number of plays public let lastWatchedAt: Date? public let lastUpdatedAt: Date? public let show: TraktShow public let seasons: [TraktWatchedSeason]? enum CodingKeys: String, CodingKey { case plays case lastWatchedAt = "last_watched_at" case lastUpdatedAt = "last_updated_at" case show case seasons } public init(plays: Int, lastWatchedAt: Date?, lastUpdatedAt: Date?, show: TraktShow, seasons: [TraktWatchedSeason]?) { self.plays = plays self.lastWatchedAt = lastWatchedAt self.lastUpdatedAt = lastUpdatedAt self.show = show self.seasons = seasons } }
mit
f2db90f38388c211aeab9aa364feb5b0
26.6
122
0.65735
4.351351
false
false
false
false
andrewlowson/Visiocast
Visucast/PodcastEpisode.swift
1
1390
// // PodcastEpisode.swift // Visiocast // // Podcast Episode Object with details on Title, duration, file size and file location // // Created by Andrew Lowson on 29/07/2015. // Copyright (c) 2015 Andrew Lowson. All rights reserved. // import Foundation class PodcastEpisode: NSObject { var episodeTitle: String? // Title of particular episode var episodeDownloadURL: NSURL? var episodeSubtitle: String? // Brief summary of episode var episodeDescription: String? // longer summary of show var episodeDate: NSDate? // release date var episodeDuration: String? // duration in seconds var episodeID: String? // Unique ID for the file (will be used when subscriptions are added) var episodeSize: Int // size of file in bytes var podcast: Podcast? // Podcast Object associated with episode // constructor to assign instance variables when PodcastEpisode object is instantiated init(title: String, description: String, date: NSDate, duration: String, download: String, subtitle: String, size: Int, podcast: Podcast) { self.episodeTitle = title self.episodeDownloadURL = NSURL(string: download) self.episodeDescription = description self.episodeDuration = duration self.episodeDate = date self.episodeSubtitle = subtitle self.episodeSize = size self.podcast = podcast } }
gpl-2.0
a19a790523102b9fb0b6ccf1de620bb9
38.742857
143
0.710791
4.602649
false
false
false
false
dangthaison91/SwagGen
Templates/Swift/APIResponse.swift
1
3145
{% include "Includes/header.stencil" %} import Foundation import Alamofire public protocol APIResponseValue: CustomDebugStringConvertible, CustomStringConvertible { associatedtype SuccessType var statusCode: Int { get } var successful: Bool { get } var response: Any { get } init(statusCode: Int, data: Data) throws var success: SuccessType? { get } } public enum APIResponseResult<SuccessType, FailureType>: CustomStringConvertible, CustomDebugStringConvertible { case success(SuccessType) case failure(FailureType) public var value: Any { switch self { case .success(let value): return value case .failure(let value): return value } } public var successful: Bool { switch self { case .success: return true case .failure: return false } } public var description: String { return "\(successful ? "success" : "failure")" } public var debugDescription: String { return "\(description):\n\(value)" } } public struct APIResponse<T: APIResponseValue> { /// The APIRequest used for this response public let request: APIRequest<T> /// The result of the response . public let result: APIResult<T> /// The URL request sent to the server. public let urlRequest: URLRequest? /// The server's response to the URL request. public let urlResponse: HTTPURLResponse? /// The data returned by the server. public let data: Data? /// The timeline of the complete lifecycle of the request. public let timeline: Timeline? init(request: APIRequest<T>, result: APIResult<T>, urlRequest: URLRequest? = nil, urlResponse: HTTPURLResponse? = nil, data: Data? = nil, timeline: Timeline? = nil) { self.request = request self.result = result self.urlRequest = urlRequest self.urlResponse = urlResponse self.data = data self.timeline = timeline } } extension APIResponse: CustomStringConvertible, CustomDebugStringConvertible { public var description:String { var string = "\(request)" switch result { case .success(let value): string += " returned \(value.statusCode)" let responseString = "\(type(of: value.response))" if responseString != "()" { string += ": \(responseString)" } case .failure(let error): string += " failed: \(error)" } return string } public var debugDescription: String { var string = description if let response = result.value?.response { if let debugStringConvertible = response as? CustomDebugStringConvertible { string += "\n\(debugStringConvertible.debugDescription)" } else if let prettyPrinted = response as? PrettyPrintable { string += "\n\(prettyPrinted.prettyPrinted)" } else if let prettyPrinted = response as? [PrettyPrintable] { string += "\n\(prettyPrinted.map { $0.prettyPrinted }.joined(separator: "\n"))" } } return string } }
mit
36c5ab638e87b5f97cbbc3723bc7344e
29.833333
170
0.633068
5.023962
false
false
false
false
ArnavChawla/InteliChat
Carthage/Checkouts/swift-sdk/Source/ConversationV1/Models/UpdateValue.swift
2
3972
/** * Copyright IBM Corporation 2018 * * 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 /** UpdateValue. */ public struct UpdateValue: Encodable { /// Specifies the type of value. public enum ValueType: String { case synonyms = "synonyms" case patterns = "patterns" } /// The text of the entity value. This string must conform to the following restrictions: - It cannot contain carriage return, newline, or tab characters. - It cannot consist of only whitespace characters. - It must be no longer than 64 characters. public var value: String? /// Any metadata related to the entity value. public var metadata: [String: JSON]? /// Specifies the type of value. public var valueType: String? /// An array of synonyms for the entity value. You can provide either synonyms or patterns (as indicated by **type**), but not both. A synonym must conform to the following resrictions: - It cannot contain carriage return, newline, or tab characters. - It cannot consist of only whitespace characters. - It must be no longer than 64 characters. public var synonyms: [String]? /// An array of patterns for the entity value. You can provide either synonyms or patterns (as indicated by **type**), but not both. A pattern is a regular expression no longer than 128 characters. For more information about how to specify a pattern, see the [documentation](https://console.bluemix.net/docs/services/conversation/entities.html#creating-entities). public var patterns: [String]? // Map each property name to the key that shall be used for encoding/decoding. private enum CodingKeys: String, CodingKey { case value = "value" case metadata = "metadata" case valueType = "type" case synonyms = "synonyms" case patterns = "patterns" } /** Initialize a `UpdateValue` with member variables. - parameter value: The text of the entity value. This string must conform to the following restrictions: - It cannot contain carriage return, newline, or tab characters. - It cannot consist of only whitespace characters. - It must be no longer than 64 characters. - parameter metadata: Any metadata related to the entity value. - parameter valueType: Specifies the type of value. - parameter synonyms: An array of synonyms for the entity value. You can provide either synonyms or patterns (as indicated by **type**), but not both. A synonym must conform to the following resrictions: - It cannot contain carriage return, newline, or tab characters. - It cannot consist of only whitespace characters. - It must be no longer than 64 characters. - parameter patterns: An array of patterns for the entity value. You can provide either synonyms or patterns (as indicated by **type**), but not both. A pattern is a regular expression no longer than 128 characters. For more information about how to specify a pattern, see the [documentation](https://console.bluemix.net/docs/services/conversation/entities.html#creating-entities). - returns: An initialized `UpdateValue`. */ public init(value: String? = nil, metadata: [String: JSON]? = nil, valueType: String? = nil, synonyms: [String]? = nil, patterns: [String]? = nil) { self.value = value self.metadata = metadata self.valueType = valueType self.synonyms = synonyms self.patterns = patterns } }
mit
9043a2ef6014d0d854f8a9f85c96bfa2
54.943662
386
0.717774
4.597222
false
false
false
false
vladrusu-3pillar/JSON-fork
Source/JSONSerializer.swift
1
3691
// JSONSerializer.swift // // The MIT License (MIT) // // Copyright (c) 2015 Zewo // // 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. // // This file has been modified from its original project Swift-JsonSerializer public class JSONSerializer { public init() {} public func serialize(json: JSON) -> Data { return serializeToString(json).data } public func serializeToString(json: JSON) -> String { switch json { case .nullValue: return "null" case .booleanValue(let b): return b ? "true" : "false" case .numberValue(let n): return serializeNumber(n) case .stringValue(let s): return escapeAsJSONString(s) case .arrayValue(let a): return serializeArray(a) case .objectValue(let o): return serializeObject(o) } } func serializeNumber(n: Double) -> String { if n == Double(Int64(n)) { return Int64(n).description } else { return n.description } } func serializeArray(a: [JSON]) -> String { var s = "[" for i in 0 ..< a.count { s += serializeToString(a[i]) if i != (a.count - 1) { s += "," } } return s + "]" } func serializeObject(o: [String: JSON]) -> String { var s = "{" var i = 0 for entry in o { s += "\(escapeAsJSONString(entry.0)):\(serialize(entry.1))" if i != (o.count - 1) { s += "," } i += 1 } return s + "}" } } public final class PrettyJSONSerializer: JSONSerializer { var indentLevel = 0 override public func serializeArray(a: [JSON]) -> String { var s = "[" indentLevel += 1 for i in 0 ..< a.count { s += "\n" s += indent() s += serializeToString(a[i]) if i != (a.count - 1) { s += "," } } indentLevel -= 1 return s + "\n" + indent() + "]" } override public func serializeObject(o: [String: JSON]) -> String { var s = "{" indentLevel += 1 var i = 0 for (key, value) in o { s += "\n" s += indent() s += "\(escapeAsJSONString(key)): \(serialize(value))" if i != (o.count - 1) { s += "," } i += 1 } indentLevel -= 1 return s + "\n" + indent() + "}" } func indent() -> String { var s = "" for _ in 0 ..< indentLevel { s += " " } return s } }
mit
80e338df5f3c0753e3c46f830601006b
26.552239
81
0.548361
4.33216
false
false
false
false
zcfsmile/Swifter
BasicSyntax/011函数/011Functions.playground/Contents.swift
1
3377
//: Playground - noun: a place where people can play import UIKit var str = "Hello, playground" //: func greet(person: String) -> String { let greeting = "Hello, " + person + "!" return greeting } print(greet(person: "Anna")) // 参数默认值 func addTwoNumber(_ parameter1: Int, parameter2: Int = 12) -> Int { return parameter1 + parameter2 } print(addTwoNumber(5)) // 17 // 可变参数 // 一个函数最多只能拥有一个可变参数。 // 可变参数的传入值在函数体中变为此类型的一个数组。 func arithmeticMean(_ numbers: Double...) -> Double { var total: Double = 0 for number in numbers { total += number } return total / Double(numbers.count) } arithmeticMean(1, 2, 3, 4, 5) // 3 // 输入输出参数 // 函数参数默认是常量。在函数体中修改参数会导致编译错误。 // 如果想要一个函数可以修改参数的值,并且这些修改在函数调用之后还存在,需要使用输入输出参数 // 注意 输入输出参数不能有默认值,而且可变参数不能用 inout 标记。只能传递变量给输入输出参数。你不能传入常量或者字面量,因为这些量是不能被修改的。当传入的参数作为输入输出参数时,需要在参数名前加 & 符,表示这个值可以被函数修改。 func swapTwoInts(_ a: inout Int, _ b: inout Int) { let temporaryA = a a = b b = temporaryA } var a = 3 var b = 10 swapTwoInts(&a, &b) print(a) // 10 print(b) // 3 // 函数类型 // 函数的类型由函数的参数类型和返回类型组成。 func addTwoInts(_ a: Int, _ b: Int) -> Int { return a + b } func multiplyTwoInts(_ a: Int, _ b: Int) -> Int { return a * b } // 上述两个函数的类型是 (Int, Int) -> (Int) func printHelloWorld() { print("Hello, world") } // () -> Void // 使用函数类型 var matchFunction: (Int, Int) -> Int = addTwoInts matchFunction(2, 3) // 5 matchFunction = multiplyTwoInts matchFunction(2, 3) // 6 // 函数类型作为参数类型 func printMathResult(_ matchFunction: (Int, Int) -> Int, _ a: Int, _ b: Int) { print(matchFunction(a, b)) } printMathResult(addTwoInts, 3, 5) // 8 // 函数类型作为返回类型 func stepForward(_ input: Int) -> Int { return input + 1 } func stepBackward(_ input: Int) -> Int { return input - 1 } func chooseStepFunction(backward: Bool) -> (Int) -> Int { return backward ? stepBackward : stepForward } var currentvalue = 3 let currentFunc = chooseStepFunction(backward: currentvalue > 0) while currentvalue != 0 { print(currentvalue) currentvalue = currentFunc(currentvalue) } // 嵌套函数 // 可以把函数定义在别的函数体中,称作 嵌套函数(nested functions)。 // 默认情况下,嵌套函数是对外界不可见的,但是可以被它们的外围函数(enclosing function)调用。一个外围函数也可以返回它的某一个嵌套函数,使得这个函数可以在其他域中被使用。 func chooseStepFunc(backward: Bool) -> (Int) -> Int { func stepForward(input: Int) -> Int { return input + 1 } func stepBackward(input: Int) -> Int { return input - 1 } return backward ? stepBackward : stepForward } var currentV = -4 let currentF = chooseStepFunc(backward: currentV > 0) while currentV != 0 { print(currentV) currentV = currentF(currentV) }
mit
a87a5775c12604ace57a0f8995bda4ab
22.935185
120
0.673114
3.016336
false
false
false
false
chernyog/SQLite-Note
SQLite/SQLite/SQLiteHelper.swift
1
4084
// // SQLiteHelper.swift // 01-SQLite入门 // // Created by 陈勇 on 15/3/14. // Copyright (c) 2015年 zhssit. All rights reserved. // import Foundation /// SQLite数据库处理帮助类 /// /// 此类中封装了关于SQLite数据库处理的业务函数 class SQLiteHelper { private static let instance = SQLiteHelper() /// 全局的数据访问接口 class var sharedInstance: SQLiteHelper { return instance } var db: COpaquePointer = nil /// 打开数据库 /// /// :param: dbName 数据库名称 /// /// :returns: 返回 是否打开成功 func openDatabase(dbName: String) -> Bool { let path = dbName.documentPath() println(path) return sqlite3_open(path, &db) == SQLITE_OK } /// 创建 T_Department 和 T_Employee 表 /// /// :returns: 返回 是否创建成功 func createTable() -> Bool { let sql = "CREATE TABLE \n" + "IF NOT EXISTS T_Department (\n" + "id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,\n" + "DepartmentNo CHAR(10) NOT NULL DEFAULT '',\n" + "Name CHAR(50) NOT NULL DEFAULT '' \n" + "); \n" + "CREATE TABLE IF NOT EXISTS T_Employee ( \n" + "'id' INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, \n" + "'name' TEXT NOT NULL, \n" + "'age' INTEGER NOT NULL, \n" + "'department_id' INTEGER, \n" + "CONSTRAINT 'FK_DEP_ID' FOREIGN KEY ('department_id') REFERENCES 'T_Department' ('id') \n" + ");" return executeSql(sql) } /// 执行INSERT、UPDATE、DELETE SQL语句 /// /// :param: sql SQL语句 /// /// :returns: 返回 是否执行成功 func executeSql(sql: String) -> Bool { return sqlite3_exec(db, sql, nil, nil, nil) == SQLITE_OK } /// 执行SELECT SQL语句,返回结果集 /// /// :param: sql SQL语句 /// /// :returns: 返回 结果集 func query(sql: String) -> [AnyObject]? { var dataSet: [AnyObject]? var stmt: COpaquePointer = nil if sqlite3_prepare_v2(db, sql, -1, &stmt, nil) == SQLITE_OK { // println(stmt) dataSet = [AnyObject]() while sqlite3_step(stmt) == SQLITE_ROW { dataSet!.append(singleData(stmt)!) } println(dataSet!) } else { println("未知错误!") } // 释放语句,防止内存泄露! sqlite3_finalize(stmt) return dataSet } func singleData(stmt: COpaquePointer) -> [AnyObject]? { var result = [AnyObject]() // 返回该表的列数 let count = sqlite3_column_count(stmt) // println("count=\(count)") // #define SQLITE_INTEGER 1 // #define SQLITE_FLOAT 2 // #define SQLITE_BLOB 4 // #define SQLITE_NULL 5 // #ifdef SQLITE_TEXT // # undef SQLITE_TEXT // #else // # define SQLITE_TEXT 3 // #endif // #define SQLITE3_TEXT 3 for index in 0..<count { let type = sqlite3_column_type(stmt, index) // 根据字段的类型,提取对应列的值 switch type { case SQLITE_INTEGER: result.append(Int(sqlite3_column_int64(stmt, index))) case SQLITE_FLOAT: result.append(sqlite3_column_double(stmt, index)) case SQLITE_NULL: result.append(NSNull()) case SQLITE_TEXT: let rrrrr: UnsafePointer<UInt8> = sqlite3_column_text(stmt, index) let chars = UnsafePointer<CChar>(sqlite3_column_text(stmt, index)) let str = String(CString: chars, encoding: NSUTF8StringEncoding)! result.append(str) case let type: println("不支持的类型 \(type)") } } // println(result) return result } }
mit
5fcf7e1357e013c17be8bd971d7f3423
26.456522
104
0.515048
3.830131
false
false
false
false
ruslanskorb/CoreStore
CoreStoreDemo/CoreStoreDemo/List and Object Observers Demo/CollectionViewDemoViewController.swift
1
5347
// // CollectionViewDemoViewController.swift // CoreStoreDemo // // Created by John Estropia on 2019/10/17. // Copyright © 2019 John Rommel Estropia. All rights reserved. // import UIKit import CoreStore // MARK: - CollectionViewDemoViewController final class CollectionViewDemoViewController: UICollectionViewController { // MARK: UIViewController override func viewDidLoad() { super.viewDidLoad() let navigationItem = self.navigationItem navigationItem.leftBarButtonItems = [ self.editButtonItem, UIBarButtonItem( barButtonSystemItem: .trash, target: self, action: #selector(self.resetBarButtonItemTouched(_:)) ) ] let filterBarButton = UIBarButtonItem( title: ColorsDemo.filter.rawValue, style: .plain, target: self, action: #selector(self.filterBarButtonItemTouched(_:)) ) navigationItem.rightBarButtonItems = [ UIBarButtonItem( barButtonSystemItem: .add, target: self, action: #selector(self.addBarButtonItemTouched(_:)) ), UIBarButtonItem( barButtonSystemItem: .refresh, target: self, action: #selector(self.shuffleBarButtonItemTouched(_:)) ), filterBarButton ] self.filterBarButton = filterBarButton self.dataSource = DiffableDataSource.CollectionView<Palette>( collectionView: self.collectionView, dataStack: ColorsDemo.stack, cellProvider: { (collectionView, indexPath, palette) in let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "PaletteCollectionViewCell", for: indexPath) as! PaletteCollectionViewCell cell.colorView?.backgroundColor = palette.color cell.label?.text = palette.colorText return cell }, supplementaryViewProvider: { (collectionView, kind, indexPath) in switch kind { case UICollectionView.elementKindSectionHeader: let view = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "PaletteCollectionSectionHeaderView", for: indexPath) as! PaletteCollectionSectionHeaderView view.label?.text = ColorsDemo.palettes.snapshot.sectionIDs[indexPath.section] return view default: return nil } } ) ColorsDemo.palettes.addObserver(self) { [weak self] (listPublisher) in guard let self = self else { return } self.filterBarButton?.title = ColorsDemo.filter.rawValue self.dataSource?.apply(listPublisher.snapshot, animatingDifferences: true) } self.dataSource?.apply(ColorsDemo.palettes.snapshot, animatingDifferences: false) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { super.prepare(for: segue, sender: sender) switch (segue.identifier, segue.destination, sender) { case ("ObjectObserverDemoViewController"?, let destinationViewController as ObjectObserverDemoViewController, let palette as ObjectPublisher<Palette>): destinationViewController.setPalette(palette) default: break } } // MARK: UICollectionViewDelegate override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { collectionView.deselectItem(at: indexPath, animated: true) self.performSegue( withIdentifier: "ObjectObserverDemoViewController", sender: ColorsDemo.palettes.snapshot[indexPath] ) } // MARK: Private private var filterBarButton: UIBarButtonItem? private var dataSource: DiffableDataSource.CollectionView<Palette>? deinit { ColorsDemo.palettes.removeObserver(self) } @IBAction private dynamic func resetBarButtonItemTouched(_ sender: AnyObject?) { ColorsDemo.stack.perform( asynchronous: { (transaction) in try transaction.deleteAll(From<Palette>()) }, completion: { _ in } ) } @IBAction private dynamic func filterBarButtonItemTouched(_ sender: AnyObject?) { ColorsDemo.filter = ColorsDemo.filter.next() } @IBAction private dynamic func addBarButtonItemTouched(_ sender: AnyObject?) { ColorsDemo.stack.perform( asynchronous: { (transaction) in let palette = transaction.create(Into<Palette>()) palette.setInitialValues(in: transaction) }, completion: { _ in } ) } @IBAction private dynamic func shuffleBarButtonItemTouched(_ sender: AnyObject?) { ColorsDemo.stack.perform( asynchronous: { (transaction) in for palette in try transaction.fetchAll(From<Palette>()) { palette.hue .= Palette.randomHue() palette.colorName .= nil } }, completion: { _ in } ) } }
mit
02bc73e802918d4ec2d07b3e45127d4a
30.633136
206
0.613543
6.013498
false
false
false
false
megabitsenmzq/PomoNow-iOS
PomoNow/PomoNow/SettingsTableViewController.swift
1
7027
// // SettingsTableViewController.swift // PomoNow // // Created by Megabits on 15/10/13. // Copyright © 2015年 Jinyu Meng. All rights reserved. // import UIKit import MessageUI class SettingsTableViewController: UITableViewController ,MFMailComposeViewControllerDelegate{ @IBOutlet weak var workLabel: UILabel! @IBOutlet weak var breakLabel: UILabel! @IBOutlet weak var longBreakLabel: UILabel! @IBOutlet weak var longBreakDelayLabel: UILabel! @IBOutlet weak var tsSwitch: UISwitch! @IBOutlet weak var asSwitch: UISwitch! @IBOutlet weak var dlsSwitch: UISwitch! @IBOutlet weak var ctSwitch: UISwitch! @IBAction func timerSoundSwitch(_ sender: UISwitch) { pomodoroClass.enableTimerSound = sender.isOn pomodoroClass.stopSound() } @IBAction func alarmSoundSwitch(_ sender: UISwitch) { pomodoroClass.enableAlarmSound = sender.isOn } @IBAction func disableLockScreenSwitch(_ sender: UISwitch) { isDisableLockScreen = sender.isOn setDefaults ("main.isDisableLockScreen",value: isDisableLockScreen as AnyObject) let app = UIApplication.shared app.isIdleTimerDisabled = isDisableLockScreen } @IBAction func continuousTimingSwitch(_ sender: UISwitch) { pomodoroClass.longBreakEnable = sender.isOn } override func viewDidLoad() { super.viewDidLoad() //设置初始值的显示 self.workLabel.text = self.updateDisplay(0) self.breakLabel.text = self.updateDisplay(1) self.longBreakLabel.text = self.updateDisplay(2) tsSwitch.isOn = pomodoroClass.enableTimerSound asSwitch.isOn = pomodoroClass.enableAlarmSound dlsSwitch.isOn = isDisableLockScreen ctSwitch.isOn = pomodoroClass.longBreakEnable longBreakDelayLabel.text = "\(pomodoroClass.longBreakCount) " + NSLocalizedString("Focus Cycle", comment: "pd") } override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 10 } override func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? { //使列表项可以点击 if indexPath.section == 0 && indexPath.row >= 5 && indexPath.row <= 8 { return indexPath } else { return nil } } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { //点击列表项的处理 if indexPath.section == 0 { switch indexPath.row{ case 5: Dialog().showDatePicker(NSLocalizedString("Set Focus Cycle Length", comment: "spl"), doneButtonTitle: NSLocalizedString("Done", comment: "done"), cancelButtonTitle: NSLocalizedString("Cancel", comment: "cancel"),defaultTime: Double(pomodoroClass.pomoTime), datePickerMode: .countDownTimer) { (timer) -> Void in let setTimer = Int(timer - (timer.truncatingRemainder(dividingBy: 60))) if setTimer != pomodoroClass.pomoTime { pomodoroClass.pomoTime = setTimer pomodoroClass.stop() } self.workLabel.text = self.updateDisplay(0) } case 6: Dialog().showDatePicker(NSLocalizedString("Set Break Length", comment: "sbl"), doneButtonTitle: NSLocalizedString("Done", comment: "done"), cancelButtonTitle: NSLocalizedString("Cancel", comment: "cancel"),defaultTime: Double(pomodoroClass.breakTime), datePickerMode: .countDownTimer) { (timer) -> Void in let setTimer = Int(timer - (timer.truncatingRemainder(dividingBy: 60))) if setTimer != pomodoroClass.breakTime { pomodoroClass.breakTime = setTimer pomodoroClass.stop() } self.breakLabel.text = self.updateDisplay(1) } case 7: Dialog().showDatePicker(NSLocalizedString("Set Long Break Length", comment: "slbl"), doneButtonTitle: NSLocalizedString("Done", comment: "done"), cancelButtonTitle: NSLocalizedString("Cancel", comment: "cancel"),defaultTime: Double(pomodoroClass.longBreakTime), datePickerMode: .countDownTimer) { (timer) -> Void in let setTimer = Int(timer - (timer.truncatingRemainder(dividingBy: 60))) if setTimer != pomodoroClass.longBreakTime { pomodoroClass.longBreakTime = setTimer pomodoroClass.stop() } self.longBreakLabel.text = self.updateDisplay(2) } case 8: Dialog().showPicker(NSLocalizedString("Set Long break delay", comment: "slbd"), doneButtonTitle: NSLocalizedString("Done", comment: "done"), cancelButtonTitle: NSLocalizedString("Cancel", comment: "cancel"), defaults: pomodoroClass.longBreakCount - 1) { (rowSelect) -> Void in if Int(rowSelect) + 1 != pomodoroClass.longBreakCount { pomodoroClass.longBreakCount = Int(rowSelect) + 1 pomodoroClass.stop() } self.longBreakDelayLabel.text = "\(pomodoroClass.longBreakCount) " + NSLocalizedString("Focus Cycle", comment: "pd") } default:break } } } func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) { controller.dismiss(animated: true, completion: nil) } func updateDisplay(_ select:Int) -> String { //输出时间的文本表示 var display = "" switch pomodoroClass.getStringOfTime(select) { case 1:display = pomodoroClass.timerLabelSec + " Sec" case 2:display = pomodoroClass.timerLabelMin + " " + NSLocalizedString("min", comment: "min") case 3:display = pomodoroClass.timerLabelHour + " " + NSLocalizedString("h", comment: "hour") + " " + pomodoroClass.timerLabelMin + " " + NSLocalizedString("min", comment: "min") default:break } return display } fileprivate let defaults = UserDefaults.standard func getDefaults (_ key: String) -> AnyObject? { if key != "" { return defaults.object(forKey: key) as AnyObject } else { return nil } } func setDefaults (_ key: String,value: AnyObject) { if key != "" { defaults.set(value,forKey: key) } } }
mit
c3dd9564bbe6b4e51b3788dc0c67bdd1
44.477124
316
0.599741
5.356428
false
false
false
false
auth0/Lock.iOS-OSX
LockTests/Models/AuthStyleSpec.swift
1
11532
// AuthStyleSpec.swift // // Copyright (c) 2016 Auth0 (http://auth0.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Quick import Nimble @testable import Lock private let NameKey = "name" private let IconKey = "icon_name" private let StyleKey = "style" private let FirstClassStyleExample = "style" func forStyle(_ style: AuthStyle, name: String, iconName: String) -> [String: Any] { return [ StyleKey: style, NameKey: name, IconKey: iconName ] } class AuthStyleSpecSharedExamplesConfiguration: QuickConfiguration { override class func configure(_ configuration: Configuration) { sharedExamples(FirstClassStyleExample) { (context: SharedExampleContext) in let style = context()[StyleKey] as! AuthStyle let name = context()[NameKey] as! String let iconName = context()[IconKey] as! String describe("for \(name.lowercased())") { it("should have correct name") { expect(style.name) == name } it("should have a color") { expect(style.normalColor) != UIColor.a0_orange } it("should have icon") { expect(style.image.name) == iconName expect(style.image.bundle) == Lock.bundle } } } } } class AuthStyleSpec: QuickSpec { override func spec() { describe("init") { let strategy = AuthStyle(name: "a name") it("should build with a name") { expect(strategy.name) == "a name" } it("should have default image") { expect(strategy.image.name) == "ic_auth_auth0" } it("should have default color") { expect(strategy.normalColor) == UIColor.a0_orange } it("should have default highligted color") { expect(strategy.highlightedColor) == UIColor.a0_orange.a0_darker(0.3) } it("should have default foreground color") { expect(strategy.foregroundColor) == UIColor.white } it("should not have default border color") { expect(strategy.borderColor).to(beNil()) } it("should have main bundle") { expect(strategy.image.bundle) == bundleForLock() } } describe("titles") { it("should provide login title") { let strategy = AuthStyle(name: "facebook") expect(strategy.localizedLoginTitle) == "Sign in with facebook" } it("should provide signup title") { let strategy = AuthStyle(name: "facebook") expect(strategy.localizedSignUpTitle) == "Sign up with facebook" } } describe("first class connections") { [ forStyle(.Amazon, name: "Amazon", iconName: "ic_auth_amazon"), forStyle(.Aol, name: "AOL", iconName: "ic_auth_aol"), forStyle(.Apple, name: "Apple", iconName: "ic_auth_apple"), forStyle(.Baidu, name: "百度", iconName: "ic_auth_baidu"), forStyle(.Bitbucket, name: "Bitbucket", iconName: "ic_auth_bitbucket"), forStyle(.Dropbox, name: "Dropbox", iconName: "ic_auth_dropbox"), forStyle(.Dwolla, name: "Dwolla", iconName: "ic_auth_dwolla"), forStyle(.Ebay, name: "Ebay", iconName: "ic_auth_ebay"), forStyle(.Evernote, name: "Evernote", iconName: "ic_auth_evernote"), forStyle(.EvernoteSandbox, name: "Evernote (sandbox)", iconName: "ic_auth_evernote"), forStyle(.Exact, name: "Exact", iconName: "ic_auth_exact"), forStyle(.Facebook, name: "Facebook", iconName: "ic_auth_facebook"), forStyle(.Fitbit, name: "Fitbit", iconName: "ic_auth_fitbit"), forStyle(.Github, name: "GitHub", iconName: "ic_auth_github"), forStyle(.Google, name: "Google", iconName: "ic_auth_google"), forStyle(.Instagram, name: "Instagram", iconName: "ic_auth_instagram"), forStyle(.Linkedin, name: "LinkedIn", iconName: "ic_auth_linkedin"), forStyle(.Miicard, name: "miiCard", iconName: "ic_auth_miicard"), forStyle(.Paypal, name: "PayPal", iconName: "ic_auth_paypal"), forStyle(.PaypalSandbox, name: "PayPal (sandbox)", iconName: "ic_auth_paypal"), forStyle(.PlanningCenter, name: "Planning Center", iconName: "ic_auth_planningcenter"), forStyle(.RenRen, name: "人人", iconName: "ic_auth_renren"), forStyle(.Salesforce, name: "Salesforce", iconName: "ic_auth_salesforce"), forStyle(.SalesforceCommunity, name: "Salesforce Community", iconName: "ic_auth_salesforce"), forStyle(.SalesforceSandbox, name: "Salesforce (sandbox)", iconName: "ic_auth_salesforce"), forStyle(.Shopify, name: "Shopify", iconName: "ic_auth_shopify"), forStyle(.Soundcloud, name: "SoundCloud", iconName: "ic_auth_soundcloud"), forStyle(.TheCity, name: "The City", iconName: "ic_auth_thecity"), forStyle(.TheCitySandbox, name: "The City (sandbox)", iconName: "ic_auth_thecity"), forStyle(.ThirtySevenSignals, name: "Basecamp", iconName: "ic_auth_thirtysevensignals"), forStyle(.Twitter, name: "Twitter", iconName: "ic_auth_twitter"), forStyle(.Vkontakte, name: "VKontakte", iconName: "ic_auth_vk"), forStyle(.Microsoft, name: "Microsoft Account", iconName: "ic_auth_microsoft"), forStyle(.Wordpress, name: "WordPress", iconName: "ic_auth_wordpress"), forStyle(.Yahoo, name: "Yahoo!", iconName: "ic_auth_yahoo"), forStyle(.Yammer, name: "Yammer", iconName: "ic_auth_yammer"), forStyle(.Yandex, name: "Yandex", iconName: "ic_auth_yandex"), forStyle(.Weibo, name: "新浪微博", iconName: "ic_auth_weibo"), ].forEach { style in itBehavesLike(FirstClassStyleExample) { return style } } } describe("style for strategy") { it("should default to auth0 style") { let style = AuthStyle.style(forStrategy: "random", connectionName: "connection") expect(style.name) == "connection" expect(style.normalColor) == UIColor.a0_orange } [ ("ad", AuthStyle.Microsoft), ("adfs", AuthStyle.Microsoft), ("amazon", AuthStyle.Amazon), ("aol", AuthStyle.Aol), ("apple", AuthStyle.Apple), ("baidu", AuthStyle.Baidu), ("bitbucket", AuthStyle.Bitbucket), ("dropbox", AuthStyle.Dropbox), ("dwolla", AuthStyle.Dwolla), ("ebay", AuthStyle.Ebay), ("evernote", AuthStyle.Evernote), ("evernote-sandbox", AuthStyle.EvernoteSandbox), ("exact", AuthStyle.Exact), ("facebook", AuthStyle.Facebook), ("fitbit", AuthStyle.Fitbit), ("github", AuthStyle.Github), ("google-oauth2", AuthStyle.Google), ("instagram", AuthStyle.Instagram), ("linkedin", AuthStyle.Linkedin), ("miicard", AuthStyle.Miicard), ("paypal", AuthStyle.Paypal), ("paypal-sandbox", AuthStyle.PaypalSandbox), ("planningcenter", AuthStyle.PlanningCenter), ("renren", AuthStyle.RenRen), ("salesforce", AuthStyle.Salesforce), ("salesforce-community", AuthStyle.SalesforceCommunity), ("salesforce-sandbox", AuthStyle.SalesforceSandbox), ("shopify", AuthStyle.Shopify), ("soundcloud", AuthStyle.Soundcloud), ("thecity", AuthStyle.TheCity), ("thecity-sandbox", AuthStyle.TheCitySandbox), ("thirtysevensignals", AuthStyle.ThirtySevenSignals), ("twitter", AuthStyle.Twitter), ("vkontakte", AuthStyle.Vkontakte), ("windowslive", AuthStyle.Microsoft), ("wordpress", AuthStyle.Wordpress), ("yahoo", AuthStyle.Yahoo), ("yammer", AuthStyle.Yammer), ("yandex", AuthStyle.Yandex), ("waad", AuthStyle.Google), ("weibo", AuthStyle.Weibo), ].forEach { (strategy, expected) in it("should match \(strategy) style") { let style = AuthStyle.style(forStrategy: strategy, connectionName: "connection1") expect(style) == expected } } } describe("style button color states") { let style: Style = Style.Auth0 it("should have orange for normal") { expect(style.primaryButtonColor(forState: .normal)) == UIColor.a0_orange } it("should be darker for highlighted") { let baseColor = UIColor.a0_orange expect(style.primaryButtonColor(forState: .highlighted)) == baseColor.a0_darker(0.20) } it("should match disabled color") { expect(style.primaryButtonColor(forState: .disabled)) == UIColor(red: 0.8902, green: 0.898, blue: 0.9059, alpha: 1.0 ) } it("should match disabled color") { expect(style.primaryButtonTintColor(forState: .disabled)) == UIColor(red: 0.5725, green: 0.5804, blue: 0.5843, alpha: 1.0 ) } it("should match tint disabled color") { expect(style.primaryButtonTintColor(forState: .normal)) == UIColor.white } } } } extension AuthStyle: Equatable, CustomStringConvertible { public var description: String { return "AuthStyle(name=\(name))" } } public func ==(lhs: AuthStyle, rhs: AuthStyle) -> Bool { return lhs.name == rhs.name && lhs.normalColor == rhs.normalColor && lhs.highlightedColor == rhs.highlightedColor && lhs.foregroundColor == rhs.foregroundColor && lhs.image.name == rhs.image.name }
mit
d60431bc62a64482444ca310fb646fbc
43.635659
199
0.571292
4.645422
false
false
false
false
bartoszj/acextract
acextractTests/AssetsCatalogTests.swift
1
2235
// // AcextractTests.swift // AcextractTests // // Created by Bartosz Janda on 12.06.2016. // Copyright © 2016 Bartosz Janda. All rights reserved. // import XCTest class FakeOperation: Operation { var executed = false func read(catalog: AssetsCatalog) throws { executed = true } } class AssetsCatalogTests: XCTestCase { // MARK: Tests /** Success */ func testCreateAssetsCatalog01() { do { _ = try AssetsCatalog(path: Asset.assets.path) } catch { XCTFail("Cannot create AssetsCatalog object") } } /** File not found. */ func testCreateAssetsCatalog02() { do { _ = try AssetsCatalog(path: "Fake path") XCTFail("AssetsCatalog should not be created") } catch AssetsCatalogError.fileDoesntExists { } catch { XCTFail("Unknown exception \(error)") } } /** Incorrect file. */ func testCreateAssetsCatalog03() { guard let path = Asset.bundle.path(forResource: "data/fake_assets", ofType: nil) else { XCTFail("Cannot find fake asset") return } do { _ = try AssetsCatalog(path: path) XCTFail("AssetsCatalog should not be created") } catch AssetsCatalogError.cannotOpenAssetsCatalog { } catch { XCTFail("Unknown exception \(error)") } } /** Test one operation. */ func testOperation01() { do { let operation = FakeOperation() try assetsContainer.iOS.performOperation(operation: operation) XCTAssertTrue(operation.executed) } catch { XCTFail("Unknown exception \(error)") } } /** Test two operations. */ func testOperation02() { do { let operation1 = FakeOperation() let operation2 = FakeOperation() try assetsContainer.iOS.performOperations(operations: [operation1, operation2]) XCTAssertTrue(operation1.executed) XCTAssertTrue(operation2.executed) } catch { XCTFail("Unknown exception \(error)") } } }
mit
3a120dfabf20661267410fd5a4564b7d
23.021505
95
0.564458
4.899123
false
true
false
false
LoveZYForever/HXWeiboPhotoPicker
Pods/HXPHPicker/Sources/HXPHPicker/Picker/PickerResult.swift
1
4149
// // PickerResult.swift // HXPHPicker // // Created by Slience on 2021/3/8. // import UIKit import AVFoundation public struct PickerResult { /// 已选的资源 /// getURLs 获取原始资源的URL public let photoAssets: [PhotoAsset] /// 是否选择的原图 public let isOriginal: Bool /// 初始化 /// - Parameters: /// - photoAssets: 对应 PhotoAsset 数据的数组 /// - isOriginal: 是否原图 public init( photoAssets: [PhotoAsset], isOriginal: Bool ) { self.photoAssets = photoAssets self.isOriginal = isOriginal } } // MARK: Get Image / Video URL public extension PickerResult { /// 获取 image /// - Parameters: /// - compressionScale: 压缩比例,获取系统相册里的资源时有效 /// - imageHandler: 每一次获取image都会触发 /// - completionHandler: 全部获取完成(失败的不会添加) func getImage( compressionScale: CGFloat = 0.5, imageHandler: ImageHandler? = nil, completionHandler: @escaping ([UIImage]) -> Void ) { photoAssets.getImage( compressionScale: compressionScale, imageHandler: imageHandler, completionHandler: completionHandler ) } /// 获取视频地址 /// - Parameters: /// - exportPreset: 视频分辨率,默认`ratio_640x480`,传 nil 获取则是原始视频 /// - videoQuality: 视频质量[0-10],默认4,`exportPreset`不为nil时有效 /// - exportSession: 导出视频时对应的 AVAssetExportSession,exportPreset不为nil时触发 /// - videoURLHandler: 每一次获取视频地址都会触发 /// - completionHandler: 全部获取完成(失败的不会添加) func getVideoURL( exportPreset: ExportPreset? = .ratio_640x480, videoQuality: Int = 4, exportSession: AVAssetExportSessionHandler? = nil, videoURLHandler: URLHandler? = nil, completionHandler: @escaping ([URL]) -> Void ) { photoAssets.getVideoURL( exportPreset: exportPreset, videoQuality: videoQuality, exportSession: exportSession, videoURLHandler: videoURLHandler, completionHandler: completionHandler ) } } // MARK: Get Original URL public extension PickerResult { /// 获取已选资源的地址 /// 不包括网络资源,如果网络资源编辑过则会获取 /// - Parameters: /// - options: 获取的类型 /// - compression: 压缩参数,nil - 原图 /// - completion: result func getURLs( options: Options = .any, compression: PhotoAsset.Compression? = nil, completion: @escaping ([URL]) -> Void ) { photoAssets.getURLs( options: options, compression: compression, completion: completion ) } /// 获取已选资源的地址 /// 包括网络图片 /// - Parameters: /// - options: 获取的类型 /// - compression: 压缩参数,nil - 原图 /// - handler: 获取到url的回调 /// - completionHandler: 全部获取完成 func getURLs( options: Options = .any, compression: PhotoAsset.Compression? = nil, urlReceivedHandler handler: URLHandler? = nil, completionHandler: @escaping ([URL]) -> Void ) { photoAssets.getURLs( options: options, compression: compression, urlReceivedHandler: handler, completionHandler: completionHandler ) } } extension PickerResult { /// 图片、PhotoAsset 对象、索引 public typealias ImageHandler = (UIImage?, PhotoAsset, Int) -> Void /// 导出视频时对应的 AVAssetExportSession 对象、PhotoAsset 对象、索引 public typealias AVAssetExportSessionHandler = (AVAssetExportSession, PhotoAsset, Int) -> Void /// 获取URL的结果、PhotoAsset 对象、索引 public typealias URLHandler = (Result<AssetURLResult, AssetError>, PhotoAsset, Int) -> Void }
mit
020f699d0e79d40240f6a1629568fad0
27.448819
98
0.605868
4.342548
false
false
false
false
Duraiamuthan/HybridWebRTC_iOS
WebRTCSupport/Pods/XWebView/XWebView/XWVLogging.swift
1
4726
/* Copyright 2015 XWebView 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 Darwin public typealias asl_object_t = COpaquePointer @_silgen_name("asl_open") func asl_open(ident: UnsafePointer<Int8>, _ facility: UnsafePointer<Int8>, _ opts: UInt32) -> asl_object_t @_silgen_name("asl_close") func asl_close(obj: asl_object_t) @_silgen_name("asl_vlog") func asl_vlog(obj: asl_object_t, _ msg: asl_object_t, _ level: Int32, _ format: UnsafePointer<Int8>, _ ap: CVaListPointer) -> Int32 @_silgen_name("asl_add_output_file") func asl_add_output_file(client: asl_object_t, _ descriptor: Int32, _ msg_fmt: UnsafePointer<Int8>, _ time_fmt: UnsafePointer<Int8>, _ filter: Int32, _ text_encoding: Int32) -> Int32 @_silgen_name("asl_set_output_file_filter") func asl_set_output_file_filter(asl: asl_object_t, _ descriptor: Int32, _ filter: Int32) -> Int32 public class XWVLogging : XWVScripting { public enum Level : Int32 { case Emergency = 0 case Alert = 1 case Critical = 2 case Error = 3 case Warning = 4 case Notice = 5 case Info = 6 case Debug = 7 private static let symbols : [Character] = [ "\0", "\0", "$", "!", "?", "-", "+", " " ] private init?(symbol: Character) { guard symbol != "\0", let value = Level.symbols.indexOf(symbol) else { return nil } self = Level(rawValue: Int32(value))! } } public struct Filter : OptionSetType { private var value: Int32 public var rawValue: Int32 { return value } public init(rawValue: Int32) { self.value = rawValue } public init(mask: Level) { self.init(rawValue: 1 << mask.rawValue) } public init(upto: Level) { self.init(rawValue: 1 << (upto.rawValue + 1) - 1) } public init(filter: Level...) { self.init(rawValue: filter.reduce(0) { $0 | $1.rawValue }) } } public var filter: Filter { didSet { asl_set_output_file_filter(client, STDERR_FILENO, filter.rawValue) } } private let client: asl_object_t private var lock: pthread_mutex_t = pthread_mutex_t() public init(facility: String, format: String? = nil) { client = asl_open(nil, facility, 0) pthread_mutex_init(&lock, nil) #if DEBUG filter = Filter(upto: .Debug) #else filter = Filter(upto: .Notice) #endif let format = format ?? "$((Time)(lcl)) $(Facility) <$((Level)(char))>: $(Message)" asl_add_output_file(client, STDERR_FILENO, format, "sec", filter.rawValue, 1) } deinit { asl_close(client) pthread_mutex_destroy(&lock) } public func log(message: String, level: Level) { pthread_mutex_lock(&lock) asl_vlog(client, nil, level.rawValue, message, getVaList([])) pthread_mutex_unlock(&lock) } public func log(message: String, level: Level? = nil) { var msg = message var lvl = level ?? .Debug if level == nil, let ch = msg.characters.first, l = Level(symbol: ch) { msg = msg[msg.startIndex.successor() ..< msg.endIndex] lvl = l } log(msg, level: lvl) } @objc public func invokeDefaultMethodWithArguments(args: [AnyObject]!) -> AnyObject! { guard args.count > 0 else { return nil } let message = args[0] as? String ?? "\(args[0])" var level: Level? = nil if args.count > 1, let num = args[1] as? Int { if 3 <= num && num <= 7 { level = Level(rawValue: Int32(num)) } else { level = .Debug } } log(message, level: level) return nil } } private let logger = XWVLogging(facility: "org.xwebview.xwebview") func log(message: String, level: XWVLogging.Level? = nil) { logger.log(message, level: level) } @noreturn func die(@autoclosure message: ()->String, file: StaticString = #file, line: UInt = #line) { logger.log(message(), level: .Alert) fatalError(message, file: file, line: line) }
gpl-3.0
4178f5b4a85ab437831438ca0974af00
34.007407
219
0.591621
3.805153
false
false
false
false
gyro-n/PaymentsIos
Example/Tests/MockRouter.swift
1
1874
// // MockRouter.swift // GyronPayments // // Created by David Ye on 2017/09/05. // Copyright © 2017 CocoaPods. All rights reserved. // import Foundation import EnvoyAmbassador /// Router WebApp for routing requests to different WebApp open class MockRouter: WebApp { var routes: [String: WebApp] = [:] open var notFoundResponse: WebApp = DataResponse( statusCode: 404, statusMessage: "Not found" ) private let semaphore = DispatchSemaphore(value: 1) public init() { } open subscript(path: String) -> WebApp? { get { // enter critical section _ = semaphore.wait(timeout: DispatchTime.distantFuture) defer { semaphore.signal() } return routes[path] } set { // enter critical section _ = semaphore.wait(timeout: DispatchTime.distantFuture) defer { semaphore.signal() } routes[path] = newValue! } } open func app( _ environ: [String: Any], startResponse: @escaping ((String, [(String, String)]) -> Void), sendBody: @escaping ((Data) -> Void) ) { let path = environ["PATH_INFO"] as! String if let (webApp, captures) = matchRoute(to: path) { var environ = environ environ["ambassador.router_captures"] = captures webApp.app(environ, startResponse: startResponse, sendBody: sendBody) return } return notFoundResponse.app(environ, startResponse: startResponse, sendBody: sendBody) } private func matchRoute(to searchPath: String) -> (WebApp, [String])? { if let r = routes[searchPath] { return (r, []) } else { return nil } } }
mit
add04a054925096056fec61e7f229f53
26.955224
94
0.552589
4.741772
false
false
false
false
TonyJin99/SinaWeibo
SinaWeibo/SinaWeibo/TJNavigationController.swift
1
2104
// // TJNavigationController.swift // SinaWeibo // // Created by Tony.Jin on 7/23/16. // Copyright © 2016 Innovatis Tech. All rights reserved. // import UIKit class TJNavigationController: UINavigationController { override func viewDidLoad() { super.viewDidLoad() } override func pushViewController(viewController: UIViewController, animated: Bool) { if self.viewControllers.count > 0{ viewController.hidesBottomBarWhenPushed = true let backBtn = UIButton(type: UIButtonType.Custom) backBtn.addTarget(self, action: #selector(self.back), forControlEvents: UIControlEvents.TouchUpInside) backBtn.setBackgroundImage(UIImage(named: "navigationbar_back"), forState: UIControlState.Normal) backBtn.setBackgroundImage(UIImage(named: "navigationbar_back_highlighted"), forState: UIControlState.Highlighted) let size = backBtn.currentBackgroundImage?.size backBtn.frame = CGRectMake(0, 0, (size?.width)!, (size?.height)!) viewController.navigationItem.leftBarButtonItem = UIBarButtonItem(customView: backBtn) let moreBtn = UIButton(type: UIButtonType.Custom) moreBtn.addTarget(self, action: #selector(self.more), forControlEvents: UIControlEvents.TouchUpInside) moreBtn.setBackgroundImage(UIImage(named: "navigationbar_more"), forState: UIControlState.Normal) moreBtn.setBackgroundImage(UIImage(named: "navigationbar_more_highlighted"), forState: UIControlState.Highlighted) let size_more = moreBtn.currentBackgroundImage?.size moreBtn.frame = CGRectMake(0, 0, (size_more?.width)!, (size_more?.height)!) viewController.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: moreBtn) } super.pushViewController(viewController, animated: true) } func back(){ self.popViewControllerAnimated(true) } func more(){ self.popToRootViewControllerAnimated(true) } }
apache-2.0
0f711a3af7c288b1209b19ea065c6422
37.944444
126
0.677128
5.364796
false
false
false
false
naokits/my-programming-marathon
iPhoneSensorDemo/Pods/RxCocoa/RxCocoa/iOS/UITableView+Rx.swift
7
10888
// // UITableView+Rx.swift // RxCocoa // // Created by Krunoslav Zaher on 4/2/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // #if os(iOS) || os(tvOS) import Foundation #if !RX_NO_MODULE import RxSwift #endif import UIKit // Items extension UITableView { /** Binds sequences of elements to table view rows. - parameter source: Observable sequence of items. - parameter cellFactory: Transform between sequence elements and view cells. - returns: Disposable object that can be used to unbind. */ public func rx_itemsWithCellFactory<S: SequenceType, O: ObservableType where O.E == S> (source: O) -> (cellFactory: (UITableView, Int, S.Generator.Element) -> UITableViewCell) -> Disposable { return { cellFactory in let dataSource = RxTableViewReactiveArrayDataSourceSequenceWrapper<S>(cellFactory: cellFactory) return self.rx_itemsWithDataSource(dataSource)(source: source) } } /** Binds sequences of elements to table view rows. - parameter cellIdentifier: Identifier used to dequeue cells. - parameter source: Observable sequence of items. - parameter configureCell: Transform between sequence elements and view cells. - parameter cellType: Type of table view cell. - returns: Disposable object that can be used to unbind. */ public func rx_itemsWithCellIdentifier<S: SequenceType, Cell: UITableViewCell, O : ObservableType where O.E == S> (cellIdentifier: String, cellType: Cell.Type = Cell.self) -> (source: O) -> (configureCell: (Int, S.Generator.Element, Cell) -> Void) -> Disposable { return { source in return { configureCell in let dataSource = RxTableViewReactiveArrayDataSourceSequenceWrapper<S> { (tv, i, item) in let indexPath = NSIndexPath(forItem: i, inSection: 0) let cell = tv.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! Cell configureCell(i, item, cell) return cell } return self.rx_itemsWithDataSource(dataSource)(source: source) } } } /** Binds sequences of elements to table view rows using a custom reactive data used to perform the transformation. - parameter dataSource: Data source used to transform elements to view cells. - parameter source: Observable sequence of items. - returns: Disposable object that can be used to unbind. */ public func rx_itemsWithDataSource<DataSource: protocol<RxTableViewDataSourceType, UITableViewDataSource>, S: SequenceType, O: ObservableType where DataSource.Element == S, O.E == S> (dataSource: DataSource) -> (source: O) -> Disposable { return { source in return source.subscribeProxyDataSourceForObject(self, dataSource: dataSource, retainDataSource: false) { [weak self] (_: RxTableViewDataSourceProxy, event) -> Void in guard let tableView = self else { return } dataSource.tableView(tableView, observedEvent: event) } } } } extension UITableView { /** Factory method that enables subclasses to implement their own `rx_delegate`. - returns: Instance of delegate proxy that wraps `delegate`. */ public override func rx_createDelegateProxy() -> RxScrollViewDelegateProxy { return RxTableViewDelegateProxy(parentObject: self) } /** Factory method that enables subclasses to implement their own `rx_dataSource`. - returns: Instance of delegate proxy that wraps `dataSource`. */ public func rx_createDataSourceProxy() -> RxTableViewDataSourceProxy { return RxTableViewDataSourceProxy(parentObject: self) } /** Reactive wrapper for `dataSource`. For more information take a look at `DelegateProxyType` protocol documentation. */ public var rx_dataSource: DelegateProxy { return proxyForObject(RxTableViewDataSourceProxy.self, self) } /** Installs data source as forwarding delegate on `rx_dataSource`. It enables using normal delegate mechanism with reactive delegate mechanism. - parameter dataSource: Data source object. - returns: Disposable object that can be used to unbind the data source. */ public func rx_setDataSource(dataSource: UITableViewDataSource) -> Disposable { let proxy = proxyForObject(RxTableViewDataSourceProxy.self, self) return installDelegate(proxy, delegate: dataSource, retainDelegate: false, onProxyForObject: self) } // events /** Reactive wrapper for `delegate` message `tableView:didSelectRowAtIndexPath:`. */ public var rx_itemSelected: ControlEvent<NSIndexPath> { let source = rx_delegate.observe(#selector(UITableViewDelegate.tableView(_:didSelectRowAtIndexPath:))) .map { a in return a[1] as! NSIndexPath } return ControlEvent(events: source) } /** Reactive wrapper for `delegate` message `tableView:didDeselectRowAtIndexPath:`. */ public var rx_itemDeselected: ControlEvent<NSIndexPath> { let source = rx_delegate.observe(#selector(UITableViewDelegate.tableView(_:didDeselectRowAtIndexPath:))) .map { a in return a[1] as! NSIndexPath } return ControlEvent(events: source) } /** Reactive wrapper for `delegate` message `tableView:accessoryButtonTappedForRowWithIndexPath:`. */ public var rx_itemAccessoryButtonTapped: ControlEvent<NSIndexPath> { let source: Observable<NSIndexPath> = rx_delegate.observe(#selector(UITableViewDelegate.tableView(_:accessoryButtonTappedForRowWithIndexPath:))) .map { a in return a[1] as! NSIndexPath } return ControlEvent(events: source) } /** Reactive wrapper for `delegate` message `tableView:commitEditingStyle:forRowAtIndexPath:`. */ public var rx_itemInserted: ControlEvent<NSIndexPath> { let source = rx_dataSource.observe(#selector(UITableViewDataSource.tableView(_:commitEditingStyle:forRowAtIndexPath:))) .filter { a in return UITableViewCellEditingStyle(rawValue: (a[1] as! NSNumber).integerValue) == .Insert } .map { a in return (a[2] as! NSIndexPath) } return ControlEvent(events: source) } /** Reactive wrapper for `delegate` message `tableView:commitEditingStyle:forRowAtIndexPath:`. */ public var rx_itemDeleted: ControlEvent<NSIndexPath> { let source = rx_dataSource.observe(#selector(UITableViewDataSource.tableView(_:commitEditingStyle:forRowAtIndexPath:))) .filter { a in return UITableViewCellEditingStyle(rawValue: (a[1] as! NSNumber).integerValue) == .Delete } .map { a in return (a[2] as! NSIndexPath) } return ControlEvent(events: source) } /** Reactive wrapper for `delegate` message `tableView:moveRowAtIndexPath:toIndexPath:`. */ public var rx_itemMoved: ControlEvent<ItemMovedEvent> { let source: Observable<ItemMovedEvent> = rx_dataSource.observe(#selector(UITableViewDataSource.tableView(_:moveRowAtIndexPath:toIndexPath:))) .map { a in return ((a[1] as! NSIndexPath), (a[2] as! NSIndexPath)) } return ControlEvent(events: source) } /** Reactive wrapper for `delegate` message `tableView:didSelectRowAtIndexPath:`. It can be only used when one of the `rx_itemsWith*` methods is used to bind observable sequence, or any other data source conforming to `SectionedViewDataSourceType` protocol. ``` tableView.rx_modelSelected(MyModel.self) .map { ... ``` */ public func rx_modelSelected<T>(modelType: T.Type) -> ControlEvent<T> { let source: Observable<T> = rx_itemSelected.flatMap { [weak self] indexPath -> Observable<T> in guard let view = self else { return Observable.empty() } return Observable.just(try view.rx_modelAtIndexPath(indexPath)) } return ControlEvent(events: source) } /** Reactive wrapper for `delegate` message `tableView:didDeselectRowAtIndexPath:`. It can be only used when one of the `rx_itemsWith*` methods is used to bind observable sequence, or any other data source conforming to `SectionedViewDataSourceType` protocol. ``` tableView.rx_modelDeselected(MyModel.self) .map { ... ``` */ public func rx_modelDeselected<T>(modelType: T.Type) -> ControlEvent<T> { let source: Observable<T> = rx_itemDeselected.flatMap { [weak self] indexPath -> Observable<T> in guard let view = self else { return Observable.empty() } return Observable.just(try view.rx_modelAtIndexPath(indexPath)) } return ControlEvent(events: source) } /** Synchronous helper method for retrieving a model at indexPath through a reactive data source. */ public func rx_modelAtIndexPath<T>(indexPath: NSIndexPath) throws -> T { let dataSource: SectionedViewDataSourceType = castOrFatalError(self.rx_dataSource.forwardToDelegate(), message: "This method only works in case one of the `rx_items*` methods was used.") let element = try dataSource.modelAtIndexPath(indexPath) return castOrFatalError(element) } } #endif #if os(tvOS) extension UITableView { /** Reactive wrapper for `delegate` message `tableView:didUpdateFocusInContext:withAnimationCoordinator:`. */ public var rx_didUpdateFocusInContextWithAnimationCoordinator: ControlEvent<(context: UIFocusUpdateContext, animationCoordinator: UIFocusAnimationCoordinator)> { let source = rx_delegate.observe(#selector(UITableViewDelegate.tableView(_:didUpdateFocusInContext:withAnimationCoordinator:))) .map { a -> (context: UIFocusUpdateContext, animationCoordinator: UIFocusAnimationCoordinator) in let context = a[1] as! UIFocusUpdateContext let animationCoordinator = a[2] as! UIFocusAnimationCoordinator return (context: context, animationCoordinator: animationCoordinator) } return ControlEvent(events: source) } } #endif
mit
293acd8f47042131bf035db3f40f9f53
36.412371
194
0.646459
5.416418
false
false
false
false
asoderman/Swift-Task
swift-task/SecondViewController.swift
1
2756
import UIKit class SecondViewController: UIViewController, UITextFieldDelegate { var taskManager: TaskManager var titleField: UITextField! var descField: UITextField! override func loadView() { view = UIView(frame: UIScreen.mainScreen().bounds) } init(taskManager: TaskManager) { self.taskManager = taskManager super.init(nibName: nil, bundle: nil) } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. let whiteColor = UIColor.whiteColor() view.backgroundColor = whiteColor // Fixes animation when transitioning to this View // Updates the NavigationController accordingly navigationItem.title = "Add a Task" navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.Plain, target: self, action: Selector("doneButtonTapped")) // Creates the UITextField for the title titleField = UITextField(frame: CGRectMake(40.0, 100.0, 240.0, 34.0)) titleField.placeholder = "Task Title" titleField.borderStyle = UITextBorderStyle.RoundedRect titleField.becomeFirstResponder() titleField.delegate = self self.view.addSubview(titleField) // Creates the UITextField for the description descField = UITextField(frame: CGRectMake(40.0, 175.0, 240.0, 34.0)) descField.placeholder = "Description" descField.borderStyle = UITextBorderStyle.RoundedRect descField.delegate = self self.view.addSubview(descField) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func touchesBegan(touches: NSSet!, withEvent event: UIEvent!) { // Hides keyboard if whitespace is tapped self.view.endEditing(true) } func doneButtonTapped() { if (titleField.text != ""){ self.view.endEditing(true) taskManager.addTask(titleField.text, desc: descField.text) navigationController.popViewControllerAnimated(true) } } // UITextFieldDelegate func textFieldShouldReturn(textField: UITextField!) -> Bool { // Return key behavior -- Moves to next field or hides keyboard depending on context if (textField.placeholder == titleField.placeholder) { descField.becomeFirstResponder() } if (textField.placeholder == descField.placeholder) { textField.resignFirstResponder() } return true } }
mit
d71316f2fc20664a94e4975f7be4d783
31.423529
161
0.640784
5.647541
false
false
false
false
AndreMuis/FiziksFunhouse
FiziksFunhouse/Model/FFHBallNode.swift
1
1306
// // FFHBall.swift // FiziksFunhouse // // Created by Andre Muis on 5/5/16. // Copyright © 2016 Andre Muis. All rights reserved. // import SceneKit class FFHBallNode: SCNNode { required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } init(type: FFHBallType) { super.init() let material: SCNMaterial = SCNMaterial() material.diffuse.contents = type.color material.specular.contents = UIColor.white let geometry: SCNSphere = SCNSphere(radius: type.radius) geometry.materials = [material] self.geometry = geometry let physicsBody: SCNPhysicsBody = SCNPhysicsBody(type: .dynamic, shape: nil) physicsBody.categoryBitMask = type.categoryBitMask physicsBody.contactTestBitMask = Constants.allCategoriesBitMask physicsBody.collisionBitMask = Constants.allCategoriesBitMask physicsBody.mass = pow(type.radius / Constants.ballBaseRadius, 3.0) physicsBody.restitution = 1.0 physicsBody.friction = 0.0 physicsBody.rollingFriction = 0.0 physicsBody.damping = 0.0 physicsBody.angularDamping = 0.0 self.physicsBody = physicsBody } }
mit
c1b26450fbc4410ef9704faf4708123e
19.714286
84
0.62682
4.711191
false
false
false
false
Raizlabs/ios-template
PRODUCTNAME/app/Pods/Anchorage/Source/NSLayoutAnchor+MultiplierConstraints.swift
2
3777
// // NSLayoutAnchor+MultiplierConstraints.swift // Anchorage // // Created by Aleksandr Gusev on 7/21/17. // // Copyright 2016 Raizlabs and other contributors // http://raizlabs.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. #if os(macOS) import Cocoa #else import UIKit #endif extension NSLayoutXAxisAnchor { func constraint(equalTo anchor: NSLayoutXAxisAnchor, multiplier m: CGFloat, constant c: CGFloat = 0.0) -> NSLayoutConstraint { let constraint = self.constraint(equalTo: anchor, constant: c) return constraint.with(multiplier: m) } func constraint(greaterThanOrEqualTo anchor: NSLayoutXAxisAnchor, multiplier m: CGFloat, constant c: CGFloat = 0.0) -> NSLayoutConstraint { let constraint = self.constraint(greaterThanOrEqualTo: anchor, constant: c) return constraint.with(multiplier: m) } func constraint(lessThanOrEqualTo anchor: NSLayoutXAxisAnchor, multiplier m: CGFloat, constant c: CGFloat = 0.0) -> NSLayoutConstraint { let constraint = self.constraint(lessThanOrEqualTo: anchor, constant: c) return constraint.with(multiplier: m) } } extension NSLayoutYAxisAnchor { func constraint(equalTo anchor: NSLayoutYAxisAnchor, multiplier m: CGFloat, constant c: CGFloat = 0.0) -> NSLayoutConstraint { let constraint = self.constraint(equalTo: anchor, constant: c) return constraint.with(multiplier: m) } func constraint(greaterThanOrEqualTo anchor: NSLayoutYAxisAnchor, multiplier m: CGFloat, constant c: CGFloat = 0.0) -> NSLayoutConstraint { let constraint = self.constraint(greaterThanOrEqualTo: anchor, constant: c) return constraint.with(multiplier: m) } func constraint(lessThanOrEqualTo anchor: NSLayoutYAxisAnchor, multiplier m: CGFloat, constant c: CGFloat = 0.0) -> NSLayoutConstraint { let constraint = self.constraint(lessThanOrEqualTo: anchor, constant: c) return constraint.with(multiplier: m) } } private extension NSLayoutConstraint { func with(multiplier: CGFloat) -> NSLayoutConstraint { return NSLayoutConstraint(item: firstItem!, attribute: firstAttribute, relatedBy: relation, toItem: secondItem, attribute: secondAttribute, multiplier: multiplier, constant: constant) } }
mit
3f5d45a58f1e066378e6f3fd7e96597f
40.505495
83
0.651046
5.188187
false
false
false
false
PauloMigAlmeida/Signals
SwiftSignalKit/Atomic.swift
1
804
import Foundation public final class Atomic<T> { private var lock: OSSpinLock = 0 private var value: T public init(value: T) { self.value = value } public func with<R>(f: T -> R) -> R { OSSpinLockLock(&self.lock) let result = f(self.value) OSSpinLockUnlock(&self.lock) return result } public func modify(f: T -> T) -> T { OSSpinLockLock(&self.lock) let result = f(self.value) self.value = result OSSpinLockUnlock(&self.lock) return result } public func swap(value: T) -> T { OSSpinLockLock(&self.lock) let previous = self.value self.value = value OSSpinLockUnlock(&self.lock) return previous } }
mit
1d4f9fe2c96f7726e0cbb5a2cda8612f
21.333333
41
0.538557
4.369565
false
false
false
false
RobotsAndPencils/SwiftCharts
SwiftCharts/AxisValues/ChartAxisValue.swift
1
1666
// // ChartAxisValue.swift // swift_charts // // Created by ischuetz on 01/03/15. // Copyright (c) 2015 ivanschuetz. All rights reserved. // import UIKit /** A ChartAxisValue models a value along a particular chart axis. For example, two ChartAxisValues represent the two components of a ChartPoint. It has a backing Double scalar value, which provides a canonical form for all subclasses to be laid out along an axis. It also has one or more labels that are drawn in the chart. This class is not meant to be instantiated directly. Use one of the existing subclasses or create a new one. */ public class ChartAxisValue: Equatable, CustomStringConvertible { public let scalar: Double public let labelSettings: ChartLabelSettings public var hidden = false /// The labels that will be displayed in the chart public var labels: [ChartAxisLabel] { let axisLabel = ChartAxisLabel(text: self.description, settings: self.labelSettings) axisLabel.hidden = self.hidden return [axisLabel] } public init(scalar: Double, labelSettings: ChartLabelSettings = ChartLabelSettings()) { self.scalar = scalar self.labelSettings = labelSettings } public var copy: ChartAxisValue { return self.copy(self.scalar) } public func copy(scalar: Double) -> ChartAxisValue { return ChartAxisValue(scalar: scalar, labelSettings: self.labelSettings) } // MARK: CustomStringConvertible public var description: String { return String(scalar) } } public func ==(lhs: ChartAxisValue, rhs: ChartAxisValue) -> Bool { return lhs.scalar == rhs.scalar }
apache-2.0
0da0066cc8f0d65b8e5737918423eba9
32.32
321
0.709484
4.828986
false
false
false
false
4jchc/4jchc-AVFundation
02-音乐播放/02-音乐播放/Classes/Other/Tool/XMGLrcTool.swift
1
2822
// // XMGLrcline.swift // 02-音乐播放 // // Created by 蒋进 on 16/3/8. // Copyright © 2016年 蒋进. All rights reserved. // import UIKit class XMGLrcTool: NSObject { /// 根据歌词名称来返回该歌词的对象数组(歌词每一行) class func lrcToolWithLrcName(lrcName:String)->NSArray { // 1.拿到歌词文件的路径 let lrcPath = NSBundle.mainBundle().pathForResource(lrcName, ofType: nil) //承载转换的模型 let tempArr = NSMutableArray() do{ // 2.读取歌词 let lrcString = try String(contentsOfFile: lrcPath!) // 3.拿到歌词的数组 let lrcArr = lrcString.componentsSeparatedByString("\n") // 4.遍历每一句歌词,转成模型 for lrclineString:NSString in lrcArr { if lrclineString.hasPrefix("[ti:") || lrclineString.hasPrefix("[ar:") || lrclineString.hasPrefix("[al:") || !lrclineString.hasPrefix("["){ continue } // 将歌词转成模型 let lrcLine = XMGLrcline.lrcLineWithLrclineString(lrclineString as String) tempArr.addObject(lrcLine) } }catch{ print("这里真的没有了啊") } return tempArr } // static func lrcToolWithLrcName(lrcName:String)->NSArray{ // // // 1.拿到歌词文件的路径 // let lrcPath:String = NSBundle.mainBundle().pathForResource(lrcName, ofType: nil)! // // 2.读取歌词 // // let lrcString:NSString = try! NSString(contentsOfFile: lrcPath, encoding: NSUTF8StringEncoding) // let lrcString:NSString = try! String(contentsOfFile: lrcPath) // // 3.拿到歌词的数组 // let lrcArray:[String] = lrcString.componentsSeparatedByString("\n") // // // 4.遍历每一句歌词,转成模型 // let tempArray = NSMutableArray() // for lrclineString:NSString in lrcArray { // // // 过滤不需要的歌词的行 // if lrclineString.hasPrefix("[ti:") || lrclineString.hasPrefix("[ar:") || lrclineString.hasPrefix("[al:") || !lrclineString.hasPrefix("["){ // // continue // } // // // 拿到每一句歌词 // /* // [ti:心碎了无痕] // [ar:张学友] // [al:] // */ // // 将歌词转成模型 // let lrcLine:XMGLrcline = XMGLrcline.lrcLineWithLrclineString(lrcString as String) // tempArray.addObject(lrcLine) // } // return tempArray; // } }
mit
bf572428f1d69537cd910a4a0394218c
29.817073
156
0.512861
4.082391
false
false
false
false
nheagy/WordPress-iOS
WordPress/Classes/ViewRelated/Me/SettingsCommon.swift
1
1208
import RxSwift protocol SettingsController: ImmuTableController {} // MARK: - Actions extension SettingsController { func editText(changeType: (AccountSettingsChangeWithString), hint: String? = nil, service: AccountSettingsService) -> ImmuTableRowControllerGenerator { return { row in let row = row as! EditableTextRow return self.controllerForEditableText(row, changeType: changeType, hint: hint, service: service) } } func controllerForEditableText(row: EditableTextRow, changeType: (AccountSettingsChangeWithString), hint: String? = nil, isPassword: Bool = false, service: AccountSettingsService) -> SettingsTextViewController { let title = row.title let value = row.value let controller = SettingsTextViewController( text: value, placeholder: "\(title)...", hint: hint, isPassword: isPassword) controller.title = title controller.onValueChanged = { value in let change = changeType(value) service.saveChange(change) DDLogSwift.logDebug("\(title) changed: \(value)") } return controller } }
gpl-2.0
d8f92955baf2eabf2eda142e6887e68c
33.542857
215
0.65149
5.490909
false
false
false
false
lacyrhoades/CasualUX
Transitions/CrossfadeTransition/CrossfadeTransitionViewController.swift
1
2303
// // CrossfadeTransitionViewController.swift // CasualUX // // Created by Lacy Rhoades on 5/24/16. // Copyright © 2016 Lacy Rhoades. All rights reserved. // import UIKit class CrossfadeTransitionViewController: UIViewController { var centerView: UIView! var presentationDelegate: CrossfadeTransitioningDelegate! override func viewDidLoad() { super.viewDidLoad() let backgroundView = UIImageView(image: UIImage(named: "SampleImage")) backgroundView.contentMode = .ScaleAspectFill backgroundView.frame = self.view.bounds backgroundView.autoresizingMask = [UIViewAutoresizing.FlexibleHeight, UIViewAutoresizing.FlexibleWidth] backgroundView.backgroundColor = UIColor.lightGrayColor() self.view.addSubview(backgroundView) self.centerView = UIView() self.centerView.backgroundColor = UIColor.blueColor() self.centerView.translatesAutoresizingMaskIntoConstraints = false self.view.addSubview(self.centerView) let tap = UITapGestureRecognizer(target: self, action: #selector(didTapCenterView)) self.centerView.addGestureRecognizer(tap) self.view.addConstraint(NSLayoutConstraint(item: self.centerView, attribute: .CenterX, relatedBy: .Equal, toItem: self.view, attribute: .CenterX, multiplier: 1, constant: 0)) self.view.addConstraint(NSLayoutConstraint(item: self.centerView, attribute: .CenterY, relatedBy: .Equal, toItem: self.view, attribute: .CenterY, multiplier: 1, constant: 0)) self.view.addConstraint(NSLayoutConstraint(item: self.centerView, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: 200)) self.view.addConstraint(NSLayoutConstraint(item: self.centerView, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: 300)) } func didTapCenterView() { let vc = BlueViewController() vc.modalPresentationStyle = .Custom vc.transitioningDelegate = self.presentationDelegate self.presentViewController(vc, animated: true) { // done } } override func prefersStatusBarHidden() -> Bool { return false } }
mit
7fc3e84f2d342232e50c293bc27f5711
42.433962
184
0.70417
5.09292
false
false
false
false
whitepaperclip/Exsilio-iOS
Exsilio/ActiveTourViewController.swift
1
9961
// // ActiveTourViewController.swift // Exsilio // // Created by Nick Kezhaya on 6/23/16. // // import UIKit import Alamofire import SwiftyJSON import SVProgressHUD import SCLAlertView import CoreLocation import Mapbox class ActiveTourViewController: UIViewController { @IBOutlet var navView: DirectionsHeaderView? @IBOutlet var tabView: TabControlsView? @IBOutlet var mapView: MGLMapView? @IBOutlet var activeWaypointView: ActiveWaypointView? @IBOutlet var navTop: NSLayoutConstraint? @IBOutlet var tabBottom: NSLayoutConstraint? @IBOutlet var activeWaypointTop: NSLayoutConstraint? var tourActive = false var currentStepIndex = 0 var shownWaypointIds = [Int]() var waypointInfoViewVisible = false var startingPoint: CLLocationCoordinate2D? var allStepsCache: [JSON]? var tourJSON: JSON? var directionsJSON: JSON? override func viewDidLoad() { super.viewDidLoad() setNeedsStatusBarAppearanceUpdate() view.isUserInteractionEnabled = false mapView?.logoView.isHidden = true mapView?.attributionButton.isHidden = true SVProgressHUD.show() CurrentTourSingleton.sharedInstance.refreshTour { json in self.tourJSON = json self.drawTour() SVProgressHUD.dismiss() self.view.isUserInteractionEnabled = true } navView?.delegate = self tabView?.delegate = self activeWaypointView?.delegate = self navigationItem.leftBarButtonItem = UIBarButtonItem(image: UI.BackIcon, style: .plain, target: self, action: #selector(dismissModal)) activeWaypointTop?.constant = self.view.frame.height activeWaypointView?.layoutIfNeeded() } func dismissModal() { self.dismiss(animated: true, completion: nil) } func startTour(_ completion: (() -> Void)?) { if let location = self.mapView?.userLocation { SVProgressHUD.show() let params = ["latitude": location.coordinate.latitude, "longitude": location.coordinate.longitude] let id = self.tourJSON!["id"].int! Alamofire.request("\(API.URL)\(API.ToursPath)/\(id)/start", method: .get, parameters: params, headers: API.authHeaders()).responseJSON { response in switch response.result { case .success(let jsonObj): let json = JSON(jsonObj) self.directionsJSON = json MapHelper.drawPath(from: json, withColor: UI.RedColor, mapView: self.mapView!) self.shownWaypointIds = [] self.cacheAllSteps() self.mapView?.delegate = self fallthrough default: SVProgressHUD.dismiss() completion?() } } } else { completion?() } } func updateUIForCurrentStep() { if let currentStep = self.currentStep(), let allStepsCache = self.allStepsCache { self.navView?.updateStep(currentStep) self.tabView?.updateStepIndex(self.currentStepIndex, outOf: allStepsCache.count) } } func currentStep() -> JSON? { guard let allStepsCache = self.allStepsCache , allStepsCache.count > self.currentStepIndex else { return nil } return allStepsCache[self.currentStepIndex] } func currentWaypoint() -> JSON? { let distanceToLocation: ((CLLocation) -> Double?) = { location in if let userLocationCoordinate = self.mapView?.userLocation?.coordinate { let userLocation = CLLocation(latitude: userLocationCoordinate.latitude, longitude: userLocationCoordinate.longitude) return userLocation.distance(from: location) } return nil } if let waypoints = self.tourJSON?["waypoints"].array { let sorted = waypoints.sorted { (a, b) in let latitudeA = a["latitude"].floatValue let latitudeB = b["latitude"].floatValue let longitudeA = a["longitude"].floatValue let longitudeB = b["longitude"].floatValue let locationA = CLLocation(latitude: Double(latitudeA), longitude: Double(longitudeA)) let locationB = CLLocation(latitude: Double(latitudeB), longitude: Double(longitudeB)) return distanceToLocation(locationA) ?? 0.0 < distanceToLocation(locationB) ?? 0.0 } return sorted.first } return nil } func drawTour() { MapHelper.drawTour(tourJSON!, mapView: mapView!) MapHelper.setMapBounds(for: tourJSON!, mapView: mapView!) } @discardableResult func cacheAllSteps() -> [JSON] { if let cache = self.allStepsCache { return cache } var steps: [JSON] = [] let appendToSteps: ((JSON?) -> Void) = { json in guard let json = json else { return } json["routes"][0]["legs"].array?.forEach { leg in leg["steps"].array?.forEach { steps.append($0) } } } appendToSteps(directionsJSON) appendToSteps(tourJSON) allStepsCache = steps return steps } func toggleWaypointInfoView() { if let waypoint = self.currentWaypoint() { navView?.layoutIfNeeded() tabView?.layoutIfNeeded() activeWaypointView?.layoutIfNeeded() if !waypointInfoViewVisible { activeWaypointView?.updateWaypoint(waypoint) } UIView.animate(withDuration: 0.5, animations: { if self.waypointInfoViewVisible { self.navTop?.constant = 0 self.tabBottom?.constant = 0 self.activeWaypointTop?.constant = self.view.frame.height self.waypointInfoViewVisible = false } else { self.navTop?.constant = -self.navView!.frame.height self.tabBottom?.constant = self.navView!.frame.height self.activeWaypointTop?.constant = 30 self.waypointInfoViewVisible = true } self.navView?.layoutIfNeeded() self.tabView?.layoutIfNeeded() self.activeWaypointView?.layoutIfNeeded() self.mapView?.layoutIfNeeded() }) } } override var preferredStatusBarStyle : UIStatusBarStyle { return .default } } extension ActiveTourViewController: TabControlsDelegate { func willChangeTabState(_ state: TabState) { if state == .activeTour { startTour() { self.tourActive = true self.updateUIForCurrentStep() self.mapView?.setUserTrackingMode(.followWithCourse, animated: true) } } else if state == .tourPreview { tourActive = false MapHelper.setMapBounds(for: tourJSON!, mapView: mapView!) mapView?.clear() allStepsCache = nil drawTour() } } func willMoveToNextStep() { if allStepsCache == nil || currentStepIndex == allStepsCache!.count { return } currentStepIndex += 1 updateUIForCurrentStep() } func willMoveToPreviousStep() { if currentStepIndex == 0 { return } currentStepIndex -= 1 updateUIForCurrentStep() } func willDisplayWaypointInfo() { activeWaypointView?.sticky = true toggleWaypointInfoView() } } extension ActiveTourViewController: ActiveWaypointViewDelegate { func activeWaypointViewWillBeDismissed() { self.toggleWaypointInfoView() } } extension ActiveTourViewController: DirectionsHeaderDelegate { func willDismissFromHeader() { self.dismissModal() } } extension ActiveTourViewController: MGLMapViewDelegate { func mapView(_ mapView: MGLMapView, didUpdate userLocation: MGLUserLocation?) { guard let userLocation = userLocation else { return } let location = CLLocation(latitude: userLocation.coordinate.latitude, longitude: userLocation.coordinate.longitude) if let step = currentStep(), let latitude = step["end_location"]["lat"].float, let longitude = step["end_location"]["lng"].float { let endLocation = CLLocation(latitude: Double(latitude), longitude: Double(longitude)) let distanceMeters = location.distance(from: endLocation) if distanceMeters < 10 { self.tabView?.forwardButtonTapped() } } // Are we close to a waypoint? guard let waypoints = self.tourJSON?["waypoints"].array else { return } for waypoint in waypoints { if let latitude = waypoint["latitude"].float, let longitude = waypoint["longitude"].float { let waypointLocation = CLLocation(latitude: Double(latitude), longitude: Double(longitude)) let distanceMeters = location.distance(from: waypointLocation) if let shownWaypointIndex = shownWaypointIds.index(of: waypoint["id"].intValue) { if distanceMeters >= 50 { shownWaypointIds.remove(at: shownWaypointIndex) } else { continue } } if (distanceMeters < 15 && !waypointInfoViewVisible) || (distanceMeters > 30 && waypointInfoViewVisible && activeWaypointView?.sticky != true) { shownWaypointIds.append(waypoint["id"].intValue) willDisplayWaypointInfo() return } } } } }
mit
b3c9d99412c1f70d09f3fc0fd9fe288a
32.880952
160
0.595723
5.470071
false
false
false
false
Virpik/T
src/CoreData/TCoreData.swift
1
4646
// // tCoreData.swift // // Created by Virpik on 24/12/15. // Copyright © 2015 Virpik. All rights reserved. // import Foundation import CoreData public class TCoreDataManager: NSObject { public private(set) var defaultContext: NSManagedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType) public private(set) var nameDB: String public private(set) var sqliteName: String public private(set) var bundle: Bundle public var url: URL { return self.applicationDocumentsDirectory.appendingPathComponent(self.sqliteName) } private var applicationDocumentsDirectory: URL { let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask) return urls[urls.count-1] } public init(dbName name: String, sqliteName: String = "SingleViewCoreData", bundle: Bundle = Bundle.main, drop: Bool = false) { self.nameDB = name self.sqliteName = sqliteName + ".sqlite" self.bundle = bundle super.init() if drop { print(""" !!!!!!!!!!!!!!!!!!!!!!!!! Drop Core Data !!!!!!!!!!!!!!!!!!!!!!!!! """) self.drop() } self.defaultContext = self.managedObjectContext(name: name) } public func update() { self.defaultContext = self.managedObjectContext(name: self.nameDB) } /// public func updateContext(managedObjectContext: AnyObject?) { /// if let context = managedObjectContext as? NSManagedObjectContext { /// self.defaultContext = self.managedObjectContext(name: self.nameDB, managedObjectContext: context) /// self.saveContext() /// } /// } private func managedObjectModelWithName(name: String, bundle: Bundle) -> NSManagedObjectModel { let modelURL = bundle.url(forResource: name, withExtension: "momd")! return NSManagedObjectModel(contentsOf: modelURL)! } private func persistentStoreCoordinatorWithName(name: String) -> NSPersistentStoreCoordinator { let managedObjectMode = self.managedObjectModelWithName(name: name, bundle: self.bundle) let coordinator = NSPersistentStoreCoordinator(managedObjectModel: managedObjectMode) let options = [ NSMigratePersistentStoresAutomaticallyOption: true, NSInferMappingModelAutomaticallyOption: true, NSSQLitePragmasOption: ["journal_mode": "WAL"] ] as [String : Any] do { try coordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: self.url, options: options) } catch { let failureReason = "There was an error creating or loading the application's saved data." var dict = [String: AnyObject]() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" as AnyObject dict[NSLocalizedFailureReasonErrorKey] = failureReason as AnyObject dict[NSUnderlyingErrorKey] = error as NSError let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)") abort() } return coordinator } private func managedObjectContext(name: String, managedObjectContext: NSManagedObjectContext? = nil) -> NSManagedObjectContext { let coordinator = self.persistentStoreCoordinatorWithName(name: name) let managedObjectContext = managedObjectContext ?? NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType) managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext } public func drop() { do { let _ = try FileManager.default.removeItem(at: self.url) } catch { print(#function, error) } self.defaultContext = self.managedObjectContext(name: self.nameDB) } public func saveContext () { let context = self.defaultContext if !context.hasChanges { return } DispatchQueue.main.async { do { try context.save() NSLog("context.save() try") } catch { let nserror = error as NSError NSLog("Unresolved error \(nserror), \(nserror.userInfo)") abort() } } } }
mit
be5fa86af58ae6321857ee323216b267
32.178571
135
0.616146
5.643985
false
false
false
false
apple/swift-nio
Sources/NIOPerformanceTester/SchedulingAndRunningBenchmark.swift
1
1769
//===----------------------------------------------------------------------===// // // This source file is part of the SwiftNIO open source project // // Copyright (c) 2021 Apple Inc. and the SwiftNIO project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of SwiftNIO project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// import Foundation import NIOCore import NIOPosix final class SchedulingAndRunningBenchmark: Benchmark { private var group: MultiThreadedEventLoopGroup! private var loop: EventLoop! private var dg: DispatchGroup! private var counter = 0 private let numTasks: Int init(numTasks: Int) { self.numTasks = numTasks } func setUp() throws { group = MultiThreadedEventLoopGroup(numberOfThreads: 1) loop = group.next() dg = DispatchGroup() // We are preheating the EL to avoid growing the `ScheduledTask` `PriorityQueue` // during the actual test try! self.loop.submit { var counter: Int = 0 for _ in 0..<self.numTasks { self.loop.scheduleTask(in: .nanoseconds(0)) { counter &+= 1 } } }.wait() } func tearDown() { } func run() -> Int { try! self.loop.submit { for _ in 0..<self.numTasks { self.dg.enter() self.loop.scheduleTask(in: .nanoseconds(0)) { self.counter &+= 1 self.dg.leave() } } }.wait() self.dg.wait() return counter } }
apache-2.0
7ce80938fa61a5f3779dbba1c948dee0
26.215385
88
0.519503
4.941341
false
false
false
false
LKY769215561/KYHandMade
KYHandMade/KYHandMade/Class/Other(其他)/KYProtocolFile.swift
1
2426
// // KYProtocolFile.swift // KYHandMade // // Created by Kerain on 2017/7/13. // Copyright © 2017年 广州市九章信息科技有限公司. All rights reserved. // import Foundation import Alamofire import SwiftyJSON // 从xib 中加载 view protocol Nibloadable {} // 限定UIView的子类才能共享这个方法 extension Nibloadable where Self : UIView{ // 协议或者结构体中如果要使用类方式 不用class 用static static func loadFromNib(nibname : String? = nil) -> Self{ let nib = nibname ?? "\(self)" return Bundle.main.loadNibNamed(nib, owner: nil, options: nil)?.first as! Self } } // 限定UIViewController的子类才能共享这个方法 extension Nibloadable where Self : UIViewController{ static func loadFromNib() -> Self { return Self(nibName:"\(self)" , bundle :nil) } } protocol Reusable { static var reusableIdentifier : String {get} } // UITableViewCell需遵守的协议 extension Reusable{ static var reusableIdentifier : String { return "\(self)" + "Id" } } protocol Requestable { var URLString : String {get} var type : HTTPMethod {get} var parametes : [String : Any]{get} associatedtype ResultData var data : ResultData {set get} func parseResult(_ result : Any) } extension Requestable{ // func requestData(_ finished : @escaping NetworkFinished) -> Void { // // let method = type == .get ? HTTPMethod.get : HTTPMethod.post // Alamofire.request(URLString, method: method, parameters: parametes).responseJSON { (response : DataResponse<Any>) in // guard let result = response.result.value else { // KYProgressHUD.showErrorWithStatus("失败了,赶紧跑") // return // } // finished(true, JSON(result), nil) // } // } func requestData(_ finished : @escaping ()->()) -> Void { let method = type == .get ? HTTPMethod.get : HTTPMethod.post Alamofire.request(URLString, method: method, parameters: parametes).responseJSON { (response : DataResponse<Any>) in guard let result = response.result.value else { KYProgressHUD.showErrorWithStatus("失败了,赶紧跑") return } self.parseResult(result) finished() } } }
apache-2.0
5042fd7ea14f70f51d2d6c07a15e120f
23.597826
126
0.613345
4.137112
false
false
false
false
balitm/Sherpany
Sherpany/JsonDataProcessor.swift
1
3081
// // JsonDataProcessor.swift // Sherpany // // Created by Balázs Kilvády on 3/31/16. // Copyright © 2016 kil-dev. All rights reserved. // import Foundation class JsonDataProcessor: DataProcessorProtocol { func processUsers(data: NSData) -> [UserData]? { do { let users = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? [[String: AnyObject]] var result = [UserData]() for item in users! { var userData = UserData() if let userId = item["id"] as? Int { userData.userId = Int16(userId) } if let name = item["name"] as? String { userData.name = name } if let email = item["email"] as? String { userData.email = email } if let company = item["company"] as? [String:String] { if let catchPhrase = company["catchPhrase"] { userData.catchPhrase = catchPhrase } } result.append(userData) } return result } catch { } return nil; } func processAlbums(data: NSData) -> [AlbumData]? { do { let albums = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? [[String: AnyObject]] var result = [AlbumData]() for item in albums! { var album = AlbumData() if let albumId = item["id"] as? Int { album.albumId = Int16(albumId) } if let userId = item["userId"] as? Int { album.userId = Int16(userId) } if let title = item["title"] as? String { album.title = title } result.append(album) } return result } catch { } return nil; } func processPhotos(data: NSData) -> [PhotoData]? { do { let photos = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? [[String: AnyObject]] var result = [PhotoData]() for item in photos! { var photo = PhotoData() if let photoId = item["id"] as? Int { photo.photoId = Int16(photoId) } if let albumId = item["albumId"] as? Int { photo.albumId = Int16(albumId) } if let title = item["title"] as? String { photo.title = title } if let thumbnailUrl = item["thumbnailUrl"] as? String { photo.thumbnailUrl = thumbnailUrl } result.append(photo) } return result } catch { } return nil; } // Idle function for the template. func processPictureData(data: NSData) -> NSData { return data; } }
mit
2411683786744d852088e43780496faf
32.107527
112
0.465887
5.029412
false
false
false
false
Raizlabs/Shift
Shift-Demo/Shift-Demo/Shift/UIWindow+Screenshot.swift
1
3441
// // UIWindow+Screenshot.swift // Shift // // Created by Matthew Buckley on 12/10/15. // Copyright © 2015 Raizlabs. All rights reserved. // import Foundation import UIKit extension UIWindow { public class func screenShot() -> UIImage { // Store current device orientation let orientation: UIInterfaceOrientation = UIApplication.sharedApplication().statusBarOrientation // Generate image size depending on device orientation let imageSize: CGSize = UIInterfaceOrientationIsPortrait(orientation) ? UIScreen.mainScreen().bounds.size : CGSizeMake(UIScreen.mainScreen().bounds.size.height, UIScreen.mainScreen().bounds.size.width) UIGraphicsBeginImageContextWithOptions(imageSize, false, UIScreen.mainScreen().scale) let context: CGContextRef? = UIGraphicsGetCurrentContext() if let context = context { for window in UIApplication.sharedApplication().windows { // Save the current graphics state CGContextSaveGState(context) // Move the graphics context to the center of the window CGContextTranslateCTM(context, window.center.x, window.center.y) CGContextConcatCTM(context, window.transform) // Move the graphics context left and up CGContextTranslateCTM(context, -window.bounds.size.width * window.layer.anchorPoint.x, -window.bounds.size.height * window.layer.anchorPoint.y) let pi_2: CGFloat = CGFloat(M_PI_2) let pi: CGFloat = CGFloat(M_PI) switch (orientation) { case UIInterfaceOrientation.LandscapeLeft: // Rotate graphics context 90 degrees clockwise CGContextRotateCTM(context, pi_2) // Move graphics context up CGContextTranslateCTM(context, 0, -imageSize.width) break case UIInterfaceOrientation.LandscapeRight: // Rotate graphics context 90 degrees counter-clockwise CGContextRotateCTM(context, -pi_2) // Move graphics context left CGContextTranslateCTM(context, -imageSize.height, 0) break case UIInterfaceOrientation.PortraitUpsideDown: // Rotate graphics context 180 degrees CGContextRotateCTM(context, pi) // Move graphics context left and up CGContextTranslateCTM(context, -imageSize.width, -imageSize.height) break default: break } // draw view hierarchy or render if (window.respondsToSelector(Selector("drawViewHierarchyInRect:"))) { window.drawViewHierarchyInRect(window.bounds, afterScreenUpdates: true) } else { window.layer.renderInContext(context) } CGContextRestoreGState(context) } } else { // Log an error message in case of failure print("unable to get current graphics context") } // Grab rendered image let image: UIImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image } }
mit
56e99ba2668bbb06f2b4893854a27c21
37.651685
209
0.596221
6.209386
false
false
false
false
stephencelis/SQLite.swift
Sources/SQLite/Typed/Schema.swift
1
26122
// // SQLite.swift // https://github.com/stephencelis/SQLite.swift // Copyright © 2014-2015 Stephen Celis. // // 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. // extension SchemaType { // MARK: - DROP TABLE / VIEW / VIRTUAL TABLE public func drop(ifExists: Bool = false) -> String { drop("TABLE", tableName(), ifExists) } } extension Table { // MARK: - CREATE TABLE public func create(temporary: Bool = false, ifNotExists: Bool = false, withoutRowid: Bool = false, block: (TableBuilder) -> Void) -> String { let builder = TableBuilder() block(builder) let clauses: [Expressible?] = [ create(Table.identifier, tableName(), temporary ? .temporary : nil, ifNotExists), "".wrap(builder.definitions) as Expression<Void>, withoutRowid ? Expression<Void>(literal: "WITHOUT ROWID") : nil ] return " ".join(clauses.compactMap { $0 }).asSQL() } public func create(_ query: QueryType, temporary: Bool = false, ifNotExists: Bool = false) -> String { let clauses: [Expressible?] = [ create(Table.identifier, tableName(), temporary ? .temporary : nil, ifNotExists), Expression<Void>(literal: "AS"), query ] return " ".join(clauses.compactMap { $0 }).asSQL() } // MARK: - ALTER TABLE … ADD COLUMN public func addColumn<V: Value>(_ name: Expression<V>, check: Expression<Bool>? = nil, defaultValue: V) -> String { addColumn(definition(name, V.declaredDatatype, nil, false, false, check, defaultValue, nil, nil)) } public func addColumn<V: Value>(_ name: Expression<V>, check: Expression<Bool?>, defaultValue: V) -> String { addColumn(definition(name, V.declaredDatatype, nil, false, false, check, defaultValue, nil, nil)) } public func addColumn<V: Value>(_ name: Expression<V?>, check: Expression<Bool>? = nil, defaultValue: V? = nil) -> String { addColumn(definition(name, V.declaredDatatype, nil, true, false, check, defaultValue, nil, nil)) } public func addColumn<V: Value>(_ name: Expression<V?>, check: Expression<Bool?>, defaultValue: V? = nil) -> String { addColumn(definition(name, V.declaredDatatype, nil, true, false, check, defaultValue, nil, nil)) } public func addColumn<V: Value>(_ name: Expression<V>, unique: Bool = false, check: Expression<Bool>? = nil, references table: QueryType, _ other: Expression<V>) -> String where V.Datatype == Int64 { addColumn(definition(name, V.declaredDatatype, nil, false, unique, check, nil, (table, other), nil)) } public func addColumn<V: Value>(_ name: Expression<V>, unique: Bool = false, check: Expression<Bool?>, references table: QueryType, _ other: Expression<V>) -> String where V.Datatype == Int64 { addColumn(definition(name, V.declaredDatatype, nil, false, unique, check, nil, (table, other), nil)) } public func addColumn<V: Value>(_ name: Expression<V?>, unique: Bool = false, check: Expression<Bool>? = nil, references table: QueryType, _ other: Expression<V>) -> String where V.Datatype == Int64 { addColumn(definition(name, V.declaredDatatype, nil, true, unique, check, nil, (table, other), nil)) } public func addColumn<V: Value>(_ name: Expression<V?>, unique: Bool = false, check: Expression<Bool?>, references table: QueryType, _ other: Expression<V>) -> String where V.Datatype == Int64 { addColumn(definition(name, V.declaredDatatype, nil, true, unique, check, nil, (table, other), nil)) } public func addColumn<V: Value>(_ name: Expression<V>, check: Expression<Bool>? = nil, defaultValue: V, collate: Collation) -> String where V.Datatype == String { addColumn(definition(name, V.declaredDatatype, nil, false, false, check, defaultValue, nil, collate)) } public func addColumn<V: Value>(_ name: Expression<V>, check: Expression<Bool?>, defaultValue: V, collate: Collation) -> String where V.Datatype == String { addColumn(definition(name, V.declaredDatatype, nil, false, false, check, defaultValue, nil, collate)) } public func addColumn<V: Value>(_ name: Expression<V?>, check: Expression<Bool>? = nil, defaultValue: V? = nil, collate: Collation) -> String where V.Datatype == String { addColumn(definition(name, V.declaredDatatype, nil, true, false, check, defaultValue, nil, collate)) } public func addColumn<V: Value>(_ name: Expression<V?>, check: Expression<Bool?>, defaultValue: V? = nil, collate: Collation) -> String where V.Datatype == String { addColumn(definition(name, V.declaredDatatype, nil, true, false, check, defaultValue, nil, collate)) } fileprivate func addColumn(_ expression: Expressible) -> String { " ".join([ Expression<Void>(literal: "ALTER TABLE"), tableName(), Expression<Void>(literal: "ADD COLUMN"), expression ]).asSQL() } // MARK: - ALTER TABLE … RENAME TO public func rename(_ to: Table) -> String { rename(to: to) } // MARK: - CREATE INDEX public func createIndex(_ columns: Expressible..., unique: Bool = false, ifNotExists: Bool = false) -> String { let clauses: [Expressible?] = [ create("INDEX", indexName(columns), unique ? .unique : nil, ifNotExists), Expression<Void>(literal: "ON"), tableName(qualified: false), "".wrap(columns) as Expression<Void> ] return " ".join(clauses.compactMap { $0 }).asSQL() } // MARK: - DROP INDEX public func dropIndex(_ columns: Expressible..., ifExists: Bool = false) -> String { drop("INDEX", indexName(columns), ifExists) } fileprivate func indexName(_ columns: [Expressible]) -> Expressible { let string = (["index", clauses.from.name, "on"] + columns.map { $0.expression.template }).joined(separator: " ").lowercased() let index = string.reduce("") { underscored, character in guard character != "\"" else { return underscored } guard "a"..."z" ~= character || "0"..."9" ~= character else { return underscored + "_" } return underscored + String(character) } return database(namespace: index) } } extension View { // MARK: - CREATE VIEW public func create(_ query: QueryType, temporary: Bool = false, ifNotExists: Bool = false) -> String { let clauses: [Expressible?] = [ create(View.identifier, tableName(), temporary ? .temporary : nil, ifNotExists), Expression<Void>(literal: "AS"), query ] return " ".join(clauses.compactMap { $0 }).asSQL() } // MARK: - DROP VIEW public func drop(ifExists: Bool = false) -> String { drop("VIEW", tableName(), ifExists) } } extension VirtualTable { // MARK: - CREATE VIRTUAL TABLE public func create(_ using: Module, ifNotExists: Bool = false) -> String { let clauses: [Expressible?] = [ create(VirtualTable.identifier, tableName(), nil, ifNotExists), Expression<Void>(literal: "USING"), using ] return " ".join(clauses.compactMap { $0 }).asSQL() } // MARK: - ALTER TABLE … RENAME TO public func rename(_ to: VirtualTable) -> String { rename(to: to) } } public final class TableBuilder { fileprivate var definitions = [Expressible]() public func column<V: Value>(_ name: Expression<V>, unique: Bool = false, check: Expression<Bool>? = nil, defaultValue: Expression<V>? = nil) { column(name, V.declaredDatatype, nil, false, unique, check, defaultValue, nil, nil) } public func column<V: Value>(_ name: Expression<V>, unique: Bool = false, check: Expression<Bool>? = nil, defaultValue: V) { column(name, V.declaredDatatype, nil, false, unique, check, defaultValue, nil, nil) } public func column<V: Value>(_ name: Expression<V>, unique: Bool = false, check: Expression<Bool?>, defaultValue: Expression<V>? = nil) { column(name, V.declaredDatatype, nil, false, unique, check, defaultValue, nil, nil) } public func column<V: Value>(_ name: Expression<V>, unique: Bool = false, check: Expression<Bool?>, defaultValue: V) { column(name, V.declaredDatatype, nil, false, unique, check, defaultValue, nil, nil) } public func column<V: Value>(_ name: Expression<V?>, unique: Bool = false, check: Expression<Bool>? = nil, defaultValue: Expression<V>? = nil) { column(name, V.declaredDatatype, nil, true, unique, check, defaultValue, nil, nil) } public func column<V: Value>(_ name: Expression<V?>, unique: Bool = false, check: Expression<Bool>? = nil, defaultValue: Expression<V?>) { column(name, V.declaredDatatype, nil, true, unique, check, defaultValue, nil, nil) } public func column<V: Value>(_ name: Expression<V?>, unique: Bool = false, check: Expression<Bool>? = nil, defaultValue: V) { column(name, V.declaredDatatype, nil, true, unique, check, defaultValue, nil, nil) } public func column<V: Value>(_ name: Expression<V?>, unique: Bool = false, check: Expression<Bool?>, defaultValue: Expression<V>? = nil) { column(name, V.declaredDatatype, nil, true, unique, check, defaultValue, nil, nil) } public func column<V: Value>(_ name: Expression<V?>, unique: Bool = false, check: Expression<Bool?>, defaultValue: Expression<V?>) { column(name, V.declaredDatatype, nil, true, unique, check, defaultValue, nil, nil) } public func column<V: Value>(_ name: Expression<V?>, unique: Bool = false, check: Expression<Bool?>, defaultValue: V) { column(name, V.declaredDatatype, nil, true, unique, check, defaultValue, nil, nil) } public func column<V: Value>(_ name: Expression<V>, primaryKey: Bool, check: Expression<Bool>? = nil, defaultValue: Expression<V>? = nil) { column(name, V.declaredDatatype, primaryKey ? .default : nil, false, false, check, defaultValue, nil, nil) } public func column<V: Value>(_ name: Expression<V>, primaryKey: Bool, check: Expression<Bool?>, defaultValue: Expression<V>? = nil) { column(name, V.declaredDatatype, primaryKey ? .default : nil, false, false, check, defaultValue, nil, nil) } public func column<V: Value>(_ name: Expression<V>, primaryKey: PrimaryKey, check: Expression<Bool>? = nil) where V.Datatype == Int64 { column(name, V.declaredDatatype, primaryKey, false, false, check, nil, nil, nil) } public func column<V: Value>(_ name: Expression<V>, primaryKey: PrimaryKey, check: Expression<Bool?>) where V.Datatype == Int64 { column(name, V.declaredDatatype, primaryKey, false, false, check, nil, nil, nil) } public func column<V: Value>(_ name: Expression<V>, unique: Bool = false, check: Expression<Bool>? = nil, references table: QueryType, _ other: Expression<V>) where V.Datatype == Int64 { column(name, V.declaredDatatype, nil, false, unique, check, nil, (table, other), nil) } public func column<V: Value>(_ name: Expression<V>, unique: Bool = false, check: Expression<Bool?>, references table: QueryType, _ other: Expression<V>) where V.Datatype == Int64 { column(name, V.declaredDatatype, nil, false, unique, check, nil, (table, other), nil) } public func column<V: Value>(_ name: Expression<V?>, unique: Bool = false, check: Expression<Bool>? = nil, references table: QueryType, _ other: Expression<V>) where V.Datatype == Int64 { column(name, V.declaredDatatype, nil, true, unique, check, nil, (table, other), nil) } public func column<V: Value>(_ name: Expression<V?>, unique: Bool = false, check: Expression<Bool?>, references table: QueryType, _ other: Expression<V>) where V.Datatype == Int64 { column(name, V.declaredDatatype, nil, true, unique, check, nil, (table, other), nil) } public func column<V: Value>(_ name: Expression<V>, primaryKey: Bool, check: Expression<Bool>? = nil, references table: QueryType, _ other: Expression<V>) where V.Datatype == Int64 { column(name, V.declaredDatatype, primaryKey ? .default : nil, false, false, check, nil, (table, other), nil) } public func column<V: Value>(_ name: Expression<V>, primaryKey: Bool, check: Expression<Bool?>, references table: QueryType, _ other: Expression<V>) where V.Datatype == Int64 { column(name, V.declaredDatatype, primaryKey ? .default : nil, false, false, check, nil, (table, other), nil) } public func column<V: Value>(_ name: Expression<V?>, primaryKey: Bool, check: Expression<Bool>? = nil, references table: QueryType, _ other: Expression<V>) where V.Datatype == Int64 { column(name, V.declaredDatatype, primaryKey ? .default : nil, true, false, check, nil, (table, other), nil) } public func column<V: Value>(_ name: Expression<V?>, primaryKey: Bool, check: Expression<Bool?>, references table: QueryType, _ other: Expression<V>) where V.Datatype == Int64 { column(name, V.declaredDatatype, primaryKey ? .default : nil, true, false, check, nil, (table, other), nil) } public func column<V: Value>(_ name: Expression<V>, unique: Bool = false, check: Expression<Bool>? = nil, defaultValue: Expression<V>? = nil, collate: Collation) where V.Datatype == String { column(name, V.declaredDatatype, nil, false, unique, check, defaultValue, nil, collate) } public func column<V: Value>(_ name: Expression<V>, unique: Bool = false, check: Expression<Bool>? = nil, defaultValue: V, collate: Collation) where V.Datatype == String { column(name, V.declaredDatatype, nil, false, unique, check, defaultValue, nil, collate) } public func column<V: Value>(_ name: Expression<V>, unique: Bool = false, check: Expression<Bool?>, defaultValue: Expression<V>? = nil, collate: Collation) where V.Datatype == String { column(name, V.declaredDatatype, nil, false, unique, check, defaultValue, nil, collate) } public func column<V: Value>(_ name: Expression<V>, unique: Bool = false, check: Expression<Bool?>, defaultValue: V, collate: Collation) where V.Datatype == String { column(name, V.declaredDatatype, nil, false, unique, check, defaultValue, nil, collate) } public func column<V: Value>(_ name: Expression<V?>, unique: Bool = false, check: Expression<Bool>? = nil, defaultValue: Expression<V>? = nil, collate: Collation) where V.Datatype == String { column(name, V.declaredDatatype, nil, true, unique, check, defaultValue, nil, collate) } public func column<V: Value>(_ name: Expression<V?>, unique: Bool = false, check: Expression<Bool>? = nil, defaultValue: Expression<V?>, collate: Collation) where V.Datatype == String { column(name, V.declaredDatatype, nil, true, unique, check, defaultValue, nil, collate) } public func column<V: Value>(_ name: Expression<V?>, unique: Bool = false, check: Expression<Bool>? = nil, defaultValue: V, collate: Collation) where V.Datatype == String { column(name, V.declaredDatatype, nil, true, unique, check, defaultValue, nil, collate) } public func column<V: Value>(_ name: Expression<V?>, unique: Bool = false, check: Expression<Bool?>, defaultValue: Expression<V>? = nil, collate: Collation) where V.Datatype == String { column(name, V.declaredDatatype, nil, true, unique, check, defaultValue, nil, collate) } public func column<V: Value>(_ name: Expression<V?>, unique: Bool = false, check: Expression<Bool?>, defaultValue: Expression<V?>, collate: Collation) where V.Datatype == String { column(name, V.declaredDatatype, nil, true, unique, check, defaultValue, nil, collate) } public func column<V: Value>(_ name: Expression<V?>, unique: Bool = false, check: Expression<Bool?>, defaultValue: V, collate: Collation) where V.Datatype == String { column(name, V.declaredDatatype, nil, true, unique, check, defaultValue, nil, collate) } // swiftlint:disable:next function_parameter_count fileprivate func column(_ name: Expressible, _ datatype: String, _ primaryKey: PrimaryKey?, _ null: Bool, _ unique: Bool, _ check: Expressible?, _ defaultValue: Expressible?, _ references: (QueryType, Expressible)?, _ collate: Collation?) { definitions.append(definition(name, datatype, primaryKey, null, unique, check, defaultValue, references, collate)) } // MARK: - public func primaryKey<T: Value>(_ column: Expression<T>) { primaryKey([column]) } public func primaryKey<T: Value, U: Value>(_ compositeA: Expression<T>, _ expr: Expression<U>) { primaryKey([compositeA, expr]) } public func primaryKey<T: Value, U: Value, V: Value>(_ compositeA: Expression<T>, _ expr1: Expression<U>, _ expr2: Expression<V>) { primaryKey([compositeA, expr1, expr2]) } public func primaryKey<T: Value, U: Value, V: Value, W: Value>(_ compositeA: Expression<T>, _ expr1: Expression<U>, _ expr2: Expression<V>, _ expr3: Expression<W>) { primaryKey([compositeA, expr1, expr2, expr3]) } fileprivate func primaryKey(_ composite: [Expressible]) { definitions.append("PRIMARY KEY".prefix(composite)) } public func unique(_ columns: Expressible...) { unique(columns) } public func unique(_ columns: [Expressible]) { definitions.append("UNIQUE".prefix(columns)) } public func check(_ condition: Expression<Bool>) { check(Expression<Bool?>(condition)) } public func check(_ condition: Expression<Bool?>) { definitions.append("CHECK".prefix(condition)) } public enum Dependency: String { case noAction = "NO ACTION" case restrict = "RESTRICT" case setNull = "SET NULL" case setDefault = "SET DEFAULT" case cascade = "CASCADE" } public func foreignKey<T: Value>(_ column: Expression<T>, references table: QueryType, _ other: Expression<T>, update: Dependency? = nil, delete: Dependency? = nil) { foreignKey(column, (table, other), update, delete) } public func foreignKey<T: Value>(_ column: Expression<T?>, references table: QueryType, _ other: Expression<T>, update: Dependency? = nil, delete: Dependency? = nil) { foreignKey(column, (table, other), update, delete) } public func foreignKey<T: Value, U: Value>(_ composite: (Expression<T>, Expression<U>), references table: QueryType, _ other: (Expression<T>, Expression<U>), update: Dependency? = nil, delete: Dependency? = nil) { let composite = ", ".join([composite.0, composite.1]) let references = (table, ", ".join([other.0, other.1])) foreignKey(composite, references, update, delete) } public func foreignKey<T: Value, U: Value, V: Value>(_ composite: (Expression<T>, Expression<U>, Expression<V>), references table: QueryType, _ other: (Expression<T>, Expression<U>, Expression<V>), update: Dependency? = nil, delete: Dependency? = nil) { let composite = ", ".join([composite.0, composite.1, composite.2]) let references = (table, ", ".join([other.0, other.1, other.2])) foreignKey(composite, references, update, delete) } fileprivate func foreignKey(_ column: Expressible, _ references: (QueryType, Expressible), _ update: Dependency?, _ delete: Dependency?) { let clauses: [Expressible?] = [ "FOREIGN KEY".prefix(column), reference(references), update.map { Expression<Void>(literal: "ON UPDATE \($0.rawValue)") }, delete.map { Expression<Void>(literal: "ON DELETE \($0.rawValue)") } ] definitions.append(" ".join(clauses.compactMap { $0 })) } } public enum PrimaryKey { case `default` case autoincrement } public struct Module { fileprivate let name: String fileprivate let arguments: [Expressible] public init(_ name: String, _ arguments: [Expressible]) { self.init(name: name.quote(), arguments: arguments) } init(name: String, arguments: [Expressible]) { self.name = name self.arguments = arguments } } extension Module: Expressible { public var expression: Expression<Void> { name.wrap(arguments) } } // MARK: - Private private extension QueryType { func create(_ identifier: String, _ name: Expressible, _ modifier: Modifier?, _ ifNotExists: Bool) -> Expressible { let clauses: [Expressible?] = [ Expression<Void>(literal: "CREATE"), modifier.map { Expression<Void>(literal: $0.rawValue) }, Expression<Void>(literal: identifier), ifNotExists ? Expression<Void>(literal: "IF NOT EXISTS") : nil, name ] return " ".join(clauses.compactMap { $0 }) } func rename(to: Self) -> String { " ".join([ Expression<Void>(literal: "ALTER TABLE"), tableName(), Expression<Void>(literal: "RENAME TO"), Expression<Void>(to.clauses.from.name) ]).asSQL() } func drop(_ identifier: String, _ name: Expressible, _ ifExists: Bool) -> String { let clauses: [Expressible?] = [ Expression<Void>(literal: "DROP \(identifier)"), ifExists ? Expression<Void>(literal: "IF EXISTS") : nil, name ] return " ".join(clauses.compactMap { $0 }).asSQL() } } // swiftlint:disable:next function_parameter_count private func definition(_ column: Expressible, _ datatype: String, _ primaryKey: PrimaryKey?, _ null: Bool, _ unique: Bool, _ check: Expressible?, _ defaultValue: Expressible?, _ references: (QueryType, Expressible)?, _ collate: Collation?) -> Expressible { let clauses: [Expressible?] = [ column, Expression<Void>(literal: datatype), primaryKey.map { Expression<Void>(literal: $0 == .autoincrement ? "PRIMARY KEY AUTOINCREMENT" : "PRIMARY KEY") }, null ? nil : Expression<Void>(literal: "NOT NULL"), unique ? Expression<Void>(literal: "UNIQUE") : nil, check.map { " ".join([Expression<Void>(literal: "CHECK"), $0]) }, defaultValue.map { "DEFAULT".prefix($0) }, references.map(reference), collate.map { " ".join([Expression<Void>(literal: "COLLATE"), $0]) } ] return " ".join(clauses.compactMap { $0 }) } private func reference(_ primary: (QueryType, Expressible)) -> Expressible { " ".join([ Expression<Void>(literal: "REFERENCES"), primary.0.tableName(qualified: false), "".wrap(primary.1) as Expression<Void> ]) } private enum Modifier: String { case unique = "UNIQUE" case temporary = "TEMPORARY" }
mit
cabce5b373eebb7e4db28c8280ed1929
43.038786
134
0.59215
4.471747
false
false
false
false
Rajat-Dhasmana/wain
Wain/Wain/AppDelegate.swift
1
4587
// // AppDelegate.swift // Wain // // Created by Rajat Dhasmana on 03/03/17. // Copyright © 2017 appinventiv. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var persistentContainer: NSPersistentContainer = { /* The persistent container for the application. This implementation creates and returns a container, having loaded the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. */ let container = NSPersistentContainer(name: "Wain") container.loadPersistentStores(completionHandler: { (storeDescription, error) in if let error = error as NSError? { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. /* Typical reasons for an error here include: * The parent directory does not exist, cannot be created, or disallows writing. * The persistent store is not accessible, due to permissions or data protection when the device is locked. * The device is out of space. * The store could not be migrated to the current model version. Check the error message to determine what the actual problem was. */ fatalError("Unresolved error \(error), \(error.userInfo)") } }) return container }() // MARK: - Core Data Saving support func saveContext () { let context = persistentContainer.viewContext if context.hasChanges { do { try context.save() } catch { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError fatalError("Unresolved error \(nserror), \(nserror.userInfo)") } } } }
mit
0bdd310163c12d90c5b5cf0218f3192f
48.311828
285
0.685565
5.827192
false
false
false
false
Legoless/iOS-Course
2015-1/Lesson10/Gamebox/Gamebox/ViewController.swift
1
3498
// // ViewController.swift // Gamebox // // Created by Dal Rupnik on 21/10/15. // Copyright © 2015 Unified Sense. All rights reserved. // import UIKit class ViewController: UIViewController, UITextFieldDelegate, ImageViewControllerDelegate { let manager = GameManager.shared @IBOutlet weak var resultLabel: UILabel! @IBOutlet weak var nameTextField: UITextField! @IBOutlet weak var prioritySlider: UISlider! @IBOutlet weak var notesTextView: UITextView! override func viewDidLoad() { super.viewDidLoad() resultLabel.text = "Click to add game!" nameTextField.delegate = self if let gameName = NSUserDefaults.standardUserDefaults().objectForKey("GameName") as? String { nameTextField.text = gameName } } func textFieldDidEndEditing(textField: UITextField) { print("ENDED EDITING") if (textField == self.nameTextField) { print ("NAME ENDED") } } @IBAction func addGameButtonTap(sender: UIButton) { guard let name = nameTextField.text where name.characters.count > 0 else { resultLabel.text = "Verify your data!" resultLabel.textColor = UIColor.redColor() if nameTextField.text!.characters.count == 0 { var center = nameTextField.center center.x = self.view.center.x var centerLeft = center centerLeft.x -= 10 var centerRight = center centerRight.x += 10 UIView.animateWithDuration(0.2, animations: { self.nameTextField.center = centerLeft }, completion: { success in UIView.animateWithDuration(0.2, animations: { self.nameTextField.center = centerRight }, completion: { success2 in UIView.animateWithDuration(0.2) { self.nameTextField.center = center } }) }) } return } let game = Game(name: name, priority: UInt(prioritySlider.value)) if notesTextView.text.characters.count > 0 { game.notes = notesTextView.text } manager.games.append(game) resultLabel.text = "Added! There are \(manager.games.count) games in database!" resultLabel.textColor = UIColor.blackColor() UIView.animateWithDuration(0.3, animations: { () -> Void in sender.transform = CGAffineTransformMakeScale(1.05, 1.05) }) { success in UIView.animateWithDuration(0.3) { sender.transform = CGAffineTransformIdentity } } GameManager.shared.save() } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "ImageSegue" { let viewController = segue.destinationViewController as! ImageViewController viewController.delegate = self } } func imageViewControllerDidFinish(imageViewController: ImageViewController) { imageViewController.dismissViewControllerAnimated(true, completion: nil) } }
mit
5390e773e380d3110323d46b8236b2ab
32.304762
101
0.558193
5.818636
false
false
false
false
White-Label/Swift-SDK
Example/WhiteLabel/CollectionTableViewController.swift
1
5423
// // CollectionTableViewController.swift // // Created by Alex Givens http://alexgivens.com on 7/28/16 // Copyright © 2016 Noon Pacific LLC http://noonpacific.com // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import UIKit import CoreData import WhiteLabel class CollectionTableViewController: UITableViewController { var fetchedResultsController: NSFetchedResultsController<WLCollection>! let paging = PagingGenerator(startPage: 1) override func viewDidLoad() { super.viewDidLoad() title = "Loading label..." refreshControl?.addTarget(self, action: #selector(handleRefresh), for: .valueChanged) // Get your label WhiteLabel.GetLabel { result in let label = result.value self.title = label?.name } // Setup fetched results controller let fetchRequest = WLCollection.sortedFetchRequest() let managedObjectContext = CoreDataStack.shared.backgroundManagedObjectContext fetchedResultsController = NSFetchedResultsController( fetchRequest: fetchRequest, managedObjectContext: managedObjectContext, sectionNameKeyPath: nil, cacheName: nil) fetchedResultsController.delegate = self do { try fetchedResultsController.performFetch() } catch { fatalError("Failed to initialize FetchedResultsController: \(error)") } // Setup the paging generator with White Label paging.next = { page, completionMarker in if page == 1 { WLCollection.deleteCollections() } WhiteLabel.ListCollections(page: page) { result, total, pageSize in switch result { case .success(let collections): if collections.count < pageSize { self.paging.reachedEnd() } completionMarker(true) case .failure(let error): debugPrint(error) completionMarker(false) } } } paging.getNext() // Initial load } @objc func handleRefresh(refreshControl: UIRefreshControl) { paging.reset() paging.getNext() { refreshControl.endRefreshing() } } // MARK: Data Source override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return fetchedResultsController.sections?[section].numberOfObjects ?? 0 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: CellIdentifier.Collection, for: indexPath) let collection = fetchedResultsController.object(at: indexPath) cell.textLabel?.text = collection.title cell.detailTextLabel?.text = String(collection.mixtapeCount) return cell } // MARK: Delegate override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { if // Infinite scroll trigger let cellCount = tableView.dataSource?.tableView(tableView, numberOfRowsInSection: indexPath.section), indexPath.row == cellCount - 1, paging.isFetchingPage == false, paging.didReachEnd == false { paging.getNext() } } // MARK: Navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { guard segue.identifier == SegueIdentifier.CollectionsToMixtapes, let mixtapeTableViewController = segue.destination as? MixtapeTableViewController, let selectedIndexPath = tableView.indexPathsForSelectedRows?[0] else { return } let collection = fetchedResultsController.object(at: selectedIndexPath) mixtapeTableViewController.collection = collection } } extension CollectionTableViewController: NSFetchedResultsControllerDelegate { func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) { tableView.reloadData() } }
mit
0064917c499a20f9e095100bfb398b55
36.136986
121
0.65142
5.630322
false
false
false
false
maximkhatskevich/MKHAPIClient
.setup/Setup/main.swift
1
3778
import PathKit import XCERepoConfigurator // MARK: - PRE-script invocation output print("\n") print("--- BEGIN of '\(Executable.name)' script ---") // MARK: - // MARK: Parameters Spec.BuildSettings.swiftVersion.value = "5.3" let localRepo = try Spec.LocalRepo.current() let remoteRepo = try Spec.RemoteRepo( accountName: localRepo.context, name: localRepo.name ) let travisCI = ( address: "https://travis-ci.com/\(remoteRepo.accountName)/\(remoteRepo.name)", branch: "master" ) let company = ( prefix: "XCE", name: remoteRepo.accountName ) let project = ( name: remoteRepo.name, summary: "Lightweight HTTP-based API client", copyrightYear: 2016 ) let productName = company.prefix + project.name let authors = [ ("Maxim Khatskevich", "[email protected]") ] typealias PerSubSpec<T> = ( core: T, tests: T ) let subSpecs: PerSubSpec = ( "Core", "AllTests" ) let targetNames: PerSubSpec = ( productName, productName + subSpecs.tests ) let sourcesLocations: PerSubSpec = ( Spec.Locations.sources + subSpecs.core, Spec.Locations.tests + subSpecs.tests ) // MARK: Parameters - Summary localRepo.report() remoteRepo.report() // MARK: - // MARK: Write - ReadMe try ReadMe() .addGitHubLicenseBadge( account: company.name, repo: project.name ) .addGitHubTagBadge( account: company.name, repo: project.name ) .addSwiftPMCompatibleBadge() .addWrittenInSwiftBadge( version: Spec.BuildSettings.swiftVersion.value ) .addStaticShieldsBadge( "platforms", status: "macOS | iOS | tvOS | watchOS | Linux", color: "blue", title: "Supported platforms", link: "Package.swift" ) .add(""" [![Build Status](\(travisCI.address).svg?branch=\(travisCI.branch))](\(travisCI.address)) """ ) .add(""" # \(project.name) \(project.summary) """ ) .prepare( removeRepeatingEmptyLines: false ) .writeToFileSystem( ifFileExists: .skip ) // MARK: Write - License try License .MIT( copyrightYear: UInt(project.copyrightYear), copyrightEntity: authors.map{ $0.0 }.joined(separator: ", ") ) .prepare() .writeToFileSystem() // MARK: Write - GitHub - PagesConfig try GitHub .PagesConfig() .prepare() .writeToFileSystem() // MARK: Write - Git - .gitignore try Git .RepoIgnore() .addMacOSSection() .addCocoaSection() .addSwiftPackageManagerSection(ignoreSources: true) .add( """ # we don't need to store project file, # as we generate it on-demand *.\(Xcode.Project.extension) """ ) .prepare() .writeToFileSystem() // MARK: Write - Package.swift try CustomTextFile(""" // swift-tools-version:\(Spec.BuildSettings.swiftVersion.value) import PackageDescription let package = Package( name: "\(productName)", products: [ .library( name: "\(productName)", targets: [ "\(targetNames.core)" ] ) ], targets: [ .target( name: "\(targetNames.core)", path: "\(sourcesLocations.core)" ), .testTarget( name: "\(targetNames.tests)", dependencies: [ "\(targetNames.core)" ], path: "\(sourcesLocations.tests)" ), ] ) """ ) .prepare( at: ["Package.swift"] ) .writeToFileSystem() // MARK: - POST-script invocation output print("--- END of '\(Executable.name)' script ---")
mit
01014c837ee7710f47d8a821ca29fc8d
19.203209
97
0.571731
4.006363
false
false
false
false
practicalswift/swift
test/Constraints/keypath.swift
8
1039
// RUN: %target-swift-frontend -typecheck -verify %S/Inputs/keypath.swift -primary-file %s struct S { let i: Int init() { let _: WritableKeyPath<S, Int> = \.i // no error for Swift 3/4 S()[keyPath: \.i] = 1 // expected-error@-1 {{cannot assign through subscript: function call returns immutable value}} } } func test() { let _: WritableKeyPath<C, Int> = \.i // no error for Swift 3/4 C()[keyPath: \.i] = 1 // warning on write with literal keypath // expected-warning@-1 {{forming a writable keypath to property}} let _ = C()[keyPath: \.i] // no warning for a read } // SR-7339 class Some<T, V> { init(keyPath: KeyPath<T, ((V) -> Void)?>) { } } class Demo { var here: (() -> Void)? } // FIXME: This error is better than it was, but the diagnosis should break it down more specifically to 'here's type. let some = Some(keyPath: \Demo.here) // expected-error@-1 {{cannot convert value of type 'ReferenceWritableKeyPath<Demo, (() -> Void)?>' to expected argument type 'KeyPath<_, ((_) -> Void)?>'}}
apache-2.0
836ca3413f74e29f286d100e2fb4bec3
27.861111
156
0.634264
3.417763
false
false
false
false
AlesTsurko/AudioKit
Examples/OSX/Swift/HelloWorld/HelloWorld/ViewController.swift
5
1260
// // ViewController.swift // HelloWorld // // Created by Nicholas Arner on 2/28/15. // Copyright (c) 2015 AudioKit. All rights reserved. // import Cocoa class ViewController: NSViewController { // STEP 1 : Set up an instance variable for the instrument let instrument = AKInstrument() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. // STEP 2 : Define the instrument as a simple oscillator let oscillator = AKOscillator() instrument.connect(oscillator) instrument.connect(AKAudioOutput(audioSource: oscillator)) // STEP 3 : Add the instrument to the orchestra and start the orchestra AKOrchestra.addInstrument(instrument) AKOrchestra.start() } // STEP 4 : React to a button press on the Storyboard UI by // playing or stopping the instrument and updating the button text. @IBAction func toggleSound(sender: NSButton){ if !(sender.title == "Stop") { instrument.play() sender.title = "Stop" } else { instrument.stop() sender.title = "Play Sine Wave at 440HZ" } } }
lgpl-3.0
e0c4b13d1336404aab106bd603075623
29
80
0.62381
4.772727
false
false
false
false
lukevanin/OCRAI
GoogleVisionAPI/JSON.swift
1
4314
// // JSON.swift // CardScanner // // Created by Luke Van In on 2017/02/19. // Copyright © 2017 Luke Van In. All rights reserved. // import Foundation // MARK: Serialize JSON extension GoogleVisionAPI.Image { var json: Any { return [ "content": data.base64EncodedString(options: []) ] } } extension GoogleVisionAPI.FeatureType { var json: Any { switch self { case .logoDetection: return "LOGO_DETECTION" case .labelDetection: return "LABEL_DETECTION" case .textDetection: return "TEXT_DETECTION" case .safeSearchDetection: return "SAFE_SEARCH_DETECTION" case .imageProperties: return "IMAGE_PROPERTIES" } } } extension GoogleVisionAPI.Feature { var json: Any { var output = [String: Any]() output["type"] = type.json if let maxResults = maxResults { output["maxResults"] = maxResults } return output } } extension GoogleVisionAPI.AnnotationImageRequest { var json: Any { return [ "image": image.json, "features": features.map { $0.json } ] } } // MARK: JSON Deserialization extension GoogleVisionAPI.Status { init(json: Any) throws { guard let entity = json as? [String: Any], let code = entity["code"] as? Int, let message = entity["message"] as? String else { throw GoogleVisionAPI.APIError.parse } self.code = code self.message = message } } extension GoogleVisionAPI.Vertex { init(json: Any) throws { let entity = json as? [String: Any] self.x = entity?["x"] as? Double self.y = entity?["y"] as? Double } } extension GoogleVisionAPI.BoundingPoly { init(json: Any) throws { guard let entities = json as? [String: Any], let vertices = entities["vertices"] as? [Any] else { throw GoogleVisionAPI.APIError.parse } self.vertices = try vertices.map { try GoogleVisionAPI.Vertex(json: $0) } } } extension GoogleVisionAPI.EntityAnnotation { init(json: Any) throws { guard let entity = json as? [String: Any] else { throw GoogleVisionAPI.APIError.parse } self.mid = entity["mid"] as? String self.locale = entity["locale"] as? String self.description = entity["description"] as? String self.score = entity["score"] as? Double self.confidence = entity["confidence"] as? Double self.topicality = entity["topicality"] as? Double if let json = entity["boundingPoly"] { self.boundingPoly = try GoogleVisionAPI.BoundingPoly(json: json) } else { self.boundingPoly = nil } } } extension GoogleVisionAPI.AnnotateImageResponse { init(json: Any) throws { guard let entity = json as? [String: Any] else { throw GoogleVisionAPI.APIError.parse } if let textAnnotations = entity["textAnnotations"] as? [Any] { self.textAnnotations = try textAnnotations.map { try GoogleVisionAPI.EntityAnnotation(json: $0) } } else { self.textAnnotations = nil } if let labelAnnotations = entity["labelAnnotations"] as? [Any] { self.labelAnnotations = try labelAnnotations.map { try GoogleVisionAPI.EntityAnnotation(json: $0) } } else { self.labelAnnotations = nil } if let logoAnnotations = entity["logoAnnotations"] as? [Any] { self.logoAnnotations = try logoAnnotations.map { try GoogleVisionAPI.EntityAnnotation(json: $0) } } else { self.logoAnnotations = nil } if let json = entity["error"] as? [Any] { self.error = try GoogleVisionAPI.Status(json: json) } else { self.error = nil } } }
mit
2732882d305a2e75023276189b341656
25.139394
81
0.5393
4.632653
false
false
false
false
wikimedia/apps-ios-wikipedia
Wikipedia/Code/WMFTwoFactorPasswordViewController.swift
1
14535
import UIKit fileprivate enum WMFTwoFactorNextFirstResponderDirection: Int { case forward = 1 case reverse = -1 } fileprivate enum WMFTwoFactorTokenDisplayMode { case shortNumeric case longAlphaNumeric } class WMFTwoFactorPasswordViewController: WMFScrollViewController, UITextFieldDelegate, WMFDeleteBackwardReportingTextFieldDelegate, Themeable { @IBOutlet fileprivate var titleLabel: UILabel! @IBOutlet fileprivate var subTitleLabel: UILabel! @IBOutlet fileprivate var tokenLabel: UILabel! @IBOutlet fileprivate var tokenAlertLabel: UILabel! @IBOutlet fileprivate var oathTokenFields: [ThemeableTextField]! @IBOutlet fileprivate var oathTokenFieldsStackView: UIStackView! @IBOutlet fileprivate var displayModeToggle: UILabel! @IBOutlet fileprivate var backupOathTokenField: ThemeableTextField! @IBOutlet fileprivate var loginButton: WMFAuthButton! fileprivate var theme = Theme.standard public var funnel: WMFLoginFunnel? public var userName:String? public var password:String? public var captchaID:String? public var captchaWord:String? @objc func displayModeToggleTapped(_ recognizer: UITapGestureRecognizer) { guard recognizer.state == .ended else { return } switch displayMode { case .longAlphaNumeric: displayMode = .shortNumeric case .shortNumeric: displayMode = .longAlphaNumeric } } fileprivate var displayMode: WMFTwoFactorTokenDisplayMode = .shortNumeric { didSet { switch displayMode { case .longAlphaNumeric: backupOathTokenField.isHidden = false oathTokenFieldsStackView.isHidden = true tokenLabel.text = WMFLocalizedString("field-backup-token-title", value:"Backup code", comment:"Title for backup token field") displayModeToggle.text = WMFLocalizedString("two-factor-login-with-regular-code", value:"Use verification code", comment:"Button text for showing text fields for normal two factor login") case .shortNumeric: backupOathTokenField.isHidden = true oathTokenFieldsStackView.isHidden = false tokenLabel.text = WMFLocalizedString("field-token-title", value:"Verification code", comment:"Title for token field") displayModeToggle.text = WMFLocalizedString("two-factor-login-with-backup-code", value:"Use one of your backup codes", comment:"Button text for showing text field for backup code two factor login") } oathTokenFields.forEach {$0.text = nil} backupOathTokenField.text = nil if isViewLoaded && (view.window != nil) { makeAppropriateFieldFirstResponder() } } } fileprivate func makeAppropriateFieldFirstResponder() { switch displayMode { case .longAlphaNumeric: backupOathTokenField?.becomeFirstResponder() case .shortNumeric: oathTokenFields.first?.becomeFirstResponder() } } @IBAction fileprivate func loginButtonTapped(withSender sender: UIButton) { save() } fileprivate func areRequiredFieldsPopulated() -> Bool { switch displayMode { case .longAlphaNumeric: guard backupOathTokenField.text.wmf_safeCharacterCount > 0 else { return false } return true case .shortNumeric: return oathTokenFields.first(where:{ $0.text.wmf_safeCharacterCount == 0 }) == nil } } @IBAction func textFieldDidChange(_ sender: ThemeableTextField) { enableProgressiveButton(areRequiredFieldsPopulated()) guard displayMode == .shortNumeric, sender.text.wmf_safeCharacterCount > 0 else { return } makeNextTextFieldFirstResponder(currentTextField: sender, direction: .forward) } fileprivate func makeNextTextFieldFirstResponder(currentTextField: ThemeableTextField, direction: WMFTwoFactorNextFirstResponderDirection) { guard let index = oathTokenFields.firstIndex(of: currentTextField) else { return } let nextIndex = index + direction.rawValue guard nextIndex > -1, nextIndex < oathTokenFields.count else { return } oathTokenFields[nextIndex].becomeFirstResponder() } func wmf_deleteBackward(_ sender: WMFDeleteBackwardReportingTextField) { guard displayMode == .shortNumeric, sender.text.wmf_safeCharacterCount == 0 else { return } makeNextTextFieldFirstResponder(currentTextField: sender, direction: .reverse) } func enableProgressiveButton(_ highlight: Bool) { loginButton.isEnabled = highlight } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) enableProgressiveButton(false) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) makeAppropriateFieldFirstResponder() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) enableProgressiveButton(false) } fileprivate func allowedCharacterSet() -> CharacterSet { switch displayMode { case .longAlphaNumeric: return CharacterSet.init(charactersIn: " ").union(CharacterSet.alphanumerics) case .shortNumeric: return CharacterSet.decimalDigits } } fileprivate func maxTextFieldCharacterCount() -> Int { // Presently backup tokens are 16 digit, but may contain spaces and their length // may change in future, so for now just set a sensible upper limit. switch displayMode { case .longAlphaNumeric: return 24 case .shortNumeric: return 1 } } func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { // Disallow invalid characters. guard (string.rangeOfCharacter(from: allowedCharacterSet().inverted) == nil) else { return false } // Always allow backspace. guard string != "" else { return true } // Support numeric code pasting when showing individual digit UITextFields - i.e. when displayMode == .shortNumeric. // If displayMode == .shortNumeric 'string' has been verified to be comprised of decimal digits by this point. // Backup code (when displayMode == .longAlphaNumeric) pasting already works as-is because it uses a single UITextField. if displayMode == .shortNumeric && string.count == oathTokenFields.count{ for (field, char) in zip(oathTokenFields, string) { field.text = String(char) } enableProgressiveButton(areRequiredFieldsPopulated()) return false } // Enforce max count. let countIfAllowed = textField.text.wmf_safeCharacterCount + string.count return (countIfAllowed <= maxTextFieldCharacterCount()) } func textFieldDidBeginEditing(_ textField: UITextField) { tokenAlertLabel.isHidden = true // In the storyboard we've set the text fields' to "Clear when editing begins", but // the "Editing changed" handler "textFieldDidChange" isn't called when this clearing // happens, so update progressive buttons' enabled state here too. enableProgressiveButton(areRequiredFieldsPopulated()) } public func textFieldShouldReturn(_ textField: UITextField) -> Bool { guard displayMode == .longAlphaNumeric else { return true } save() return true } override func viewDidLoad() { super.viewDidLoad() oathTokenFields.sort { $0.tag < $1.tag } oathTokenFields.forEach { $0.rightViewMode = .never $0.textAlignment = .center } // Cast fields once here to set 'deleteBackwardDelegate' rather than casting everywhere else UITextField is expected. if let fields = oathTokenFields as? [WMFDeleteBackwardReportingTextField] { fields.forEach {$0.deleteBackwardDelegate = self} }else{ assertionFailure("Underlying oathTokenFields from storyboard were expected to be of type 'WMFDeleteBackwardReportingTextField'.") } navigationItem.leftBarButtonItem = UIBarButtonItem(image: UIImage(named:"close"), style: .plain, target:self, action:#selector(closeButtonPushed(_:))) navigationItem.leftBarButtonItem?.accessibilityLabel = CommonStrings.closeButtonAccessibilityLabel loginButton.setTitle(WMFLocalizedString("two-factor-login-continue", value:"Continue log in", comment:"Button text for finishing two factor login"), for: .normal) titleLabel.text = WMFLocalizedString("two-factor-login-title", value:"Log in to your account", comment:"Title for two factor login interface") subTitleLabel.text = WMFLocalizedString("two-factor-login-instructions", value:"Please enter two factor verification code", comment:"Instructions for two factor login interface") displayMode = .shortNumeric displayModeToggle.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(displayModeToggleTapped(_:)))) view.wmf_configureSubviewsForDynamicType() apply(theme: theme) } @objc func closeButtonPushed(_ : UIBarButtonItem) { dismiss(animated: true, completion: nil) } fileprivate func token() -> String { switch displayMode { case .longAlphaNumeric: return backupOathTokenField.text! case .shortNumeric: return oathTokenFields.reduce("", { $0 + ($1.text ?? "") }) } } fileprivate func save() { wmf_hideKeyboard() tokenAlertLabel.isHidden = true enableProgressiveButton(false) guard let userName = userName, let password = password else { return } WMFAlertManager.sharedInstance.showAlert(WMFLocalizedString("account-creation-logging-in", value:"Logging in...", comment:"Alert shown after account successfully created and the user is being logged in automatically.\n{{Identical|Logging in}}"), sticky: true, dismissPreviousAlerts: true, tapCallBack: nil) WMFAuthenticationManager.sharedInstance.login(username: userName, password: password, retypePassword: nil, oathToken: token(), captchaID: captchaID, captchaWord: captchaWord) { (loginResult) in switch loginResult { case .success(_): let loggedInMessage = String.localizedStringWithFormat(WMFLocalizedString("main-menu-account-title-logged-in", value:"Logged in as %1$@", comment:"Header text used when account is logged in. %1$@ will be replaced with current username."), userName) WMFAlertManager.sharedInstance.showSuccessAlert(loggedInMessage, sticky: false, dismissPreviousAlerts: true, tapCallBack: nil) let presenter = self.presentingViewController self.dismiss(animated: true, completion: { presenter?.wmf_showEnableReadingListSyncPanel(theme: self.theme, oncePerLogin: true) }) self.funnel?.logSuccess() case .failure(let error): if let error = error as? WMFAccountLoginError { switch error { case .temporaryPasswordNeedsChange: WMFAlertManager.sharedInstance.dismissAlert() self.showChangeTempPasswordViewController() return case .wrongToken: self.tokenAlertLabel.text = error.localizedDescription self.tokenAlertLabel.isHidden = false self.funnel?.logError(error.localizedDescription) WMFAlertManager.sharedInstance.dismissAlert() return default: break } self.enableProgressiveButton(true) WMFAlertManager.sharedInstance.showErrorAlert(error as NSError, sticky: true, dismissPreviousAlerts: true, tapCallBack: nil) self.funnel?.logError(error.localizedDescription) self.oathTokenFields.forEach {$0.text = nil} self.backupOathTokenField.text = nil self.makeAppropriateFieldFirstResponder() } default: break } } } func showChangeTempPasswordViewController() { guard let presenter = presentingViewController, let changePasswordVC = WMFChangePasswordViewController.wmf_initialViewControllerFromClassStoryboard() else { assertionFailure("Expected view controller(s) not found") return } changePasswordVC.apply(theme: theme) dismiss(animated: true, completion: { changePasswordVC.userName = self.userName let navigationController = WMFThemeableNavigationController(rootViewController: changePasswordVC, theme: self.theme) presenter.present(navigationController, animated: true, completion: nil) }) } func apply(theme: Theme) { self.theme = theme guard viewIfLoaded != nil else { return } view.backgroundColor = theme.colors.paperBackground view.tintColor = theme.colors.link tokenAlertLabel.textColor = theme.colors.error var fields = oathTokenFields ?? [] fields.append(backupOathTokenField) for textField in fields { textField.apply(theme: theme) } titleLabel.textColor = theme.colors.primaryText tokenLabel.textColor = theme.colors.secondaryText displayModeToggle.textColor = theme.colors.link subTitleLabel.textColor = theme.colors.secondaryText } }
mit
398951f7fe504dee51904bfe084e9bbd
40.647564
314
0.642656
6.099454
false
false
false
false
gitgitcode/LearnSwift
0-learn/0-learn/protocal.swift
1
2433
// // protocal.swift // 0-learn // // Created by xuthus on 15/5/31. // Copyright (c) 2015年 xuthus. All rights reserved. // import Foundation func repeats<Item>(item: Item, times: Int) -> [Item] { var result = [Item]() for i in 0..<times { result.append(item) } return result } func test() { var f = repeats("knock", 4) println(f) } //test() //enum OptionalValue<T> { // case None // case Some(T) //} //var possibleInteger: OptionalValue<Int> = .None //possibleInteger = .Some(100) // //func anyCommonElements <T, U where T: SequenceType, U:SequenceType, // T.Generator.Element: Equatable, T.Generator.Element == U.Generator.Element>( // lhs: T,rhs: U ) -> Bool { // for lhsItem in lhs { // for rhsItem in rhs { // if lhsItem == rhsItem { // return true // } // // } // } //} //直接在类的外面调用类内部的方法,会出现Bug:Expressions are not allowed at the top level。 //在App工程里, .swift 文件都是编译成模块的,不能有 top level code。 // //  先明确一个概念,一个 .swift 文件执行是从它的第一条非声明语句(表达式、控制结构)开始的,同时包括声明中的赋值部分(对应为 mov 指令或者 lea 指令),所有这些语句,构成了该 .swift 文件的 top_level_code() 函数。而所有的声明,包括结构体、类、枚举及其方法,都不属于 top_level_code() 代码部分,其中的代码逻辑,包含在其他区域,top_level_code() 可以直接调用他们。程序的入口是隐含的一个 main(argc, argv) 函数,该函数执行逻辑是设置全局变量 C_ARGC C_ARGV,然后调用 top_level_code()。不是所有的 .swift 文件都可以作为模块,目前看,任何包含表达式语句和控制语句的 .swift 文件都不可以作为模块。正常情况下模块可以包含全局变量(var)、全局常量(let)、结构体(struct)、类(class)、枚举(enum)、协议(protocol)、扩展(extension)、函数(func)、以及全局属性(var { get set })。这里的全局,指的是定义在 top level 。这里说的表达式指 expression ,语句指 statement ,声明指 declaration 。因此,如果代码中直接在类的外面调用类内部的方法,则该.swift 文件是编译不成的模块的,所以会编译报错。
apache-2.0
1bdb055b7ca40fe784f6e65e739b8bf1
33.791667
615
0.645896
2.700647
false
false
false
false
bitboylabs/selluv-ios
selluv-ios/selluv-ios/Classes/Controller/UI/Tabs/Tab1SelluvMain/SLV_1a5_SelluvMainNew.swift
1
14101
// // SLV_1a5_SelluvMainNew.swift // selluv-ios // // Created by 조백근 on 2016. 11. 9.. // Copyright © 2016년 BitBoy Labs. All rights reserved. // /* 셀럽 서브탭 신상 */ import Foundation import UIKit import SwifterSwift import PullToRefresh class SLV_1a5_SelluvMainNew: UICollectionViewController { var itemInfo: IndicatorInfo = "New"//tab 정보 let refresher = PullToRefresh() var itemList: [SLVDetailProduct] = [] let delegateHolder = SLVTabContainNavigationControllerDelegate() weak var delegate: SLVButtonBarDelegate?// 델리게이트. weak var myNavigationDelegate: SLVNavigationControllerDelegate?// push를 위한 네비게이션 override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.loadProducts(isContinue: false) } override func viewDidLoad() { super.viewDidLoad() self.prepare() self.loadProducts(isContinue: false) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func linkDelegate(controller: AnyObject) { self.delegate = controller as? SLVButtonBarDelegate // self.myNavigationDelegate = controller as? SLVNavigationControllerDelegate } func prepare() { self.navigationController!.delegate = delegateHolder self.view.backgroundColor = UIColor.clear self.automaticallyAdjustsScrollViewInsets = false self.loadProducts(isContinue: false) let collection :UICollectionView = collectionView!; collection.remembersLastFocusedIndexPath = true collection.frame = screenBounds collection.setCollectionViewLayout(CHTCollectionViewWaterfallLayout(), animated: false) collection.backgroundColor = UIColor.clear // collection.register(SLVMainFeedItemCell.self, forCellWithReuseIdentifier: selluvWaterFallCellIdentify) collection.register(UINib(nibName: "SLVUserProductCell", bundle: nil), forCellWithReuseIdentifier: selluvWaterFallCellIdentify) collection.reloadData() refresher.position = .bottom collection.addPullToRefresh(refresher) { self.loadProducts(isContinue: true) } } func setupLongPress() { let overlay = GHContextMenuView() overlay.delegate = self overlay.dataSource = self let selector = #selector(GHContextMenuView.longPressDetected(_:)) let longPress = UILongPressGestureRecognizer(target: overlay, action: selector) self.collectionView?.addGestureRecognizer(longPress) } deinit { self.collectionView?.removePullToRefresh((self.collectionView?.bottomPullToRefresh!)!) } override func scrollViewDidScroll(_ scrollView: UIScrollView) { if scrollView == self.collectionView { let off = scrollView.contentOffset if off.y > 0 { // hide self.delegate?.hideByScroll() } else { //show self.delegate?.showByScroll() } } } //MARK: DataCalling func loadProducts(isContinue: Bool) { let parent = self.delegate as! SLV_110_SelluvMainController SelluvHomeTabModel.shared.mainNewProducts(same: isContinue) { (success, products) in if let products = products { self.itemList.append(contentsOf: products) parent.delay(time: 0.2) { self.collectionView?.reloadData() } } } } } // MARK: - IndicatorInfoProvider extension SLV_1a5_SelluvMainNew: IndicatorInfoProvider { func indicatorInfo(for pagerTabStripController: PagerTabStripViewController) -> IndicatorInfo { return itemInfo } } // MARK: - Collection View extension SLV_1a5_SelluvMainNew { override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let collectionCell: SLVUserProductCell = collectionView.dequeueReusableCell(withReuseIdentifier: selluvWaterFallCellIdentify, for: indexPath as IndexPath) as! SLVUserProductCell collectionCell.delegate = self let item = self.itemList[indexPath.row] collectionCell.setupData(item: item) collectionCell.isMainTab = true collectionCell.updateHiddenStyle() return collectionCell } override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int{ return self.itemList.count } override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let cell = collectionView.cellForItem(at: indexPath) as! SLVUserProductCell collectionView.setToIndexPath(indexPath: indexPath as NSIndexPath) let board = UIStoryboard(name:"Main", bundle: nil) let productController = board.instantiateViewController(withIdentifier: "SLV_501_ProcuctDetailController") as! SLV_501_ProcuctDetailController productController.listProductInfo = cell.info productController.parentCellImage = cell.imageViewContent!.image productController.imagePath = indexPath as NSIndexPath? navigationController?.pushViewController(productController, animated: true) } func pageViewControllerLayout () -> UICollectionViewFlowLayout { let flowLayout = UICollectionViewFlowLayout() let itemSize = self.navigationController!.isNavigationBarHidden ? CGSize(width: screenWidth, height: screenHeight+20) : CGSize(width: screenWidth, height: screenHeight-navigationHeaderAndStatusbarHeight) flowLayout.itemSize = itemSize flowLayout.minimumLineSpacing = 0 flowLayout.minimumInteritemSpacing = 0 flowLayout.scrollDirection = .horizontal return flowLayout } } extension SLV_1a5_SelluvMainNew: CHTCollectionViewDelegateWaterfallLayout, SLVCollectionTransitionProtocol { func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize{ var itemSize = DEFAULT_PHOTO_SIZE var isFinish = true if self.itemList.count > 0 && self.itemList.count >= indexPath.row + 1 { let info = self.itemList[indexPath.row] var name = "" if info.photos != nil { if (info.photos?.count)! > 0 { name = (info.photos?.first)! } } if SelluvHomeTabModel.shared.isOnlyStyles == true { name = (info.styles?.first)! } if name != "" { var from = URL(string: "\(dnProduct)\(name)") if SelluvHomeTabModel.shared.isOnlyStyles == true { from = URL(string: "\(dnStyle)\(name)") } isFinish = false ImageScout.shared.scoutImage(url: from!) { error, size, type in isFinish = true if let error = error { print(error.code) } else { print("Size: \(size)") print("Type: \(type.rawValue)") itemSize = size } } } } var cnt: Int = 0 var sec: Double = 0 while(isFinish == false && 2 < sec ) { RunLoop.current.run(until: Date(timeIntervalSinceNow: 0.01)) cnt = cnt + 1 sec = Double(cnt) * Double(0.01) } let imageHeight = itemSize.height*gridWidth/itemSize.width + SLVUserProductCell.infoHeight + SLVUserProductCell.humanHeight log.debug("remote image calc cell width: \(gridWidth) , height: \(imageHeight)") return CGSize(width: gridWidth, height: imageHeight) } func transitionTabCollectionView() -> UICollectionView!{ return collectionView } } extension SLV_1a5_SelluvMainNew: SLVCollectionLinesDelegate { // 스타일 영역을 터치한다. func didTouchedStyleThumbnail(info: AnyObject) { let item = info["item"] as! SLVDetailProduct let image = info["image"] as! UIImage let board = UIStoryboard(name:"Sell", bundle: nil) let controller = board.instantiateViewController(withIdentifier: "SLV_318_SellPhotoEdit") as! SLV_318_SellPhotoEdit controller.photoMode = .viewer(urlString: dnStyle, items: item.styles!) controller.setupViewer { let mBoard = UIStoryboard(name:"Main", bundle: nil) let productController = mBoard.instantiateViewController(withIdentifier: "SLV_501_ProcuctDetailController") as! SLV_501_ProcuctDetailController productController.listProductInfo = item productController.imageContent?.image = image self.navigationController?.pushViewController(productController, animated: true) } self.present(controller, animated: true, completion: { // controller.moveCurrentIndex(index: 0) }) // let board = UIStoryboard(name:"Main", bundle: nil) // let controller = board.instantiateViewController(withIdentifier: "SLVProductPhotoViewer") as! SLVProductPhotoViewer // controller.modalPresentationStyle = .overCurrentContext // controller.setupData(type: .style, photos: item.styles!, items: []) // controller.setupViewer(block: { (viewPath, image, viewType, viewItem) in // // let productController = board.instantiateViewController(withIdentifier: "SLV_501_ProcuctDetailController") as! SLV_501_ProcuctDetailController // productController.listProductInfo = item // productController.imageContent?.image = image // //productController.imagePath = indexPath as NSIndexPath? // self.navigationController?.pushViewController(productController, animated: true) // // }) // self.present(controller, animated: true, completion: { // controller.moveIndex(index: 0) // }) } // 좋아요를 터치한다. func didTouchedLikeButton(info: AnyObject) { } func didTouchedItemDescription(info: AnyObject) { } func didTouchedUserDescription(info: AnyObject) { } } extension SLV_1a5_SelluvMainNew: GHContextOverlayViewDataSource, GHContextOverlayViewDelegate { func shouldShowMenu(at point: CGPoint) -> Bool { let path = self.collectionView?.indexPathForItem(at: point) if path != nil { let cell = self.collectionView?.cellForItem(at: path!) return cell != nil } return false } func shouldShowMenuOnParentImage(at point: CGPoint) -> UIImage! { let path = self.collectionView?.indexPathForItem(at: point) if path != nil { let cell = self.collectionView?.cellForItem(at: path!) as? SLVUserProductCell if cell != nil { let image = cell!.imageViewContent?.image return image } } return nil } func shouldShowMenuParentImageFrame(at point: CGPoint) -> CGRect { let path = self.collectionView?.indexPathForItem(at: point) if path != nil { let cell = self.collectionView?.cellForItem(at: path!) as? SLVUserProductCell if cell != nil { let frame = cell?.imageViewContent?.frame var newFrame = self.view?.convert(frame!, to: nil) let x = ((screenWidth/2) > point.x) ? 17:(screenWidth/2 + 5) newFrame?.origin.x = x return newFrame! } } return .zero } func numberOfMenuItems() -> Int { return 4 } func itemInfoForItem(at index: Int) -> GHContextItemView! { let itemView = GHContextItemView() switch index { case 0: itemView.typeDesc = "좋아요" itemView.baseImage = UIImage(named: "longpress-like-nor.png") itemView.selectedImage = UIImage(named: "longpress-like-focus.png") // itemView.baseImage = UIImage(named: "longpress-like-not-nor.png") // itemView.selectedImage = UIImage(named: "longpress-like-not-focus.png") break case 1: itemView.typeDesc = "피드" itemView.baseImage = UIImage(named: "longpress-feed-nor.png") itemView.selectedImage = UIImage(named: "longpress-feed-focus.png") break case 2: itemView.typeDesc = "공유" itemView.baseImage = UIImage(named: "longpress-share-nor.png") itemView.selectedImage = UIImage(named: "longpress-share-focus.png") break case 3: itemView.typeDesc = "더보기" itemView.baseImage = UIImage(named: "longpress-more-nor.png") itemView.selectedImage = UIImage(named: "longpress-more-focus.png") break default: break } return itemView } func didSelectItem(at selectedIndex: Int, forMenuAt point: CGPoint) { // let path = self.collectionView?.indexPathForItem(at: point) var message = "" switch selectedIndex { case 0: message = "좋아요 selected" break case 1: message = "피드 selected" break case 2: message = "공유 selected" break case 3: message = "더보기 selected" break default: break } AlertHelper.alert(message: message) } }
mit
fabdf8d05fb804c183b3983dff05bad9
37.490358
185
0.619668
5.252632
false
false
false
false
ppraveentr/MobileCore
Tests/CoreUtilityTests/ViewElementsTests.swift
1
1068
// // ViewElementsTests.swift // CoreUtilityTests // // Created by Praveen P on 30/06/20. // Copyright © 2020 Praveen Prabhakar. All rights reserved. // import XCTest final class ViewElementsTests: XCTestCase { func testfindShadowImage() { // let let view = UIView() let image1 = UIImageView(frame: .zero) let image2 = UIImageView(frame: .zero) let image3 = UIImageView(frame: CGRect(x: 20, y: 20, width: 20, height: 20)) // when view.addSubview(image1) view.addSubview(image2) view.addSubview(image3) // then XCTAssertEqual(view.findShadowImage()?.count, 2) } func testfindInSubView() { // let let view = UIView() let view1 = UIView(frame: .zero) let image = UIImageView(frame: .zero) // when view.addSubview(view1) view.addSubview(image) // then let foundView: UIImageView? = view.findInSubView() XCTAssertNotNil(foundView) XCTAssertEqual(foundView, image) } }
mit
3b2bb8dab9bc37eed09064b1a2edfe44
25.675
84
0.599813
4.041667
false
true
false
false
OlehKulykov/OKAlertController
OKAlertControllerUITests/OKAlertControllerUITests.swift
1
2391
/* * Copyright (c) 2016 Oleh Kulykov <[email protected]> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ import XCTest @testable import OKAlertController class OKAlertControllerUITests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method. XCUIApplication().launch() // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } func testShowHide() { XCUIDevice.shared().orientation = .portrait let app = XCUIApplication() for buttonTitle in ["Ut enim ad minim veniam", "Duis aute irure dolor", "Destructive", "Cancel"] { app.buttons["Show alert"].tap() XCTAssertTrue(app.alerts.count == 1, "Alert not showed, broken logic") app.alerts["1"].collectionViews.buttons[buttonTitle].tap() XCTAssertTrue(app.alerts.count == 0, "Alert not dismissed, broken logic") } } }
mit
85b4b45edff59c583fb4c239975bcad1
40.189655
182
0.715781
4.44052
false
true
false
false
kamawshuang/iOS---Animation
Autolayerout动画(十)/结合Autolayerot 与 Animation/PackingList/ViewController_20151130170740.swift
1
3357
/* * Copyright (c) 2015 Razeware LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ import UIKit class ViewController: UIViewController { //MARK: IB outlets @IBOutlet weak var menuHeightConstraint: NSLayoutConstraint! @IBOutlet var tableView: UITableView! @IBOutlet var buttonMenu: UIButton! @IBOutlet var titleLabel: UILabel! //MARK: further class variables var slider: HorizontalItemList! var isMenuOpen = false var items: [Int] = [5, 6, 7] //MARK: class methods @IBAction func actionToggleMenu(sender: AnyObject) { UIView.animateWithDuration(0, delay: 0.4, usingSpringWithDamping: 0.5, initialSpringVelocity: 30, options: [], animations: { self.isMenuOpen = !self.isMenuOpen self.menuHeightConstraint.constant = self.isMenuOpen ? 200.0 : 60 self.titleLabel.text = self.isMenuOpen ? "Select Title" : "Pack Item" self.view.layoutIfNeeded() }, completion: nil) } func showItem(index: Int) { print("tapped item \(index)") } } let itemTitles = ["Icecream money", "Great weather", "Beach ball", "Swim suit for him", "Swim suit for her", "Beach games", "Ironing board", "Cocktail mood", "Sunglasses", "Flip flops"] extension ViewController: UITableViewDelegate, UITableViewDataSource { // MARK: View Controller methods override func viewDidLoad() { super.viewDidLoad() self.tableView?.rowHeight = 54.0 } // MARK: Table View methods func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return items.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell cell.accessoryType = .None cell.textLabel?.text = itemTitles[items[indexPath.row]] cell.imageView?.image = UIImage(named: "summericons_100px_0\(items[indexPath.row]).png") return cell } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: true) showItem(items[indexPath.row]) } }
apache-2.0
fc89f557d4105fa1b1d330b96eea5c90
32.247525
185
0.71969
4.611264
false
false
false
false
NghiaTranUIT/Titan
TitanCore/TitanCore/NotificationManager.swift
2
1882
// // NotificationManager.swift // TitanCore // // Created by Nghia Tran on 4/11/17. // Copyright © 2017 nghiatran. All rights reserved. // import Foundation public enum NotificationType: String { // Preifx private static let NotificationPrefix = "com.fe.titan" // Enum case prepareLayoutForSelectedDatabase case openDetailDatabaseWindow case windowWillClose // To String func toString() -> String { if self.rawValue == NotificationType.windowWillClose.rawValue { return Notification.Name.NSWindowWillClose.rawValue } return NotificationType.NotificationPrefix + self.rawValue } } open class NotificationManager { public class func postNotificationOnMainThreadType(_ type: NotificationType, object: AnyObject? = nil, userInfo: [String: Any]? = nil) { NotificationCenter.default.postNotificationOnMainThreadName(type.toString(), object: object, userInfo: userInfo) } public class func observeNotificationType(_ type: NotificationType, observer: AnyObject, selector aSelector: Selector, object anObject: AnyObject?) { NotificationCenter.default.addObserver(observer, selector: aSelector, name: NSNotification.Name(rawValue: type.toString()), object: anObject) } public class func removeAllObserve(_ observer: AnyObject) { NotificationCenter.default.removeObserver(observer) } } // // MARK: - Private extension NotificationCenter { public func postNotificationOnMainThreadName(_ name: String, object: AnyObject?, userInfo: [String: Any]?) { // Create new Internal Notification let noti = Notification(name: Notification.Name(rawValue: name), object: object, userInfo: userInfo) self.performSelector(onMainThread: #selector(post(_:)), with: noti, waitUntilDone: true) } }
mit
5ede5f7dd958e917ca3a8710dff79708
32.589286
153
0.703349
5.00266
false
false
false
false
mshafer/stock-portfolio-ios
Portfolio/AppDelegate.swift
1
3443
// // AppDelegate.swift // Portfolio // // Created by Michael Shafer on 22/09/15. // Copyright © 2015 mshafer. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. let splitViewController = self.window!.rootViewController as! UISplitViewController let navigationController = splitViewController.viewControllers[splitViewController.viewControllers.count-1] as! UINavigationController navigationController.topViewController!.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem() splitViewController.delegate = self return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } // MARK: - Split view func splitViewController(splitViewController: UISplitViewController, collapseSecondaryViewController secondaryViewController:UIViewController, ontoPrimaryViewController primaryViewController:UIViewController) -> Bool { guard let secondaryAsNavController = secondaryViewController as? UINavigationController else { return false } guard let topAsDetailController = secondaryAsNavController.topViewController as? DetailViewController else { return false } if topAsDetailController.detailItem == nil { // Return true to indicate that we have handled the collapse by doing nothing; the secondary controller will be discarded. return true } return false } func preferredStatusBarStyle() -> UIStatusBarStyle { return UIStatusBarStyle.LightContent } }
gpl-3.0
cf2c281f5c9df5f27dacf72f02a37fa2
51.953846
285
0.762347
6.224231
false
false
false
false
nkirby/Humber
Humber/_src/Table View Cells/IssueHeaderCell.swift
1
1472
// ======================================================= // Humber // Nathaniel Kirby // ======================================================= import UIKit import HMCore import HMGithub // ======================================================= class IssueHeaderCell: UITableViewCell { @IBOutlet var titleLabel: UILabel! @IBOutlet var descriptionLabel: UILabel! override func awakeFromNib() { super.awakeFromNib() } override func prepareForReuse() { super.prepareForReuse() self.titleLabel.text = "" self.descriptionLabel.text = "" } // ======================================================= internal func render(model model: GithubIssueModel) { self.backgroundColor = Theme.color(type: .CellBackgroundColor) let titleAttrString = NSAttributedString(string: "#\(model.issueNumber) \(model.title)", attributes: [ NSForegroundColorAttributeName: Theme.color(type: .PrimaryTextColor), NSFontAttributeName: Theme.font(type: .Bold(14.0)) ]) self.titleLabel.attributedText = titleAttrString let descAttrString = NSAttributedString(string: model.body, attributes: [ NSForegroundColorAttributeName: Theme.color(type: .SecondaryTextColor), NSFontAttributeName: Theme.font(type: .Regular(12.0)) ]) self.descriptionLabel.attributedText = descAttrString } }
mit
770e2c1fdad25ca0c222ae8a9c71a986
30.319149
110
0.55163
5.935484
false
false
false
false
moqada/mobile-webview-example
ios/WebViewSample/ViewController.swift
1
1517
// // ViewController.swift // WebViewSample // // Created by Masahiko Okada on 2015/10/05. // // import UIKit import AudioToolbox class ViewController: UIViewController, UIWebViewDelegate { @IBOutlet weak var mainWebView: UIWebView! @IBOutlet weak var SecondViewButton: UIButton! var URL_STRING = "https://moqada.github.io/mobile-webview-example/" // var URL_STRING = "http://localhost:8000/index.html" override func viewDidLoad() { super.viewDidLoad() // URL をリクエスト let url = NSURL(string: URL_STRING) let req = NSURLRequest(URL: url!) // WebView にリクエスト投げてもらう mainWebView.loadRequest(req) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool { let url = request.URL let scheme = url!.scheme // myscheme の場合は何か処理 if scheme == "myscheme" { AudioServicesPlayAlertSound(SystemSoundID(kSystemSoundID_Vibrate)) return false } // myscheme 以外はスルー return true } // MARK: Actions @IBAction func tappedSecondViewButton(sender: UIButton) { print("tapped") performSegueWithIdentifier("showSecondView", sender: sender) } }
mit
3902baed8409900cdacfac33f0b76681
23.627119
137
0.653131
4.583596
false
false
false
false
tbkka/swift-protobuf
Sources/SwiftProtobuf/JSONEncodingVisitor.swift
3
13866
// Sources/SwiftProtobuf/JSONEncodingVisitor.swift - JSON encoding visitor // // Copyright (c) 2014 - 2016 Apple Inc. and the project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See LICENSE.txt for license information: // https://github.com/apple/swift-protobuf/blob/master/LICENSE.txt // // ----------------------------------------------------------------------------- /// /// Visitor that writes a message in JSON format. /// // ----------------------------------------------------------------------------- import Foundation /// Visitor that serializes a message into JSON format. internal struct JSONEncodingVisitor: Visitor { private var encoder = JSONEncoder() private var nameMap: _NameMap private var extensions: ExtensionFieldValueSet? private let options: JSONEncodingOptions /// The JSON text produced by the visitor, as raw UTF8 bytes. var dataResult: Data { return encoder.dataResult } /// The JSON text produced by the visitor, as a String. internal var stringResult: String { return encoder.stringResult } /// Creates a new visitor for serializing a message of the given type to JSON /// format. init(type: Message.Type, options: JSONEncodingOptions) throws { if let nameProviding = type as? _ProtoNameProviding.Type { self.nameMap = nameProviding._protobuf_nameMap } else { throw JSONEncodingError.missingFieldNames } self.options = options } mutating func startArray() { encoder.startArray() } mutating func endArray() { encoder.endArray() } mutating func startObject(message: Message) { self.extensions = (message as? ExtensibleMessage)?._protobuf_extensionFieldValues encoder.startObject() } mutating func startArrayObject(message: Message) { self.extensions = (message as? ExtensibleMessage)?._protobuf_extensionFieldValues encoder.startArrayObject() } mutating func endObject() { encoder.endObject() } mutating func encodeField(name: String, stringValue value: String) { encoder.startField(name: name) encoder.putStringValue(value: value) } mutating func encodeField(name: String, jsonText text: String) { encoder.startField(name: name) encoder.append(text: text) } mutating func visitUnknown(bytes: Data) throws { // JSON encoding has no provision for carrying proto2 unknown fields. } mutating func visitSingularFloatField(value: Float, fieldNumber: Int) throws { try startField(for: fieldNumber) encoder.putFloatValue(value: value) } mutating func visitSingularDoubleField(value: Double, fieldNumber: Int) throws { try startField(for: fieldNumber) encoder.putDoubleValue(value: value) } mutating func visitSingularInt32Field(value: Int32, fieldNumber: Int) throws { try startField(for: fieldNumber) encoder.putInt32(value: value) } mutating func visitSingularInt64Field(value: Int64, fieldNumber: Int) throws { try startField(for: fieldNumber) encoder.putInt64(value: value) } mutating func visitSingularUInt32Field(value: UInt32, fieldNumber: Int) throws { try startField(for: fieldNumber) encoder.putUInt32(value: value) } mutating func visitSingularUInt64Field(value: UInt64, fieldNumber: Int) throws { try startField(for: fieldNumber) encoder.putUInt64(value: value) } mutating func visitSingularFixed32Field(value: UInt32, fieldNumber: Int) throws { try startField(for: fieldNumber) encoder.putUInt32(value: value) } mutating func visitSingularSFixed32Field(value: Int32, fieldNumber: Int) throws { try startField(for: fieldNumber) encoder.putInt32(value: value) } mutating func visitSingularBoolField(value: Bool, fieldNumber: Int) throws { try startField(for: fieldNumber) encoder.putBoolValue(value: value) } mutating func visitSingularStringField(value: String, fieldNumber: Int) throws { try startField(for: fieldNumber) encoder.putStringValue(value: value) } mutating func visitSingularBytesField(value: Data, fieldNumber: Int) throws { try startField(for: fieldNumber) encoder.putBytesValue(value: value) } private mutating func _visitRepeated<T>( value: [T], fieldNumber: Int, encode: (inout JSONEncoder, T) throws -> () ) throws { assert(!value.isEmpty) try startField(for: fieldNumber) var comma = false encoder.startArray() for v in value { if comma { encoder.comma() } comma = true try encode(&encoder, v) } encoder.endArray() } mutating func visitSingularEnumField<E: Enum>(value: E, fieldNumber: Int) throws { try startField(for: fieldNumber) if let e = value as? _CustomJSONCodable { let json = try e.encodedJSONString(options: options) encoder.append(text: json) } else if !options.alwaysPrintEnumsAsInts, let n = value.name { encoder.appendQuoted(name: n) } else { encoder.putEnumInt(value: value.rawValue) } } mutating func visitSingularMessageField<M: Message>(value: M, fieldNumber: Int) throws { try startField(for: fieldNumber) if let m = value as? _CustomJSONCodable { let json = try m.encodedJSONString(options: options) encoder.append(text: json) } else if let newNameMap = (M.self as? _ProtoNameProviding.Type)?._protobuf_nameMap { // Preserve outer object's name and extension maps; restore them before returning let oldNameMap = self.nameMap let oldExtensions = self.extensions defer { self.nameMap = oldNameMap self.extensions = oldExtensions } // Install inner object's name and extension maps self.nameMap = newNameMap startObject(message: value) try value.traverse(visitor: &self) endObject() } else { throw JSONEncodingError.missingFieldNames } } mutating func visitSingularGroupField<G: Message>(value: G, fieldNumber: Int) throws { // Google does not serialize groups into JSON } mutating func visitRepeatedFloatField(value: [Float], fieldNumber: Int) throws { try _visitRepeated(value: value, fieldNumber: fieldNumber) { (encoder: inout JSONEncoder, v: Float) in encoder.putFloatValue(value: v) } } mutating func visitRepeatedDoubleField(value: [Double], fieldNumber: Int) throws { try _visitRepeated(value: value, fieldNumber: fieldNumber) { (encoder: inout JSONEncoder, v: Double) in encoder.putDoubleValue(value: v) } } mutating func visitRepeatedInt32Field(value: [Int32], fieldNumber: Int) throws { try _visitRepeated(value: value, fieldNumber: fieldNumber) { (encoder: inout JSONEncoder, v: Int32) in encoder.putInt32(value: v) } } mutating func visitRepeatedInt64Field(value: [Int64], fieldNumber: Int) throws { try _visitRepeated(value: value, fieldNumber: fieldNumber) { (encoder: inout JSONEncoder, v: Int64) in encoder.putInt64(value: v) } } mutating func visitRepeatedUInt32Field(value: [UInt32], fieldNumber: Int) throws { try _visitRepeated(value: value, fieldNumber: fieldNumber) { (encoder: inout JSONEncoder, v: UInt32) in encoder.putUInt32(value: v) } } mutating func visitRepeatedUInt64Field(value: [UInt64], fieldNumber: Int) throws { try _visitRepeated(value: value, fieldNumber: fieldNumber) { (encoder: inout JSONEncoder, v: UInt64) in encoder.putUInt64(value: v) } } mutating func visitRepeatedSInt32Field(value: [Int32], fieldNumber: Int) throws { try visitRepeatedInt32Field(value: value, fieldNumber: fieldNumber) } mutating func visitRepeatedSInt64Field(value: [Int64], fieldNumber: Int) throws { try visitRepeatedInt64Field(value: value, fieldNumber: fieldNumber) } mutating func visitRepeatedFixed32Field(value: [UInt32], fieldNumber: Int) throws { try visitRepeatedUInt32Field(value: value, fieldNumber: fieldNumber) } mutating func visitRepeatedFixed64Field(value: [UInt64], fieldNumber: Int) throws { try visitRepeatedUInt64Field(value: value, fieldNumber: fieldNumber) } mutating func visitRepeatedSFixed32Field(value: [Int32], fieldNumber: Int) throws { try visitRepeatedInt32Field(value: value, fieldNumber: fieldNumber) } mutating func visitRepeatedSFixed64Field(value: [Int64], fieldNumber: Int) throws { try visitRepeatedInt64Field(value: value, fieldNumber: fieldNumber) } mutating func visitRepeatedBoolField(value: [Bool], fieldNumber: Int) throws { try _visitRepeated(value: value, fieldNumber: fieldNumber) { (encoder: inout JSONEncoder, v: Bool) in encoder.putBoolValue(value: v) } } mutating func visitRepeatedStringField(value: [String], fieldNumber: Int) throws { try _visitRepeated(value: value, fieldNumber: fieldNumber) { (encoder: inout JSONEncoder, v: String) in encoder.putStringValue(value: v) } } mutating func visitRepeatedBytesField(value: [Data], fieldNumber: Int) throws { try _visitRepeated(value: value, fieldNumber: fieldNumber) { (encoder: inout JSONEncoder, v: Data) in encoder.putBytesValue(value: v) } } mutating func visitRepeatedEnumField<E: Enum>(value: [E], fieldNumber: Int) throws { if let _ = E.self as? _CustomJSONCodable.Type { let options = self.options try _visitRepeated(value: value, fieldNumber: fieldNumber) { (encoder: inout JSONEncoder, v: E) throws in let e = v as! _CustomJSONCodable let json = try e.encodedJSONString(options: options) encoder.append(text: json) } } else { let alwaysPrintEnumsAsInts = options.alwaysPrintEnumsAsInts try _visitRepeated(value: value, fieldNumber: fieldNumber) { (encoder: inout JSONEncoder, v: E) throws in if !alwaysPrintEnumsAsInts, let n = v.name { encoder.appendQuoted(name: n) } else { encoder.putEnumInt(value: v.rawValue) } } } } mutating func visitRepeatedMessageField<M: Message>(value: [M], fieldNumber: Int) throws { assert(!value.isEmpty) try startField(for: fieldNumber) var comma = false encoder.startArray() if let _ = M.self as? _CustomJSONCodable.Type { for v in value { if comma { encoder.comma() } comma = true let json = try v.jsonString(options: options) encoder.append(text: json) } } else if let newNameMap = (M.self as? _ProtoNameProviding.Type)?._protobuf_nameMap { // Preserve name and extension maps for outer object let oldNameMap = self.nameMap let oldExtensions = self.extensions // Restore outer object's name and extension maps before returning defer { self.nameMap = oldNameMap self.extensions = oldExtensions } self.nameMap = newNameMap for v in value { startArrayObject(message: v) try v.traverse(visitor: &self) encoder.endObject() } } else { throw JSONEncodingError.missingFieldNames } encoder.endArray() } mutating func visitRepeatedGroupField<G: Message>(value: [G], fieldNumber: Int) throws { assert(!value.isEmpty) // Google does not serialize groups into JSON } // Packed fields are handled the same as non-packed fields, so JSON just // relies on the default implementations in Visitor.swift mutating func visitMapField<KeyType, ValueType: MapValueType>(fieldType: _ProtobufMap<KeyType, ValueType>.Type, value: _ProtobufMap<KeyType, ValueType>.BaseType, fieldNumber: Int) throws { try startField(for: fieldNumber) encoder.append(text: "{") var mapVisitor = JSONMapEncodingVisitor(encoder: encoder, options: options) for (k,v) in value { try KeyType.visitSingular(value: k, fieldNumber: 1, with: &mapVisitor) try ValueType.visitSingular(value: v, fieldNumber: 2, with: &mapVisitor) } encoder = mapVisitor.encoder encoder.append(text: "}") } mutating func visitMapField<KeyType, ValueType>(fieldType: _ProtobufEnumMap<KeyType, ValueType>.Type, value: _ProtobufEnumMap<KeyType, ValueType>.BaseType, fieldNumber: Int) throws where ValueType.RawValue == Int { try startField(for: fieldNumber) encoder.append(text: "{") var mapVisitor = JSONMapEncodingVisitor(encoder: encoder, options: options) for (k, v) in value { try KeyType.visitSingular(value: k, fieldNumber: 1, with: &mapVisitor) try mapVisitor.visitSingularEnumField(value: v, fieldNumber: 2) } encoder = mapVisitor.encoder encoder.append(text: "}") } mutating func visitMapField<KeyType, ValueType>(fieldType: _ProtobufMessageMap<KeyType, ValueType>.Type, value: _ProtobufMessageMap<KeyType, ValueType>.BaseType, fieldNumber: Int) throws { try startField(for: fieldNumber) encoder.append(text: "{") var mapVisitor = JSONMapEncodingVisitor(encoder: encoder, options: options) for (k,v) in value { try KeyType.visitSingular(value: k, fieldNumber: 1, with: &mapVisitor) try mapVisitor.visitSingularMessageField(value: v, fieldNumber: 2) } encoder = mapVisitor.encoder encoder.append(text: "}") } /// Helper function that throws an error if the field number could not be /// resolved. private mutating func startField(for number: Int) throws { let name: _NameMap.Name? if options.preserveProtoFieldNames { name = nameMap.names(for: number)?.proto } else { name = nameMap.names(for: number)?.json } if let name = name { encoder.startField(name: name) } else if let name = extensions?[number]?.protobufExtension.fieldName { encoder.startExtensionField(name: name) } else { throw JSONEncodingError.missingFieldNames } } }
apache-2.0
2c0f9fb9050e8b790c22532ca5ce99aa
33.321782
217
0.690826
4.478682
false
false
false
false
kgellci/QuickTable
QuickTable/Classes/QuickSection.swift
1
6544
// // QuickSection.swift // Pods // // Created by Kris Gellci on 5/11/17. // // import UIKit // MARK: Protocols /// Protocol for the UITableViewDelegate and UITableViewDataSource to communicate with QuickSections public protocol QuickSectionProtocol { /// The section header title var headerTitle: String? { get set } // The section footer title var footerTitle: String? { get set } // the Table View row height var rowHeight: CGFloat? { get set } /// A way to retrieve a row from the sections rows /// - Parameter index: the index for the row to be retrieved /// - Returns: The QuickRow at the given index func quickRowForIndex(_ index: Int) -> QuickRow /// A way to retrieve the number of rows in the section /// - Returns: the number of rows in the section func numberOfRows() -> Int /// A way to retrieve the height for a given row /// - Parameter index: the index for the row for which the height is needed /// - Returns: The height of the row at the given index. Defaults to UITableViewAutomaticDimension func heightForRowAtIndex(_ index: Int) -> CGFloat } // MARK: Enums /// Options used to configure any subclass of QuickSectionBase public enum QuickSectionOption { /// Pass in a String to set the section header title case headerTitle(String) /// Pass in a String to set the section footer title case footerTitle(String) /// Pass in an Int to set the number of rows in a section. Used for QuickSectionDynamic only case rowCount(Int) /// Pass in a CGFloat to defince the default height for all rows in the section case rowHeight(CGFloat) } // MARK: Typealiases /// Similar to UITableViewDataSource cellForRowAtIndexPath public typealias QuickSectionDynamicRowBlock = (Int) -> QuickRow // MARK: Classes /// QuickSectionBase is a base class, not to be instantiated on its own, use one of the subclasses public class QuickSectionBase: QuickSectionProtocol { public var headerTitle: String? public var footerTitle: String? public var rowHeight: CGFloat? /// parses the options and populates the Section fileprivate func populateFromOptions(_ options: [QuickSectionOption]) { for option in options { populateFromOption(option) } } /// populates the appropriate value on the section based on the passed in option fileprivate func populateFromOption(_ option: QuickSectionOption) { switch option { case .headerTitle(let text): headerTitle = text case .footerTitle(let text): footerTitle = text case .rowHeight(let rowHeight): self.rowHeight = rowHeight default: print("\(option) not handled by super") } } public func numberOfRows() -> Int { assert(false, "numberOfRows not implemented in subclass") return 0 } public func quickRowForIndex(_ index: Int) -> QuickRow { assert(false, "cellModelAtRow not implemented in subclass") return QuickRow(reuseIdentifier: "", styleBlock: nil) } public func heightForRowAtIndex(_ index: Int) -> CGFloat { assert(false, "heightForRow not implemented in subclass") return 0 } } /// A dynamic way to define a UITableView section public class QuickSectionDynamic: QuickSectionBase { /// block will fire when the QuickRow is needed for display or calculating height private let quickRowFetchBlock: QuickSectionDynamicRowBlock /// number of rows in this section var rowCount: Int = 0 public init(options: [QuickSectionOption], quickRowFetchBlock: @escaping QuickSectionDynamicRowBlock) { self.quickRowFetchBlock = quickRowFetchBlock super.init() self.populateFromOptions(options) } override func populateFromOption(_ option: QuickSectionOption) { switch option { case .rowCount(let count): rowCount = count default: super.populateFromOption(option) } } override public func numberOfRows() -> Int { return rowCount } public override func quickRowForIndex(_ index: Int) -> QuickRow { return quickRowFetchBlock(index) } public override func heightForRowAtIndex(_ index: Int) -> CGFloat { if let rowHeight = rowHeight { return rowHeight } return quickRowFetchBlock(index).height() } } // A way to define a section of rows in a UITableView public class QuickSection: QuickSectionBase { /// QuickRow models to display in the section public var quickRowModels = [QuickRow]() /// instantiate an empty QuickSection public override init() { super.init() } /// Instantiate a QuickSection from the given QuickRows /// - Parameter quickRowModels: QuickRow Array which the section will display public init(quickRowModels: [QuickRow]) { super.init() self.quickRowModels = quickRowModels } /// instantiate a QuickSection populated by the given options /// - Parameter options: something public init(options: [QuickSectionOption]) { super.init() self.populateFromOptions(options) } /// instantiate a QuickSection populated by the given options and QuickRows /// - Parameter quickRowModels: QuickRow Array which the section will display /// - Parameter options: something public init(quickRowModels: [QuickRow], options: [QuickSectionOption]) { super.init() self.quickRowModels = quickRowModels self.populateFromOptions(options) } /// A convenient way to add a single QuickRow to a QuickSections rows. The QuickRow will be added to the end. /// - Parameter left: The QuickSection to add the QuickRow to /// - Parameter right: The QuickRow to be added to the QuickSections list of rows public static func +=(left: QuickSection, right: QuickRow) { // 1 left.quickRowModels.append(right) } public override func quickRowForIndex(_ index: Int) -> QuickRow { return quickRowModels[index] } override public func numberOfRows() -> Int { return quickRowModels.count } public override func heightForRowAtIndex(_ index: Int) -> CGFloat { if let rowHeight = rowHeight { return rowHeight } return quickRowModels[index].height() } }
mit
4184ba544b46ec04509702c60aac9438
31.884422
113
0.665037
5.096573
false
false
false
false
APUtils/APExtensions
APExtensions/Classes/Storyboard/UIView+Storyboard.swift
1
2711
// // UIView+Storyboard.swift // APExtensions // // Created by Anton Plebanovich on 19.02.16. // Copyright © 2019 Anton Plebanovich. All rights reserved. // import UIKit // ******************************* MARK: - Border public extension UIView { @IBInspectable var borderColor: UIColor? { get { guard let borderColor = layer.borderColor else { return nil } return UIColor(cgColor: borderColor) } set { layer.borderColor = newValue?.cgColor } } @IBInspectable var borderWidth: CGFloat { get { return layer.borderWidth } set { layer.borderWidth = newValue } } /// Sets border width equal to 1 pixel @IBInspectable var borderOnePixelWidth: Bool { get { return layer.borderWidth == 1.0 / UIScreen.main.scale } set { if newValue { layer.borderWidth = 1.0 / UIScreen.main.scale } else { layer.borderWidth = 1.0 } } } } // ******************************* MARK: - Corner Radius public extension UIView { @IBInspectable var cornerRadius: CGFloat { get { return layer.cornerRadius } set { layer.cornerRadius = newValue } } } // ******************************* MARK: - Shadow public extension UIView { @IBInspectable var shadowColor: UIColor? { get { guard let shadowColor = layer.shadowColor else { return nil } return UIColor(cgColor: shadowColor) } set { layer.shadowColor = newValue?.cgColor } } @IBInspectable var shadowOffset: CGPoint { get { return CGPoint(x: layer.shadowOffset.width, y: layer.shadowOffset.height) } set { layer.shadowOffset = CGSize(width: newValue.x, height: newValue.y) } } @IBInspectable var shadowOpacity: Float { get { return layer.shadowOpacity } set { layer.shadowOpacity = newValue } } @IBInspectable var shadowRadius: CGFloat { get { return layer.shadowRadius } set { layer.shadowRadius = newValue } } /// Apply square path for shadow. This increases performance for shadow drawing in case shadow is square. @IBInspectable var shadowApplyPath: Bool { get { return layer.shadowPath != nil } set { layer.shadowPath = UIBezierPath(rect: bounds).cgPath } } }
mit
05384691a3bd1136a2797f0f2fc9621f
23.196429
109
0.517343
5.211538
false
false
false
false
AntonTheDev/XCode-DI-Templates
Source/ProjectTemplates/tvOS/XCode-DI.xctemplate/Source/Extensions/NSMutableAttributedString+PSD.swift
2
3050
// // NSMutableAttributedString+PSD.swift // HUGE START // // Copyright © 2017 HUGE Inc. All rights reserved. import Foundation import UIKit extension NSMutableAttributedString { convenience init?(copyString: String?, font : UIFont, tracking : CGFloat = 0.0, leading : CGFloat = 0.0, textAlignment : NSTextAlignment = NSTextAlignment.left, lineBreakMode : NSLineBreakMode = NSLineBreakMode.byTruncatingTail, color : UIColor = UIColor.white, underlined : Bool = false, bold : Bool = false) { self.init(string: copyString ?? "") let attributes = customAttributes(font: font, tracking : tracking, leading : leading, textAlignment : textAlignment, lineBreakMode : lineBreakMode, color : color, underlined : underlined, bold : bold) setAttributes(attributes, range: NSMakeRange(0, length)) } private func customAttributes(font : UIFont, tracking : CGFloat = 0.0, leading : CGFloat = 0.0, textAlignment : NSTextAlignment = NSTextAlignment.left, lineBreakMode : NSLineBreakMode = NSLineBreakMode.byTruncatingTail, color : UIColor = UIColor.white, underlined : Bool = false, bold : Bool = false) -> Dictionary<NSAttributedStringKey , AnyObject> { var attributes = Dictionary<NSAttributedStringKey , AnyObject>() let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.minimumLineHeight = leading / 2.0 paragraphStyle.maximumLineHeight = leading / 2.0 paragraphStyle.alignment = textAlignment paragraphStyle.lineBreakMode = lineBreakMode if underlined { attributes[NSAttributedStringKey.underlineStyle] = NSUnderlineStyle.styleSingle.rawValue as AnyObject? } attributes[NSAttributedStringKey.paragraphStyle] = paragraphStyle attributes[NSAttributedStringKey.foregroundColor] = color if bold { attributes[NSAttributedStringKey.font] = UIFont(descriptor: font.fontDescriptor.withSymbolicTraits(.traitBold)!, size: font.pointSize) } else { attributes[NSAttributedStringKey.font] = font } if tracking != 0.0 { attributes[NSAttributedStringKey.kern] = (font.pointSize * tracking / CGFloat(1000.0) as AnyObject?) } return attributes } }
mit
9810b5adb4852ce18f880b494fb63876
40.767123
146
0.52673
6.913832
false
false
false
false
richardpiazza/SOSwift
Tests/SOSwiftTests/DataDownloadTests.swift
1
794
import XCTest @testable import SOSwift class DataDownloadTests: XCTestCase { static var allTests = [ ("testSchema", testSchema), ("testDecode", testDecode), ("testEncode", testEncode), ] public static var dataDownload: DataDownload { let dataDownload = DataDownload() return dataDownload } func testSchema() throws { XCTAssertEqual(DataDownload.schemaName, "DataDownload") } func testDecode() throws { let json = """ { } """ let dataDownload = try DataDownload.make(with: json) } func testEncode() throws { let dictionary = try DataDownloadTests.dataDownload.asDictionary() } }
mit
01034e88ac7b0ecbc0a0bc66d4652f3a
19.894737
74
0.554156
5.552448
false
true
false
false
rsmoz/swift-package-manager
Tests/sys/PathTests.swift
1
8556
/* This source file is part of the Swift.org open source project Copyright 2015 Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for Swift project authors */ import XCTest import XCTestCaseProvider import POSIX @testable import sys class PathTests: XCTestCase, XCTestCaseProvider { var allTests : [(String, () throws -> Void)] { return [ ("test", test), ("testPrecombined", testPrecombined), ("testExtraSeparators", testExtraSeparators), ("testEmpties", testEmpties), ("testNormalizePath", testNormalizePath), ("testJoinWithAbsoluteReturnsLastAbsoluteComponent", testJoinWithAbsoluteReturnsLastAbsoluteComponent), ("testParentDirectory", testParentDirectory), ] } func test() { XCTAssertEqual(Path.join("a","b","c","d"), "a/b/c/d") XCTAssertEqual(Path.join("/a","b","c","d"), "/a/b/c/d") XCTAssertEqual(Path.join("/", "a"), "/a") XCTAssertEqual(Path.join("//", "a"), "/a") XCTAssertEqual(Path.join("//", "//", "/", "///", "", "/", "//", "a"), "/a") XCTAssertEqual(Path.join("//", "//a//"), "/a") XCTAssertEqual(Path.join("/////"), "/") } func testPrecombined() { XCTAssertEqual(Path.join("a","b/c","d/"), "a/b/c/d") XCTAssertEqual(Path.join("a","b///c","d/"), "a/b/c/d") XCTAssertEqual(Path.join("/a","b/c","d/"), "/a/b/c/d") XCTAssertEqual(Path.join("/a","b///c","d/"), "/a/b/c/d") } func testExtraSeparators() { XCTAssertEqual(Path.join("a","b/","c/","d/"), "a/b/c/d") XCTAssertEqual(Path.join("/a","b/","c/","d/"), "/a/b/c/d") } func testEmpties() { XCTAssertEqual(Path.join("a","b/","","","c//","d/", ""), "a/b/c/d") XCTAssertEqual(Path.join("/a","b/","","","c//","d/", ""), "/a/b/c/d") } func testNormalizePath() { XCTAssertEqual("".normpath, ".") XCTAssertEqual("foo/../bar".normpath, "bar") XCTAssertEqual("foo///..///bar///baz".normpath, "bar/baz") XCTAssertEqual("foo/../bar/./".normpath, "bar") XCTAssertEqual("/".normpath, "/") XCTAssertEqual("////".normpath, "/") XCTAssertEqual("/abc/..".normpath, "/") XCTAssertEqual("/abc/def///".normpath, "/abc/def") XCTAssertEqual("../abc/def/".normpath, "../abc/def") XCTAssertEqual("../abc/../def/".normpath, "../def") XCTAssertEqual(".".normpath, ".") XCTAssertEqual("./././.".normpath, ".") XCTAssertEqual("./././../.".normpath, "..") // Only run tests using HOME if it is defined. if POSIX.getenv("HOME") != nil { XCTAssertEqual("~".normpath, Path.home) XCTAssertEqual("~abc".normpath, Path.join(Path.home, "..", "abc").normpath) } } func testJoinWithAbsoluteReturnsLastAbsoluteComponent() { XCTAssertEqual(Path.join("foo", "/abc/def"), "/abc/def") } func testParentDirectory() { XCTAssertEqual("foo/bar/baz".parentDirectory, "foo/bar") XCTAssertEqual("foo/bar/baz".parentDirectory.parentDirectory, "foo") XCTAssertEqual("/bar".parentDirectory, "/") XCTAssertEqual("/".parentDirectory.parentDirectory, "/") XCTAssertEqual("/bar/../foo/..//".parentDirectory.parentDirectory, "/") } } class WalkTests: XCTestCase, XCTestCaseProvider { var allTests : [(String, () throws -> Void)] { return [ ("testNonRecursive", testNonRecursive), ("testRecursive", testRecursive), ("testSymlinksNotWalked", testSymlinksNotWalked), ("testWalkingADirectorySymlinkResolvesOnce", testWalkingADirectorySymlinkResolvesOnce), ] } func testNonRecursive() { var expected = ["/usr", "/bin", "/sbin"] for x in walk("/", recursively: false) { if let i = expected.indexOf(x) { expected.removeAtIndex(i) } XCTAssertEqual(1, x.characters.split("/").count) } XCTAssertEqual(expected.count, 0) } func testRecursive() { let root = Path.join(__FILE__, "../../../Sources").normpath var expected = [ Path.join(root, "dep"), Path.join(root, "sys") ] for x in walk(root) { if let i = expected.indexOf(x) { expected.removeAtIndex(i) } } XCTAssertEqual(expected.count, 0) } func testSymlinksNotWalked() { do { try mkdtemp("foo") { root in let root = try realpath(root) //FIXME not good that we need this? try mkdir(root, "foo") try mkdir(root, "bar/baz/goo") try symlink(create: "\(root)/foo/symlink", pointingAt: "\(root)/bar", relativeTo: root) XCTAssertTrue("\(root)/foo/symlink".isSymlink) XCTAssertEqual(try! realpath("\(root)/foo/symlink"), "\(root)/bar") XCTAssertTrue(try! realpath("\(root)/foo/symlink/baz").isDirectory) let results = walk(root, "foo").map{$0} XCTAssertEqual(results, ["\(root)/foo/symlink"]) } } catch { XCTFail("\(error)") } } func testWalkingADirectorySymlinkResolvesOnce() { try! mkdtemp("foo") { root in let root = try realpath(root) //FIXME not good that we need this? try mkdir(root, "foo/bar") try mkdir(root, "abc/bar") try symlink(create: "\(root)/symlink", pointingAt: "\(root)/foo", relativeTo: root) try symlink(create: "\(root)/foo/baz", pointingAt: "\(root)/abc", relativeTo: root) XCTAssertTrue(Path.join(root, "symlink").isSymlink) let results = walk(root, "symlink").map{$0}.sort() // we recurse a symlink to a directory, so this should work, // but `abc` should not show because `baz` is a symlink too // and that should *not* be followed XCTAssertEqual(results, ["\(root)/symlink/bar", "\(root)/symlink/baz"]) } } } class StatTests: XCTestCase, XCTestCaseProvider { var allTests : [(String, () throws -> Void)] { return [ ("test_isdir", test_isdir), ("test_isfile", test_isfile), ("test_realpath", test_realpath), ("test_basename", test_basename), ] } func test_isdir() { XCTAssertTrue("/usr".isDirectory) XCTAssertTrue("/etc/passwd".isFile) try! mkdtemp("foo") { root in try mkdir(root, "foo/bar") try symlink(create: "\(root)/symlink", pointingAt: "\(root)/foo", relativeTo: root) XCTAssertTrue("\(root)/foo/bar".isDirectory) XCTAssertTrue("\(root)/symlink/bar".isDirectory) XCTAssertTrue("\(root)/symlink".isDirectory) XCTAssertTrue("\(root)/symlink".isSymlink) try POSIX.rmdir("\(root)/foo/bar") try POSIX.rmdir("\(root)/foo") XCTAssertTrue("\(root)/symlink".isSymlink) XCTAssertFalse("\(root)/symlink".isDirectory) XCTAssertFalse("\(root)/symlink".isFile) } } func test_isfile() { XCTAssertTrue(!"/usr".isFile) XCTAssertTrue("/etc/passwd".isFile) } func test_realpath() { XCTAssertEqual(try! realpath("."), try! getcwd()) } func test_basename() { XCTAssertEqual("base", "foo/bar/base".basename) XCTAssertEqual("base.ext", "foo/bar/base.ext".basename) XCTAssertNotEqual("bar", "foo/bar/base".basename) XCTAssertNotEqual("base.ext", "foo/bar/base".basename) } } class RelativePathTests: XCTestCase, XCTestCaseProvider { var allTests : [(String, () throws -> Void)] { return [ ("testAbsolute", testAbsolute), ("testRelative", testRelative), ("testMixed", testMixed), ] } func testAbsolute() { XCTAssertEqual("2/3", Path("/1/2/3").relative(to: "/1/")) XCTAssertEqual("3/4", Path("/1/2////3/4///").relative(to: "////1//2//")) } func testRelative() { XCTAssertEqual("3/4", Path("1/2/3/4").relative(to: "1/2")) } func testMixed() { XCTAssertEqual("3/4", Path(try! getcwd() + "/1/2/3/4").relative(to: "1/2")) } }
apache-2.0
06dd19f9de0c8cf07f77a04ac0ba0d12
32.952381
115
0.55353
4.246154
false
true
false
false
raymondshadow/SwiftDemo
SwiftApp/Pods/RxSwift/RxSwift/Observables/Timeout.swift
4
5457
// // Timeout.swift // RxSwift // // Created by Tomi Koskinen on 13/11/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // extension ObservableType { /** Applies a timeout policy for each element in the observable sequence. If the next element isn't received within the specified timeout duration starting from its predecessor, a TimeoutError is propagated to the observer. - seealso: [timeout operator on reactivex.io](http://reactivex.io/documentation/operators/timeout.html) - parameter dueTime: Maximum duration between values before a timeout occurs. - parameter scheduler: Scheduler to run the timeout timer on. - returns: An observable sequence with a `RxError.timeout` in case of a timeout. */ public func timeout(_ dueTime: RxTimeInterval, scheduler: SchedulerType) -> Observable<E> { return Timeout(source: self.asObservable(), dueTime: dueTime, other: Observable.error(RxError.timeout), scheduler: scheduler) } /** Applies a timeout policy for each element in the observable sequence, using the specified scheduler to run timeout timers. If the next element isn't received within the specified timeout duration starting from its predecessor, the other observable sequence is used to produce future messages from that point on. - seealso: [timeout operator on reactivex.io](http://reactivex.io/documentation/operators/timeout.html) - parameter dueTime: Maximum duration between values before a timeout occurs. - parameter other: Sequence to return in case of a timeout. - parameter scheduler: Scheduler to run the timeout timer on. - returns: The source sequence switching to the other sequence in case of a timeout. */ public func timeout<O: ObservableConvertibleType>(_ dueTime: RxTimeInterval, other: O, scheduler: SchedulerType) -> Observable<E> where E == O.E { return Timeout(source: self.asObservable(), dueTime: dueTime, other: other.asObservable(), scheduler: scheduler) } } final private class TimeoutSink<O: ObserverType>: Sink<O>, LockOwnerType, ObserverType { typealias E = O.E typealias Parent = Timeout<E> private let _parent: Parent let _lock = RecursiveLock() private let _timerD = SerialDisposable() private let _subscription = SerialDisposable() private var _id = 0 private var _switched = false init(parent: Parent, observer: O, cancel: Cancelable) { self._parent = parent super.init(observer: observer, cancel: cancel) } func run() -> Disposable { let original = SingleAssignmentDisposable() self._subscription.disposable = original self._createTimeoutTimer() original.setDisposable(self._parent._source.subscribe(self)) return Disposables.create(_subscription, _timerD) } func on(_ event: Event<E>) { switch event { case .next: var onNextWins = false self._lock.performLocked { onNextWins = !self._switched if onNextWins { self._id = self._id &+ 1 } } if onNextWins { self.forwardOn(event) self._createTimeoutTimer() } case .error, .completed: var onEventWins = false self._lock.performLocked { onEventWins = !self._switched if onEventWins { self._id = self._id &+ 1 } } if onEventWins { self.forwardOn(event) self.dispose() } } } private func _createTimeoutTimer() { if self._timerD.isDisposed { return } let nextTimer = SingleAssignmentDisposable() self._timerD.disposable = nextTimer let disposeSchedule = self._parent._scheduler.scheduleRelative(self._id, dueTime: self._parent._dueTime) { state in var timerWins = false self._lock.performLocked { self._switched = (state == self._id) timerWins = self._switched } if timerWins { self._subscription.disposable = self._parent._other.subscribe(self.forwarder()) } return Disposables.create() } nextTimer.setDisposable(disposeSchedule) } } final private class Timeout<Element>: Producer<Element> { fileprivate let _source: Observable<Element> fileprivate let _dueTime: RxTimeInterval fileprivate let _other: Observable<Element> fileprivate let _scheduler: SchedulerType init(source: Observable<Element>, dueTime: RxTimeInterval, other: Observable<Element>, scheduler: SchedulerType) { self._source = source self._dueTime = dueTime self._other = other self._scheduler = scheduler } override func run<O : ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element { let sink = TimeoutSink(parent: self, observer: observer, cancel: cancel) let subscription = sink.run() return (sink: sink, subscription: subscription) } }
apache-2.0
dc136ff8f4fdd282c1db843dcdec6f2c
35.13245
316
0.617485
5.226054
false
false
false
false
carabina/Taylor
Taylor/Request.swift
1
4614
// // request.swift // TaylorTest // // Created by Jorge Izquierdo on 19/06/14. // Copyright (c) 2014 Jorge Izquierdo. All rights reserved. // import Foundation import QuartzCore public class Request { public var path: String { didSet { var comps = self.path.componentsSeparatedByString("/") //We don't care about the first element, which will always be nil since paths are like this: "/something" for i in 1..<comps.count { self.pathComponents.append(comps[i]) } } } public var pathComponents: [String] = [String]() public var arguments: Dictionary<String, String> = Dictionary<String, String>() // ?hello=world -> arguments["hello"] public var parameters: Dictionary<String, String> = Dictionary<String, String>() // /:something -> parameters["something"] public var method: Taylor.HTTPMethod = .UNDEFINED public var headers: Dictionary<String, String> = Dictionary<String, String>() //var bodyData: NSData? public var bodyString: NSString? public var body: Dictionary<String, String> = Dictionary<String, String>() internal var startTime: Double = CACurrentMediaTime() var _protocol: String? convenience init(){ self.init(data: nil) } init(data d: NSData?){ self.path = String() //Parsing data from socket to build a HTTP request if d != nil { self.parseRequest(d!) } } private func parseRequest(d: NSData){ //TODO: Parse data line by line, so if body content is not UTF8 encoded, this doesn't crash let string = NSString(data: d, encoding: NSUTF8StringEncoding) var http: [String] = string!.componentsSeparatedByString("\r\n") as [String] //Parse method if http.count > 0 { // The delimiter can be any number of blank spaces var startLineArr: [String] = http[0].characters.split { $0 == " " }.map { String($0) } if startLineArr.count > 0 { if let m = Taylor.HTTPMethod(rawValue: startLineArr[0]) { self.method = m } } //Parse URL if startLineArr.count > 1 { let url = startLineArr[1] var urlElements: [String] = url.componentsSeparatedByString("?") as [String] self.path = urlElements[0] if urlElements.count == 2 { let args = urlElements[1].componentsSeparatedByString("&") as [String] for a in args { var arg = a.componentsSeparatedByString("=") as [String] //Would be nicer changing it to something that checks if element in array exists var value = "" if arg.count > 1 { value = arg[1] } // Adding the values removing the %20 bullshit and stuff self.arguments.updateValue(value.stringByRemovingPercentEncoding!, forKey: arg[0].stringByRemovingPercentEncoding!) } } } //TODO: Parse HTTP version if startLineArr.count > 2{ _protocol = startLineArr[2] } } //Parse Headers var i = 0 while ++i < http.count { let content = http[i] if content == "" { // This newline means headers have ended and body started (New line already got parsed ("\r\n")) break } var header = content.componentsSeparatedByString(": ") as [String] if header.count == 2 { self.headers.updateValue(header[1], forKey: header[0]) } } if i < http.count && (self.method == Taylor.HTTPMethod.POST || false) { // Add other methods that support body data let str = NSMutableString() while ++i < http.count { str.appendString("\(http[i])\n") } self.bodyString = str } } }
mit
987170c64c31a5f7c3963405c2e31599
31.723404
139
0.493065
5.396491
false
false
false
false
opentok/opentok-ios-sdk-samples-swift
Multiparty-UICollectionView/Multiparty-UICollectionView/ChatViewController.swift
1
5854
// // ViewController.swift // 7.Multiparty-UICollectionView // // Created by Roberto Perez Cubero on 17/04/2017. // Copyright © 2017 tokbox. All rights reserved. // import UIKit import OpenTok // *** Fill the following variables using your own Project info *** // *** https://tokbox.com/account/#/ *** // Replace with your OpenTok API key let kApiKey = "" // Replace with your generated session ID let kSessionId = "" // Replace with your generated token let kToken = "" class ChatViewController: UICollectionViewController { lazy var session: OTSession = { return OTSession(apiKey: kApiKey, sessionId: kSessionId, delegate: self)! }() lazy var publisher: OTPublisher = { let settings = OTPublisherSettings() settings.name = UIDevice.current.name return OTPublisher(delegate: self, settings: settings)! }() var subscribers: [OTSubscriber] = [] override func viewDidLoad() { super.viewDidLoad() doConnect() } /** * Asynchronously begins the session connect process. Some time later, we will * expect a delegate method to call us back with the results of this action. */ fileprivate func doConnect() { var error: OTError? defer { processError(error) } session.connect(withToken: kToken, error: &error) } /** * Sets up an instance of OTPublisher to use with this session. OTPubilsher * binds to the device camera and microphone, and will provide A/V streams * to the OpenTok session. */ fileprivate func doPublish() { var error: OTError? defer { processError(error) } session.publish(publisher, error: &error) collectionView?.reloadData() } /** * Instantiates a subscriber for the given stream and asynchronously begins the * process to begin receiving A/V content for this stream. Unlike doPublish, * this method does not add the subscriber to the view hierarchy. Instead, we * add the subscriber only after it has connected and begins receiving data. */ fileprivate func doSubscribe(_ stream: OTStream) { var error: OTError? defer { processError(error) } guard let subscriber = OTSubscriber(stream: stream, delegate: self) else { print("Error while subscribing") return } session.subscribe(subscriber, error: &error) subscribers.append(subscriber) collectionView?.reloadData() } fileprivate func cleanupSubscriber(_ stream: OTStream) { subscribers = subscribers.filter { $0.stream?.streamId != stream.streamId } collectionView?.reloadData() } fileprivate func processError(_ error: OTError?) { if let err = error { showAlert(errorStr: err.localizedDescription) } } fileprivate func showAlert(errorStr err: String) { DispatchQueue.main.async { let controller = UIAlertController(title: "Error", message: err, preferredStyle: .alert) controller.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil)) self.present(controller, animated: true, completion: nil) } } // MARK: - UICollectionView methods override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return subscribers.count + 1 } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "videoCell", for: indexPath) let videoView: UIView? = { if (indexPath.row == 0) { return publisher.view } else { let sub = subscribers[indexPath.row - 1] return sub.view } }() if let viewToAdd = videoView { viewToAdd.frame = cell.bounds cell.addSubview(viewToAdd) } return cell } } // MARK: - OTSession delegate callbacks extension ChatViewController: OTSessionDelegate { func sessionDidConnect(_ session: OTSession) { print("Session connected") doPublish() } func sessionDidDisconnect(_ session: OTSession) { print("Session disconnected") } func session(_ session: OTSession, streamCreated stream: OTStream) { print("Session streamCreated: \(stream.streamId)") doSubscribe(stream) } func session(_ session: OTSession, streamDestroyed stream: OTStream) { print("Session streamDestroyed: \(stream.streamId)") cleanupSubscriber(stream) } func session(_ session: OTSession, didFailWithError error: OTError) { print("session Failed to connect: \(error.localizedDescription)") } } // MARK: - OTPublisher delegate callbacks extension ChatViewController: OTPublisherDelegate { func publisher(_ publisher: OTPublisherKit, streamCreated stream: OTStream) { } func publisher(_ publisher: OTPublisherKit, streamDestroyed stream: OTStream) { } func publisher(_ publisher: OTPublisherKit, didFailWithError error: OTError) { print("Publisher failed: \(error.localizedDescription)") } } // MARK: - OTSubscriber delegate callbacks extension ChatViewController: OTSubscriberDelegate { func subscriberDidConnect(toStream subscriberKit: OTSubscriberKit) { print("Subscriber connected") } func subscriber(_ subscriber: OTSubscriberKit, didFailWithError error: OTError) { print("Subscriber failed: \(error.localizedDescription)") } func subscriberVideoDataReceived(_ subscriber: OTSubscriber) { } }
mit
f43269b70b2c8b0ff996fb45d81949b9
30.983607
130
0.649581
5.054404
false
false
false
false
ResearchSuite/ResearchSuiteAppFramework-iOS
Source/Core/Classes/RSAFCorePersistentStoreSubscriber.swift
1
1644
// // RSAFCorePersistentStoreSubscriber.swift // Pods // // Created by James Kizer on 3/22/17. // // import UIKit final public class RSAFCorePersistentStoreSubscriber: RSAFBasePersistentStoreSubscriber { static let kLoggedIn: String = "LoggedIn" static let kExtensibleStorage: String = "ExtensibleStorage" let loggedIn: RSAFPersistedValue<Bool> let extensibleStorage: RSAFPersistedValueMap override public init(stateManager: RSAFStateManager.Type) { self.loggedIn = RSAFPersistedValue<Bool>(key: RSAFCorePersistentStoreSubscriber.kLoggedIn, stateManager: stateManager) self.extensibleStorage = RSAFPersistedValueMap(key: RSAFCorePersistentStoreSubscriber.kExtensibleStorage, stateManager: stateManager) super.init(stateManager: stateManager) } open override func loadState() -> RSAFCoreState { return RSAFCoreState( loggedIn: self.loggedIn.get() ?? false, extensibleStorage: self.extensibleStorage.get() ) } // open func newState(state: RSAFCoreState) { // self.extensibleStorage.set(map: RSAFCoreSelectors.getExtensibleStorage(state)) // } open override func newState(state: RSAFBaseState) { if let coreState = state as? RSAFCoreState { self.loggedIn.set(value: RSAFCoreSelectors.isLoggedIn(coreState)) self.extensibleStorage.set(map: RSAFCoreSelectors.getExtensibleStorage(coreState)) } } // // open override func newState(state: RSAFCoreState) { // self.extensibleStorage.set(map: self.selectors.getExtensibleStorage(state)) // } }
apache-2.0
4070b3f3069583825628db98e805b6d3
34.73913
141
0.708029
4.793003
false
false
false
false
svanimpe/around-the-table
Sources/AroundTheTable/ViewModels/ActivityViewModel.swift
1
4601
import Foundation import HTMLEntities /** View model for **activity-closed.stencil**, **activity-host.stencil** and **activity-player.stencil**. */ struct ActivityViewModel: Codable { let base: BaseViewModel struct UserViewModel: Codable { let id: Int let name: String let picture: String init(_ user: User) throws { guard let id = user.id else { throw log(ServerError.unpersistedEntity) } self.id = id self.name = user.name.htmlEscape() self.picture = user.picture?.absoluteString ?? Settings.defaultProfilePicture } } struct ActivityViewModel: Codable { let id: Int let host: UserViewModel let name: String let picture: String let game: Int? let playingTime: ClosedRange<Int>? let playerCount: ClosedRange<Int> let prereservedSeats: Int let availableSeats: Int let requiredPlayerCountReached: Bool let seatOptions: [Int] let date: String let time: String let isOver: Bool let deadlineDate: String let deadlineTime: String let deadlineHasPassed: Bool let location: Location let distance: Int let info: String let isCancelled: Bool init(_ activity: Activity) throws { guard let id = activity.id, let distance = activity.distance else { throw log(ServerError.unpersistedEntity) } self.id = id self.host = try UserViewModel(activity.host) self.name = activity.name self.picture = activity.picture?.absoluteString ?? Settings.defaultGamePicture self.game = activity.game?.id self.playingTime = activity.game?.playingTime self.playerCount = activity.playerCount self.prereservedSeats = activity.prereservedSeats self.availableSeats = activity.availableSeats self.requiredPlayerCountReached = playerCount.upperBound - availableSeats >= playerCount.lowerBound self.seatOptions = availableSeats > 0 ? Array(1...availableSeats) : Array(1...playerCount.upperBound) self.date = activity.date.formatted(format: "EEEE d MMMM") self.time = activity.date.formatted(timeStyle: .short) self.isOver = activity.date < Date() self.deadlineDate = activity.deadline.formatted(format: "EEEE d MMMM") self.deadlineTime = activity.deadline.formatted(timeStyle: .short) self.deadlineHasPassed = activity.deadline < Date() self.location = activity.location self.distance = Int(ceil(distance / 1000)) self.info = activity.info.htmlEscape() self.isCancelled = activity.isCancelled } } let activity: ActivityViewModel struct RegistrationViewModel: Codable { let player: UserViewModel let seats: Int let willCauseOverBooking: Bool init(_ registration: Activity.Registration, for activity: Activity) throws { self.player = try UserViewModel(registration.player) self.seats = registration.seats self.willCauseOverBooking = registration.seats > activity.availableSeats } } let approvedRegistrations: [RegistrationViewModel] let pendingRegistrations: [RegistrationViewModel] let userIsHost: Bool let userIsPlayer: Bool let userIsPending: Bool let registrationHasOpened: Bool let userHasAutoApprove: Bool init(base: BaseViewModel, activity: Activity, user: User?, hostsUserHasJoined: [User]) throws { self.base = base self.activity = try ActivityViewModel(activity) approvedRegistrations = try activity.approvedRegistrations.map { try RegistrationViewModel($0, for: activity) } pendingRegistrations = try activity.pendingRegistrations.map { try RegistrationViewModel($0, for: activity) } userIsHost = activity.host == user userIsPlayer = activity.approvedRegistrations.contains { $0.player == user } userIsPending = activity.pendingRegistrations.contains { $0.player == user } registrationHasOpened = activity.date.subtracting30Days < Date() userHasAutoApprove = !hostsUserHasJoined.contains(activity.host) // TODO: https://bugs.swift.org/browse/SR-944 // && !userIsHost && !userIsPending } }
bsd-2-clause
fd3a4633be407f0e5bf6262db99c510f
37.024793
119
0.633341
5.006529
false
false
false
false
IntrepidPursuits/swift-wisdom
SwiftWisdom/Core/UIKit/UIView+GetConstraints.swift
1
6580
//// //// UIView+GetConstraints.swift //// Created by Paul Rolfe on 7/31/15. //// Copyright (c) 2015 Paul Rolfe. All rights reserved. //// /* The idea is that you can call view.ip_topConstraint or view.ip_heightConstraint on any view and you'll be given the editable constraint that deals with that attribute. Optionally you can use the base function ip_constraintForAttribute() and pass in the toItem and itemAttribute. It is less convienient but more accurate. */ import Foundation import UIKit public extension UIView { /// This computed property result may be unexpected when inspecting views with multiple constraints on an attribute. var ip_widthConstraint: NSLayoutConstraint? { return ip_constraintForAttribute(.width) } /// This computed property result may be unexpected when inspecting views with multiple constraints on an attribute. var ip_heightConstraint: NSLayoutConstraint? { return ip_constraintForAttribute(.height) } /// This computed property result may be unexpected when inspecting views with multiple constraints on an attribute. var ip_topConstraint: NSLayoutConstraint? { return ip_constraintForAttribute(.top) } /// This computed property result may be unexpected when inspecting views with multiple constraints on an attribute. var ip_bottomConstraint: NSLayoutConstraint? { return ip_constraintForAttribute(.bottom) } /// This computed property result may be unexpected when inspecting views with multiple constraints on an attribute. var ip_leadingConstraint: NSLayoutConstraint? { return ip_constraintForAttribute(.leading) } /// This computed property result may be unexpected when inspecting views with multiple constraints on an attribute. var ip_trailingConstraint: NSLayoutConstraint? { return ip_constraintForAttribute(.trailing) } /// This computed property result may be unexpected when inspecting views with multiple constraints on an attribute. var ip_centerXConstraint: NSLayoutConstraint? { return ip_constraintForAttribute(.centerX) } /// This computed property result may be unexpected when inspecting views with multiple constraints on an attribute. var ip_centerYConstraint: NSLayoutConstraint? { return ip_constraintForAttribute(.centerY) } /// This computed property result may be unexpected when inspecting views with multiple constraints on an attribute. var ip_aspectRatioConstraint: NSLayoutConstraint? { return ip_constraintForAttribute(.height, toView: self, viewAttribute: .width) } /** More precise way of getting constraints for a view. The constraint does not have to belong to the reciever -- this method searches the superview for the matching constraint as well. :param: attribute Attribute to look for belonging to the receiver :param: view1 Defaults to the receiver, but could be any subview as well. :param: view2 Probably a UIView, that view1 is related to. :param: viewAttribute Attribute that should be used with the toItem :returns: The first constraint that matches. May return unexpected constraint if receiver contains multiple constraints with this item and itemAttribute. */ func ip_constraintForAttribute(_ attribute: NSLayoutConstraint.Attribute, onView: UIView? = nil, toView: UIView? = nil, viewAttribute: NSLayoutConstraint.Attribute? = nil) -> NSLayoutConstraint? { let onView = onView ?? self if let toAttribute = viewAttribute, let toItem = toView { return constraints.filter { constraint in return constraint.ip_relatesView(view: onView, viaAttribute: attribute, toView: toItem, andItsAttribute: toAttribute) } .first } else if let toItem = toView { return constraints.filter { constraint in return constraint.ip_relatesView(view: onView, viaAttribute: attribute, toView: toItem) } .first } else { if attribute == .height || attribute == .width { //For size constraints return constraints.filter { constraint in return constraint.ip_isIntrinsicConstraintWithView(view: onView, andAttribute: attribute) } .first } else { // For simple positioning constraints return constraints.filter { constraint in return constraint.ip_relatesView(view: onView, viaAttribute: attribute) } .first } } } } extension NSLayoutConstraint { public func ip_relatesView(view view1: UIView, viaAttribute attribute1: NSLayoutConstraint.Attribute, toView view2: UIView, andItsAttribute attribute2: NSLayoutConstraint.Attribute) -> Bool { let possibility1 = (firstItem as? UIView == view1 && firstAttribute == attribute1 && secondItem as? UIView == view2 && secondAttribute == attribute2) let possibility2 = (secondItem as? UIView == view1 && secondAttribute == attribute1 && firstItem as? UIView == view2 && firstAttribute == attribute2) return possibility1 || possibility2 } public func ip_relatesView(view view1: UIView, viaAttribute attribute1: NSLayoutConstraint.Attribute, toView view2: UIView) -> Bool { let possibility1 = (firstItem as? UIView == view1 && firstAttribute == attribute1 && secondItem as? UIView == view2) let possibility2 = (secondItem as? UIView == view1 && secondAttribute == attribute1 && firstItem as? UIView == view2) return possibility1 || possibility2 } public func ip_relatesView(view view1: UIView, viaAttribute attribute1: NSLayoutConstraint.Attribute) -> Bool { let possibility1 = (firstItem as? UIView == view1 && firstAttribute == attribute1) let possibility2 = (secondItem as? UIView == view1 && secondAttribute == attribute1) return possibility1 || possibility2 } public func ip_isIntrinsicConstraintWithView(view view1: UIView, andAttribute attribute1: NSLayoutConstraint.Attribute) -> Bool { return (firstItem as? UIView == view1 && firstAttribute == attribute1) } }
mit
477d9c133a7e0c2a4fa8eee291afb88a
42.576159
200
0.669757
5.543387
false
false
false
false
AlexChekanov/Gestalt
Gestalt/SupportingClasses/General classes Extensions/UIColor+adjust.swift
1
746
import UIKit extension UIColor { func lighter(by percentage:CGFloat=30.0) -> UIColor? { return self.adjust(by: abs(percentage) ) } func darker(by percentage:CGFloat=30.0) -> UIColor? { return self.adjust(by: -1 * abs(percentage) ) } func adjust(by percentage:CGFloat=30.0) -> UIColor? { var r:CGFloat=0, g:CGFloat=0, b:CGFloat=0, a:CGFloat=0; if(self.getRed(&r, green: &g, blue: &b, alpha: &a)){ return UIColor(red: min(r + percentage/100, 1.0), green: min(g + percentage/100, 1.0), blue: min(b + percentage/100, 1.0), alpha: a) }else{ return nil } } }
apache-2.0
d4e4042b3201eb453d80a230c480427e
30.083333
63
0.506702
3.586538
false
false
false
false
jakecraige/SwiftLint
Source/SwiftLintFramework/File+SwiftLint.swift
1
1284
// // File+SwiftLint.swift // SwiftLint // // Created by JP Simard on 2015-05-16. // Copyright (c) 2015 Realm. All rights reserved. // import SourceKittenFramework import SwiftXPC typealias Line = (index: Int, content: String) extension File { public func matchPattern(pattern: String, withSyntaxKinds syntaxKinds: [SyntaxKind]) -> [NSRange] { return matchPattern(pattern).filter { _, kindsInRange in return kindsInRange.count == syntaxKinds.count && zip(kindsInRange, syntaxKinds).filter({ $0.0 != $0.1 }).count == 0 }.map { $0.0 } } public func matchPattern(pattern: String) -> [(NSRange, [SyntaxKind])] { let regex = try! NSRegularExpression(pattern: pattern, options: []) let range = NSRange(location: 0, length: contents.utf16.count) let syntax = syntaxMap let matches = regex.matchesInString(contents, options: [], range: range) return matches.map { match in let tokensInRange = syntax.tokens.filter { NSLocationInRange($0.offset, match.range) } let kindsInRange = tokensInRange.flatMap { SyntaxKind(rawValue: $0.type) } return (match.range, kindsInRange) } } }
mit
811bf52df43edd924e7820031e3c8b52
32.789474
82
0.613707
4.265781
false
false
false
false
rodrigo196/swift-calculator
Calculator/CalculatorBrain.swift
1
2648
// // CalculatorBrain.swift // Calculator // // Created by Rodrigo Fernandes bulgarelli on 12/04/17. // Copyright © 2017 Rodrigo Fernandes bulgarelli. All rights reserved. // import Foundation struct CalculatorBrain { private var accumulator: Double? private var pendingBinaryOperation: PendingBinaryOperation? private enum Operation { case constant(Double) case unaryOperation((Double) -> Double) case binaryOperation((Double, Double) -> Double) case equals } private var operations: Dictionary<String, Operation> = [ "π" : Operation.constant(Double.pi), "e" : Operation.constant(M_E), "√" : Operation.unaryOperation(sqrt), "cos" : Operation.unaryOperation(cos), "±" : Operation.unaryOperation({-$0}), "x" : Operation.binaryOperation({$0 * $1}), "+" : Operation.binaryOperation({$0 + $1}), "-" : Operation.binaryOperation({$0 - $1}), "/" : Operation.binaryOperation({$0 / $1}), "=" : Operation.equals ] var result: Double? { get { return accumulator } } mutating func setOperand(_ operand: Double){ accumulator = operand } mutating func performOperation(_ symbol: String){ if let operation = operations[symbol] { switch operation { case .constant(let constant): accumulator = constant case .unaryOperation(let operation): if let value = accumulator { accumulator = operation(value) } case .binaryOperation(let operation): if accumulator != nil{ if pendingBinaryOperation != nil{ performPendingBinaryOperation() } pendingBinaryOperation = PendingBinaryOperation(function: operation, firstOperand: accumulator!) } case .equals: performPendingBinaryOperation() } } } private mutating func performPendingBinaryOperation(){ if pendingBinaryOperation != nil && accumulator != nil { accumulator = pendingBinaryOperation!.perform(with: accumulator!) pendingBinaryOperation = nil } } private struct PendingBinaryOperation { let function : (Double, Double) -> Double let firstOperand: Double func perform(with secondOperand: Double) -> Double { return function(firstOperand, secondOperand) } } }
apache-2.0
0414619b1fd83888c752447e43122826
29.37931
116
0.568672
5.371951
false
false
false
false
pauljohanneskraft/Math
CoreMath/Classes/Functions/Discrete Functions/Interpolation/NearestNeighborInterpolation.swift
1
890
// // NearestNeighborInterpolation.swift // Math // // Created by Paul Kraft on 23.11.17. // Copyright © 2017 pauljohanneskraft. All rights reserved. // public struct NearestNeighborInterpolation { public var function: DiscreteFunction public init(function: DiscreteFunction) { self.function = function } } extension NearestNeighborInterpolation: Interpolation { public func call(x: Number) -> Number { guard let index = points.index(where: { $0.x >= x }) else { return points.last?.y ?? 0 } guard index > 0 else { return points.first?.y ?? 0 } let lowerBound = points[index - 1] let upperBound = points[index] let lowerDistance = x - lowerBound.x let upperDistance = upperBound.x - x return lowerDistance < upperDistance ? lowerBound.y : upperBound.y } }
mit
95193755ab5dbf3af9178fbbca33123a
27.677419
74
0.631046
4.357843
false
false
false
false
apple/swift
test/Concurrency/Runtime/custom_executors.swift
1
1309
// RUN: %target-run-simple-swift( -Xfrontend -disable-availability-checking %import-libdispatch -parse-as-library) | %FileCheck %s // REQUIRES: concurrency // REQUIRES: executable_test // UNSUPPORTED: freestanding // UNSUPPORTED: back_deployment_runtime // REQUIRES: concurrency_runtime actor Simple { var count = 0 func report() { print("simple.count == \(count)") count += 1 } } actor Custom { var count = 0 let simple = Simple() @available(SwiftStdlib 5.1, *) nonisolated var unownedExecutor: UnownedSerialExecutor { print("custom unownedExecutor") return simple.unownedExecutor } func report() async { print("custom.count == \(count)") count += 1 await simple.report() } } @available(SwiftStdlib 5.1, *) @main struct Main { static func main() async { print("begin") let actor = Custom() await actor.report() await actor.report() await actor.report() print("end") } } // CHECK: begin // CHECK-NEXT: custom unownedExecutor // CHECK-NEXT: custom.count == 0 // CHECK-NEXT: simple.count == 0 // CHECK-NEXT: custom unownedExecutor // CHECK-NEXT: custom.count == 1 // CHECK-NEXT: simple.count == 1 // CHECK-NEXT: custom unownedExecutor // CHECK-NEXT: custom.count == 2 // CHECK-NEXT: simple.count == 2 // CHECK-NEXT: end
apache-2.0
e56e9fb1cc322718dd2065a6dd737fbd
21.186441
130
0.665393
3.761494
false
false
false
false
Kawoou/KWDrawerController
DrawerController/View/TranslucentView.swift
1
7452
/* The MIT License (MIT) Copyright (c) 2017 Kawoou (Jungwon An) 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 internal class TranslucentView: UIView { // MARK: - Property override var frame: CGRect { get { return super.frame } set { var rect = CGRect(x: 0, y: 0, width: newValue.width, height: newValue.height) if effectView.frame.width > rect.width { rect.size.width = effectView.frame.width } if effectView.frame.height > rect.height { rect.size.height = effectView.frame.height } effectView.frame = rect super.frame = newValue translucentView.frame = bounds } } override var bounds: CGRect { get { return super.bounds } set { var rect = CGRect(x: 0, y: 0, width: newValue.width, height: newValue.height) if effectView.bounds.width > rect.width { rect.size.width = effectView.bounds.width } if effectView.bounds.height > rect.height { rect.size.height = effectView.bounds.height } effectView.bounds = rect super.bounds = newValue translucentView.frame = bounds } } override var backgroundColor: UIColor? { get { if isInitialize { return backgroundView.backgroundColor } else { return super.backgroundColor } } set(value) { if isInitialize { backgroundView.backgroundColor = value super.backgroundColor = UIColor.clear } else { super.backgroundColor = value } } } override var alpha: CGFloat { get { if isInitialize { return blurView.alpha } else { return super.alpha } } set(value) { if isInitialize { blurView.alpha = value super.alpha = 1.0 } else { super.alpha = value } } } // MARK: - Internal private var isInitialize: Bool = false private var translucentView: UIView = UIView() private var effectView: UIView = UIView() private var backgroundView: UIView = UIView() private var blurView: UIView! // MARK: - Private private func initialize() { /// Golden-Path guard !isInitialize else { return } translucentView.frame = bounds translucentView.backgroundColor = .clear translucentView.clipsToBounds = true translucentView.autoresizingMask = [.flexibleBottomMargin, .flexibleLeftMargin, .flexibleRightMargin, .flexibleTopMargin] insertSubview(translucentView, at: 0) effectView.frame = bounds effectView.backgroundColor = .clear effectView.clipsToBounds = true effectView.autoresizingMask = [.flexibleBottomMargin, .flexibleLeftMargin, .flexibleRightMargin, .flexibleTopMargin] translucentView.addSubview(effectView) let rect = CGRect(x: 0, y: -1, width: bounds.width, height: bounds.height + 1) if let customBlurClass: AnyObject.Type = NSClassFromString("_UICustomBlurEffect") { let customBlurObject: NSObject.Type = customBlurClass as! NSObject.Type let blurEffect = customBlurObject.init() as! UIBlurEffect blurEffect.setValue(1.0, forKeyPath: "scale") blurEffect.setValue(CGFloat(25), forKeyPath: "blurRadius") let visualEffectView = UIVisualEffectView(effect: blurEffect) visualEffectView.frame = rect visualEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight] visualEffectView.alpha = alpha effectView.addSubview(visualEffectView) blurView = visualEffectView } else { let toolBar = UIToolbar(frame: rect) toolBar.barTintColor = UIColor(white: 0.8, alpha: 1.0) toolBar.barStyle = .black toolBar.autoresizingMask = [.flexibleWidth, .flexibleHeight] toolBar.alpha = alpha effectView.addSubview(toolBar) blurView = toolBar } super.alpha = 1.0 backgroundView.frame = bounds backgroundView.backgroundColor = backgroundColor backgroundView.autoresizingMask = [.flexibleWidth, .flexibleHeight] effectView.addSubview(backgroundView) super.backgroundColor = UIColor.clear isInitialize = true } // MARK: - Lifecycle override var subviews: [UIView] { get { if isInitialize { var array = super.subviews array.remove(at: array.index(of: translucentView)!) return array } else { return super.subviews } } } #if swift(>=4.2) override func sendSubviewToBack(_ view: UIView) { if isInitialize { insertSubview(view, aboveSubview: translucentView) } else { super.sendSubviewToBack(view) } } #else override func sendSubview(toBack view: UIView) { if isInitialize { insertSubview(view, aboveSubview: translucentView) } else { super.sendSubview(toBack: view) } } #endif override func insertSubview(_ view: UIView, at index: Int) { if isInitialize { super.insertSubview(view, at: index + 1) } else { super.insertSubview(view, at: index) } } override func exchangeSubview(at index1: Int, withSubviewAt index2: Int) { if isInitialize { super.exchangeSubview(at: index1 + 1, withSubviewAt: index2 + 1) } else { super.exchangeSubview(at: index1, withSubviewAt: index2) } } override init(frame: CGRect) { super.init(frame: frame) initialize() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) initialize() } }
mit
5e159ecac87f79edbd3fd9d155558411
31.25974
129
0.587225
5.303915
false
false
false
false
qiuncheng/study-for-swift
learn-rx-swift/Chocotastic-starter/Pods/RxSwift/RxSwift/Observables/Implementations/Reduce.swift
6
2282
// // Reduce.swift // Rx // // Created by Krunoslav Zaher on 4/1/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import Foundation class ReduceSink<SourceType, AccumulateType, O: ObserverType> : Sink<O>, ObserverType { typealias ResultType = O.E typealias Parent = Reduce<SourceType, AccumulateType, ResultType> private let _parent: Parent private var _accumulation: AccumulateType init(parent: Parent, observer: O) { _parent = parent _accumulation = parent._seed super.init(observer: observer) } func on(_ event: Event<SourceType>) { switch event { case .next(let value): do { _accumulation = try _parent._accumulator(_accumulation, value) } catch let e { forwardOn(.error(e)) dispose() } case .error(let e): forwardOn(.error(e)) dispose() case .completed: do { let result = try _parent._mapResult(_accumulation) forwardOn(.next(result)) forwardOn(.completed) dispose() } catch let e { forwardOn(.error(e)) dispose() } } } } class Reduce<SourceType, AccumulateType, ResultType> : Producer<ResultType> { typealias AccumulatorType = (AccumulateType, SourceType) throws -> AccumulateType typealias ResultSelectorType = (AccumulateType) throws -> ResultType fileprivate let _source: Observable<SourceType> fileprivate let _seed: AccumulateType fileprivate let _accumulator: AccumulatorType fileprivate let _mapResult: ResultSelectorType init(source: Observable<SourceType>, seed: AccumulateType, accumulator: @escaping AccumulatorType, mapResult: @escaping ResultSelectorType) { _source = source _seed = seed _accumulator = accumulator _mapResult = mapResult } override func run<O: ObserverType>(_ observer: O) -> Disposable where O.E == ResultType { let sink = ReduceSink(parent: self, observer: observer) sink.disposable = _source.subscribe(sink) return sink } }
mit
175acca853d46ce342eaca48eae6e810
29.824324
145
0.594476
4.980349
false
false
false
false
vector-im/vector-ios
Riot/Modules/Rooms/ShowDirectory/ShowDirectoryViewController.swift
1
13136
// File created from ScreenTemplate // $ createScreen.sh Rooms/ShowDirectory ShowDirectory /* Copyright 2020 New Vector Ltd Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import UIKit final class ShowDirectoryViewController: UIViewController { // MARK: - Constants private enum Constants { static let networkHeaderViewEstimatedHeight: CGFloat = 40.0 } // MARK: - Properties // MARK: Outlets @IBOutlet private weak var mainTableView: UITableView! @IBOutlet private weak var vibrancyEffectView: UIVisualEffectView! @IBOutlet private weak var vibrancyEffectContentView: UIView! @IBOutlet private weak var blurEffectView: UIVisualEffectView! @IBOutlet private weak var blurEffectContentView: UIView! @IBOutlet private weak var createRoomButton: UIButton! { didSet { createRoomButton.setTitle(VectorL10n.searchableDirectoryCreateNewRoom, for: .normal) } } // MARK: Private private var viewModel: ShowDirectoryViewModelType! private var theme: Theme! private var keyboardAvoider: KeyboardAvoider? private var errorPresenter: MXKErrorPresentation! private var activityPresenter: ActivityIndicatorPresenter! private lazy var footerSpinnerView: UIActivityIndicatorView = { let spinner = UIActivityIndicatorView(style: .whiteLarge) spinner.transform = CGAffineTransform(scaleX: 0.75, y: 0.75) spinner.color = .darkGray spinner.hidesWhenStopped = false spinner.backgroundColor = .clear spinner.startAnimating() return spinner }() private lazy var mainSearchBar: UISearchBar = { let bar = UISearchBar(frame: CGRect(origin: .zero, size: CGSize(width: 600, height: 44))) bar.autoresizingMask = .flexibleWidth bar.showsCancelButton = false bar.placeholder = VectorL10n.searchableDirectorySearchPlaceholder bar.setBackgroundImage(UIImage.vc_image(from: .clear), for: .any, barMetrics: .default) bar.delegate = self return bar }() private var sections: [ShowDirectorySection] = [] private let screenTracker = AnalyticsScreenTracker(screen: .roomDirectory) // MARK: - Setup class func instantiate(with viewModel: ShowDirectoryViewModelType) -> ShowDirectoryViewController { let viewController = StoryboardScene.ShowDirectoryViewController.initialScene.instantiate() viewController.viewModel = viewModel viewController.theme = ThemeService.shared().theme return viewController } // MARK: - Life cycle override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.setupViews() self.keyboardAvoider = KeyboardAvoider(scrollViewContainerView: self.view, scrollView: self.mainTableView) self.activityPresenter = ActivityIndicatorPresenter() self.errorPresenter = MXKErrorAlertPresentation() self.registerThemeServiceDidChangeThemeNotification() self.update(theme: self.theme) self.viewModel.viewDelegate = self self.viewModel.process(viewAction: .loadData(false)) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.keyboardAvoider?.startAvoiding() screenTracker.trackScreen() } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) self.keyboardAvoider?.stopAvoiding() } override var preferredStatusBarStyle: UIStatusBarStyle { return self.theme.statusBarStyle } // MARK: - Private private func addSpinnerFooterView() { footerSpinnerView.startAnimating() self.mainTableView.tableFooterView = footerSpinnerView } private func removeSpinnerFooterView() { footerSpinnerView.stopAnimating() self.mainTableView.tableFooterView = UIView() } private func update(theme: Theme) { self.theme = theme self.view.backgroundColor = theme.headerBackgroundColor self.mainTableView.backgroundColor = theme.backgroundColor self.mainTableView.separatorColor = theme.lineBreakColor if let navigationBar = self.navigationController?.navigationBar { theme.applyStyle(onNavigationBar: navigationBar) navigationBar.setBackgroundImage(UIImage.vc_image(from: theme.headerBackgroundColor), for: .default) } theme.applyStyle(onSearchBar: mainSearchBar) theme.applyStyle(onButton: createRoomButton) if #available(iOS 13.0, *) { vibrancyEffectView.overrideUserInterfaceStyle = theme.userInterfaceStyle vibrancyEffectContentView.overrideUserInterfaceStyle = theme.userInterfaceStyle blurEffectView.overrideUserInterfaceStyle = theme.userInterfaceStyle blurEffectContentView.overrideUserInterfaceStyle = theme.userInterfaceStyle } self.mainTableView.reloadData() } private func registerThemeServiceDidChangeThemeNotification() { NotificationCenter.default.addObserver(self, selector: #selector(themeDidChange), name: .themeServiceDidChangeTheme, object: nil) } @objc private func themeDidChange() { self.update(theme: ThemeService.shared().theme) } private func setupViews() { self.mainTableView.keyboardDismissMode = .interactive self.mainTableView.register(headerFooterViewType: DirectoryNetworkTableHeaderFooterView.self) self.mainTableView.register(cellType: DirectoryRoomTableViewCell.self) self.mainTableView.rowHeight = 76 self.mainTableView.tableFooterView = UIView() let cancelBarButtonItem = MXKBarButtonItem(title: VectorL10n.cancel, style: .plain) { [weak self] in self?.cancelButtonAction() } self.navigationItem.rightBarButtonItem = cancelBarButtonItem self.navigationItem.titleView = mainSearchBar } private func render(viewState: ShowDirectoryViewState) { switch viewState { case .loading: self.renderLoading() case .loaded(let sections): self.renderLoaded(sections: sections) case .error(let error): self.render(error: error) case .loadedWithoutUpdate: self.renderLoadedWithoutUpdate() } } private func renderLoading() { addSpinnerFooterView() } private func renderLoaded(sections: [ShowDirectorySection]) { removeSpinnerFooterView() self.sections = sections self.mainTableView.reloadData() } private func renderLoadedWithoutUpdate() { removeSpinnerFooterView() } private func render(error: Error) { removeSpinnerFooterView() self.errorPresenter.presentError(from: self, forError: error, animated: true) { // If the join failed, reload the table view self.mainTableView.reloadData() } } // MARK: - Actions @IBAction private func createRoomButtonTapped(_ sender: UIButton) { viewModel.process(viewAction: .createNewRoom) } private func cancelButtonAction() { self.viewModel.process(viewAction: .cancel) } } // MARK: - UITableViewDataSource extension ShowDirectoryViewController: UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return self.sections.count } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { let directorySection = self.sections[section] switch directorySection { case .searchInput: return 1 case.publicRoomsDirectory(let viewModel): return viewModel.roomsCount } } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let section = self.sections[indexPath.section] let cellViewModel: DirectoryRoomTableViewCellVM? switch section { case .searchInput(let searchInputViewData): cellViewModel = searchInputViewData case.publicRoomsDirectory(let viewModel): cellViewModel = viewModel.roomViewModel(at: indexPath.row) } let cell: DirectoryRoomTableViewCell = tableView.dequeueReusableCell(for: indexPath) if let cellViewModel = cellViewModel { cell.configure(withViewModel: cellViewModel) } cell.indexPath = indexPath cell.delegate = self cell.update(theme: self.theme) return cell } } // MARK: - UITableViewDataDelegate extension ShowDirectoryViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { cell.backgroundColor = theme.backgroundColor // Update the selected background view cell.selectedBackgroundView = UIView() cell.selectedBackgroundView?.backgroundColor = theme.selectedBackgroundColor } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) viewModel.process(viewAction: .selectRoom(indexPath)) } func scrollViewDidScroll(_ scrollView: UIScrollView) { // Trigger inconspicuous pagination when user scrolls down if (scrollView.contentSize.height - scrollView.contentOffset.y - scrollView.frame.size.height) < 300 { viewModel.process(viewAction: .loadData(false)) } } func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let sectionHeaderView: UIView? let directorySection = self.sections[section] switch directorySection { case .searchInput: sectionHeaderView = nil case .publicRoomsDirectory(let viewModel): guard let view: DirectoryNetworkTableHeaderFooterView = tableView.dequeueReusableHeaderFooterView() else { return nil } if let name = viewModel.directoryServerDisplayname { let title = VectorL10n.searchableDirectoryXNetwork(name) view.configure(withViewModel: DirectoryNetworkVM(title: title)) } view.update(theme: self.theme) view.delegate = self sectionHeaderView = view } return sectionHeaderView } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return UITableView.automaticDimension } func tableView(_ tableView: UITableView, estimatedHeightForHeaderInSection section: Int) -> CGFloat { let directorySection = self.sections[section] let estimatedHeight: CGFloat switch directorySection { case .searchInput: estimatedHeight = 0.0 case .publicRoomsDirectory: estimatedHeight = Constants.networkHeaderViewEstimatedHeight } return estimatedHeight } } // MARK: - UISearchBarDelegate extension ShowDirectoryViewController { override func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { viewModel.process(viewAction: .search(searchText)) } } // MARK: - extension ShowDirectoryViewController: DirectoryRoomTableViewCellDelegate { func directoryRoomTableViewCellDidTapJoin(_ cell: DirectoryRoomTableViewCell) { cell.startJoining() viewModel.process(viewAction: .joinRoom(cell.indexPath)) } } // MARK: - DirectoryNetworkTableHeaderFooterViewDelegate extension ShowDirectoryViewController: DirectoryNetworkTableHeaderFooterViewDelegate { func directoryNetworkTableHeaderFooterViewDidTapSwitch(_ view: DirectoryNetworkTableHeaderFooterView) { viewModel.process(viewAction: .switchServer) } } // MARK: - ShowDirectoryViewModelViewDelegate extension ShowDirectoryViewController: ShowDirectoryViewModelViewDelegate { func showDirectoryViewModel(_ viewModel: ShowDirectoryViewModelType, didUpdateViewState viewSate: ShowDirectoryViewState) { self.render(viewState: viewSate) } }
apache-2.0
de4f744a7f0a2cd5c781c527f655fd5a
33.47769
137
0.680116
5.87215
false
false
false
false