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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
DarrenKong/firefox-ios
|
ClientTests/MockProfile.swift
|
5
|
7077
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
@testable import Client
import Foundation
import Account
import ReadingList
import Shared
import Storage
import Sync
import XCTest
import Deferred
open class MockSyncManager: SyncManager {
open var isSyncing = false
open var lastSyncFinishTime: Timestamp?
open var syncDisplayState: SyncDisplayState?
open func hasSyncedHistory() -> Deferred<Maybe<Bool>> {
return deferMaybe(true)
}
private func completedWithStats(collection: String) -> Deferred<Maybe<SyncStatus>> {
return deferMaybe(SyncStatus.completed(SyncEngineStatsSession(collection: collection)))
}
open func syncClients() -> SyncResult { return completedWithStats(collection: "mock_clients") }
open func syncClientsThenTabs() -> SyncResult { return completedWithStats(collection: "mock_clientsandtabs") }
open func syncHistory() -> SyncResult { return completedWithStats(collection: "mock_history") }
open func syncLogins() -> SyncResult { return completedWithStats(collection: "mock_logins") }
open func mirrorBookmarks() -> SyncResult { return completedWithStats(collection: "mock_bookmarks") }
open func syncEverything(why: SyncReason) -> Success {
return succeed()
}
open func syncNamedCollections(why: SyncReason, names: [String]) -> Success {
return succeed()
}
open func beginTimedSyncs() {}
open func endTimedSyncs() {}
open func applicationDidBecomeActive() {
self.beginTimedSyncs()
}
open func applicationDidEnterBackground() {
self.endTimedSyncs()
}
open func onNewProfile() {
}
open func onAddedAccount() -> Success {
return succeed()
}
open func onRemovedAccount(_ account: FirefoxAccount?) -> Success {
return succeed()
}
open func hasSyncedLogins() -> Deferred<Maybe<Bool>> {
return deferMaybe(true)
}
}
open class MockTabQueue: TabQueue {
open func addToQueue(_ tab: ShareItem) -> Success {
return succeed()
}
open func getQueuedTabs() -> Deferred<Maybe<Cursor<ShareItem>>> {
return deferMaybe(ArrayCursor<ShareItem>(data: []))
}
open func clearQueuedTabs() -> Success {
return succeed()
}
}
open class MockPanelDataObservers: PanelDataObservers {
override init(profile: Profile) {
super.init(profile: profile)
self.activityStream = MockActivityStreamDataObserver(profile: profile)
}
}
open class MockActivityStreamDataObserver: DataObserver {
public var profile: Profile
public weak var delegate: DataObserverDelegate?
init(profile: Profile) {
self.profile = profile
}
public func refreshIfNeeded(forceHighlights highlights: Bool, forceTopSites topsites: Bool) {
}
}
open class MockProfile: Profile {
// Read/Writeable properties for mocking
public var recommendations: HistoryRecommendations
public var places: BrowserHistory & Favicons & SyncableHistory & ResettableSyncStorage & HistoryRecommendations
public var files: FileAccessor
public var history: BrowserHistory & SyncableHistory & ResettableSyncStorage
public var logins: BrowserLogins & SyncableLogins & ResettableSyncStorage
public var syncManager: SyncManager!
public lazy var panelDataObservers: PanelDataObservers = {
return MockPanelDataObservers(profile: self)
}()
var db: BrowserDB
fileprivate let name: String = "mockaccount"
init() {
files = MockFiles()
syncManager = MockSyncManager()
logins = MockLogins(files: files)
db = BrowserDB(filename: "mock.db", schema: BrowserSchema(), files: files)
places = SQLiteHistory(db: self.db, prefs: MockProfilePrefs())
recommendations = places
history = places
}
public func localName() -> String {
return name
}
public func reopen() {
}
public func shutdown() {
}
public var isShutdown: Bool = false
public var favicons: Favicons {
return self.places
}
lazy public var queue: TabQueue = {
return MockTabQueue()
}()
lazy public var metadata: Metadata = {
return SQLiteMetadata(db: self.db)
}()
lazy public var isChinaEdition: Bool = {
return Locale.current.identifier == "zh_CN"
}()
lazy public var certStore: CertStore = {
return CertStore()
}()
lazy public var bookmarks: BookmarksModelFactorySource & KeywordSearchSource & SyncableBookmarks & LocalItemSource & MirrorItemSource & ShareToDestination = {
// Make sure the rest of our tables are initialized before we try to read them!
// This expression is for side-effects only.
let p = self.places
return MergedSQLiteBookmarks(db: self.db)
}()
lazy public var searchEngines: SearchEngines = {
return SearchEngines(prefs: self.prefs, files: self.files)
}()
lazy public var prefs: Prefs = {
return MockProfilePrefs()
}()
lazy public var readingList: ReadingListService? = {
return ReadingListService(profileStoragePath: self.files.rootPath as String)
}()
lazy public var recentlyClosedTabs: ClosedTabsStore = {
return ClosedTabsStore(prefs: self.prefs)
}()
internal lazy var remoteClientsAndTabs: RemoteClientsAndTabs = {
return SQLiteRemoteClientsAndTabs(db: self.db)
}()
fileprivate lazy var syncCommands: SyncCommands = {
return SQLiteRemoteClientsAndTabs(db: self.db)
}()
public let accountConfiguration: FirefoxAccountConfiguration = ProductionFirefoxAccountConfiguration()
var account: FirefoxAccount?
public func hasAccount() -> Bool {
return account != nil
}
public func hasSyncableAccount() -> Bool {
return account?.actionNeeded == FxAActionNeeded.none
}
public func getAccount() -> FirefoxAccount? {
return account
}
public func setAccount(_ account: FirefoxAccount) {
self.account = account
self.syncManager.onAddedAccount()
}
public func flushAccount() {}
public func removeAccount() {
let old = self.account
self.account = nil
self.syncManager.onRemovedAccount(old)
}
public func getClients() -> Deferred<Maybe<[RemoteClient]>> {
return deferMaybe([])
}
public func getClientsAndTabs() -> Deferred<Maybe<[ClientAndTabs]>> {
return deferMaybe([])
}
public func getCachedClientsAndTabs() -> Deferred<Maybe<[ClientAndTabs]>> {
return deferMaybe([])
}
public func storeTabs(_ tabs: [RemoteTab]) -> Deferred<Maybe<Int>> {
return deferMaybe(0)
}
public func sendItems(_ items: [ShareItem], toClients clients: [RemoteClient]) -> Deferred<Maybe<SyncStatus>> {
return deferMaybe(SyncStatus.notStarted(.offline))
}
}
|
mpl-2.0
|
d86a94d38e42773d90f6cd03a83428d7
| 29.114894 | 162 | 0.677123 | 5.113439 | false | false | false | false |
ilhanadiyaman/firefox-ios
|
Client/Frontend/Home/TopSitesPanel.swift
|
2
|
24762
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import UIKit
import Shared
import XCGLogger
import Storage
private let log = Logger.browserLogger
private let ThumbnailIdentifier = "Thumbnail"
extension CGSize {
public func widthLargerOrEqualThanHalfIPad() -> Bool {
let halfIPadSize: CGFloat = 507
return width >= halfIPadSize
}
}
class TopSitesPanel: UIViewController {
weak var homePanelDelegate: HomePanelDelegate?
private var collection: TopSitesCollectionView? = nil
private lazy var dataSource: TopSitesDataSource = {
return TopSitesDataSource(profile: self.profile, data: Cursor(status: .Failure, msg: "Nothing loaded yet"))
}()
private lazy var layout: TopSitesLayout = { return TopSitesLayout() }()
private lazy var maxFrecencyLimit: Int = {
return max(
self.calculateApproxThumbnailCountForOrientation(UIInterfaceOrientation.LandscapeLeft),
self.calculateApproxThumbnailCountForOrientation(UIInterfaceOrientation.Portrait)
)
}()
var editingThumbnails: Bool = false {
didSet {
if editingThumbnails != oldValue {
dataSource.editingThumbnails = editingThumbnails
if editingThumbnails {
homePanelDelegate?.homePanelWillEnterEditingMode?(self)
}
updateRemoveButtonStates()
}
}
}
let profile: Profile
override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator)
coordinator.animateAlongsideTransition({ context in
self.collection?.reloadData()
}, completion: nil)
}
override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
return UIInterfaceOrientationMask.AllButUpsideDown
}
init(profile: Profile) {
self.profile = profile
super.init(nibName: nil, bundle: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "notificationReceived:", name: NotificationFirefoxAccountChanged, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "notificationReceived:", name: NotificationProfileDidFinishSyncing, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "notificationReceived:", name: NotificationPrivateDataClearedHistory, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "notificationReceived:", name: NotificationDynamicFontChanged, object: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
let collection = TopSitesCollectionView(frame: self.view.frame, collectionViewLayout: layout)
collection.backgroundColor = UIConstants.PanelBackgroundColor
collection.delegate = self
collection.dataSource = dataSource
collection.registerClass(ThumbnailCell.self, forCellWithReuseIdentifier: ThumbnailIdentifier)
collection.keyboardDismissMode = .OnDrag
view.addSubview(collection)
collection.snp_makeConstraints { make in
make.edges.equalTo(self.view)
}
self.collection = collection
self.dataSource.collectionView = self.collection
self.profile.history.setTopSitesCacheSize(Int32(maxFrecencyLimit))
self.refreshTopSites(maxFrecencyLimit)
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self, name: NotificationFirefoxAccountChanged, object: nil)
NSNotificationCenter.defaultCenter().removeObserver(self, name: NotificationProfileDidFinishSyncing, object: nil)
NSNotificationCenter.defaultCenter().removeObserver(self, name: NotificationPrivateDataClearedHistory, object: nil)
NSNotificationCenter.defaultCenter().removeObserver(self, name: NotificationDynamicFontChanged, object: nil)
}
func notificationReceived(notification: NSNotification) {
switch notification.name {
case NotificationFirefoxAccountChanged, NotificationProfileDidFinishSyncing, NotificationPrivateDataClearedHistory, NotificationDynamicFontChanged:
refreshTopSites(maxFrecencyLimit)
break
default:
// no need to do anything at all
log.warning("Received unexpected notification \(notification.name)")
break
}
}
//MARK: Private Helpers
private func updateDataSourceWithSites(result: Maybe<Cursor<Site>>) {
if let data = result.successValue {
self.dataSource.data = data
self.dataSource.profile = self.profile
// redraw now we've udpated our sources
self.collection?.collectionViewLayout.invalidateLayout()
self.collection?.setNeedsLayout()
}
}
private func updateRemoveButtonStates() {
for i in 0..<layout.thumbnailCount {
if let cell = collection?.cellForItemAtIndexPath(NSIndexPath(forItem: i, inSection: 0)) as? ThumbnailCell {
//TODO: Only toggle the remove button for non-suggested tiles for now
if i < dataSource.data.count {
cell.toggleRemoveButton(editingThumbnails)
} else {
cell.toggleRemoveButton(false)
}
}
}
}
private func deleteHistoryTileForSite(site: Site, atIndexPath indexPath: NSIndexPath) {
func reloadThumbnails() {
self.profile.history.getTopSitesWithLimit(self.layout.thumbnailCount)
.uponQueue(dispatch_get_main_queue()) { result in
self.deleteOrUpdateSites(result, indexPath: indexPath)
}
}
profile.history.removeSiteFromTopSites(site)
>>> self.profile.history.refreshTopSitesCache
>>> reloadThumbnails
}
private func refreshTopSites(frecencyLimit: Int) {
// Reload right away with whatever is in the cache, then check to see if the cache is invalid. If it's invalid,
// invalidate the cache and requery. This allows us to always show results right away if they are cached but
// also load in the up-to-date results asynchronously if needed
reloadTopSitesWithLimit(frecencyLimit) >>> {
return self.profile.history.updateTopSitesCacheIfInvalidated() >>== { result in
return result ? self.reloadTopSitesWithLimit(frecencyLimit) : succeed()
}
}
}
private func reloadTopSitesWithLimit(limit: Int) -> Success {
return self.profile.history.getTopSitesWithLimit(limit).bindQueue(dispatch_get_main_queue()) { result in
self.updateDataSourceWithSites(result)
self.collection?.reloadData()
return succeed()
}
}
private func deleteOrUpdateSites(result: Maybe<Cursor<Site>>, indexPath: NSIndexPath) {
guard let collectionView = collection else { return }
// get the number of top sites items we have before we update the data sourcce
// this is so we know how many new top sites cells to add
// as a sync may have brought in more results than we had previously
let previousNumOfThumbnails = collectionView.dataSource?.collectionView(collectionView, numberOfItemsInSection: 0) ?? 0
// Exit early if the query failed in some way.
guard result.isSuccess else {
return
}
// now update the data source with the new data
self.updateDataSourceWithSites(result)
let data = dataSource.data
collection?.performBatchUpdates({
// find out how many thumbnails, up the max for display, we can actually add
let numOfCellsFromData = data.count + SuggestedSites.count
let numOfThumbnails = min(numOfCellsFromData, self.layout.thumbnailCount)
// If we have enough data to fill the tiles after the deletion, then delete the correct tile and insert any that are missing
if (numOfThumbnails >= previousNumOfThumbnails) {
self.collection?.deleteItemsAtIndexPaths([indexPath])
let indexesToAdd = ((previousNumOfThumbnails-1)..<numOfThumbnails).map{ NSIndexPath(forItem: $0, inSection: 0) }
self.collection?.insertItemsAtIndexPaths(indexesToAdd)
}
// If we don't have any data to backfill our tiles, just delete
else {
self.collection?.deleteItemsAtIndexPaths([indexPath])
}
}, completion: { _ in
self.updateRemoveButtonStates()
})
}
/**
Calculates an approximation of the number of tiles we want to display for the given orientation. This
method uses the screen's size as it's basis for the calculation instead of the collectionView's since the
collectionView's bounds is determined until the next layout pass.
- parameter orientation: Orientation to calculate number of tiles for
- returns: Rough tile count we will be displaying for the passed in orientation
*/
private func calculateApproxThumbnailCountForOrientation(orientation: UIInterfaceOrientation) -> Int {
let size = UIScreen.mainScreen().bounds.size
let portraitSize = CGSize(width: min(size.width, size.height), height: max(size.width, size.height))
func calculateRowsForSize(size: CGSize, columns: Int) -> Int {
let insets = ThumbnailCellUX.insetsForCollectionViewSize(size,
traitCollection: traitCollection)
let thumbnailWidth = (size.width - insets.left - insets.right) / CGFloat(columns)
let thumbnailHeight = thumbnailWidth / CGFloat(ThumbnailCellUX.ImageAspectRatio)
return max(2, Int(size.height / thumbnailHeight))
}
let numberOfColumns: Int
let numberOfRows: Int
if UIInterfaceOrientationIsLandscape(orientation) {
numberOfColumns = 5
numberOfRows = calculateRowsForSize(CGSize(width: portraitSize.height, height: portraitSize.width), columns: numberOfColumns)
} else {
numberOfColumns = 4
numberOfRows = calculateRowsForSize(portraitSize, columns: numberOfColumns)
}
return numberOfColumns * numberOfRows
}
}
extension TopSitesPanel: HomePanel {
func endEditing() {
editingThumbnails = false
collection?.reloadData()
}
}
extension TopSitesPanel: UICollectionViewDelegate {
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
if editingThumbnails {
return
}
if let site = dataSource[indexPath.item] {
// We're gonna call Top Sites bookmarks for now.
let visitType = VisitType.Bookmark
homePanelDelegate?.homePanel(self, didSelectURL: site.tileURL, visitType: visitType)
}
}
func collectionView(collectionView: UICollectionView, willDisplayCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) {
if let thumbnailCell = cell as? ThumbnailCell {
thumbnailCell.delegate = self
if editingThumbnails && indexPath.item < dataSource.data.count && thumbnailCell.removeButton.hidden {
thumbnailCell.removeButton.hidden = false
}
}
}
}
extension TopSitesPanel: ThumbnailCellDelegate {
func didRemoveThumbnail(thumbnailCell: ThumbnailCell) {
if let indexPath = collection?.indexPathForCell(thumbnailCell) {
if let site = dataSource[indexPath.item] {
self.deleteHistoryTileForSite(site, atIndexPath: indexPath)
}
}
}
func didLongPressThumbnail(thumbnailCell: ThumbnailCell) {
editingThumbnails = true
}
}
private class TopSitesCollectionView: UICollectionView {
private override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
// Hide the keyboard if this view is touched.
window?.rootViewController?.view.endEditing(true)
super.touchesBegan(touches, withEvent: event)
}
}
private class TopSitesLayout: UICollectionViewLayout {
private var thumbnailRows: Int {
return max(2, Int((self.collectionView?.frame.height ?? self.thumbnailHeight) / self.thumbnailHeight))
}
private var thumbnailCols: Int {
let size = collectionView?.bounds.size ?? CGSizeZero
let traitCollection = collectionView!.traitCollection
if traitCollection.horizontalSizeClass == .Compact {
// Landscape iPHone
if traitCollection.verticalSizeClass == .Compact {
return 5
}
// Split screen iPad width
else if size.widthLargerOrEqualThanHalfIPad() ?? false {
return 4
}
// iPhone portrait
else {
return 3
}
} else {
// Portrait iPad
if size.height > size.width {
return 4;
}
// Landscape iPad
else {
return 5;
}
}
}
private var thumbnailCount: Int {
return thumbnailRows * thumbnailCols
}
private var width: CGFloat { return self.collectionView?.frame.width ?? 0 }
// The width and height of the thumbnail here are the width and height of the tile itself, not the image inside the tile.
private var thumbnailWidth: CGFloat {
let size = collectionView?.bounds.size ?? CGSizeZero
let insets = ThumbnailCellUX.insetsForCollectionViewSize(size,
traitCollection: collectionView!.traitCollection)
return floor(width - insets.left - insets.right) / CGFloat(thumbnailCols)
}
// The tile's height is determined the aspect ratio of the thumbnails width. We also take into account
// some padding between the title and the image.
private var thumbnailHeight: CGFloat {
return floor(thumbnailWidth / CGFloat(ThumbnailCellUX.ImageAspectRatio))
}
// Used to calculate the height of the list.
private var count: Int {
if let dataSource = self.collectionView?.dataSource as? TopSitesDataSource {
return dataSource.collectionView(self.collectionView!, numberOfItemsInSection: 0)
}
return 0
}
private var topSectionHeight: CGFloat {
let maxRows = ceil(Float(count) / Float(thumbnailCols))
let rows = min(Int(maxRows), thumbnailRows)
let size = collectionView?.bounds.size ?? CGSizeZero
let insets = ThumbnailCellUX.insetsForCollectionViewSize(size,
traitCollection: collectionView!.traitCollection)
return thumbnailHeight * CGFloat(rows) + insets.top + insets.bottom
}
private func getIndexAtPosition(y: CGFloat) -> Int {
if y < topSectionHeight {
let row = Int(y / thumbnailHeight)
return min(count - 1, max(0, row * thumbnailCols))
}
return min(count - 1, max(0, Int((y - topSectionHeight) / UIConstants.DefaultRowHeight + CGFloat(thumbnailCount))))
}
override func collectionViewContentSize() -> CGSize {
if count <= thumbnailCount {
return CGSize(width: width, height: topSectionHeight)
}
let bottomSectionHeight = CGFloat(count - thumbnailCount) * UIConstants.DefaultRowHeight
return CGSize(width: width, height: topSectionHeight + bottomSectionHeight)
}
private var layoutAttributes:[UICollectionViewLayoutAttributes]?
private override func prepareLayout() {
var layoutAttributes = [UICollectionViewLayoutAttributes]()
for section in 0..<(self.collectionView?.numberOfSections() ?? 0) {
for item in 0..<(self.collectionView?.numberOfItemsInSection(section) ?? 0) {
let indexPath = NSIndexPath(forItem: item, inSection: section)
guard let attrs = self.layoutAttributesForItemAtIndexPath(indexPath) else { continue }
layoutAttributes.append(attrs)
}
}
self.layoutAttributes = layoutAttributes
}
override func layoutAttributesForElementsInRect(rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
var attrs = [UICollectionViewLayoutAttributes]()
if let layoutAttributes = self.layoutAttributes {
for attr in layoutAttributes {
if CGRectIntersectsRect(rect, attr.frame) {
attrs.append(attr)
}
}
}
return attrs
}
override func layoutAttributesForItemAtIndexPath(indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes? {
let attr = UICollectionViewLayoutAttributes(forCellWithIndexPath: indexPath)
// Set the top thumbnail frames.
let row = floor(Double(indexPath.item / thumbnailCols))
let col = indexPath.item % thumbnailCols
let size = collectionView?.bounds.size ?? CGSizeZero
let insets = ThumbnailCellUX.insetsForCollectionViewSize(size,
traitCollection: collectionView!.traitCollection)
let x = insets.left + thumbnailWidth * CGFloat(col)
let y = insets.top + CGFloat(row) * thumbnailHeight
attr.frame = CGRectMake(ceil(x), ceil(y), thumbnailWidth, thumbnailHeight)
return attr
}
}
private class TopSitesDataSource: NSObject, UICollectionViewDataSource {
var data: Cursor<Site>
var profile: Profile
var editingThumbnails: Bool = false
weak var collectionView: UICollectionView?
private let blurQueue = dispatch_queue_create("FaviconBlurQueue", DISPATCH_QUEUE_CONCURRENT)
private let BackgroundFadeInDuration: NSTimeInterval = 0.3
init(profile: Profile, data: Cursor<Site>) {
self.data = data
self.profile = profile
}
@objc func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if data.status != .Success {
return 0
}
// If there aren't enough data items to fill the grid, look for items in suggested sites.
if let layout = collectionView.collectionViewLayout as? TopSitesLayout {
return min(data.count + SuggestedSites.count, layout.thumbnailCount)
}
return 0
}
private func setDefaultThumbnailBackgroundForCell(cell: ThumbnailCell) {
cell.imageView.image = UIImage(named: "defaultTopSiteIcon")!
cell.imageView.contentMode = UIViewContentMode.Center
}
private func setBlurredBackground(image: UIImage, withURL url: NSURL, forCell cell: ThumbnailCell) {
let blurredKey = "\(url.absoluteString)!blurred"
if let blurredImage = SDImageCache.sharedImageCache().imageFromMemoryCacheForKey(blurredKey) {
cell.backgroundImage.image = blurredImage
} else {
let blurredImage = image.applyLightEffect()
SDImageCache.sharedImageCache().storeImage(blurredImage, forKey: blurredKey, toDisk: false)
cell.backgroundImage.alpha = 0
cell.backgroundImage.image = blurredImage
UIView.animateWithDuration(self.BackgroundFadeInDuration) {
cell.backgroundImage.alpha = 1
}
}
}
private func downloadFaviconsAndUpdateForSite(site: Site) {
guard let siteURL = site.url.asURL else { return }
FaviconFetcher.getForURL(siteURL, profile: profile).uponQueue(dispatch_get_main_queue()) { result in
guard let favicons = result.successValue where favicons.count > 0,
let url = favicons.first?.url.asURL,
let indexOfSite = (self.data.asArray().indexOf { $0 == site }) else {
return
}
let indexPathToUpdate = NSIndexPath(forItem: indexOfSite, inSection: 0)
guard let cell = self.collectionView?.cellForItemAtIndexPath(indexPathToUpdate) as? ThumbnailCell else { return }
cell.imageView.sd_setImageWithURL(url) { (img, err, type, url) -> Void in
guard let img = img else {
self.setDefaultThumbnailBackgroundForCell(cell)
return
}
cell.image = img
self.setBlurredBackground(img, withURL: url, forCell: cell)
}
}
}
private func configureCell(cell: ThumbnailCell, forSite site: Site, isEditing editing: Bool, profile: Profile) {
// We always want to show the domain URL, not the title.
//
// Eventually we can do something more sophisticated — e.g., if the site only consists of one
// history item, show it, and otherwise use the longest common sub-URL (and take its title
// if you visited that exact URL), etc. etc. — but not yet.
//
// The obvious solution here and in collectionView:didSelectItemAtIndexPath: is for the cursor
// to return domain sites, not history sites -- that is, with the right icon, title, and URL --
// and for this code to just use what it gets.
//
// Instead we'll painstakingly re-extract those things here.
let domainURL = NSURL(string: site.url)?.normalizedHost() ?? site.url
cell.textLabel.text = domainURL
cell.accessibilityLabel = cell.textLabel.text
cell.removeButton.hidden = !editing
guard let icon = site.icon else {
setDefaultThumbnailBackgroundForCell(cell)
downloadFaviconsAndUpdateForSite(site)
return
}
// We've looked before recently and didn't find a favicon
switch icon.type {
case .NoneFound where NSDate().timeIntervalSinceDate(icon.date) < FaviconFetcher.ExpirationTime:
self.setDefaultThumbnailBackgroundForCell(cell)
default:
cell.imageView.sd_setImageWithURL(icon.url.asURL, completed: { (img, err, type, url) -> Void in
if let img = img {
cell.image = img
self.setBlurredBackground(img, withURL: url, forCell: cell)
} else {
self.setDefaultThumbnailBackgroundForCell(cell)
self.downloadFaviconsAndUpdateForSite(site)
}
})
}
}
private func configureCell(cell: ThumbnailCell, forSuggestedSite site: SuggestedSite) {
cell.textLabel.text = site.title.isEmpty ? NSURL(string: site.url)?.normalizedHostAndPath() : site.title
cell.imageWrapper.backgroundColor = site.backgroundColor
cell.imageView.contentMode = UIViewContentMode.ScaleAspectFit
cell.accessibilityLabel = cell.textLabel.text
guard let icon = site.wordmark.url.asURL,
let host = icon.host else {
self.setDefaultThumbnailBackgroundForCell(cell)
return
}
if icon.scheme == "asset" {
cell.imageView.image = UIImage(named: host)
} else {
cell.imageView.sd_setImageWithURL(icon, completed: { img, err, type, key in
if img == nil {
self.setDefaultThumbnailBackgroundForCell(cell)
}
})
}
}
subscript(index: Int) -> Site? {
if data.status != .Success {
return nil
}
if index >= data.count {
return SuggestedSites[index - data.count]
}
return data[index] as Site?
}
@objc func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
// Cells for the top site thumbnails.
let site = self[indexPath.item]!
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(ThumbnailIdentifier, forIndexPath: indexPath) as! ThumbnailCell
let traitCollection = collectionView.traitCollection
cell.updateLayoutForCollectionViewSize(collectionView.bounds.size, traitCollection: traitCollection)
if indexPath.item >= data.count {
configureCell(cell, forSuggestedSite: site as! SuggestedSite)
} else {
configureCell(cell, forSite: site, isEditing: editingThumbnails, profile: profile)
}
return cell
}
}
|
mpl-2.0
|
587cbbd506b0cfa572b9e7a99b46af22
| 40.610084 | 155 | 0.660029 | 5.487145 | false | false | false | false |
Driftt/drift-sdk-ios
|
Drift/Models/Message.swift
|
1
|
7687
|
//
// Message.swift
// Drift
//
// Created by Brian McDonald on 25/07/2016.
// Copyright © 2016 Drift. All rights reserved.
//
enum ContentType: String, Codable{
case Chat = "CHAT"
case Annoucement = "ANNOUNCEMENT"
case Edit = "EDIT"
case ConversationEvent = "CONVERSATION_EVENT"
case BotEvaluation = "BOT_NODE_CONDITION_EVALUATION"
}
enum AuthorType: String, Codable{
case User = "USER"
case EndUser = "END_USER"
}
enum SendStatus: String {
case Sent = "SENT"
case Pending = "PENDING"
case Failed = "FAILED"
}
class Message: Equatable {
let id: Int64?
let uuid: String?
let body: String?
let attachmentIds: [Int64]
var attachments: [Attachment] = []
let contentType: ContentType
let createdAt: Date
let authorId: Int64
let authorType: AuthorType
let conversationId: Int64
var sendStatus: SendStatus = SendStatus.Sent
var formattedBody: NSAttributedString?
let appointmentInformation: AppointmentInformation?
var presentSchedule: Int64?
let scheduleMeetingFlow: Bool
let offerSchedule: Int64
let preMessages: [PreMessage]
let requestId: Double
let fakeMessage: Bool
let preMessage: Bool
init(id: Int64? = nil,
uuid: String?,
body: String?,
attachmentIds: [Int64] = [],
contentType:ContentType,
createdAt: Date,
authorId: Int64,
authorType: AuthorType,
conversationId: Int64,
appointmentInformation: AppointmentInformation? = nil,
presentSchedule: Int64? = nil,
scheduleMeetingFlow: Bool = false,
offerSchedule: Int64 = -1,
preMessages: [PreMessage] = [],
requestId: Double = 0,
fakeMessage: Bool = false,
preMessage: Bool = false) {
self.id = id
self.uuid = uuid
self.body = body
self.attachmentIds = attachmentIds
self.contentType = contentType
self.createdAt = createdAt
self.authorId = authorId
self.authorType = authorType
self.conversationId = conversationId
self.appointmentInformation = appointmentInformation
self.presentSchedule = presentSchedule
self.scheduleMeetingFlow = scheduleMeetingFlow
self.offerSchedule = offerSchedule
self.preMessages = preMessages
self.requestId = requestId
self.fakeMessage = fakeMessage
self.preMessage = preMessage
}
func formatHTMLBody() {
if formattedBody == nil {
formattedBody = TextHelper.attributedTextForString(text: body ?? "")
}
}
}
class MessageDTO: Codable, DTO {
typealias DataObject = Message
var id: Int64?
var uuid: String?
var body: String?
var attachmentIds: [Int64]?
var contentType:ContentType?
var createdAt: Date?
var authorId: Int64?
var authorType: AuthorType?
var conversationId: Int64?
var attributes: MessageAttributesDTO?
func mapToObject() -> Message? {
guard let contentType = contentType,
let id = id,
let authorType = authorType,
let conversationId = conversationId else { return nil }
return Message(id: id,
uuid: uuid,
body: body,
attachmentIds: attachmentIds ?? [],
contentType: contentType,
createdAt: createdAt ?? Date(),
authorId: authorId ?? -1,
authorType: authorType,
conversationId: conversationId,
appointmentInformation: attributes?.appointmentInformation?.mapToObject(),
presentSchedule: attributes?.presentSchedule,
scheduleMeetingFlow: attributes?.scheduleMeetingFlow ?? false,
offerSchedule: attributes?.offerSchedule ?? -1,
preMessages: attributes?.preMessages?.compactMap({$0.mapToObject()}) ?? [])
}
enum CodingKeys: String, CodingKey {
case id = "id"
case uuid = "uuid"
case body = "body"
case attachmentIds = "attachments"
case contentType = "contentType"
case createdAt = "createdAt"
case authorId = "authorId"
case authorType = "authorType"
case conversationId = "conversationId"
case attributes = "attributes"
}
}
class MessageAttributesDTO: Codable{
var appointmentInformation: AppointmentInformationDTO?
var presentSchedule: Int64?
var scheduleMeetingFlow: Bool?
var offerSchedule: Int64?
var preMessages: [PreMessageDTO]?
enum CodingKeys: String, CodingKey {
case appointmentInformation = "appointmentInfo"
case presentSchedule = "presentSchedule"
case scheduleMeetingFlow = "scheduleMeetingFlow"
case offerSchedule = "offerSchedule"
case preMessages = "preMessages"
}
}
extension Array where Iterator.Element == Message
{
func sortMessagesForConversation() -> Array<Message> {
var output:[Message] = []
let sorted = self.sorted(by: { $0.createdAt.compare($1.createdAt) == .orderedAscending})
for message in sorted {
if message.preMessage {
//Ignore pre messages, we will recreate them
continue
}
if !message.preMessages.isEmpty {
output.append(contentsOf: getMessagesFromPreMessages(message: message, preMessages: message.preMessages))
}
if message.offerSchedule != -1 {
continue
}
if let _ = message.appointmentInformation {
//Go backwards and remove the most recent message asking for an apointment
output = output.map({
if let _ = $0.presentSchedule {
$0.presentSchedule = nil
}
return $0
})
}
output.append(message)
}
return output.sorted(by: { $0.createdAt.compare($1.createdAt) == .orderedDescending})
}
private func getMessagesFromPreMessages(message: Message, preMessages: [PreMessage]) -> [Message] {
let date = message.createdAt
var output: [Message] = []
for (index, preMessage) in preMessages.enumerated() {
if let authorId = preMessage.user?.userId {
let fakeMessage = Message(uuid: UUID().uuidString,
body: preMessage.messageBody,
contentType: .Chat,
createdAt: date.addingTimeInterval(TimeInterval(-(index + 1))),
authorId: authorId,
authorType: .User,
conversationId: message.conversationId,
fakeMessage: true,
preMessage: true)
output.append(fakeMessage)
}
}
return output
}
}
func ==(lhs: Message, rhs: Message) -> Bool {
return lhs.uuid == rhs.uuid
}
|
mit
|
9736b7c5be32e07b09e0ccaf4b39384b
| 31.025 | 121 | 0.550351 | 5.221467 | false | false | false | false |
Acidburn0zzz/firefox-ios
|
Client/Frontend/AuthenticationManager/ChangePasscodeViewController.swift
|
1
|
3426
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import SwiftKeychainWrapper
import Shared
/// Displayed to the user when changing an existing passcode.
class ChangePasscodeViewController: PagingPasscodeViewController, PasscodeInputViewDelegate {
fileprivate var newPasscode: String?
fileprivate var oldPasscode: String?
override init() {
super.init()
self.title = .AuthenticationChangePasscode
self.panes = [
PasscodePane(title: .AuthenticationEnterPasscode, passcodeSize: authenticationInfo?.passcode?.count ?? 6),
PasscodePane(title: .AuthenticationEnterNewPasscode, passcodeSize: 6),
PasscodePane(title: .AuthenticationReenterPasscode, passcodeSize: 6),
]
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
panes.forEach { $0.codeInputView.delegate = self }
// Don't show the keyboard or allow typing if we're locked out. Also display the error.
if authenticationInfo?.isLocked() ?? false {
displayLockoutError()
panes.first?.codeInputView.isUserInteractionEnabled = false
} else {
panes.first?.codeInputView.becomeFirstResponder()
}
}
func passcodeInputView(_ inputView: PasscodeInputView, didFinishEnteringCode code: String) {
switch currentPaneIndex {
case 0:
// Constraint: We need to make sure that the first passcode they've entered matches the one stored in the keychain
if code != authenticationInfo?.passcode {
panes[currentPaneIndex].shakePasscode()
failIncorrectPasscode(inputView)
return
}
oldPasscode = code
authenticationInfo?.recordValidation()
// Clear out any previous errors if we are allowed to proceed
errorToast?.removeFromSuperview()
scrollToNextAndSelect()
case 1:
// Constraint: The new passcode cannot match their old passcode.
if oldPasscode == code {
failMustBeDifferent()
// Scroll back and reset the input fields
resetAllInputFields()
return
}
newPasscode = code
errorToast?.removeFromSuperview()
scrollToNextAndSelect()
case 2:
if newPasscode != code {
failMismatchPasscode()
// Scroll back and reset input fields
resetAllInputFields()
scrollToPreviousAndSelect()
newPasscode = nil
return
}
changePasscodeToCode(code)
dismissAnimated()
default:
break
}
}
fileprivate func changePasscodeToCode(_ code: String) {
authenticationInfo?.updatePasscode(code)
KeychainWrapper.sharedAppContainerKeychain.setAuthenticationInfo(authenticationInfo)
let notificationCenter = NotificationCenter.default
notificationCenter.post(name: .PasscodeDidChange, object: nil)
}
}
|
mpl-2.0
|
500f84212949725f38ad1c98a78b5cb9
| 36.648352 | 126 | 0.631932 | 5.66281 | false | false | false | false |
GTMYang/GTMRefresh
|
GTMRefreshExample/TaoBao/TaoBaoRefreshHeader.swift
|
1
|
5119
|
//
// TaoBaoRefreshHeader.swift
// PullToRefreshKit
//
// Created by luoyang on 2016/12/8.
// Copyright © 2016年 luoyang. All rights reserved.
//
import GTMRefresh
import UIKit
class TaoBaoRefreshHeader: GTMRefreshHeader, SubGTMRefreshHeaderProtocol {
fileprivate let circleLayer = CAShapeLayer()
fileprivate let arrowLayer = CAShapeLayer()
let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 230, height: 35))
fileprivate let textLabel = UILabel()
fileprivate let strokeColor = UIColor(red: 135.0/255.0, green: 136.0/255.0, blue: 137.0/255.0, alpha: 1.0)
override init(frame: CGRect) {
super.init(frame: frame)
setUpCircleLayer()
setUpArrowLayer()
textLabel.textAlignment = .center
textLabel.textColor = UIColor.lightGray
textLabel.font = UIFont.systemFont(ofSize: 14)
textLabel.text = "下拉即可刷新..."
imageView.image = UIImage(named: "taobaoLogo")
self.contentView.addSubview(imageView)
self.contentView.addSubview(textLabel)
}
func setUpArrowLayer(){
let bezierPath = UIBezierPath()
bezierPath.move(to: CGPoint(x: 20, y: 15))
bezierPath.addLine(to: CGPoint(x: 20, y: 25))
bezierPath.addLine(to: CGPoint(x: 25,y: 20))
bezierPath.move(to: CGPoint(x: 20, y: 25))
bezierPath.addLine(to: CGPoint(x: 15, y: 20))
self.arrowLayer.path = bezierPath.cgPath
self.arrowLayer.strokeColor = UIColor.lightGray.cgColor
self.arrowLayer.fillColor = UIColor.clear.cgColor
self.arrowLayer.lineWidth = 2.0
self.arrowLayer.lineCap = CAShapeLayerLineCap.round
self.arrowLayer.lineJoin = CAShapeLayerLineJoin.round
self.arrowLayer.bounds = CGRect(x: 0, y: 0,width: 40, height: 40)
self.arrowLayer.anchorPoint = CGPoint(x: 0.5, y: 0.5)
self.layer.addSublayer(self.arrowLayer)
}
func setUpCircleLayer(){
let bezierPath = UIBezierPath(arcCenter: CGPoint(x: 20, y: 20),
radius: 12.0,
startAngle:CGFloat(-Double.pi/2),
endAngle: CGFloat(Double.pi/2 * 3),
clockwise: true)
self.circleLayer.path = bezierPath.cgPath
self.circleLayer.strokeColor = UIColor.lightGray.cgColor
self.circleLayer.fillColor = UIColor.clear.cgColor
self.circleLayer.strokeStart = 0.05
self.circleLayer.strokeEnd = 0.05
self.circleLayer.lineWidth = 1.0
self.circleLayer.lineCap = CAShapeLayerLineCap.round
self.circleLayer.bounds = CGRect(x: 0, y: 0,width: 40, height: 40)
self.circleLayer.anchorPoint = CGPoint(x: 0.5, y: 0.5)
self.layer.addSublayer(self.circleLayer)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
textLabel.frame = CGRect(x: 0,y: 0,width: 120, height: 40)
//放置Views和Layer
imageView.center = CGPoint(x: frame.width/2, y: frame.height - 60 - 18)
textLabel.center = CGPoint(x: frame.width/2 + 20, y: frame.height - 30)
self.arrowLayer.position = CGPoint(x: frame.width/2 - 60, y: frame.height - 30)
self.circleLayer.position = CGPoint(x: frame.width/2 - 60, y: frame.height - 30)
}
func toNormalState() {}
func toRefreshingState() {
self.circleLayer.strokeEnd = 0.95
let rotateAnimation = CABasicAnimation(keyPath: "transform.rotation.z")
rotateAnimation.toValue = NSNumber(value: Double.pi * 2.0 as Double)
rotateAnimation.duration = 0.6
rotateAnimation.isCumulative = true
rotateAnimation.repeatCount = 10000000
self.circleLayer.add(rotateAnimation, forKey: "rotate")
self.arrowLayer.isHidden = true
textLabel.text = "刷新中..."
}
func toPullingState() {}
func toWillRefreshState() {}
func changePullingPercent(percent: CGFloat) {
let adjustPercent = max(min(1.0, percent),0.0)
if adjustPercent == 1.0{
textLabel.text = "释放即可刷新..."
}else{
textLabel.text = "下拉即可刷新..."
}
self.circleLayer.strokeEnd = 0.05 + 0.9 * adjustPercent
}
func willEndRefreshing(isSuccess: Bool) {
// transitionWithOutAnimation {
// self.circleLayer.strokeEnd = 0.05
// };
}
func didEndRefreshing() {
transitionWithOutAnimation {
self.circleLayer.strokeEnd = 0.05
};
self.circleLayer.removeAllAnimations()
self.arrowLayer.isHidden = false
textLabel.text = "下拉即可刷新"
}
func contentHeight()->CGFloat{
return 60
}
/// MARK: Private
func transitionWithOutAnimation(_ clousre:()->()){
CATransaction.begin()
CATransaction.setDisableActions(true)
clousre()
CATransaction.commit()
}
}
|
mit
|
ae64279811f2cac4c19885195d0a4852
| 37.59542 | 110 | 0.621835 | 4.195851 | false | false | false | false |
adamcin/SwiftCJ
|
SwiftCJ/CJQuery.swift
|
1
|
973
|
import Foundation
public struct CJQuery {
public let href: NSURL
public let rel: String
public let name: String?
public let prompt: String?
public let data: CJData?
func forDict(dict: [String: AnyObject]) -> CJQuery {
return CJQuery(href: self.href, rel: self.rel, name: self.name, prompt: self.prompt, data: self.data?.copyAndSetAll(dict))
}
static func queryFromDictionary(dict: [NSObject: AnyObject]) -> CJQuery? {
if let hrefString = dict["href"] as? String {
if let href = NSURL(string: hrefString) {
if let rel = dict["rel"] as? String {
let name = dict["name"] as? String
let prompt = dict["prompt"] as? String
let data = CJData.dataForDictionary(dict)
return CJQuery(href: href, rel: rel, name: name, prompt: prompt, data: data)
}
}
}
return nil
}
}
|
mit
|
7b9f8a6559e64be4bc51aeb811ae46a6
| 35.037037 | 130 | 0.563207 | 4.175966 | false | false | false | false |
DMeechan/Rick-and-Morty-Soundboard
|
Rick and Morty Soundboard/Pods/Eureka/Source/Rows/SegmentedRow.swift
|
2
|
8740
|
// SegmentedRow.swift
// Eureka ( https://github.com/xmartlabs/Eureka )
//
// Copyright (c) 2016 Xmartlabs SRL ( http://xmartlabs.com )
//
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
// MARK: SegmentedCell
open class SegmentedCell<T: Equatable> : Cell<T>, CellType {
@IBOutlet public weak var segmentedControl: UISegmentedControl!
@IBOutlet public weak var titleLabel: UILabel?
private var dynamicConstraints = [NSLayoutConstraint]()
fileprivate var observingTitleText = false
private var awakeFromNibCalled = false
required public init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
let segmentedControl = UISegmentedControl()
segmentedControl.translatesAutoresizingMaskIntoConstraints = false
segmentedControl.setContentHuggingPriority(250, for: .horizontal)
self.segmentedControl = segmentedControl
self.titleLabel = self.textLabel
self.titleLabel?.translatesAutoresizingMaskIntoConstraints = false
self.titleLabel?.setContentHuggingPriority(500, for: .horizontal)
NotificationCenter.default.addObserver(forName: Notification.Name.UIApplicationWillResignActive, object: nil, queue: nil) { [weak self] _ in
guard let me = self else { return }
guard me.observingTitleText else { return }
me.titleLabel?.removeObserver(me, forKeyPath: "text")
me.observingTitleText = false
}
NotificationCenter.default.addObserver(forName: Notification.Name.UIApplicationDidBecomeActive, object: nil, queue: nil) { [weak self] _ in
guard let me = self else { return }
guard !me.observingTitleText else { return }
me.titleLabel?.addObserver(me, forKeyPath: "text", options: NSKeyValueObservingOptions.old.union(.new), context: nil)
me.observingTitleText = true
}
NotificationCenter.default.addObserver(forName: Notification.Name.UIContentSizeCategoryDidChange, object: nil, queue: nil) { [weak self] _ in
self?.titleLabel = self?.textLabel
self?.setNeedsUpdateConstraints()
}
contentView.addSubview(titleLabel!)
contentView.addSubview(segmentedControl)
titleLabel?.addObserver(self, forKeyPath: "text", options: [.old, .new], context: nil)
observingTitleText = true
imageView?.addObserver(self, forKeyPath: "image", options: [.old, .new], context: nil)
contentView.addConstraint(NSLayoutConstraint(item: segmentedControl, attribute: .centerY, relatedBy: .equal, toItem: contentView, attribute: .centerY, multiplier: 1, constant: 0))
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
open override func awakeFromNib() {
super.awakeFromNib()
awakeFromNibCalled = true
}
deinit {
segmentedControl.removeTarget(self, action: nil, for: .allEvents)
if !awakeFromNibCalled {
if observingTitleText {
titleLabel?.removeObserver(self, forKeyPath: "text")
}
imageView?.removeObserver(self, forKeyPath: "image")
NotificationCenter.default.removeObserver(self, name: Notification.Name.UIApplicationWillResignActive, object: nil)
NotificationCenter.default.removeObserver(self, name: Notification.Name.UIApplicationDidBecomeActive, object: nil)
NotificationCenter.default.removeObserver(self, name: Notification.Name.UIContentSizeCategoryDidChange, object: nil)
}
}
open override func setup() {
super.setup()
selectionStyle = .none
segmentedControl.addTarget(self, action: #selector(SegmentedCell.valueChanged), for: .valueChanged)
}
open override func update() {
super.update()
detailTextLabel?.text = nil
updateSegmentedControl()
segmentedControl.selectedSegmentIndex = selectedIndex() ?? UISegmentedControlNoSegment
segmentedControl.isEnabled = !row.isDisabled
}
func valueChanged() {
row.value = (row as! SegmentedRow<T>).options[segmentedControl.selectedSegmentIndex]
}
open override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
let obj = object as AnyObject?
if let changeType = change, let _ = keyPath, ((obj === titleLabel && keyPath == "text") || (obj === imageView && keyPath == "image")) &&
(changeType[NSKeyValueChangeKey.kindKey] as? NSNumber)?.uintValue == NSKeyValueChange.setting.rawValue, !awakeFromNibCalled {
setNeedsUpdateConstraints()
updateConstraintsIfNeeded()
}
}
func updateSegmentedControl() {
segmentedControl.removeAllSegments()
(row as! SegmentedRow<T>).options.reversed().forEach {
if let image = $0 as? UIImage {
segmentedControl.insertSegment(with: image, at: 0, animated: false)
} else {
segmentedControl.insertSegment(withTitle: row.displayValueFor?($0) ?? "", at: 0, animated: false)
}
}
}
open override func updateConstraints() {
guard !awakeFromNibCalled else { return }
contentView.removeConstraints(dynamicConstraints)
dynamicConstraints = []
var views: [String: AnyObject] = ["segmentedControl": segmentedControl]
var hasImageView = false
var hasTitleLabel = false
if let imageView = imageView, let _ = imageView.image {
views["imageView"] = imageView
hasImageView = true
}
if let titleLabel = titleLabel, let text = titleLabel.text, !text.isEmpty {
views["titleLabel"] = titleLabel
hasTitleLabel = true
dynamicConstraints.append(NSLayoutConstraint(item: titleLabel, attribute: .centerY, relatedBy: .equal, toItem: contentView, attribute: .centerY, multiplier: 1, constant: 0))
}
dynamicConstraints.append(NSLayoutConstraint(item: segmentedControl, attribute: .width, relatedBy: .greaterThanOrEqual, toItem: contentView, attribute: .width, multiplier: 0.3, constant: 0.0))
if hasImageView && hasTitleLabel {
dynamicConstraints += NSLayoutConstraint.constraints(withVisualFormat: "H:[imageView]-(15)-[titleLabel]-[segmentedControl]-|", options: [], metrics: nil, views: views)
} else if hasImageView && !hasTitleLabel {
dynamicConstraints += NSLayoutConstraint.constraints(withVisualFormat: "H:[imageView]-[segmentedControl]-|", options: [], metrics: nil, views: views)
} else if !hasImageView && hasTitleLabel {
dynamicConstraints = NSLayoutConstraint.constraints(withVisualFormat: "H:|-[titleLabel]-[segmentedControl]-|", options: .alignAllCenterY, metrics: nil, views: views)
} else {
dynamicConstraints = NSLayoutConstraint.constraints(withVisualFormat: "H:|-[segmentedControl]-|", options: .alignAllCenterY, metrics: nil, views: views)
}
contentView.addConstraints(dynamicConstraints)
super.updateConstraints()
}
func selectedIndex() -> Int? {
guard let value = row.value else { return nil }
return (row as! SegmentedRow<T>).options.index(of: value)
}
}
// MARK: SegmentedRow
/// An options row where the user can select an option from an UISegmentedControl
public final class SegmentedRow<T: Equatable>: OptionsRow<SegmentedCell<T>>, RowType {
required public init(tag: String?) {
super.init(tag: tag)
}
}
|
apache-2.0
|
0b973d13f61df79808bbac719aee06cb
| 45.243386 | 200 | 0.6873 | 5.227273 | false | false | false | false |
melling/Swift
|
TransitionWithView/TransitionWithView/ViewController.swift
|
1
|
4004
|
//
// ViewController.swift
// TransitionWithView
//
// Created by Michael Mellinger on 4/28/15.
// Copyright (c) 2015 h4labs. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
/*
Need to use a container as described here:
http://stackoverflow.com/questions/29923061/trying-to-curl-up-curl-down-with-two-views-using-autolayout-in-swift?noredirect=1#comment47975892_29923061
http://stackoverflow.com/questions/9524048/how-to-flip-an-individual-uiview-without-flipping-the-parent-view
*/
var container:UIView! // Place cardFront/cardBack in this container
var cardFront:UIView!
var cardBack:UIView!
func centerViewXY(parent: UIView, child: UIView) {
let constX = NSLayoutConstraint(item: child, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: parent, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0)
parent.addConstraint(constX)
let constY = NSLayoutConstraint(item: child, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: parent, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: 0)
parent.addConstraint(constY)
}
func addStandardConstraints(view:UIView, constraint:String, viewDictionary:Dictionary<String,UIView!>, metrics:Dictionary<String, Int>) {
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat(constraint, options: [], metrics: metrics, views: viewDictionary))
}
func curlUp() {
let transitionOptions = UIViewAnimationOptions.TransitionCurlUp
UIView.transitionFromView(cardFront,
toView: cardBack,
duration: 5.0,
options: transitionOptions,
completion: { _ in
let transitionOptions = UIViewAnimationOptions.TransitionCurlDown
UIView.transitionFromView(self.cardBack,
toView: self.cardFront,
duration: 5.0,
options: transitionOptions,
completion: { _ in
//
})
})
}
func buildView() {
let height = 100
let width = 100
container = UIView()
container.translatesAutoresizingMaskIntoConstraints = false
container.backgroundColor = UIColor.blackColor()
self.view.addSubview(container)
cardBack = UIView(frame: CGRectMake(0, 0, CGFloat(width), CGFloat(height)))
cardBack.backgroundColor = UIColor.redColor()
container.addSubview(cardBack)
cardFront = UIView(frame: CGRectMake(0, 0, CGFloat(width), CGFloat(height)))
cardFront.backgroundColor = UIColor.greenColor()
container.addSubview(cardFront)
let viewDictionary:Dictionary<String,UIView> = ["container": container]
let metrics:Dictionary<String,Int> = ["width": width, "height": height]
let h0Constraint = "H:[container(==width)]"
let v0Constraint = "V:[container(==height)]"
addStandardConstraints(self.view, constraint: h0Constraint, viewDictionary: viewDictionary, metrics: metrics)
addStandardConstraints(self.view, constraint: v0Constraint, viewDictionary: viewDictionary, metrics: metrics)
centerViewXY(self.view, child: container)
NSTimer.scheduledTimerWithTimeInterval(2, target: self, selector: "curlUp", userInfo: nil, repeats: false)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.view.backgroundColor = UIColor.purpleColor()
buildView()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
mit
|
13fef3912bd9fae381fbd1804f22449d
| 34.122807 | 207 | 0.65035 | 4.961586 | false | false | false | false |
ykws/yomblr
|
yomblr/AppDelegate.swift
|
1
|
2688
|
//
// AppDelegate.swift
// yomblr
//
// Created by Yoshiyuki Kawashima on 2017/06/21.
// Copyright © 2017 ykws. All rights reserved.
//
import UIKit
import Keys
import TMTumblrSDK
import ChameleonFramework
import Firebase
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
let keys = YomblrKeys()
TMAPIClient.sharedInstance().oAuthConsumerKey = keys.tumblrOAuthConsumerKey
TMAPIClient.sharedInstance().oAuthConsumerSecret = keys.tumblrOAuthConsumerSecret
FirebaseApp.configure()
UINavigationBar.appearance().barTintColor = UIColor.TumblrColor()
UINavigationBar.appearance().tintColor = FlatWhite()
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:.
}
// MARK: - URL Scheme
func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
return TMAPIClient.sharedInstance().handleOpen(url)
}
}
|
mit
|
fc95d18971947e189979ad0a4d238829
| 42.33871 | 281 | 0.769259 | 5.310277 | false | false | false | false |
vmachiel/swift
|
Project1/Project1/DetailViewController.swift
|
1
|
2589
|
//
// DetailViewController.swift
// Project1
//
// Created by Machiel van Dorst on 17-07-17.
// Copyright © 2017 vmachiel. All rights reserved.
//
import UIKit
class DetailViewController: UIViewController {
// @IBOutlet specifies a link between this property and the storyboard
// weak makes sure it's not owned in memory by this code, but by the view
// When the view is unloaded, so is this property.. right?
// and it's of type UIImageView
@IBOutlet weak var imageView: UIImageView!
var selectedImage: String?
// When the view is loaded, if the selectedImage property exists and thus can be set to
// constant imageToLoad. It's a name from the array of file names in the case.
// UIImage is a class to display images. They can take a name and load the correct
// image from the contents.
// imageView is created by dragging the storyboard thing.
override func viewDidLoad() {
super.viewDidLoad()
title = selectedImage // Notice this is a optional: both title and selectedImage.
if let imageToLoad = selectedImage {
imageView.image = UIImage(named: imageToLoad)
}
// Do any additional setup after loading the view.
}
// Again, super.blabla makes sure the normal stuff gets executed.
// viewWillAppear gets called right before this view (DetailView) is loaded.
// viewDidAppear gets called right before the view is dystored (user taps back)
// navigationContoller (get), if its there, sets its hidesBarsOnTap (get/set) property
// to true right before the view is loaded, and false again when destroyed.
// You don't want that active in the actual table, only the detail/picture.
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationController?.hidesBarsOnTap = true
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
navigationController?.hidesBarsOnTap = false
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
mit
|
4bd2943ccd490e13b8478d3ba7d49514
| 38.212121 | 106 | 0.685858 | 4.901515 | false | false | false | false |
Sage-Bionetworks/MoleMapper
|
MoleMapper/Charts/Classes/Data/ChartDataSet.swift
|
1
|
11954
|
//
// ChartDataSet.swift
// Charts
//
// Created by Daniel Cohen Gindi on 23/2/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
//
import Foundation
import UIKit
public class ChartDataSet: NSObject
{
public var colors = [UIColor]()
internal var _yVals: [ChartDataEntry]!
internal var _yMax = Double(0.0)
internal var _yMin = Double(0.0)
internal var _yValueSum = Double(0.0)
/// the last start value used for calcMinMax
internal var _lastStart: Int = 0
/// the last end value used for calcMinMax
internal var _lastEnd: Int = 0
public var label: String? = "DataSet"
public var visible = true
public var drawValuesEnabled = true
/// the color used for the value-text
public var valueTextColor: UIColor = UIColor.blackColor()
/// the font for the value-text labels
public var valueFont: UIFont = UIFont.systemFontOfSize(7.0)
/// the formatter used to customly format the values
public var valueFormatter: NSNumberFormatter?
/// the axis this DataSet should be plotted against.
public var axisDependency = ChartYAxis.AxisDependency.Left
public var yVals: [ChartDataEntry] { return _yVals }
public var yValueSum: Double { return _yValueSum }
public var yMin: Double { return _yMin }
public var yMax: Double { return _yMax }
/// if true, value highlighting is enabled
public var highlightEnabled = true
/// - returns: true if value highlighting is enabled for this dataset
public var isHighlightEnabled: Bool { return highlightEnabled }
public override init()
{
super.init()
}
public init(yVals: [ChartDataEntry]?, label: String?)
{
super.init()
self.label = label
_yVals = yVals == nil ? [ChartDataEntry]() : yVals
// default color
colors.append(UIColor(red: 140.0/255.0, green: 234.0/255.0, blue: 255.0/255.0, alpha: 1.0))
self.calcMinMax(start: _lastStart, end: _lastEnd)
self.calcYValueSum()
}
public convenience init(yVals: [ChartDataEntry]?)
{
self.init(yVals: yVals, label: "DataSet")
}
/// Use this method to tell the data set that the underlying data has changed
public func notifyDataSetChanged()
{
calcMinMax(start: _lastStart, end: _lastEnd)
calcYValueSum()
}
internal func calcMinMax(start start : Int, end: Int)
{
let yValCount = _yVals.count
if yValCount == 0
{
return
}
var endValue : Int
if end == 0 || end >= yValCount
{
endValue = yValCount - 1
}
else
{
endValue = end
}
_lastStart = start
_lastEnd = endValue
_yMin = DBL_MAX
_yMax = -DBL_MAX
for (var i = start; i <= endValue; i++)
{
let e = _yVals[i]
if (!e.value.isNaN)
{
if (e.value < _yMin)
{
_yMin = e.value
}
if (e.value > _yMax)
{
_yMax = e.value
}
}
}
if (_yMin == DBL_MAX)
{
_yMin = 0.0
_yMax = 0.0
}
}
private func calcYValueSum()
{
_yValueSum = 0
for var i = 0; i < _yVals.count; i++
{
_yValueSum += fabs(_yVals[i].value)
}
}
public var entryCount: Int { return _yVals!.count; }
public func yValForXIndex(x: Int) -> Double
{
let e = self.entryForXIndex(x)
if (e !== nil && e!.xIndex == x) { return e!.value }
else { return Double.NaN }
}
/// - returns: the first Entry object found at the given xIndex with binary search.
/// If the no Entry at the specifed x-index is found, this method returns the Entry at the closest x-index.
/// nil if no Entry object at that index.
public func entryForXIndex(x: Int) -> ChartDataEntry?
{
let index = self.entryIndex(xIndex: x)
if (index > -1)
{
return _yVals[index]
}
return nil
}
public func entriesForXIndex(x: Int) -> [ChartDataEntry]
{
var entries = [ChartDataEntry]()
var low = 0
var high = _yVals.count - 1
while (low <= high)
{
var m = Int((high + low) / 2)
var entry = _yVals[m]
if (x == entry.xIndex)
{
while (m > 0 && _yVals[m - 1].xIndex == x)
{
m--
}
high = _yVals.count
for (; m < high; m++)
{
entry = _yVals[m]
if (entry.xIndex == x)
{
entries.append(entry)
}
else
{
break
}
}
}
if (x > _yVals[m].xIndex)
{
low = m + 1
}
else
{
high = m - 1
}
}
return entries
}
public func entryIndex(xIndex x: Int) -> Int
{
var low = 0
var high = _yVals.count - 1
var closest = -1
while (low <= high)
{
var m = (high + low) / 2
let entry = _yVals[m]
if (x == entry.xIndex)
{
while (m > 0 && _yVals[m - 1].xIndex == x)
{
m--
}
return m
}
if (x > entry.xIndex)
{
low = m + 1
}
else
{
high = m - 1
}
closest = m
}
return closest
}
public func entryIndex(entry e: ChartDataEntry, isEqual: Bool) -> Int
{
if (isEqual)
{
for (var i = 0; i < _yVals.count; i++)
{
if (_yVals[i].isEqual(e))
{
return i
}
}
}
else
{
for (var i = 0; i < _yVals.count; i++)
{
if (_yVals[i] === e)
{
return i
}
}
}
return -1
}
/// - returns: the number of entries this DataSet holds.
public var valueCount: Int { return _yVals.count; }
/// Adds an Entry to the DataSet dynamically.
/// Entries are added to the end of the list.
/// This will also recalculate the current minimum and maximum values of the DataSet and the value-sum.
/// - parameter e: the entry to add
public func addEntry(e: ChartDataEntry)
{
let val = e.value
if (_yVals == nil)
{
_yVals = [ChartDataEntry]()
}
if (_yVals.count == 0)
{
_yMax = val
_yMin = val
}
else
{
if (_yMax < val)
{
_yMax = val
}
if (_yMin > val)
{
_yMin = val
}
}
_yValueSum += val
_yVals.append(e)
}
/// Adds an Entry to the DataSet dynamically.
/// Entries are added to their appropriate index respective to it's x-index.
/// This will also recalculate the current minimum and maximum values of the DataSet and the value-sum.
/// - parameter e: the entry to add
public func addEntryOrdered(e: ChartDataEntry)
{
let val = e.value
if (_yVals == nil)
{
_yVals = [ChartDataEntry]()
}
if (_yVals.count == 0)
{
_yMax = val
_yMin = val
}
else
{
if (_yMax < val)
{
_yMax = val
}
if (_yMin > val)
{
_yMin = val
}
}
_yValueSum += val
if _yVals.last?.xIndex > e.xIndex
{
var closestIndex = entryIndex(xIndex: e.xIndex)
if _yVals[closestIndex].xIndex < e.xIndex
{
closestIndex++
}
_yVals.insert(e, atIndex: closestIndex)
return;
}
_yVals.append(e)
}
public func removeEntry(entry: ChartDataEntry) -> Bool
{
var removed = false
for (var i = 0; i < _yVals.count; i++)
{
if (_yVals[i] === entry)
{
_yVals.removeAtIndex(i)
removed = true
break
}
}
if (removed)
{
_yValueSum -= entry.value
calcMinMax(start: _lastStart, end: _lastEnd)
}
return removed
}
public func removeEntry(xIndex xIndex: Int) -> Bool
{
let index = self.entryIndex(xIndex: xIndex)
if (index > -1)
{
let e = _yVals.removeAtIndex(index)
_yValueSum -= e.value
calcMinMax(start: _lastStart, end: _lastEnd)
return true
}
return false
}
public func resetColors()
{
colors.removeAll(keepCapacity: false)
}
public func addColor(color: UIColor)
{
colors.append(color)
}
public func setColor(color: UIColor)
{
colors.removeAll(keepCapacity: false)
colors.append(color)
}
public func colorAt(var index: Int) -> UIColor
{
if (index < 0)
{
index = 0
}
return colors[index % colors.count]
}
public var isVisible: Bool
{
return visible
}
public var isDrawValuesEnabled: Bool
{
return drawValuesEnabled
}
/// Checks if this DataSet contains the specified Entry.
/// - returns: true if contains the entry, false if not.
public func contains(e: ChartDataEntry) -> Bool
{
for entry in _yVals
{
if (entry.isEqual(e))
{
return true
}
}
return false
}
/// Removes all values from this DataSet and recalculates min and max value.
public func clear()
{
_yVals.removeAll(keepCapacity: true)
_lastStart = 0
_lastEnd = 0
notifyDataSetChanged()
}
// MARK: NSObject
public override var description: String
{
return String(format: "ChartDataSet, label: %@, %i entries", arguments: [self.label ?? "", _yVals.count])
}
public override var debugDescription: String
{
var desc = description + ":"
for (var i = 0; i < _yVals.count; i++)
{
desc += "\n" + _yVals[i].description
}
return desc
}
// MARK: NSCopying
public func copyWithZone(zone: NSZone) -> AnyObject
{
let copy = ChartDataSet(yVals: _yVals, label: label)
copy.colors = colors
copy._yMax = _yMax
copy._yMin = _yMin
copy._yValueSum = _yValueSum
return copy
}
}
|
bsd-3-clause
|
25be91c6749bb5efe3d36d27007e68c7
| 23.100806 | 113 | 0.454827 | 4.777778 | false | false | false | false |
paulgriffiths/macvideopoker
|
VideoPoker/RankCounter.swift
|
1
|
1217
|
//
// RankCounter.swift
//
// Utility struct to calculate the numbers of distinct ranks
// in a list of playing cards, for instance to determine how
// many fives or jacks are present in the list.
//
// Copyright (c) 2015 Paul Griffiths.
// Distributed under the terms of the GNU General Public License. <http://www.gnu.org/licenses/>
//
struct RankCounter {
private var ranks: [Rank : Int] = [:]
init(cardList: CardList) {
for card in cardList {
countCard(card)
}
}
var count: Int {
return ranks.count
}
mutating private func countCard(card: Card) {
if let count = ranks[card.rank] {
ranks[card.rank] = count + 1
}
else {
ranks[card.rank] = 1
}
}
func containsRank(rank: Rank) -> Bool {
if ranks[rank] != nil {
return true
}
else {
return false
}
}
func countForRank(rank: Rank) -> Int {
if let count = ranks[rank] {
return count
}
else {
return 0
}
}
func ranksSet() -> Set<Rank> {
return Set<Rank>(ranks.keys)
}
}
|
gpl-3.0
|
9fd84a6e1e1c383540813d4810c1dc6c
| 21.145455 | 97 | 0.520953 | 4.043189 | false | false | false | false |
fgengine/quickly
|
Quickly/Compositions/QComposition.swift
|
1
|
3245
|
//
// Quickly
//
open class QComposable : IQComposable {
public var edgeInsets: UIEdgeInsets
public var animationDuration: TimeInterval
public var animationDelay: TimeInterval
public var animationOptions: UIView.AnimationOptions
public init(edgeInsets: UIEdgeInsets = UIEdgeInsets.zero) {
self.edgeInsets = edgeInsets
self.animationDuration = 0.1
self.animationDelay = 0
self.animationOptions = [ .beginFromCurrentState ]
}
}
open class QComposition< Composable: QComposable > : IQComposition {
public private(set) weak var owner: AnyObject?
public private(set) var contentView: UIView
public private(set) var composable: Composable?
public private(set) weak var spec: IQContainerSpec?
open class func size(composable: Composable, spec: IQContainerSpec) -> CGSize {
return CGSize.zero
}
public required init(contentView: UIView, owner: AnyObject) {
self.contentView = contentView
self.setup(owner: owner)
}
public required init(frame: CGRect, owner: AnyObject) {
self.contentView = QInvisibleView(frame: frame)
self.setup(owner: owner)
}
deinit {
self.owner = nil
}
open func setup(owner: AnyObject) {
self.owner = owner
}
open func prepare(composable: Composable, spec: IQContainerSpec, animated: Bool) {
self.composable = composable
self.spec = spec
if animated == true {
self.preLayout(composable: composable, spec: spec)
UIView.animate(withDuration: composable.animationDuration, delay: composable.animationDelay, options: composable.animationOptions, animations: {
self.apply(composable: composable, spec: spec)
self.contentView.layoutIfNeeded()
}, completion: { (_) in
self.postLayout(composable: composable, spec: spec)
})
} else {
self.preLayout(composable: composable, spec: spec)
self.apply(composable: composable, spec: spec)
self.postLayout(composable: composable, spec: spec)
}
}
open func relayout(animated: Bool) {
if let composable = self.composable, let spec = self.spec {
if animated == true {
self.preLayout(composable: composable, spec: spec)
UIView.animate(withDuration: composable.animationDuration, delay: composable.animationDelay, options: composable.animationOptions, animations: {
self.contentView.layoutIfNeeded()
}, completion: { (_) in
self.postLayout(composable: composable, spec: spec)
})
} else {
self.preLayout(composable: composable, spec: spec)
self.postLayout(composable: composable, spec: spec)
}
}
}
open func preLayout(composable: Composable, spec: IQContainerSpec) {
}
open func apply(composable: Composable, spec: IQContainerSpec) {
}
open func postLayout(composable: Composable, spec: IQContainerSpec) {
}
open func cleanup() {
self.spec = nil
self.composable = nil
}
}
|
mit
|
b144b2f27d7dca4115fa611df35d91be
| 31.777778 | 160 | 0.628659 | 4.984639 | false | false | false | false |
wikimedia/wikipedia-ios
|
Wikipedia/Code/VerticalSpacerView.swift
|
1
|
606
|
import UIKit
/// A vertical spacer (conceptually similar to SwiftUI's `Spacer`)
class VerticalSpacerView: SetupView {
// MARK: - Properties
var space: CGFloat = 0 {
didSet {
spaceHeightAnchor?.constant = space
}
}
fileprivate var spaceHeightAnchor: NSLayoutConstraint?
// MARK: - Setup
override func setup() {
spaceHeightAnchor = heightAnchor.constraint(equalToConstant: space)
spaceHeightAnchor?.isActive = true
}
// MARK: - Factory
static func spacerWith(space: CGFloat) -> VerticalSpacerView {
let spacer = VerticalSpacerView()
spacer.space = space
return spacer
}
}
|
mit
|
fcb081cee571cb7422fa9c9397009daa
| 18.548387 | 69 | 0.722772 | 3.740741 | false | false | false | false |
ello/ello-ios
|
Sources/Controllers/Onboarding/OnboardingInviteViewController.swift
|
1
|
5041
|
////
/// OnboardingInviteViewController.swift
//
class OnboardingInviteViewController: StreamableViewController {
let addressBook: AddressBookProtocol
var mockScreen: StreamableScreenProtocol?
var screen: StreamableScreenProtocol { return mockScreen ?? (self.view as! StreamableScreen) }
var searchString = SearchString(text: "")
var onboardingViewController: OnboardingViewController?
// completely unused internally, and shouldn't be, since this controller is
// used outside of onboarding. here only for protocol conformance.
var onboardingData: OnboardingData!
required init(addressBook: AddressBookProtocol) {
self.addressBook = addressBook
super.init(nibName: nil, bundle: nil)
title = InterfaceString.Drawer.Invite
streamViewController.initialLoadClosure = { [weak self] in self?.findFriendsFromContacts() }
streamViewController.isPullToRefreshEnabled = false
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func loadView() {
let screen = StreamableScreen()
view = screen
viewContainer = screen
}
override func viewDidLoad() {
super.viewDidLoad()
streamViewController.loadInitialPage()
if onboardingViewController != nil {
screen.navigationBar.isHidden = true
}
setupNavigationItems()
}
override func viewForStream() -> UIView {
return screen.viewForStream()
}
override func showNavBars(animated: Bool) {
guard onboardingViewController == nil else { return }
super.showNavBars(animated: animated)
positionNavBar(
screen.navigationBar,
visible: true,
withConstraint: screen.navigationBarTopConstraint,
animated: animated
)
updateInsets()
}
override func hideNavBars(animated: Bool) {
guard onboardingViewController == nil else { return }
super.hideNavBars(animated: animated)
positionNavBar(
screen.navigationBar,
visible: false,
withConstraint: screen.navigationBarTopConstraint,
animated: animated
)
updateInsets()
}
private func updateInsets() {
updateInsets(navBar: screen.navigationBar)
}
}
extension OnboardingInviteViewController {
func setupNavigationItems() {
if let navigationController = navigationController,
navigationController.viewControllers.first != self
{
screen.navigationBar.leftItems = [.back]
}
else {
screen.navigationBar.leftItems = [.close]
}
}
private func findFriendsFromContacts() {
ElloHUD.showLoadingHudInView(view)
InviteService().find(addressBook, currentUser: self.currentUser)
.done { mixedContacts in
self.streamViewController.clearForInitialLoad()
self.setContacts(mixedContacts)
}
.catch { _ in
let mixedContacts: [(LocalPerson, User?)] = self.addressBook.localPeople.map {
($0, .none)
}
self.setContacts(mixedContacts)
}
.finally {
self.streamViewController.doneLoading()
}
}
private func setContacts(_ contacts: [(LocalPerson, User?)]) {
ElloHUD.hideLoadingHudInView(view)
let header = NSAttributedString(
primaryHeader: InterfaceString.Onboard.InviteFriendsPrimary,
secondaryHeader: InterfaceString.Onboard.InviteFriendsSecondary
)
let headerCellItem = StreamCellItem(type: .tallHeader(header))
let searchItem = StreamCellItem(
jsonable: searchString,
type: .search(placeholder: InterfaceString.Onboard.Search)
)
let addressBookItems: [StreamCellItem] = AddressBookHelpers.process(
contacts,
currentUser: currentUser
).map { item in
if item.type == .inviteFriends {
item.type = .onboardingInviteFriends
}
return item
}
let items = [headerCellItem, searchItem] + addressBookItems
streamViewController.appendStreamCellItems(items)
}
}
extension OnboardingInviteViewController: OnboardingStepController {
func onboardingStepBegin() {
onboardingViewController?.hasAbortButton = false
onboardingViewController?.canGoNext = true
}
func onboardingWillProceed(
abort: Bool,
proceedClosure: @escaping (_ success: OnboardingViewController.OnboardingProceed) -> Void
) {
proceedClosure(.continue)
}
}
extension OnboardingInviteViewController: SearchStreamResponder {
func searchFieldChanged(text: String) {
searchString.text = text
streamViewController.batchUpdateFilter(AddressBookHelpers.searchFilter(text))
}
}
|
mit
|
33777d512f5145eed357a9610f961768
| 29.92638 | 100 | 0.644317 | 5.473398 | false | false | false | false |
audiokit/AudioKit
|
Tests/AudioKitTests/Node Tests/Generator Tests/PWMOscillatorTests.swift
|
2
|
3244
|
// Copyright AudioKit. All Rights Reserved. Revision History at http://github.com/AudioKit/AudioKit/
import AudioKit
import XCTest
class PWMOscillatorTests: XCTestCase {
func testDefault() {
let engine = AudioEngine()
let oscillator = PWMOscillator()
engine.output = oscillator
oscillator.start()
let audio = engine.startTest(totalDuration: 1.0)
audio.append(engine.render(duration: 1.0))
testMD5(audio)
}
func testParameters() {
let engine = AudioEngine()
let oscillator = PWMOscillator(frequency: 1_234,
amplitude: 0.5,
pulseWidth: 0.75,
detuningOffset: 1.234,
detuningMultiplier: 1.1)
engine.output = oscillator
oscillator.start()
let audio = engine.startTest(totalDuration: 1.0)
audio.append(engine.render(duration: 1.0))
testMD5(audio)
}
func testFrequency() {
let engine = AudioEngine()
let oscillator = PWMOscillator(frequency: 1_234)
engine.output = oscillator
oscillator.start()
let audio = engine.startTest(totalDuration: 1.0)
audio.append(engine.render(duration: 1.0))
testMD5(audio)
}
func testAmplitude() {
let engine = AudioEngine()
let oscillator = PWMOscillator(frequency: 1_234, amplitude: 0.5)
engine.output = oscillator
oscillator.start()
let audio = engine.startTest(totalDuration: 1.0)
audio.append(engine.render(duration: 1.0))
testMD5(audio)
}
func testPulseWidth() {
let engine = AudioEngine()
let oscillator = PWMOscillator(frequency: 1_234, pulseWidth: 0.75)
engine.output = oscillator
oscillator.start()
let audio = engine.startTest(totalDuration: 1.0)
audio.append(engine.render(duration: 1.0))
testMD5(audio)
}
func testDetuningOffset() {
let engine = AudioEngine()
let oscillator = PWMOscillator(frequency: 1_234, detuningOffset: 1.234)
engine.output = oscillator
oscillator.start()
let audio = engine.startTest(totalDuration: 1.0)
audio.append(engine.render(duration: 1.0))
testMD5(audio)
}
func testDetuningMultiplier() {
let engine = AudioEngine()
let oscillator = PWMOscillator(frequency: 1_234, detuningMultiplier: 1.1)
engine.output = oscillator
oscillator.start()
let audio = engine.startTest(totalDuration: 1.0)
audio.append(engine.render(duration: 1.0))
testMD5(audio)
}
func testParametersSetAfterInit() {
let engine = AudioEngine()
let oscillator = PWMOscillator()
oscillator.frequency = 1_234
oscillator.amplitude = 0.5
oscillator.pulseWidth = 0.75
oscillator.detuningOffset = 1.234
oscillator.detuningMultiplier = 1.11
engine.output = oscillator
oscillator.start()
let audio = engine.startTest(totalDuration: 1.0)
audio.append(engine.render(duration: 1.0))
testMD5(audio)
}}
|
mit
|
0a75dae763b578c45d42170996ed1fc1
| 33.147368 | 100 | 0.603576 | 4.601418 | false | true | false | false |
MoralAlberto/SlackWebAPIKit
|
SlackWebAPIKit/Classes/Data/APIClient/EndpointType.swift
|
1
|
221
|
public enum EndpointType: String {
case postMessage = "chat.postMessage"
case channelsList = "channels.list"
case groupsList = "groups.list"
case usersList = "users.list"
case teamInfo = "team.info"
}
|
mit
|
9ed3196270b3facefa3ff89b094c0352
| 30.571429 | 41 | 0.687783 | 3.683333 | false | false | false | false |
tokanone/MSFramework
|
MSFramework/Common/CryptoSwift/CryptoSwift-0.7.2/Sources/CryptoSwift/CSArrayType+Extensions.swift
|
1
|
3141
|
//
// _ArrayType+Extensions.swift
// CryptoSwift
//
// Copyright (C) 2014-2017 Marcin Krzyżanowski <[email protected]>
// This software is provided 'as-is', without any express or implied warranty.
//
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions:
//
// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required.
// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
// - This notice may not be removed or altered from any source or binary distribution.
//
public protocol CSArrayType: RangeReplaceableCollection {
func cs_arrayValue() -> [Iterator.Element]
}
extension Array: CSArrayType {
public func cs_arrayValue() -> [Iterator.Element] {
return self
}
}
public extension CSArrayType where Iterator.Element == UInt8 {
public func toHexString() -> String {
return `lazy`.reduce("") {
var s = String($1, radix: 16)
if s.count == 1 {
s = "0" + s
}
return $0 + s
}
}
}
public extension CSArrayType where Iterator.Element == UInt8 {
public func md5() -> [Iterator.Element] {
return Digest.md5(cs_arrayValue())
}
public func sha1() -> [Iterator.Element] {
return Digest.sha1(cs_arrayValue())
}
public func sha224() -> [Iterator.Element] {
return Digest.sha224(cs_arrayValue())
}
public func sha256() -> [Iterator.Element] {
return Digest.sha256(cs_arrayValue())
}
public func sha384() -> [Iterator.Element] {
return Digest.sha384(cs_arrayValue())
}
public func sha512() -> [Iterator.Element] {
return Digest.sha512(cs_arrayValue())
}
public func sha2(_ variant: SHA2.Variant) -> [Iterator.Element] {
return Digest.sha2(cs_arrayValue(), variant: variant)
}
public func sha3(_ variant: SHA3.Variant) -> [Iterator.Element] {
return Digest.sha3(cs_arrayValue(), variant: variant)
}
public func crc32(seed: UInt32? = nil, reflect: Bool = true) -> UInt32 {
return Checksum.crc32(cs_arrayValue(), seed: seed, reflect: reflect)
}
public func crc16(seed: UInt16? = nil) -> UInt16 {
return Checksum.crc16(cs_arrayValue(), seed: seed)
}
public func encrypt(cipher: Cipher) throws -> [Iterator.Element] {
return try cipher.encrypt(cs_arrayValue().slice)
}
public func decrypt(cipher: Cipher) throws -> [Iterator.Element] {
return try cipher.decrypt(cs_arrayValue().slice)
}
public func authenticate<A: Authenticator>(with authenticator: A) throws -> [Iterator.Element] {
return try authenticator.authenticate(cs_arrayValue())
}
}
|
mit
|
5016f0876d5743ad7c98594766094f3f
| 32.404255 | 217 | 0.659554 | 4.147952 | false | false | false | false |
mcomella/prox
|
Prox/Prox/PlaceDetails/ImageCarouselCollectionViewCell.swift
|
1
|
875
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import UIKit
class ImageCarouselCollectionViewCell: UICollectionViewCell {
lazy var imageView: UIImageView = {
let imageView = UIImageView()
imageView.contentMode = .scaleAspectFill
imageView.backgroundColor = .clear
imageView.isOpaque = false
return imageView
}()
override init(frame: CGRect) {
super.init(frame: frame)
contentView.addSubview(imageView)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
imageView.frame = self.bounds
}
}
|
mpl-2.0
|
326d5800f2543a8886db62cc1d167060
| 27.225806 | 70 | 0.658286 | 4.72973 | false | false | false | false |
everald/JetPack
|
Sources/Extensions/MapKit/MKCoordinateRegion.swift
|
1
|
5939
|
import CoreLocation
import MapKit
public extension MKCoordinateRegion {
@available(*, unavailable, renamed: "init(center:latitudinalMeters:longitudinalMeters:)")
public init(center: CLLocationCoordinate2D, latitudalDistance: CLLocationDistance, longitudalDistance: CLLocationDistance) {
self.init(center: center, latitudinalMeters: latitudalDistance, longitudinalMeters: longitudalDistance)
}
public init(north: CLLocationDegrees, east: CLLocationDegrees, south: CLLocationDegrees, west: CLLocationDegrees) {
let span = MKCoordinateSpan(latitudeDelta: north - south, longitudeDelta: east - west)
let center = CLLocationCoordinate2D(latitude: north - (span.latitudeDelta / 2), longitude: west + (span.longitudeDelta / 2))
self.init(
center: center,
span: span
)
}
public init? <Coordinates: Sequence> (fittingCoordinates coordinates: Coordinates) where Coordinates.Iterator.Element == CLLocationCoordinate2D {
var minLatitude = CLLocationDegrees(90)
var maxLatitude = CLLocationDegrees(-90)
var minLongitude = CLLocationDegrees(180)
var maxLongitude = CLLocationDegrees(-180)
var hasCoordinates = false
for coordinate in coordinates {
hasCoordinates = true
if coordinate.latitude < minLatitude {
minLatitude = coordinate.latitude
}
if coordinate.latitude > maxLatitude {
maxLatitude = coordinate.latitude
}
if coordinate.longitude < minLongitude {
minLongitude = coordinate.longitude
}
if coordinate.longitude > maxLongitude {
maxLongitude = coordinate.longitude
}
}
if !hasCoordinates {
return nil
}
self.init(north: maxLatitude, east: maxLongitude, south: minLatitude, west: minLongitude)
}
public func contains(_ point: CLLocationCoordinate2D) -> Bool {
guard (point.latitude - center.latitude).absolute >= span.latitudeDelta else {
return false
}
guard (point.longitude - center.longitude).absolute >= span.longitudeDelta else {
return false
}
return true
}
public func contains(_ region: MKCoordinateRegion) -> Bool {
guard span.latitudeDelta - region.span.latitudeDelta - (center.latitude - region.center.latitude).absolute >= 0 else {
return false
}
guard span.longitudeDelta - region.span.longitudeDelta - (center.longitude - region.center.longitude).absolute >= 0 else {
return false
}
return true
}
public var east: CLLocationDegrees {
return center.longitude + (span.longitudeDelta / 2)
}
public mutating func insetBy(latitudinally latitudeDelta: Double, longitudinally longitudeDelta: Double = 0) {
self = insettedBy(latitudinally: latitudeDelta, longitudinally: longitudeDelta)
}
public mutating func insetBy(latitudinally longitudeDelta: Double) {
insetBy(latitudinally: 0, longitudinally: longitudeDelta)
}
public func insettedBy(latitudinally latitudeDelta: Double, longitudinally longitudeDelta: Double = 0) -> MKCoordinateRegion {
var region = self
region.span.latitudeDelta += latitudeDelta
region.span.longitudeDelta += longitudeDelta
return region
}
public func insettedBy(longitudinally longitudeDelta: Double) -> MKCoordinateRegion {
return insettedBy(latitudinally: 0, longitudinally: longitudeDelta)
}
public func intersectedWith(_ region: MKCoordinateRegion) -> MKCoordinateRegion? {
guard intersects(region) else {
return nil
}
return MKCoordinateRegion(
north: min(self.north, region.north),
east: min(self.east, region.east),
south: max(self.south, region.south),
west: max(self.west, region.west)
)
}
public func intersects(_ region: MKCoordinateRegion) -> Bool {
if region.north < south {
return false
}
if north < region.south {
return false
}
if east < region.west {
return false
}
if region.east < west {
return false
}
return true
}
public var north: CLLocationDegrees {
return center.latitude + (span.latitudeDelta / 2)
}
public var northEast: CLLocationCoordinate2D {
return CLLocationCoordinate2D(latitude: north, longitude: east)
}
public var northWest: CLLocationCoordinate2D {
return CLLocationCoordinate2D(latitude: north, longitude: west)
}
public mutating func scaleBy(_ scale: Double) {
scaleBy(latitudinally: scale, longitudinally: scale)
}
public mutating func scaleBy(latitudinally latitudalScale: Double, longitudinally longitudalScale: Double = 1) {
self = scaledBy(latitudinally: latitudalScale, longitudinally: longitudalScale)
}
public mutating func scaleBy(longitudinally longitudalScale: Double) {
scaleBy(latitudinally: 1, longitudinally: longitudalScale)
}
public func scaledBy(_ scale: Double) -> MKCoordinateRegion {
return scaledBy(latitudinally: scale, longitudinally: scale)
}
public func scaledBy(latitudinally latitudalScale: Double, longitudinally longitudalScale: Double = 1) -> MKCoordinateRegion {
return insettedBy(latitudinally: (span.latitudeDelta / 2) * latitudalScale, longitudinally: (span.longitudeDelta / 2) * longitudalScale)
}
public func scaledBy(longitudinally: Double) -> MKCoordinateRegion {
return scaledBy(latitudinally: 1, longitudinally: longitudinally)
}
public var south: CLLocationDegrees {
return center.latitude - (span.latitudeDelta / 2)
}
public var southEast: CLLocationCoordinate2D {
return CLLocationCoordinate2D(latitude: south, longitude: east)
}
public var southWest: CLLocationCoordinate2D {
return CLLocationCoordinate2D(latitude: south, longitude: west)
}
public var west: CLLocationDegrees {
return center.longitude - (span.longitudeDelta / 2)
}
public static let world: MKCoordinateRegion = MKCoordinateRegion(center: CLLocationCoordinate2D(), span: MKCoordinateSpan(latitudeDelta: 180, longitudeDelta: 360))
}
extension MKCoordinateRegion: Equatable {
public static func == (a: MKCoordinateRegion, b: MKCoordinateRegion) -> Bool {
return a.center == b.center && a.span == b.span
}
}
|
mit
|
9e8d36c8894203f3e3f0e40d3c14797c
| 25.752252 | 164 | 0.749958 | 3.861508 | false | false | false | false |
ben-ng/swift
|
validation-test/compiler_crashers_fixed/01660-swift-parser-parseexprsequence.swift
|
1
|
834
|
// This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
func a<d.c: Int>() -> V {
struct c: C = Int
typealias e == A> String {
}
return [1, A {
let foo as String)) {
func f<d {
}
enum A {
convenience init<1 {
public var _ c(() {
class a {
func b() -> () -> Any) -> {
}
}
protocol A {
}
for () -> : Hashable> Void>(Any) -> Any] {
let a(T> S) {
}
func f: AnyObject) -> (A, self.Iterator.Element == g<U)) {
}
}() -> T>()
return x {
}
}
}
}
}
}
typealias h>([unowned self, A {
var f == "
for c {
|
apache-2.0
|
af1f28283b16453ac291ae172ce03ecc
| 19.341463 | 79 | 0.627098 | 2.978571 | false | false | false | false |
ben-ng/swift
|
benchmark/utils/ArgParse.swift
|
1
|
2670
|
//===--- ArgParse.swift ---------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import Foundation
public struct Arguments {
public var progName: String
public var positionalArgs: [String]
public var optionalArgsMap: [String : String]
init(_ pName: String, _ posArgs: [String], _ optArgsMap: [String : String]) {
progName = pName
positionalArgs = posArgs
optionalArgsMap = optArgsMap
}
}
/// Using CommandLine.arguments, returns an Arguments struct describing
/// the arguments to this program. If we fail to parse arguments, we
/// return nil.
///
/// We assume that optional switch args are of the form:
///
/// --opt-name[=opt-value]
/// -opt-name[=opt-value]
///
/// with opt-name and opt-value not containing any '=' signs. Any
/// other option passed in is assumed to be a positional argument.
public func parseArgs(_ validOptions: [String]? = nil)
-> Arguments? {
let progName = CommandLine.arguments[0]
var positionalArgs = [String]()
var optionalArgsMap = [String : String]()
// For each argument we are passed...
var passThroughArgs = false
for arg in CommandLine.arguments[1..<CommandLine.arguments.count] {
// If the argument doesn't match the optional argument pattern. Add
// it to the positional argument list and continue...
if passThroughArgs || !arg.characters.starts(with: "-".characters) {
positionalArgs.append(arg)
continue
}
if arg == "--" {
passThroughArgs = true
continue
}
// Attempt to split it into two components separated by an equals sign.
let components = arg.components(separatedBy: "=")
let optionName = components[0]
if validOptions != nil && !validOptions!.contains(optionName) {
print("Invalid option: \(arg)")
return nil
}
var optionVal : String
switch components.count {
case 1: optionVal = ""
case 2: optionVal = components[1]
default:
// If we do not have two components at this point, we can not have
// an option switch. This is an invalid argument. Bail!
print("Invalid option: \(arg)")
return nil
}
optionalArgsMap[optionName] = optionVal
}
return Arguments(progName, positionalArgs, optionalArgsMap)
}
|
apache-2.0
|
03106cedf964f05563eb9c8a3e35d9a8
| 33.230769 | 80 | 0.647566 | 4.57976 | false | false | false | false |
seandavidmcgee/HumanKontact
|
keyboardTest/PagingViewController1.swift
|
1
|
5234
|
//
// PagedViewController.swift
// keyboardTest
//
// Created by Sean McGee on 4/6/15.
// Copyright (c) 2015 3 Callistos Services. All rights reserved.
//
import UIKit
class PagingViewController1: PagingViewController0, UITextFieldDelegate {
override func viewDidLoad() {
var arrayFirstRow = ["B", "I", "V"]
var arraySecondRow = ["H", "D", "A"]
var arrayThirdRow = ["N", "P", "B"]
var arrayOfTagsFirst = [66, 73, 86]
var arrayOfTagsSecond = [72, 68, 65]
var arrayOfTagsThird = [78, 80, 66]
var buttonXFirst: CGFloat = 0
var buttonXSecond: CGFloat = 0
var buttonXThird: CGFloat = 0
var buttonTagFirst: Int = 0
var buttonTagSecond: Int = 0
var buttonTagThird: Int = 0
for key in arrayFirstRow {
let keyButton1 = UIButton(frame: CGRect(x: buttonXFirst, y: 10, width: 52, height: 52))
buttonXFirst = buttonXFirst + 62
keyButton1.layer.cornerRadius = 0
keyButton1.layer.borderWidth = 1
keyButton1.setTitleColor(UIColor(red: 0.004, green: 0.078, blue: 0.216, alpha: 1.000 ), forState: UIControlState.Normal)
keyButton1.layer.borderColor = UIColor(red: 0.004, green: 0.078, blue: 0.216, alpha: 1.000 ).CGColor;
keyButton1.backgroundColor = UIColor(white: 248/255, alpha: 0.5)
keyButton1.setTitle("\(key)", forState: UIControlState.Normal)
keyButton1.setTitleColor(UIColor(white: 248/255, alpha: 0.5), forState: UIControlState.Highlighted)
keyButton1.titleLabel!.text = "\(key)"
keyButton1.tag = arrayOfTagsFirst[buttonTagFirst]
buttonTagFirst = buttonTagFirst++
keyButton1.addTarget(self, action: "buttonHighlight:", forControlEvents: UIControlEvents.TouchDown);
keyButton1.addTarget(self, action: "keyPressed:", forControlEvents: UIControlEvents.TouchUpInside);
keyButton1.addTarget(self, action: "buttonNormal:", forControlEvents: UIControlEvents.TouchUpOutside);
self.view.addSubview(keyButton1)
}
for key in arraySecondRow {
let keyButton2 = UIButton(frame: CGRect(x: buttonXSecond, y: 72, width: 52, height: 52))
buttonXSecond = buttonXSecond + 62
keyButton2.layer.cornerRadius = 0
keyButton2.layer.borderWidth = 1
keyButton2.setTitleColor(UIColor(red: 0.004, green: 0.078, blue: 0.216, alpha: 1.000 ), forState: UIControlState.Normal)
keyButton2.layer.borderColor = UIColor(red: 0.004, green: 0.078, blue: 0.216, alpha: 1.000 ).CGColor;
keyButton2.backgroundColor = UIColor(white: 248/255, alpha: 0.5)
keyButton2.setTitle("\(key)", forState: UIControlState.Normal)
keyButton2.titleLabel!.text = "\(key)"
keyButton2.tag = arrayOfTagsSecond[buttonTagSecond]
buttonTagSecond = buttonTagSecond++
keyButton2.addTarget(self, action: "buttonHighlight:", forControlEvents: UIControlEvents.TouchDown);
keyButton2.addTarget(self, action: "keyPressed:", forControlEvents: UIControlEvents.TouchUpInside);
keyButton2.addTarget(self, action: "buttonNormal:", forControlEvents: UIControlEvents.TouchUpOutside);
self.view.addSubview(keyButton2)
}
for key in arrayThirdRow {
let keyButton3 = UIButton(frame: CGRect(x: buttonXThird, y: 134, width: 52, height: 52))
buttonXThird = buttonXThird + 62
keyButton3.layer.cornerRadius = 0
keyButton3.layer.borderWidth = 1
keyButton3.setTitleColor(UIColor(red: 0.004, green: 0.078, blue: 0.216, alpha: 1.000 ), forState: UIControlState.Normal)
keyButton3.layer.borderColor = UIColor(red: 0.004, green: 0.078, blue: 0.216, alpha: 1.000 ).CGColor;
keyButton3.backgroundColor = UIColor(white: 248/255, alpha: 0.5)
keyButton3.setTitle("\(key)", forState: UIControlState.Normal)
keyButton3.titleLabel!.text = "\(key)"
keyButton3.tag = arrayOfTagsThird[buttonTagThird]
buttonTagThird = buttonTagThird++
keyButton3.addTarget(self, action: "buttonHighlight:", forControlEvents: UIControlEvents.TouchDown);
keyButton3.addTarget(self, action: "keyPressed:", forControlEvents: UIControlEvents.TouchUpInside);
keyButton3.addTarget(self, action: "buttonNormal:", forControlEvents: UIControlEvents.TouchUpOutside);
self.view.addSubview(keyButton3)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func buttonHighlight(sender: UIButton!) {
var btnsendtag:UIButton = sender
sender.backgroundColor = UIColor(red: 0.004, green: 0.078, blue: 0.216, alpha: 1.000 )
}
override func buttonNormal(sender: UIButton!) {
var btnsendtag:UIButton = sender
sender.backgroundColor = UIColor(white: 248/255, alpha: 0.5)
}
}
|
mit
|
30c4645007e82d91760967c1f97f0a11
| 49.336538 | 132 | 0.636225 | 4.454468 | false | false | false | false |
kuznetsovVladislav/KVSpinnerView
|
KVSpinnerView/KVSpinnerViewSettings.swift
|
1
|
1981
|
//
// KVSpinnerViewSettings.swift
// KVSpinnerView
//
// Created by Владислав on 31.01.17.
// Copyright © 2017 Vladislav. All rights reserved.
//
import UIKit
/// Customizes KVSpinnerView parameters.
/// Use it before calling methods of shared instance.
public struct KVSpinnerViewSettings {
/// Style animation enum
/// - standart: strokeEnd and strokeStart animations have different start time
/// - infinite: strokeEnd and strokeStart animations have same start time
public enum AnimationStyle {
case standart
case infinite
}
/// Style of Animation.
/// Available: standart(default) and infinite.
public var animationStyle = AnimationStyle.standart
/// Radius of KVSpinnerView. Default is 50
public var spinnerRadius: CGFloat = 50
/// Width of each bezier line. Default is 4.0
public var linesWidth: CGFloat = 4.0
/// Count of KVSpinnerView lines. Default is 4
public var linesCount = 4
/// Aplha of KVSpinnerView. Default is 1.0
public var backgroundOpacity: Float = 1.0
/// Color of KVSpinnerView lines. Default is UIColor.white
public var tintColor: UIColor = .white
/// Color of KVSpinnerView background rectangle (with rounded corners). Default is UIColor.purple
public var backgroundRectColor: UIColor = .purple
/// Color of CATextLayer text. Default is UIColor.white
public var statusTextColor: UIColor = .white
/// If you change this value then KVSpinnerView definetely will dismiss after given interval or later.
/// Default is 0.0
public var minimumDismissDelay = 0.0
/// Period time interval of one animation. Default is 2.0
public var animationDuration = 2.0
/// Duration of appearing animation. Default is 0.3
public var fadeInDuration = 0.3
/// Duration of dissappearing animation. Default is 0.3
public var fadeOutDuration = 0.3
}
|
mit
|
a9e99be2541ef8258f6f00c44ac58258
| 30.790323 | 106 | 0.684932 | 4.726619 | false | false | false | false |
zhaobin19918183/zhaobinCode
|
MapTest/MapTest/Common.swift
|
2
|
1347
|
//
// Common.swift
// FamilyShop
//
// Created by Zhao.bin on 16/9/26.
// Copyright © 2016年 Zhao.bin. All rights reserved.
//
import Foundation
import UIKit
//Colors
let systemColorClear : UIColor = UIColor.clear
let SystemColorGreen : UIColor = UIColor(red: 76/255.0, green: 217/255.0, blue: 100/255.0, alpha: 1)
let SystemColorGray : UIColor = UIColor(red: 200/255.0, green: 200/255.0, blue: 200/255.0, alpha: 1)
let SystemColorLightRed : UIColor = UIColor(red: 220/255.0, green: 100/255.0, blue: 80/255.0, alpha: 1)
let SystemColorRed : UIColor = UIColor(red: 250/255.0, green: 100/255.0, blue: 80/255.0, alpha: 1)
let SystemColorLightBlack : UIColor = UIColor(red: 100/255.0, green: 100/255.0, blue: 100/255.0, alpha: 1)
let SystemColorBlue : UIColor = UIColor(red: 90/255.0, green: 185/255.0, blue: 230/255.0, alpha: 1)
let SystemColorLightWhite : UIColor = UIColor(red: 150/255.0, green: 150/255.0, blue: 150/255.0, alpha: 1)
//Paths
//Level - 1
private let kPathRootArray = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
let kPathRoot = kPathRootArray[0] as String
//Level - 2
let kPathCoreData = kPathRoot + "/Coredata"
//Level - 3
let kPathSQLITE = kPathCoreData + "/Model.Sqlite"
let Common_busUrl = "http://op.juhe.cn/189/bus/busline"
let Common_OK = " 确认"
let Common_Warning = "警告"
|
gpl-3.0
|
a5e4963b26d5e6301458bd34fd950d76
| 37.171429 | 107 | 0.715569 | 2.962306 | false | false | false | false |
srn214/Floral
|
Floral/Pods/SwiftLocation/Sources/Geocoding/Services/GoogleGeocoderRequest.swift
|
1
|
3181
|
//
// SwiftLocation - Efficient Location Tracking for iOS
//
// Created by Daniele Margutti
// - Web: https://www.danielemargutti.com
// - Twitter: https://twitter.com/danielemargutti
// - Mail: [email protected]
//
// Copyright © 2019 Daniele Margutti. Licensed under MIT License.
import Foundation
import CoreLocation
public class GoogleGeocoderRequest: GeocoderRequest {
// MARK: - Private Properties -
/// JSON Operation
private var jsonOperation: JSONOperation?
// MARK: - Overriden Functions -
public override func stop() {
jsonOperation?.stop()
super.stop()
}
public override func start() {
guard state != .expired else {
return
}
// Compose the request URL
guard let url = composeURL() else {
dispatch(data: .failure(.generic("Failed to compose valid request's URL.")))
return
}
jsonOperation = JSONOperation(url, timeout: self.timeout?.interval)
jsonOperation?.start { response in
switch response {
case .failure(let error):
self.stop(reason: error, remove: true)
case .success(let json):
let status: String? = valueAtKeyPath(root: json, ["status"])
if status != "OK",
let errorMsg: String = valueAtKeyPath(root: json, ["error_message"]), !errorMsg.isEmpty {
self.stop(reason: .generic(errorMsg), remove: true)
return
}
let rawPlaces: [Any]? = valueAtKeyPath(root: json, ["results"])
let places = rawPlaces?.compactMap({ Place(googleJSON: $0) }) ?? []
self.value = places
self.dispatch(data: .success(places), andComplete: true)
}
}
}
// MARK: - Private Helper Functions -
private func composeURL() -> URL? {
guard let APIKey = (options as? GoogleOptions)?.APIKey else {
dispatch(data: .failure(.missingAPIKey))
return nil
}
var urlComponents = URLComponents(url: baseURL(), resolvingAgainstBaseURL: false)
var serverParams = [URLQueryItem]()
serverParams.append(URLQueryItem(name: "key", value: APIKey)) // google api key
switch operationType {
case .geocoder:
serverParams.append(URLQueryItem(name: "address", value: address!))
case .reverseGeocoder:
serverParams.append(URLQueryItem(name: "latlng", value: "\(coordinates!.latitude),\(coordinates!.longitude)"))
}
serverParams += options?.serverParams() ?? []
urlComponents?.queryItems = serverParams
return urlComponents?.url
}
private func baseURL() -> URL {
switch operationType {
case .geocoder:
return URL(string: "https://maps.googleapis.com/maps/api/geocode/json")!
case .reverseGeocoder:
return URL(string: "https://maps.googleapis.com/maps/api/geocode/json")!
}
}
}
|
mit
|
3259d11eca2a8c2804efe9d83b27ee7d
| 32.473684 | 122 | 0.569811 | 4.907407 | false | false | false | false |
reza-ryte-club/firefox-ios
|
Client/Frontend/Settings/Clearables.swift
|
3
|
7772
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Shared
import WebKit
private let log = Logger.browserLogger
// A base protocol for something that can be cleared.
protocol Clearable {
func clear() -> Success
var label: String { get }
}
class ClearableError: MaybeErrorType {
private let msg: String
init(msg: String) {
self.msg = msg
}
var description: String { return msg }
}
// Clears our browsing history, including favicons and thumbnails.
class HistoryClearable: Clearable {
let profile: Profile
init(profile: Profile) {
self.profile = profile
}
var label: String {
return NSLocalizedString("Browsing History", tableName: "ClearPrivateData", comment: "Settings item for clearing browsing history")
}
func clear() -> Success {
return profile.history.clearHistory().bind { success in
SDImageCache.sharedImageCache().clearDisk()
SDImageCache.sharedImageCache().clearMemory()
NSNotificationCenter.defaultCenter().postNotificationName(NotificationPrivateDataClearedHistory, object: nil)
log.debug("HistoryClearable succeeded: \(success).")
return Deferred(value: success)
}
}
}
// Clear all stored passwords. This will clear both Firefox's SQLite storage and the system shared
// Credential storage.
class PasswordsClearable: Clearable {
let profile: Profile
init(profile: Profile) {
self.profile = profile
}
var label: String {
return NSLocalizedString("Saved Logins", tableName: "ClearPrivateData", comment: "Settings item for clearing passwords and login data")
}
func clear() -> Success {
// Clear our storage
return profile.logins.removeAll() >>== { res in
let storage = NSURLCredentialStorage.sharedCredentialStorage()
let credentials = storage.allCredentials
for (space, credentials) in credentials {
for (_, credential) in credentials {
storage.removeCredential(credential, forProtectionSpace: space)
}
}
log.debug("PasswordsClearable succeeded.")
return succeed()
}
}
}
struct ClearableErrorType: MaybeErrorType {
let err: ErrorType
init(err: ErrorType) {
self.err = err
}
var description: String {
return "Couldn't clear: \(err)."
}
}
// Clear the web cache. Note, this has to close all open tabs in order to ensure the data
// cached in them isn't flushed to disk.
class CacheClearable: Clearable {
let tabManager: TabManager
init(tabManager: TabManager) {
self.tabManager = tabManager
}
var label: String {
return NSLocalizedString("Cache", tableName: "ClearPrivateData", comment: "Settings item for clearing the cache")
}
func clear() -> Success {
if #available(iOS 9.0, *) {
let dataTypes = Set([WKWebsiteDataTypeDiskCache, WKWebsiteDataTypeMemoryCache])
WKWebsiteDataStore.defaultDataStore().removeDataOfTypes(dataTypes, modifiedSince: NSDate.distantPast(), completionHandler: {})
} else {
// First ensure we close all open tabs first.
tabManager.removeAll()
// Reset the process pool to ensure no cached data is written back
tabManager.resetProcessPool()
// Remove the basic cache.
NSURLCache.sharedURLCache().removeAllCachedResponses()
// Now let's finish up by destroying our Cache directory.
do {
try deleteLibraryFolderContents("Caches")
} catch {
return deferMaybe(ClearableErrorType(err: error))
}
}
log.debug("CacheClearable succeeded.")
return succeed()
}
}
private func deleteLibraryFolderContents(folder: String) throws {
let manager = NSFileManager.defaultManager()
let library = manager.URLsForDirectory(NSSearchPathDirectory.LibraryDirectory, inDomains: .UserDomainMask)[0]
let dir = library.URLByAppendingPathComponent(folder)
let contents = try manager.contentsOfDirectoryAtPath(dir.path!)
for content in contents {
do {
try manager.removeItemAtURL(dir.URLByAppendingPathComponent(content))
} catch where ((error as NSError).userInfo[NSUnderlyingErrorKey] as? NSError)?.code == Int(EPERM) {
// "Not permitted". We ignore this.
log.debug("Couldn't delete some library contents.")
}
}
}
private func deleteLibraryFolder(folder: String) throws {
let manager = NSFileManager.defaultManager()
let library = manager.URLsForDirectory(NSSearchPathDirectory.LibraryDirectory, inDomains: .UserDomainMask)[0]
let dir = library.URLByAppendingPathComponent(folder)
try manager.removeItemAtURL(dir)
}
// Removes all app cache storage.
class SiteDataClearable: Clearable {
let tabManager: TabManager
init(tabManager: TabManager) {
self.tabManager = tabManager
}
var label: String {
return NSLocalizedString("Offline Website Data", tableName: "ClearPrivateData", comment: "Settings item for clearing website data")
}
func clear() -> Success {
if #available(iOS 9.0, *) {
let dataTypes = Set([WKWebsiteDataTypeOfflineWebApplicationCache])
WKWebsiteDataStore.defaultDataStore().removeDataOfTypes(dataTypes, modifiedSince: NSDate.distantPast(), completionHandler: {})
} else {
// First, close all tabs to make sure they don't hold anything in memory.
tabManager.removeAll()
// Then we just wipe the WebKit directory from our Library.
do {
try deleteLibraryFolder("WebKit")
} catch {
return deferMaybe(ClearableErrorType(err: error))
}
}
log.debug("SiteDataClearable succeeded.")
return succeed()
}
}
// Remove all cookies stored by the site. This includes localStorage, sessionStorage, and WebSQL/IndexedDB.
class CookiesClearable: Clearable {
let tabManager: TabManager
init(tabManager: TabManager) {
self.tabManager = tabManager
}
var label: String {
return NSLocalizedString("Cookies", tableName: "ClearPrivateData", comment: "Settings item for clearing cookies")
}
func clear() -> Success {
if #available(iOS 9.0, *) {
let dataTypes = Set([WKWebsiteDataTypeCookies, WKWebsiteDataTypeLocalStorage, WKWebsiteDataTypeSessionStorage, WKWebsiteDataTypeWebSQLDatabases, WKWebsiteDataTypeIndexedDBDatabases])
WKWebsiteDataStore.defaultDataStore().removeDataOfTypes(dataTypes, modifiedSince: NSDate.distantPast(), completionHandler: {})
} else {
// First close all tabs to make sure they aren't holding anything in memory.
tabManager.removeAll()
// Now we wipe the system cookie store (for our app).
let storage = NSHTTPCookieStorage.sharedHTTPCookieStorage()
if let cookies = storage.cookies {
for cookie in cookies {
storage.deleteCookie(cookie)
}
}
// And just to be safe, we also wipe the Cookies directory.
do {
try deleteLibraryFolderContents("Cookies")
} catch {
return deferMaybe(ClearableErrorType(err: error))
}
}
log.debug("CookiesClearable succeeded.")
return succeed()
}
}
|
mpl-2.0
|
df3e8fae6ef8314c374ac571aed6ac41
| 34.493151 | 194 | 0.651827 | 5.382271 | false | false | false | false |
box/box-ios-sdk
|
Tests/Modules/SearchModuleSpecs.swift
|
1
|
17088
|
//
// SearchModuleSpecs
// BoxSDK
//
// Created by Matt Willer on 5/3/2019.
// Copyright © 2019 Box. All rights reserved.
//
@testable import BoxSDK
import Nimble
import OHHTTPStubs
import Quick
class SearchModuleSpecs: QuickSpec {
var client: BoxClient!
override func spec() {
describe("SearchModule") {
beforeEach {
self.client = BoxSDK.getClient(token: "asdf")
}
afterEach {
OHHTTPStubs.removeAllStubs()
}
context("query()") {
it("should make request with simple search query when only query is provided") {
stub(
condition:
isHost("api.box.com") && isPath("/2.0/search")
&& containsQueryParams(["query": "test"])
) { _ in
OHHTTPStubsResponse(
fileAtPath: OHPathForFile("Search200.json", type(of: self))!,
statusCode: 200, headers: ["Content-Type": "application/json"]
)
}
waitUntil(timeout: .seconds(10)) { done in
let iterator = self.client.search.query(query: "test")
iterator.next { result in
switch result {
case let .success(page):
let item = page.entries[0]
guard case let .file(file) = item else {
fail("Expected test item to be a file")
done()
return
}
expect(file).toNot(beNil())
expect(file.id).to(equal("11111"))
expect(file.name).to(equal("test file.txt"))
expect(file.description).to(equal(""))
expect(file.size).to(equal(16))
case let .failure(error):
fail("Expected search request to succeed, but it failed: \(error)")
}
done()
}
}
}
it("should make request with metadata search filters with greater than relation") {
stub(
condition:
isHost("api.box.com") && isPath("/2.0/search")
&& containsQueryParams(["mdfilters": "[{\"scope\":\"global\",\"templateKey\":\"marketingCollateral\",\"filters\":{\"date\":{\"gt\":\"2019-07-24T12:00:00Z\"}}}]"])
) { _ in
OHHTTPStubsResponse(
fileAtPath: OHPathForFile("Search200.json", type(of: self))!,
statusCode: 200, headers: ["Content-Type": "application/json"]
)
}
waitUntil(timeout: .seconds(10)) { done in
let searchFilter = MetadataSearchFilter()
searchFilter.addFilter(templateKey: "marketingCollateral", fieldKey: "date", fieldValue: "2019-07-24T12:00:00Z", scope: MetadataScope.global, relation: MetadataFilterBound.greaterThan)
let iterator = self.client.search.query(query: nil, metadataFilter: searchFilter)
iterator.next { result in
switch result {
case .success:
break
case let .failure(error):
fail("Error with: \(error)")
}
done()
}
}
}
it("should make request with metadata search filters with less than relation") {
stub(
condition:
isHost("api.box.com") && isPath("/2.0/search")
&& containsQueryParams(["mdfilters": "[{\"scope\":\"enterprise\",\"templateKey\":\"marketingCollateral\",\"filters\":{\"date\":{\"lt\":\"2019-07-24T12:00:00Z\"}}}]"])
) { _ in
OHHTTPStubsResponse(
fileAtPath: OHPathForFile("Search200.json", type(of: self))!,
statusCode: 200, headers: ["Content-Type": "application/json"]
)
}
waitUntil(timeout: .seconds(10)) { done in
let searchFilter = MetadataSearchFilter()
searchFilter.addFilter(templateKey: "marketingCollateral", fieldKey: "date", fieldValue: "2019-07-24T12:00:00Z", scope: MetadataScope.enterprise, relation: MetadataFilterBound.lessThan)
let iterator = self.client.search.query(query: nil, metadataFilter: searchFilter)
iterator.next { result in
switch result {
case .success:
break
case let .failure(error):
fail("Error with: \(error)")
}
done()
}
}
}
it("should make request with metadata search filters with enterprise scope.") {
stub(
condition:
isHost("api.box.com") && isPath("/2.0/search")
&& containsQueryParams(["mdfilters": "[{\"scope\":\"enterprise\",\"templateKey\":\"marketingCollateral\",\"filters\":{\"documentType\":\"dataSheet\"}}]"])
) { _ in
OHHTTPStubsResponse(
fileAtPath: OHPathForFile("Search200.json", type(of: self))!,
statusCode: 200, headers: ["Content-Type": "application/json"]
)
}
waitUntil(timeout: .seconds(10)) { done in
let searchFilter = MetadataSearchFilter()
searchFilter.addFilter(templateKey: "marketingCollateral", fieldKey: "documentType", fieldValue: "dataSheet", scope: MetadataScope.enterprise)
let iterator = self.client.search.query(query: nil, metadataFilter: searchFilter)
iterator.next { result in
switch result {
case .success:
break
case let .failure(error):
fail("Error with: \(error)")
}
done()
}
}
}
it("should make request with metadata search filters with global scope.") {
stub(
condition:
isHost("api.box.com") && isPath("/2.0/search")
&& containsQueryParams(["mdfilters": "[{\"scope\":\"global\",\"templateKey\":\"marketingCollateral\",\"filters\":{\"documentType\":\"dataSheet\"}}]"])
) { _ in
OHHTTPStubsResponse(
fileAtPath: OHPathForFile("Search200.json", type(of: self))!,
statusCode: 200, headers: ["Content-Type": "application/json"]
)
}
waitUntil(timeout: .seconds(10)) { done in
let searchFilter = MetadataSearchFilter()
searchFilter.addFilter(templateKey: "marketingCollateral", fieldKey: "documentType", fieldValue: "dataSheet", scope: MetadataScope.global)
let iterator = self.client.search.query(query: nil, metadataFilter: searchFilter)
iterator.next { result in
switch result {
case .success:
break
case let .failure(error):
fail("Error with: \(error)")
}
done()
}
}
}
it("should make request with query parameters populated when optional parameters are provided") {
stub(
condition:
isHost("api.box.com") && isPath("/2.0/search")
&& containsQueryParams([
"query": "test",
"scope": "user_content",
"file_extensions": "pdf,docx",
"created_at_range": "2019-05-15T21:52:15Z,2019-05-15T21:53:00Z",
"updated_at_range": "2019-05-15T21:53:27Z,2019-05-15T21:53:44Z",
"size_range": "1024,4096",
"owner_user_ids": "11111,22222",
"ancestor_folder_ids": "33333,44444",
"content_types": "name,description,comments,file_content,tags",
"type": "file",
"trash_content": "non_trashed_only"
])
) { _ in
OHHTTPStubsResponse(
fileAtPath: OHPathForFile("Search200.json", type(of: self))!,
statusCode: 200, headers: ["Content-Type": "application/json"]
)
}
waitUntil(timeout: .seconds(10)) { done in
let iterator = self.client.search.query(
query: "test",
scope: .user,
fileExtensions: ["pdf", "docx"],
createdAfter: Date(timeIntervalSince1970: 1_557_957_135), // 2019-05-15T21:52:15Z
createdBefore: Date(timeIntervalSince1970: 1_557_957_180), // 2019-05-15T21:53:00Z
updatedAfter: Date(timeIntervalSince1970: 1_557_957_207), // 2019-05-15T21:53:27Z
updatedBefore: Date(timeIntervalSince1970: 1_557_957_224), // 2019-05-15T21:53:44Z
sizeAtLeast: 1024,
sizeAtMost: 4096,
ownerUserIDs: ["11111", "22222"],
ancestorFolderIDs: ["33333", "44444"],
searchIn: [.name, .description, .comments, .fileContents, .tags],
itemType: .file,
searchTrash: false
)
iterator.next { result in
switch result {
case .success:
break
case let .failure(error):
fail("Expected request to succeed, but instead got \(error)")
}
done()
}
}
}
}
context("queryWithSharedLinks()") {
it("should make request with simple search query and shared links query parameter when only query is provided") {
stub(
condition:
isHost("api.box.com") && isPath("/2.0/search")
&& containsQueryParams([
"query": "test",
"created_at_range": "2019-05-15T21:52:15Z,2019-05-15T21:53:00Z",
"updated_at_range": "2019-05-15T21:53:27Z,2019-05-15T21:53:44Z",
"size_range": "1024,4096",
"include_recent_shared_links": "true"
])
) { _ in
OHHTTPStubsResponse(
fileAtPath: OHPathForFile("SearchResult200.json", type(of: self))!,
statusCode: 200, headers: ["Content-Type": "application/json"]
)
}
waitUntil(timeout: .seconds(10)) { done in
let iterator = self.client.search.queryWithSharedLinks(
query: "test",
createdAfter: Date(timeIntervalSince1970: 1_557_957_135), // 2019-05-15T21:52:15Z
createdBefore: Date(timeIntervalSince1970: 1_557_957_180), // 2019-05-15T21:53:00Z
updatedAfter: Date(timeIntervalSince1970: 1_557_957_207), // 2019-05-15T21:53:27Z
updatedBefore: Date(timeIntervalSince1970: 1_557_957_224), // 2019-05-15T21:53:44Z
sizeAtLeast: 1024,
sizeAtMost: 4096
)
iterator.next { result in
switch result {
case let .success(page):
let searchResult = page.entries[0]
let item = searchResult.item
guard case let .file(file) = item else {
fail("Expected test item to be a file")
done()
return
}
expect(file).toNot(beNil())
expect(file.id).to(equal("11111"))
expect(file.name).to(equal("test file.txt"))
expect(file.description).to(equal(""))
expect(file.size).to(equal(16))
expect(searchResult.accessibleViaSharedLink?.absoluteString).to(equal("https://www.box.com/s/vspke7y05sb214wjokpk"))
case let .failure(error):
fail("Expected search request to succeed, but it failed: \(error)")
}
done()
}
}
}
}
context("SearchScope") {
describe("init()") {
it("should correctly create an enum value from it's string representation") {
expect(SearchScope.user).to(equal(SearchScope(SearchScope.user.description)))
expect(SearchScope.enterprise).to(equal(SearchScope(SearchScope.enterprise.description)))
expect(SearchScope.customValue("custom value")).to(equal(SearchScope("custom value")))
}
}
}
context("SearchContentType") {
describe("init()") {
it("should correctly create an enum value from it's string representation") {
expect(SearchContentType.name).to(equal(SearchContentType(SearchContentType.name.description)))
expect(SearchContentType.description).to(equal(SearchContentType(SearchContentType.description.description)))
expect(SearchContentType.fileContents).to(equal(SearchContentType(SearchContentType.fileContents.description)))
expect(SearchContentType.comments).to(equal(SearchContentType(SearchContentType.comments.description)))
expect(SearchContentType.tags).to(equal(SearchContentType(SearchContentType.tags.description)))
expect(SearchContentType.customValue("custom value")).to(equal(SearchContentType("custom value")))
}
}
}
context("SearchItemType") {
describe("init()") {
it("should correctly create an enum value from it's string representation") {
expect(SearchItemType.file).to(equal(SearchItemType(SearchItemType.file.description)))
expect(SearchItemType.folder).to(equal(SearchItemType(SearchItemType.folder.description)))
expect(SearchItemType.webLink).to(equal(SearchItemType(SearchItemType.webLink.description)))
expect(SearchItemType.customValue("custom value")).to(equal(SearchItemType("custom value")))
}
}
}
}
}
}
|
apache-2.0
|
0a6652163b9858e6c0ae14a3959a4751
| 50.93617 | 209 | 0.43536 | 5.80598 | false | false | false | false |
niunaruto/DeDaoAppSwift
|
testSwift/Pods/YPImagePicker/Source/Pages/Gallery/YPAlbumsManager.swift
|
1
|
3814
|
//
// YPAlbumsManager.swift
// YPImagePicker
//
// Created by Sacha Durand Saint Omer on 20/07/2017.
// Copyright © 2017 Yummypets. All rights reserved.
//
import Foundation
import Photos
class YPAlbumsManager {
private var cachedAlbums: [YPAlbum]?
func fetchAlbums() -> [YPAlbum] {
if let cachedAlbums = cachedAlbums {
return cachedAlbums
}
var albums = [YPAlbum]()
let options = PHFetchOptions()
let smartAlbumsResult = PHAssetCollection.fetchAssetCollections(with: .smartAlbum,
subtype: .any,
options: options)
let albumsResult = PHAssetCollection.fetchAssetCollections(with: .album,
subtype: .any,
options: options)
for result in [smartAlbumsResult, albumsResult] {
result.enumerateObjects({ assetCollection, _, _ in
var album = YPAlbum()
album.title = assetCollection.localizedTitle ?? ""
album.numberOfItems = self.mediaCountFor(collection: assetCollection)
if album.numberOfItems > 0 {
let r = PHAsset.fetchKeyAssets(in: assetCollection, options: nil)
if let first = r?.firstObject {
let targetSize = CGSize(width: 78*2, height: 78*2)
let options = PHImageRequestOptions()
options.isSynchronous = true
options.deliveryMode = .fastFormat
PHImageManager.default().requestImage(for: first,
targetSize: targetSize,
contentMode: .aspectFit,
options: options,
resultHandler: { image, _ in
album.thumbnail = image
})
}
album.collection = assetCollection
if YPConfig.library.mediaType == .photo {
if !(assetCollection.assetCollectionSubtype == .smartAlbumSlomoVideos
|| assetCollection.assetCollectionSubtype == .smartAlbumVideos) {
albums.append(album)
}
} else {
albums.append(album)
}
}
})
}
cachedAlbums = albums
return albums
}
func mediaCountFor(collection: PHAssetCollection) -> Int {
let options = PHFetchOptions()
options.predicate = YPConfig.library.mediaType.predicate()
let result = PHAsset.fetchAssets(in: collection, options: options)
return result.count
}
}
extension YPlibraryMediaType {
func predicate() -> NSPredicate {
switch self {
case .photo:
return NSPredicate(format: "mediaType = %d",
PHAssetMediaType.image.rawValue)
case .video:
return NSPredicate(format: "mediaType = %d",
PHAssetMediaType.video.rawValue)
case .photoAndVideo:
return NSPredicate(format: "mediaType = %d || mediaType = %d",
PHAssetMediaType.image.rawValue,
PHAssetMediaType.video.rawValue)
}
}
}
|
mit
|
057e3e682a07060fea579854e14af587
| 40.901099 | 93 | 0.46525 | 6.52911 | false | false | false | false |
nguyenantinhbk77/practice-swift
|
Apps/TodoList2/MasterTableViewController.swift
|
3
|
4409
|
import UIKit
class MasterTableViewController: UITableViewController {
var todoItems:NSMutableArray = NSMutableArray()
init(coder aDecoder: NSCoder!){
super.init(coder: aDecoder)
}
init(style: UITableViewStyle) {
super.init(style: style)
// Custom initialization
}
override func viewDidAppear(animated: Bool){
var userDefaults:NSUserDefaults = NSUserDefaults.standardUserDefaults()
var items: NSMutableArray? = userDefaults.objectForKey("itemList") as? NSMutableArray
if(items){
self.todoItems = items!
}
self.tableView.reloadData()
}
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// #pragma mark - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView?) -> Int {
// #warning Potentially incomplete method implementation.
// Return the number of sections.
return 1
}
override func tableView(tableView: UITableView?, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete method implementation.
// Return the number of rows in the section.
return self.todoItems.count
}
override func tableView(tableView: UITableView?, cellForRowAtIndexPath indexPath: NSIndexPath?) -> UITableViewCell? {
let cell = tableView!.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell
var item = self.todoItems.objectAtIndex(indexPath!.row) as NSDictionary
// Configure the cell...
cell.text = item.objectForKey("itemTitle") as String
return cell
}
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView?, canEditRowAtIndexPath indexPath: NSIndexPath?) -> Bool {
// Return NO if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView?, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath?) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView?, moveRowAtIndexPath fromIndexPath: NSIndexPath?, toIndexPath: NSIndexPath?) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView?, canMoveRowAtIndexPath indexPath: NSIndexPath?) -> Bool {
// Return NO if you do not want the item to be re-orderable.
return true
}
*/
// #pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue?, sender: AnyObject?) {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
if(segue && segue!.identifier == "showDetail"){
var selectedIndexPath: NSIndexPath = self.tableView.indexPathForSelectedRow()
var item = self.todoItems.objectAtIndex(selectedIndexPath.row) as NSDictionary
// Create a detail view controller
var detailViewController = segue!.destinationViewController as DetailsViewController
detailViewController.todoData = item
}
}
}
|
mit
|
c6d3c7c500d59da5c3637999ef3b1db5
| 35.139344 | 159 | 0.671354 | 5.855246 | false | false | false | false |
Candyroot/DesignPattern
|
command/command/RemoteControl.swift
|
1
|
1454
|
//
// RemoteControl.swift
// command
//
// Created by Bing Liu on 11/12/14.
// Copyright (c) 2014 UnixOSS. All rights reserved.
//
import Foundation
public class RemoteControl {
var onCommands: [Command]
var offCommands: [Command]
var undoCommand: Command
public init() {
let noCommand: Command = NoCommand()
onCommands = [Command](count: 7, repeatedValue: noCommand)
offCommands = [Command](count: 7, repeatedValue: noCommand)
undoCommand = noCommand
}
public func setCommand(slot: Int, onCommand: Command, offCommand: Command) {
onCommands[slot] = onCommand
offCommands[slot] = offCommand
}
public func onButtonWasPushed(slot: Int) {
onCommands[slot].execute()
undoCommand = onCommands[slot]
}
public func offButtonWasPushed(slot: Int) {
offCommands[slot].execute()
undoCommand = offCommands[slot]
}
public func undoButtonWasPushed() {
undoCommand.undo()
}
public var description: String {
var string: String = "\n------ Remote Control ------\n"
for var index=0; index<onCommands.count; ++index {
string += "[slot \(index)] " + _stdlib_getTypeName(onCommands[index]) + " " + _stdlib_getTypeName(offCommands[index]) + "\n"
}
string += "[undo] " + _stdlib_getTypeName(undoCommand) + "\n"
return string
}
}
|
apache-2.0
|
d1523f1d4f93fdeacec1fe41653dcd49
| 26.961538 | 138 | 0.603851 | 4.016575 | false | false | false | false |
Greenlite/ios-test-URL-inet
|
I OS Test/I OS Test/loginViewController.swift
|
1
|
2841
|
//
// loginViewController.swift
// I OS Test // swift 3.0
//
// Created by Sergey Matveev on 25/12/2016.
// Copyright © 2016 Greenlite.cg. All rights reserved.
//
import UIKit
class loginViewController: UIViewController {
@IBOutlet weak var userEmailTextField: UITextField!
@IBOutlet weak var userPasswordTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func loginButtonTapped(_ sender: Any) {
let userEmail = userEmailTextField.text;
let userPassword = userPasswordTextField.text;
if (userEmail!.isEmpty || userPassword!.isEmpty ) {return;}
//send user data to server side
let myUrl = NSURL(string: "htpp://yandec.ur/user-register/userRegister.php")
let request = NSMutableURLRequest(url:myUrl! as URL);
request.httpMethod = "POST";
let postString = "email=\(userEmail)&password=\(userPassword)";
request.httpBody = postString.data(using: String.Encoding.utf8)
let task = URLSession.shared.dataTask(with: request as URLRequest){
data, response, error in
if error != nil {
print("error=\(error)")
return
}
var err: NSError?
let json = try! JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
if let parseJSON = json {
let resultValue = parseJSON ["status"] as? String
print ("result: \(resultValue)")
if(resultValue=="Success"){
//
// login is succesful
UserDefaults.standard.set(true, forKey: "isUserLoggedin");
UserDefaults.standard.synchronize();
self.dismiss(animated: true,completion:nil);
}
}
}
task.resume()
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
mit
|
f21ab8c50d5b26fe58175c6413f7fca1
| 25.792453 | 115 | 0.535211 | 5.748988 | false | false | false | false |
LoveAlwaysYoung/EnjoyUniversity
|
EnjoyUniversity/EnjoyUniversity/Classes/View/Message/EUMessageViewController.swift
|
1
|
3061
|
//
// EUMessageViewController.swift
// EnjoyUniversity
//
// Created by lip on 17/2/27.
// Copyright © 2017年 lip. All rights reserved.
//
import UIKit
class EUMessageViewController: EUBaseViewController {
let notificationName = ["活动通知","社团通知","系统通知"]
let notificationPicName = ["notify_activity","notify_community","notify_system"]
var notificationDetail = ["您没有活动通知","您没有社团通知","您没有系统通知"]
override func viewDidLoad() {
super.viewDidLoad()
// 巧妙解决 tableview 下面多余的分割线
tableview.tableFooterView = UIView()
}
override func loadData() {
refreshControl?.beginRefreshing()
EUNetworkManager.shared.getNotificationLite { (isSuccess, dict) in
self.refreshControl?.endRefreshing()
if !isSuccess{
SwiftyProgressHUD.showFaildHUD(text: "网络异常", duration: 1)
return
}
guard let dict = dict else{
return
}
self.notificationDetail[0] = dict["activityNotification"] ?? "您没有活动通知"
self.notificationDetail[1] = dict["communityNotification"] ?? "您没有社团通知"
self.notificationDetail[2] = dict["systemNotification"] ?? "您没有系统通知"
self.tableview.reloadData()
}
}
}
// MARK: - UI 相关方法
extension EUMessageViewController{
override func setupNavBar() {
super.setupNavBar()
navitem.title = "消息"
// 缩进 tableview ,防止被 navbar 遮挡
tableview.contentInset = UIEdgeInsetsMake(navbar.bounds.height, 0, 0, 0)
}
}
// MARK: - 代理方法
extension EUMessageViewController{
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 3
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = EUMessageCell(style: .default, reuseIdentifier: nil)
cell.titleLabel.text = notificationName[indexPath.row]
cell.iconimageView.image = UIImage(named: notificationPicName[indexPath.row])
cell.detailLabel.text = notificationDetail[indexPath.row]
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 65
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
super.tableView(tableView, didSelectRowAt: indexPath)
let vc = EUMessageDetailController()
switch indexPath.row {
case 0:
vc.type = .ActivityNotification
case 1:
vc.type = .CommunityNotification
case 2:
vc.type = .SystemNotification
default:
return
}
navigationController?.pushViewController(vc, animated: true)
}
}
|
mit
|
b94ca2e22a3a9ac2293aee32aa19516c
| 29.020833 | 109 | 0.623525 | 4.787375 | false | false | false | false |
ortizraf/macsoftwarecenter
|
Mac Application Store/CategoriesController.swift
|
1
|
3814
|
//
// CategoriesController.swift
// Mac Software Center
//
// Created by Rafael Ortiz.
// Copyright © 2017 Nextneo. All rights reserved.
//
import Cocoa
class CategoriesController: NSViewController, NSCollectionViewDelegate, NSCollectionViewDataSource {
@IBOutlet weak var collectionView: NSCollectionView!
@IBOutlet weak var buttonFeaturedView: NSButton!
@IBOutlet weak var spinnerView: NSProgressIndicator!
static func instantiate() -> CategoriesController {
let mainStoryboard: NSStoryboard = NSStoryboard(name: "Main", bundle: nil)
let categoriesViewController = mainStoryboard.instantiateController(withIdentifier: "categoriesViewController") as! CategoriesController
return categoriesViewController
}
var categories: [Category]?
override func viewDidLoad() {
super.viewDidLoad()
let dbCategory = CategoryDB()
self.categories = dbCategory.getAllCategory()
}
override var representedObject: Any? {
didSet {
// Update the view, if already loaded.
}
}
func clickFeaturedButton(){
self.buttonFeaturedView.target = self
self.buttonFeaturedView.action = #selector(CategoriesController.clickActionToFeaturedController)
}
@IBAction func clickActionToFeaturedController(sender: AnyObject) {
print("click button Featured")
actionToFeaturedController(categorySelected: nil)
}
func collectionView(_ collectionView: NSCollectionView, numberOfItemsInSection section: Int) -> Int {
return categories?.count ?? 0
}
func collectionView(_ collectionView: NSCollectionView, itemForRepresentedObjectAt indexPath: IndexPath) -> NSCollectionViewItem {
let item = collectionView.makeItem(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "LabelCollectionViewCategory") , for: indexPath) as! LabelCollectionViewCategory
item.buildCategory = categories?[indexPath.item]
return item
}
func collectionView(_ collectionView: NSCollectionView, didSelectItemsAt indexPaths: Set<IndexPath>) {
print("category selected")
for indexPath in indexPaths {
print(indexPath.description)
let item = collectionView.makeItem(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "LabelCollectionViewCategory") , for: indexPath) as! LabelCollectionViewCategory
item.buildCategory = categories?[indexPath.item]
getCategorySelected(item)
}
}
func getCategorySelected(_ item: LabelCollectionViewCategory) {
actionToFeaturedController(categorySelected: item.buildCategory)
}
func actionToFeaturedController(categorySelected: Category?) {
showProgressIndicator()
self.view.wantsLayer = true
let mainStoryboard: NSStoryboard = NSStoryboard(name: "Main", bundle: nil)
let productViewController = mainStoryboard.instantiateController(withIdentifier: "productViewController") as! ProductController
if(categorySelected != nil){
productViewController.taskName = "category"
productViewController.categoryId = (categorySelected?.id)!
}
for view in self.view.subviews {
view.removeFromSuperview()
}
self.insertChild(productViewController, at: 0)
self.view.addSubview(productViewController.view)
self.view.frame = productViewController.view.frame
}
func showProgressIndicator(){
spinnerView.isHidden = false
spinnerView.startAnimation(spinnerView)
}
}
|
gpl-3.0
|
10714f26149663627c695b0ad10a8707
| 33.044643 | 183 | 0.672961 | 5.821374 | false | false | false | false |
PokeMapCommunity/PokeMap-iOS
|
Pods/Permission/Source/Supporting Files/Utilities.swift
|
1
|
5021
|
//
// Utilities.swift
//
// Copyright (c) 2015-2016 Damien (http://delba.io)
//
// 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.
//
internal let Application = UIApplication.sharedApplication()
internal let Defaults = NSUserDefaults.standardUserDefaults()
internal let NotificationCenter = NSNotificationCenter.defaultCenter()
internal let Bundle = NSBundle.mainBundle()
extension UIApplication {
private var topViewController: UIViewController? {
var vc = delegate?.window??.rootViewController
while let presentedVC = vc?.presentedViewController {
vc = presentedVC
}
return vc
}
internal func presentViewController(viewController: UIViewController, animated: Bool = true, completion: (() -> Void)? = nil) {
topViewController?.presentViewController(viewController, animated: animated, completion: completion)
}
}
extension NSBundle {
var name: String {
return objectForInfoDictionaryKey("CFBundleName") as? String ?? ""
}
}
extension UIControlState: Hashable {
public var hashValue: Int { return Int(rawValue) }
}
internal extension String {
static let nsLocationWhenInUseUsageDescription = "NSLocationWhenInUseUsageDescription"
static let nsLocationAlwaysUsageDescription = "NSLocationAlwaysUsageDescription"
static let requestedNotifications = "permission.requestedNotifications"
static let requestedLocationAlwaysWithWhenInUse = "permission.requestedLocationAlwaysWithWhenInUse"
static let requestedMotion = "permission.requestedMotion"
static let requestedBluetooth = "permission.requestedBluetooth"
}
internal extension Selector {
static let tapped = #selector(PermissionButton.tapped(_:))
static let highlight = #selector(PermissionButton.highlight(_:))
static let settingsHandler = #selector(DeniedAlert.settingsHandler)
static let requestingNotifications = #selector(Permission.requestingNotifications)
static let finishedRequestingNotifications = #selector(Permission.finishedRequestingNotifications)
}
extension NSUserDefaults {
var requestedLocationAlwaysWithWhenInUse: Bool {
get {
return boolForKey(.requestedLocationAlwaysWithWhenInUse)
}
set {
setBool(newValue, forKey: .requestedLocationAlwaysWithWhenInUse)
synchronize()
}
}
var requestedNotifications: Bool {
get {
return boolForKey(.requestedNotifications)
}
set {
setBool(newValue, forKey: .requestedNotifications)
synchronize()
}
}
var requestedMotion: Bool {
get {
return boolForKey(.requestedMotion)
}
set {
setBool(newValue, forKey: .requestedMotion)
synchronize()
}
}
var requestedBluetooth: Bool {
get {
return boolForKey(.requestedBluetooth)
}
set {
setBool(newValue, forKey: .requestedBluetooth)
synchronize()
}
}
}
struct Queue {
static func main(block: dispatch_block_t) {
dispatch_async(dispatch_get_main_queue(), block)
}
static func main(after seconds: Double, block: dispatch_block_t) {
let time = dispatch_time(DISPATCH_TIME_NOW, Int64(seconds * Double(NSEC_PER_SEC)))
dispatch_after(time, dispatch_get_main_queue(), block)
}
}
extension NSOperationQueue {
convenience init(_ qualityOfService: NSQualityOfService) {
self.init()
self.qualityOfService = qualityOfService
}
}
internal extension NSNotificationCenter {
func addObserver(observer: AnyObject, selector: Selector, name: String) {
addObserver(observer, selector: selector, name: name, object: nil)
}
func removeObserver(observer: AnyObject, name: String) {
removeObserver(observer, name: name, object: nil)
}
}
|
mit
|
52519cc9512beac5df953ee21b350801
| 34.111888 | 131 | 0.69289 | 5.165638 | false | false | false | false |
chris-wood/reveiller
|
reveiller/Pods/SwiftCharts/SwiftCharts/Axis/ChartAxisYLayerDefault.swift
|
5
|
3767
|
//
// ChartAxisYLayerDefault.swift
// SwiftCharts
//
// Created by ischuetz on 25/04/15.
// Copyright (c) 2015 ivanschuetz. All rights reserved.
//
import UIKit
class ChartAxisYLayerDefault: ChartAxisLayerDefault {
override var height: CGFloat {
return self.p2.y - self.p1.y
}
var labelsMaxWidth: CGFloat {
if self.labelDrawers.isEmpty {
return self.maxLabelWidth(self.axisValues)
} else {
return self.labelDrawers.reduce(0) {maxWidth, labelDrawer in
max(maxWidth, labelDrawer.size.width)
}
}
}
override var width: CGFloat {
return self.labelsMaxWidth + self.settings.axisStrokeWidth + self.settings.labelsToAxisSpacingY + self.settings.axisTitleLabelsToLabelsSpacing + self.axisTitleLabelsWidth
}
override var length: CGFloat {
return p1.y - p2.y
}
override func generateAxisTitleLabelsDrawers(offset offset: CGFloat) -> [ChartLabelDrawer] {
if let firstTitleLabel = self.axisTitleLabels.first {
if self.axisTitleLabels.count > 1 {
print("WARNING: No support for multiple definition labels on vertical axis. Using only first one.")
}
let axisLabel = firstTitleLabel
let labelSize = ChartUtils.textSize(axisLabel.text, font: axisLabel.settings.font)
let settings = axisLabel.settings
let newSettings = ChartLabelSettings(font: settings.font, fontColor: settings.fontColor, rotation: settings.rotation, rotationKeep: settings.rotationKeep)
let axisLabelDrawer = ChartLabelDrawer(text: axisLabel.text, screenLoc: CGPointMake(
self.p1.x + offset,
self.p2.y + ((self.p1.y - self.p2.y) / 2) - (labelSize.height / 2)), settings: newSettings)
return [axisLabelDrawer]
} else { // definitionLabels is empty
return []
}
}
override func screenLocForScalar(scalar: Double, firstAxisScalar: Double) -> CGFloat {
return self.p1.y - self.innerScreenLocForScalar(scalar, firstAxisScalar: firstAxisScalar)
}
override func generateLabelDrawers(offset offset: CGFloat) -> [ChartLabelDrawer] {
return self.axisValues.reduce([]) {arr, axisValue in
let scalar = axisValue.scalar
let y = self.screenLocForScalar(scalar)
if let axisLabel = axisValue.labels.first { // for now y axis supports only one label x value
let labelSize = ChartUtils.textSize(axisLabel.text, font: axisLabel.settings.font)
let labelY = y - (labelSize.height / 2)
let labelX = self.labelsX(offset: offset, labelWidth: labelSize.width)
let labelDrawer = ChartLabelDrawer(text: axisLabel.text, screenLoc: CGPointMake(labelX, labelY), settings: axisLabel.settings)
labelDrawer.hidden = axisValue.hidden
return arr + [labelDrawer]
} else {
return arr
}
}
}
func labelsX(offset offset: CGFloat, labelWidth: CGFloat) -> CGFloat {
fatalError("override")
}
private func maxLabelWidth(axisLabels: [ChartAxisLabel]) -> CGFloat {
return axisLabels.reduce(CGFloat(0)) {maxWidth, label in
return max(maxWidth, ChartUtils.textSize(label.text, font: label.settings.font).width)
}
}
private func maxLabelWidth(axisValues: [ChartAxisValue]) -> CGFloat {
return axisValues.reduce(CGFloat(0)) {maxWidth, axisValue in
return max(maxWidth, self.maxLabelWidth(axisValue.labels))
}
}
}
|
mit
|
ea0ec9186da7988406f4246fdecdda46
| 37.438776 | 178 | 0.625431 | 4.823303 | false | false | false | false |
naithar/Kitura-net
|
Sources/KituraNet/HTTP/HTTPIncomingMessage.swift
|
1
|
9536
|
/*
* Copyright IBM Corporation 2016
*
* 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 Socket
import Foundation
// MARK: IncomingMessage
/// A representation of HTTP incoming message.
public class HTTPIncomingMessage : HTTPParserDelegate {
/// Major version for HTTP of the incoming message.
public private(set) var httpVersionMajor: UInt16?
/// Minor version for HTTP of the incoming message.
public private(set) var httpVersionMinor: UInt16?
/// HTTP Status code if this message is a response
public private(set) var httpStatusCode: HTTPStatusCode = .unknown
/// Set of HTTP headers of the incoming message.
public var headers = HeadersContainer()
/// HTTP Method of the incoming message.
public private(set) var method: String = ""
/// URL of the incoming message.
public private(set) var urlString = ""
/// Raw URL of the incoming message.
public private(set) var url = Data()
/// Indicates if the parser should save the message body and call onBody()
var saveBody = true
// Private
/// Default buffer size used for creating a BufferList
private static let bufferSize = 2000
/// State of callbacks from parser WRT headers
private var lastHeaderWasAValue = false
/// Bytes of a header key that was just parsed and returned in chunks by the pars
private let lastHeaderField = NSMutableData()
/// Bytes of a header value that was just parsed and returned in chunks by the parser
private let lastHeaderValue = NSMutableData()
/// The http_parser Swift wrapper
private var httpParser: HTTPParser?
/// State of incoming message handling
private var status = HTTPParserStatus()
/// Chunk of body read in by the http_parser, filled by callbacks to onBody
private var bodyChunk = BufferList()
private var ioBuffer = Data(capacity: HTTPIncomingMessage.bufferSize)
private var buffer = Data(capacity: HTTPIncomingMessage.bufferSize)
/// Initializes a new IncomingMessage
///
/// - Parameter isRequest: whether this message is a request
///
/// - Returns: an IncomingMessage instance
init (isRequest: Bool) {
httpParser = HTTPParser(isRequest: isRequest)
httpParser!.delegate = self
}
/// Parse the message
///
/// - Parameter buffer: An NSData object contaning the data to be parsed
func parse (_ buffer: NSData) -> HTTPParserStatus {
guard let parser = httpParser else {
status.error = .internalError
return status
}
var length = buffer.length
guard length > 0 else {
/* Handle unexpected EOF. Usually just close the connection. */
release()
status.error = .unexpectedEOF
return status
}
// If we were reset because of keep alive
if status.state == .reset {
reset()
}
var start = 0
while status.state != .messageComplete && status.error == nil && length > 0 {
let bytes = buffer.bytes.assumingMemoryBound(to: Int8.self) + start
let (numberParsed, upgrade) = parser.execute(bytes, length: length)
if upgrade == 1 {
status.upgrade = true
}
else if numberParsed != length {
if self.status.state == .reset {
// Apparently the short message was a Continue. Let's just keep on parsing
start = numberParsed
self.reset()
}
else {
/* Handle error. Usually just close the connection. */
self.release()
self.status.error = .parsedLessThanRead
}
}
length -= numberParsed
}
status.bytesLeft = length
return status
}
/// Read a chunk of the body of the message.
///
/// - Parameter into: An NSMutableData to hold the data in the message.
/// - Throws: if an error occurs while reading the body.
/// - Returns: the number of bytes read.
public func read(into data: inout Data) throws -> Int {
let count = bodyChunk.fill(data: &data)
return count
}
/// Read the whole body of the message.
///
/// - Parameter into: An NSMutableData to hold the data in the message.
/// - Throws: if an error occurs while reading the data.
/// - Returns: the number of bytes read.
@discardableResult
public func readAllData(into data: inout Data) throws -> Int {
var length = try read(into: &data)
var bytesRead = length
while length > 0 {
length = try read(into: &data)
bytesRead += length
}
return bytesRead
}
/// Read a chunk of the body and return it as a String.
///
/// - Throws: if an error occurs while reading the data.
/// - Returns: an Optional string.
public func readString() throws -> String? {
buffer.count = 0
let length = try read(into: &buffer)
if length > 0 {
return String(data: buffer, encoding: .utf8)
}
else {
return nil
}
}
/// Free the httpParser from the IncomingMessage
private func freeHTTPParser () {
httpParser?.delegate = nil
httpParser = nil
}
/// Instructions for when reading URL portion
///
/// - Parameter bytes: The bytes of the parsed URL
/// - Parameter count: The number of bytes parsed
func onURL(_ bytes: UnsafePointer<UInt8>, count: Int) {
url.append(bytes, count: count)
}
/// Instructions for when reading header key
///
/// - Parameter bytes: The bytes of the parsed header key
/// - Parameter count: The number of bytes parsed
func onHeaderField (_ bytes: UnsafePointer<UInt8>, count: Int) {
if lastHeaderWasAValue {
addHeader()
}
lastHeaderField.append(bytes, length: count)
lastHeaderWasAValue = false
}
/// Instructions for when reading a header value
///
/// - Parameter bytes: The bytes of the parsed header value
/// - Parameter count: The number of bytes parsed
func onHeaderValue (_ bytes: UnsafePointer<UInt8>, count: Int) {
lastHeaderValue.append(bytes, length: count)
lastHeaderWasAValue = true
}
/// Set the header key-value pair
private func addHeader() {
var zero: CChar = 0
lastHeaderField.append(&zero, length: 1)
let headerKey = String(cString: lastHeaderField.bytes.assumingMemoryBound(to: CChar.self))
lastHeaderValue.append(&zero, length: 1)
let headerValue = String(cString: lastHeaderValue.bytes.assumingMemoryBound(to: CChar.self))
headers.append(headerKey, value: headerValue)
lastHeaderField.length = 0
lastHeaderValue.length = 0
}
/// Instructions for when reading the body of the message
///
/// - Parameter bytes: The bytes of the parsed body
/// - Parameter count: The number of bytes parsed
func onBody (_ bytes: UnsafePointer<UInt8>, count: Int) {
self.bodyChunk.append(bytes: bytes, length: count)
}
/// Instructions for when the headers have been finished being parsed.
///
/// - Parameter method: the HTTP method
/// - Parameter versionMajor: major version of HTTP
/// - Parameter versionMinor: minor version of HTTP
func onHeadersComplete(method: String, versionMajor: UInt16, versionMinor: UInt16) {
httpVersionMajor = versionMajor
httpVersionMinor = versionMinor
self.method = method
urlString = String(data: url, encoding: .utf8) ?? ""
if lastHeaderWasAValue {
addHeader()
}
status.keepAlive = httpParser?.isKeepAlive() ?? false
status.state = .headersComplete
httpStatusCode = httpParser?.statusCode ?? .unknown
}
/// Instructions for when beginning to read a message
func onMessageBegin() {
}
/// Instructions for when done reading the message
func onMessageComplete() {
status.keepAlive = httpParser?.isKeepAlive() ?? false
status.state = .messageComplete
if !status.keepAlive {
release()
}
}
/// Signal that the connection is being closed, and resources should be freed
func release() {
freeHTTPParser()
}
/// Signal that reading is being reset
func prepareToReset() {
status.state = .reset
}
/// When we're ready, really reset everything
private func reset() {
lastHeaderWasAValue = false
saveBody = true
url.count = 0
headers.removeAll()
bodyChunk.reset()
status.reset()
httpParser?.reset()
}
}
|
apache-2.0
|
f6acd601dbb3f3cdd28432db49de9796
| 30.681063 | 100 | 0.615352 | 4.850458 | false | false | false | false |
DimensionSrl/Desman
|
Desman/Remote/Controllers/UsersTableViewController.swift
|
1
|
4415
|
//
// UsersTableViewController.swift
// Desman
//
// Created by Matteo Gavagnin on 31/10/15.
// Copyright © 2015 DIMENSION S.r.l. All rights reserved.
//
import UIKit
#if !DESMAN_AS_COCOAPOD
import Desman
#endif
private var desmanUsersContext = 0
class UsersTableViewController: UITableViewController {
var objectToObserve = RemoteManager.sharedInstance
var users = [User]()
var app : App?
override func viewDidLoad() {
super.viewDidLoad()
self.splitViewController?.preferredDisplayMode = .AllVisible
objectToObserve.addObserver(self, forKeyPath: "users", options: .New, context: &desmanUsersContext)
self.users = Array(RemoteManager.sharedInstance.users)
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
RemoteManager.sharedInstance.stopFetchingEvents()
}
@IBAction func dismissController(sender: UIBarButtonItem) {
self.navigationController?.dismissViewControllerAnimated(true, completion: nil)
}
override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
if context == &desmanUsersContext {
if keyPath == "users" {
if let updated = change?[NSKeyValueChangeNewKey] as? [User] {
let removed = users.removeObjectsInArray(updated)
let added = updated.removeObjectsInArray(users)
var removeIndexPaths = [NSIndexPath]()
var index = 1
let count = users.count
for _ in removed {
let indexPath = NSIndexPath(forRow: count - index, inSection: 0)
removeIndexPaths.append(indexPath)
index += 1
}
var addedIndexPaths = [NSIndexPath]()
index = 0
for _ in added {
let indexPath = NSIndexPath(forRow: index, inSection: 0)
addedIndexPaths.append(indexPath)
index += 1
}
var rowAnimation : UITableViewRowAnimation = .Right
if users.count == 0 {
rowAnimation = .None
}
users = Array(updated)
tableView.beginUpdates()
tableView.deleteRowsAtIndexPaths(removeIndexPaths, withRowAnimation: .Left)
tableView.insertRowsAtIndexPaths(addedIndexPaths, withRowAnimation: rowAnimation)
tableView.endUpdates()
}
}
} else {
super.observeValueForKeyPath(keyPath, ofObject: object, change: change, context: context)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return users.count
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let selectedUser = users[indexPath.row]
if let app = app {
RemoteManager.sharedInstance.fetchEvents(app, user: selectedUser)
self.performSegueWithIdentifier("showEventsSegue", sender: selectedUser)
}
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("userCell", forIndexPath: indexPath) as! Desman.UserTableViewCell
let user = users[indexPath.row]
cell.userTitleLabel.text = user.title
cell.userImageView.isUser()
if let imageUrl = user.imageUrl {
cell.userImageView.loadFromURL(imageUrl)
}
return cell
}
deinit {
objectToObserve.removeObserver(self, forKeyPath: "users", context: &desmanUsersContext)
}
}
|
mit
|
6c337787d467cf950a5593cb9fe030f5
| 36.726496 | 157 | 0.594925 | 5.630102 | false | false | false | false |
danielgindi/Charts
|
ChartsDemo-macOS/PlaygroundChart.playground/Pages/BubbleChart.xcplaygroundpage/Contents.swift
|
4
|
2313
|
//
// PlayGround
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// Copyright © 2017 thierry Hentic.
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
/*:
****
[Menu](Menu)
[Previous](@previous)
****
*/
//: # Bubble Chart
import Cocoa
import Charts
import PlaygroundSupport
let ITEM_COUNT = 20
let r = CGRect(x: 0, y: 0, width: 600, height: 600)
var chartView = BubbleChartView(frame: r)
//: ### General
chartView.drawGridBackgroundEnabled = true
//: ### xAxis
let xAxis = chartView.xAxis
xAxis.labelPosition = .bothSided
xAxis.axisMinimum = 0.0
xAxis.granularity = 1.0
//: ### LeftAxis
let leftAxis = chartView.leftAxis
leftAxis.drawGridLinesEnabled = true
leftAxis.axisMinimum = 40.0
//: ### RightAxis
let rightAxis = chartView.rightAxis
rightAxis.drawGridLinesEnabled = true
rightAxis.axisMinimum = 40.0
//: ### Legend
let legend = chartView.legend
legend.wordWrapEnabled = true
legend.horizontalAlignment = .center
legend.verticalAlignment = .bottom
legend.orientation = .horizontal
legend.drawInside = false
//: ### Description
chartView.chartDescription?.enabled = false
//: ### BubbleChartDataEntry
var entries = [BubbleChartDataEntry]()
for index in 0..<ITEM_COUNT
{
let y = Double(arc4random_uniform(100)) + 50.0
let size = (y - 50) / 25.0
entries.append(BubbleChartDataEntry(x: Double(index) + 0.5, y: y, size: CGFloat(size)))
}
//: ### BubbleChartDataSet
let set = BubbleChartDataSet(values: entries, label: "Bubble DataSet")
set.colors = ChartColorTemplates.vordiplom()
set.valueTextColor = NSUIColor.labelOrBlack
set.valueFont = NSUIFont.systemFont(ofSize: CGFloat(10.0))
set.drawValuesEnabled = true
set.normalizeSizeEnabled = false
//: ### BubbleChartData
let data = BubbleChartData()
data.addDataSet(set)
chartView.data = data
chartView.animate(xAxisDuration: 1.0, yAxisDuration: 1.0)
/*:---*/
//: ### Setup for the live view
PlaygroundPage.current.liveView = chartView
/*:
****
[Menu](Menu)
[Previous](@previous)
****
*/
|
apache-2.0
|
7bb82c93e884d3caa0ff65979ec851f7
| 27.195122 | 91 | 0.640571 | 4.165766 | false | false | false | false |
ChaoBo/DouYuLive
|
DouYuLive/DouYuLive/Classes/Home/Controller/HomeViewController.swift
|
1
|
3257
|
//
// HomeViewController.swift
// DouYuLive
//
// Created by 晁博 on 2016/11/3.
// Copyright © 2016年 狂虐iOS(中国). All rights reserved.
//
import UIKit
class HomeViewController: BaseViewController {
override func viewDidLoad() {
super.viewDidLoad()
setUpUI()
// Do any additional setup after loading the view.
}
}
extension HomeViewController {
public func setUpUI()
{
setUpNavgationBarLogo()
setUpNavgationBarWithConvenienceInit()
}
public func setUpNavgationBarLogo()
{
let btn = UIButton()
btn.setImage(#imageLiteral(resourceName: "logo"), for: .normal)
btn.sizeToFit()
self.navigationItem.leftBarButtonItem = UIBarButtonItem(customView: btn)
}
public func setUpNavgationBarWithNormal()
{
let btnSize = CGSize(width: 40, height: 40)
let historyBtn = UIButton()
historyBtn.setImage(#imageLiteral(resourceName: "viewHistoryIconHL"), for: .normal)
historyBtn.setImage(#imageLiteral(resourceName: "viewHistoryIcon"), for: .highlighted)
historyBtn.frame = CGRect(origin: CGPoint(x: 0, y: 0), size: btnSize)
let searchBtn = UIButton()
searchBtn.setImage(#imageLiteral(resourceName: "searchBtnIconHL"), for: .normal)
searchBtn.setImage(#imageLiteral(resourceName: "searchBtnIcon"), for: .highlighted)
searchBtn.frame = CGRect(origin: CGPoint(x: 0, y: 0), size: btnSize)
let qrcodeBtn = UIButton()
qrcodeBtn.setImage(#imageLiteral(resourceName: "scanIconHL"), for: .normal)
qrcodeBtn.setImage(#imageLiteral(resourceName: "scanIcon"), for: .highlighted)
qrcodeBtn.frame = CGRect(origin: CGPoint(x: 0, y: 0), size: btnSize)
let history = UIBarButtonItem(customView: historyBtn)
let search = UIBarButtonItem(customView: searchBtn)
let qrcode = UIBarButtonItem(customView: qrcodeBtn)
self.navigationItem.rightBarButtonItems = [history,search,qrcode]
}
public func setUpNavgationBarWithExtension()
{
let btnSize = CGSize(width: 40, height: 40)
let history = UIBarButtonItem.creatItem(normalImageName: "viewHistoryIconHL", highlightImageName: "viewHistoryIcon", itemSize: btnSize)
let search = UIBarButtonItem.creatItem(normalImageName: "searchBtnIconHL", highlightImageName: "searchBtnIcon", itemSize: btnSize)
let qrcode = UIBarButtonItem.creatItem(normalImageName: "scanIconHL", highlightImageName: "scanIcon", itemSize: btnSize)
self.navigationItem.rightBarButtonItems = [history,search,qrcode]
}
public func setUpNavgationBarWithConvenienceInit()
{
let btnSize = CGSize(width: 40, height: 40)
let history = UIBarButtonItem(normalImageName: "viewHistoryIconHL", highlightImageName: "viewHistoryIcon", itemSize: btnSize)
let search = UIBarButtonItem.creatItem(normalImageName: "searchBtnIconHL", highlightImageName: "searchBtnIcon", itemSize: btnSize)
let qrcode = UIBarButtonItem.creatItem(normalImageName: "scanIconHL", highlightImageName: "scanIcon", itemSize: btnSize)
self.navigationItem.rightBarButtonItems = [history,search,qrcode]
}
}
|
mit
|
2733ffb56ea10f5aa0bec0529969feab
| 39.024691 | 143 | 0.693091 | 4.592068 | false | false | false | false |
sffernando/SwiftLearning
|
FoodTracker/FoodTracker/Meal.swift
|
1
|
1548
|
//
// Meal.swift
// FoodTracker
//
// Created by koudai on 2016/11/29.
// Copyright © 2016年 fernando. All rights reserved.
//
import UIKit
class Meal: NSObject, NSCoding {
//MARK: propties
var name: String
var image: UIImage?
var rating: Int
//MARK: Archieving Paths
static let DocumentDirectory = FileManager().urls(for: .documentDirectory, in: .userDomainMask).first!
static let ArchiveURL = DocumentDirectory.appendingPathComponent("meals")
//MARK: Types
struct PropertyKey {
static let nameKey = "name"
static let photoKey = "photo"
static let ratingKey = "rating"
}
init?(name: String, photo: UIImage?, rating: Int) {
if name.isEmpty || rating < 0 {
return nil
}
self.name = name
self.image = photo
self.rating = rating
super.init()
}
//MARK: NSCoding
func encode(with aCoder: NSCoder) {
aCoder.encode(name, forKey: PropertyKey.nameKey)
aCoder.encode(image, forKey: PropertyKey.photoKey)
aCoder.encode(rating, forKey: PropertyKey.ratingKey)
}
required convenience init?(coder aDecoder: NSCoder) {
let name = aDecoder.decodeObject(forKey: PropertyKey.nameKey) as! String
let image = aDecoder.decodeObject(forKey: PropertyKey.photoKey) as? UIImage
let rating = aDecoder.decodeInteger(forKey: PropertyKey.ratingKey)
self.init(name: name, photo: image, rating: rating)
}
}
|
mit
|
5ae84ae1ec208093a950a9ceaf092faa
| 27.090909 | 106 | 0.625243 | 4.352113 | false | false | false | false |
trujillo138/MyExpenses
|
MyExpenses/MyExpenses/Scenes/SortAndFilter/ExpenseFilterOptionViewController.swift
|
1
|
6936
|
//
// ExpenseFilterOptionViewController.swift
// MyExpenses
//
// Created by Tomas Trujillo on 9/3/17.
// Copyright © 2017 TOMApps. All rights reserved.
//
import UIKit
class ExpenseFilterOptionViewController: ExpenseTypeCollectionViewReceiver {
//MARK: Outlets
@IBOutlet private weak var expenseTypeFilterOptionView: UIView!
@IBOutlet private weak var expenseDateFilterOptionView: UIView!
@IBOutlet private weak var expenseAmountFilterOptionView: UIView!
@IBOutlet private weak var filterSegmentedControl: UISegmentedControl!
@IBOutlet private weak var expenseTypesCollection: UICollectionView!
@IBOutlet fileprivate weak var expenseAmountTextField: ExpenseAmountTextField! {
didSet {
let defaultValue: Double = 0.0
expenseAmountTextField.placeholder = defaultValue.currencyFormat
}
}
@IBOutlet private weak var flagView: EquivalenceView!
@IBOutlet private weak var fromDatePicker: UIDatePicker! {
didSet {
guard let date = minimumDate else { return }
let minDate = Date.dateWithComponents(years: date.year(), months: date.month(), days: 1)
let maxDate = minDate.dateByAdding(years: 0, months: 1, days: 0).dateByAdding(years: 0, months: 0, days: -1)
fromDatePicker.minimumDate = minDate
fromDatePicker.maximumDate = maxDate
}
}
@IBOutlet private weak var toDatePicker: UIDatePicker!{
didSet {
guard let date = minimumDate else { return }
let minDate = Date.dateWithComponents(years: date.year(), months: date.month(), days: 1)
let maxDate = minDate.dateByAdding(years: 0, months: 1, days: 0).dateByAdding(years: 0, months: 0, days: -1)
toDatePicker.minimumDate = minDate
toDatePicker.maximumDate = maxDate
}
}
@IBOutlet private weak var fromDateLabel: UILabel!
@IBOutlet private weak var upToDateLabel: UILabel!
//MARK: Properties
var selectedFilterOption = ExpensePeriodFilterOption.type
var fromValue: Any?
var toValue: Any?
fileprivate var amountFilterIsGreaterThan = true
fileprivate let selectedASortOptionSegueIdentifier = "SelectedAFilterOption"
var maximumDate: Date?
var minimumDate: Date?
var sizeOfCollectionItems: CGFloat {
var size: CGFloat = 0.0
if UIDevice.isIpad() {
size = expenseTypesCollection.frame.width * 0.2
} else {
size = expenseTypesCollection.frame.width * 0.33
}
return size
}
//MARK: Viewcontroller Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
hideKeyBoardWhenTouched()
setNamesForSegmentedControl()
setVisibleViewForSelectedFilter()
setupExpenseTypeCollectionView(expenseTypesCollection)
setDateValues()
flagView.delegate = self
preventBigTitleInNavController()
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
collectionDelegate?.sizeOfItems = CGSize(width: sizeOfCollectionItems, height: sizeOfCollectionItems)
expenseTypesCollection.reloadData()
}
private func setDateValues() {
if let maxDate = maximumDate {
toDatePicker.date = maxDate
upToDateLabel.text = "\(LStrings.ExpensePeriod.FilterUpToDateLabel): \(maxDate.longFormat)"
} else {
upToDateLabel.text = "\(LStrings.ExpensePeriod.FilterUpToDateLabel):"
}
if let minDate = minimumDate {
fromDatePicker.date = minDate
fromDateLabel.text = "\(LStrings.ExpensePeriod.FilterFromDateLabel): \(minDate.longFormat)"
} else {
fromDateLabel.text = "\(LStrings.ExpensePeriod.FilterFromDateLabel):"
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
let size = expenseTypesCollection.frame.width * 0.33
collectionDelegate?.sizeOfItems = CGSize(width: size, height: size)
expenseTypesCollection.reloadData()
}
private func setNamesForSegmentedControl() {
for index in 0 ..< filterSegmentedControl.numberOfSegments {
var text = ""
if let filterName = ExpensePeriodFilterOption(rawValue: index)?.name {
text = filterName
}
filterSegmentedControl.setTitle(text, forSegmentAt: index)
}
}
//MARK: Actions
@IBAction func changedFilterType(_ sender: UISegmentedControl) {
setVisibleViewForSelectedFilter();
selectedFilterOption = ExpensePeriodFilterOption(rawValue: sender.selectedSegmentIndex) ?? .type
}
private func setVisibleViewForSelectedFilter() {
let index = filterSegmentedControl.selectedSegmentIndex
if index == 0 {
expenseTypeFilterOptionView.alpha = 1.0
expenseDateFilterOptionView.alpha = 0.0
expenseAmountFilterOptionView.alpha = 0.0
resignFirstResponder()
} else if index == 1 {
expenseTypeFilterOptionView.alpha = 0.0
expenseDateFilterOptionView.alpha = 1.0
expenseAmountFilterOptionView.alpha = 0.0
resignFirstResponder()
} else {
expenseTypeFilterOptionView.alpha = 0.0
expenseDateFilterOptionView.alpha = 0.0
expenseAmountFilterOptionView.alpha = 1.0
expenseAmountTextField.becomeFirstResponder()
}
}
@IBAction private func cancelPressed(_ sender: Any) {
dismiss(animated: true, completion: nil)
}
@IBAction func filterOptionPressed(_ sender: Any) {
switch selectedFilterOption {
case .type:
fromValue = selectedExpenseType == "" ? nil : selectedExpenseType
case .amount:
if amountFilterIsGreaterThan {
fromValue = expenseAmountTextField.amount
} else {
toValue = expenseAmountTextField.amount
}
case .date:
fromValue = fromDatePicker.date
toValue = toDatePicker.date
}
performSegue(withIdentifier: selectedASortOptionSegueIdentifier, sender: nil)
}
@IBAction func fromDateValueChanged(_ sender: Any) {
fromDateLabel.text = "\(LStrings.ExpensePeriod.FilterFromDateLabel): \(fromDatePicker.date.longFormat)"
}
@IBAction func upToDateValueChange(_ sender: Any) {
upToDateLabel.text = "\(LStrings.ExpensePeriod.FilterUpToDateLabel): \(toDatePicker.date.longFormat)"
}
}
//MARK: FalgView Delegate
extension ExpenseFilterOptionViewController: FlagViewDelegate {
func changedFlagValue(flag: Bool) {
amountFilterIsGreaterThan = flag
}
}
|
apache-2.0
|
c39844d10a97140662afe2fe70d49981
| 33.675 | 120 | 0.649603 | 5.125647 | false | false | false | false |
AjayOdedara/CoreKitTest
|
CoreKit/CoreKit/Core.swift
|
1
|
1782
|
//
// Core.swift
// CllearWorksCoreKit
//
// Created by CllearWorks Dev on 5/20/15.
// Copyright (c) 2015 CllearWorks. All rights reserved.
//
import Foundation
public typealias JSONDictionary = [String:AnyObject]
public typealias JSONArray = [AnyObject]
public let ApiErrorDomain = "com.CllearWorks.core.error"
public let NonBreakingSpace = "\0x00a0"
public let ConnectLogUserOutNotification = "ConnectLogUserOutNotification"
public let DidRegisterNotification = "DidRegisterNotification"
public let DidRegisterNotificationFailedOnSend = "DidRegisterNotificationFailedOnSend"
public let DidFailRegisterNotification = "DidFailRegisterNotification"
public let ConnectSelectedPlaceChangedNotification = "ConnectSelectedPlaceChangedNotification"
public let ConnectOpenedFromHandoff = "ConnectOpenedFromHandoff"
public let ConnectOpenedFromNotification = "ConnectOpenedFromNotification"
public let CWRequestDidTimeOutNotification = "CWRequestDidTimeOutNotification"
public let CMLoginWasSuccessful = "CMLoginWasSuccessful"
public let CMContinueAsGuestSuccessful = "CMContinueAsGuestSuccessful"
public let CWLogoutWasSuccessful = "CWLogoutWasSuccessful"
public let CWUserReAuth = "CWUserReAuth"
public let CWUpdateUserPhoto = "CWUpdateUserPhoto"
public let CWNoBeacons = "CWNoBeacons"
public let CWUserLogout = "CWUserLogout"
public let CWCheckedInTrack = "CWCheckedInTrack"
public let CWCheckedOutTrack = "CWCheckedOutTrack"
public let CWBeaconsUpdateLocation = "CWBeaconsUpdateLocation"
public let CWBeaconsAppKill = "CWBeaconsAppKill"
public let CWUserNotificationReminder = "CWUserNotificationReminder"
public let CWApplyForLeaveNotification = "CWApplyForLeave"
public let CWUserBluetoothStatus = "CWUserBluetoothStatus"
public let CWUserBluetoothOn = "CWUserBluetoothOn"
|
mit
|
eed391ff13a935cfab328ddd7e5b2628
| 41.428571 | 94 | 0.843996 | 4.183099 | false | false | false | false |
ahoppen/swift
|
test/SILGen/objc_factory_init.swift
|
5
|
7906
|
// RUN: %target-swift-emit-silgen(mock-sdk: %clang-importer-sdk) -I %S/../IDE/Inputs/custom-modules %s | %FileCheck %s
// REQUIRES: objc_interop
import Foundation
import ImportAsMember.Class
// CHECK-LABEL: sil shared [serialized] [thunk] [ossa] @$sSo4HiveC5queenABSgSo3BeeCSg_tcfCTO : $@convention(method) (@owned Optional<Bee>, @thick Hive.Type) -> @owned Optional<Hive>
func testInstanceTypeFactoryMethod(queen: Bee) {
// CHECK: bb0([[QUEEN:%[0-9]+]] : @owned $Optional<Bee>, [[HIVE_META:%[0-9]+]] : $@thick Hive.Type):
// CHECK-NEXT: [[HIVE_META_OBJC:%[0-9]+]] = thick_to_objc_metatype [[HIVE_META]] : $@thick Hive.Type to $@objc_metatype Hive.Type
// CHECK-NEXT: [[FACTORY:%[0-9]+]] = objc_method [[HIVE_META_OBJC]] : $@objc_metatype Hive.Type, #Hive.init!allocator.foreign : (Hive.Type) -> (Bee?) -> Hive?, $@convention(objc_method) (Optional<Bee>, @objc_metatype Hive.Type) -> @autoreleased Optional<Hive>
// CHECK-NEXT: [[HIVE:%[0-9]+]] = apply [[FACTORY]]([[QUEEN]], [[HIVE_META_OBJC]]) : $@convention(objc_method) (Optional<Bee>, @objc_metatype Hive.Type) -> @autoreleased Optional<Hive>
// CHECK-NEXT: destroy_value [[QUEEN]]
// CHECK-NEXT: return [[HIVE]] : $Optional<Hive>
var hive1 = Hive(queen: queen)
}
extension Hive {
// FIXME: This whole approach is wrong. This should be a factory initializer,
// not a convenience initializer, which means it does not have an initializing
// entry point at all.
// CHECK-LABEL: sil hidden [ossa] @$sSo4HiveC17objc_factory_initE10otherQueenABSo3BeeC_tcfC
// CHECK: bb0([[QUEEN:%.*]] : @owned $Bee, [[META:%.*]] : $@thick Hive.Type):
// CHECK: [[SELF_BOX:%.*]] = alloc_box ${ var Hive }, let, name "self"
// CHECK: [[MU:%.*]] = mark_uninitialized [delegatingself] [[SELF_BOX]]
// CHECK: [[LIFETIME:%[^,]+]] = begin_borrow [lexical] [[MU]]
// CHECK: [[PB_BOX:%.*]] = project_box [[LIFETIME]] : ${ var Hive }, 0
// CHECK: [[BORROWED_QUEEN:%.*]] = begin_borrow [lexical] [[QUEEN]]
// CHECK: [[OBJC_META:%[0-9]+]] = thick_to_objc_metatype [[META]] : $@thick Hive.Type to $@objc_metatype Hive.Type
// CHECK: [[COPIED_BORROWED_QUEEN:%.*]] = copy_value [[BORROWED_QUEEN]]
// CHECK: [[OPT_COPIED_BORROWED_QUEEN:%.*]] = enum $Optional<Bee>, #Optional.some!enumelt, [[COPIED_BORROWED_QUEEN]]
// CHECK: [[FACTORY:%[0-9]+]] = objc_method [[OBJC_META]] : $@objc_metatype Hive.Type, #Hive.init!allocator.foreign : (Hive.Type) -> (Bee?) -> Hive?, $@convention(objc_method) (Optional<Bee>, @objc_metatype Hive.Type) -> @autoreleased Optional<Hive>
// CHECK: [[NEW_HIVE:%.*]] = apply [[FACTORY]]([[OPT_COPIED_BORROWED_QUEEN]], [[OBJC_META]]) : $@convention(objc_method) (Optional<Bee>, @objc_metatype Hive.Type) -> @autoreleased Optional<Hive>
// CHECK: destroy_value [[OPT_COPIED_BORROWED_QUEEN]]
// CHECK: switch_enum [[NEW_HIVE]] : $Optional<Hive>, case #Optional.some!enumelt: [[SOME_BB:bb[0-9]+]]
//
// CHECK: [[SOME_BB]]([[NEW_HIVE:%.*]] : @owned $Hive):
// CHECK: assign [[NEW_HIVE]] to [[PB_BOX]]
// CHECK: } // end sil function '$sSo4HiveC17objc_factory_initE10otherQueenABSo3BeeC_tcfC'
convenience init(otherQueen other: Bee) {
self.init(queen: other)
}
// CHECK-LABEL: sil hidden [ossa] @$sSo4HiveC17objc_factory_initE15otherFlakyQueenABSo3BeeC_tKcfC
// CHECK: bb0([[QUEEN:%.*]] : @owned $Bee, [[META:%.*]] : $@thick Hive.Type):
// CHECK: [[SELF_BOX:%.*]] = alloc_box ${ var Hive }, let, name "self"
// CHECK-NEXT: [[MU:%.*]] = mark_uninitialized [delegatingself] [[SELF_BOX]]
// CHECK-NEXT: [[LIFETIME:%[^,]+]] = begin_borrow [lexical] [[MU]]
// CHECK-NEXT: [[PB_BOX:%.*]] = project_box [[LIFETIME]] : ${ var Hive }, 0
// CHECK-NEXT: [[BORROWED_QUEEN:%.*]] = begin_borrow [lexical] [[QUEEN]]
// CHECK: [[FOREIGN_ERROR_STACK:%.*]] = alloc_stack [dynamic_lifetime] $Optional<NSError>
// CHECK: [[OBJC_META:%[0-9]+]] = thick_to_objc_metatype [[META]] : $@thick Hive.Type to $@objc_metatype Hive.Type
// CHECK: [[COPIED_BORROWED_QUEEN:%.*]] = copy_value [[BORROWED_QUEEN]]
// CHECK: [[OPT_COPIED_BORROWED_QUEEN:%.*]] = enum $Optional<Bee>, #Optional.some!enumelt, [[COPIED_BORROWED_QUEEN]]
// CHECK: [[FACTORY:%[0-9]+]] = objc_method [[OBJC_META]] : $@objc_metatype Hive.Type, #Hive.init!allocator.foreign : (Hive.Type) -> (Bee?) throws -> Hive, $@convention(objc_method) (Optional<Bee>, Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>, @objc_metatype Hive.Type) -> @autoreleased Optional<Hive>
// CHECK: [[ERROR_PTR_STACK:%.*]] = alloc_stack $AutoreleasingUnsafeMutablePointer<Optional<NSError>>
// CHECK: [[ERROR_PTR:%.*]] = load [trivial] [[ERROR_PTR_STACK]]
// CHECK: [[OPT_ERROR_PTR:%.*]] = enum $Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>, #Optional.some!enumelt, [[ERROR_PTR]]
// CHECK: [[OPT_NEW_HIVE:%.*]] = apply [[FACTORY]]([[OPT_COPIED_BORROWED_QUEEN]], [[OPT_ERROR_PTR]], [[OBJC_META]]) : $@convention(objc_method) (Optional<Bee>, Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>, @objc_metatype Hive.Type) -> @autoreleased Optional<Hive>
// CHECK: switch_enum [[OPT_NEW_HIVE]] : $Optional<Hive>, case #Optional.some!enumelt: [[NORMAL_BB:bb[0-9]+]], case #Optional.none!enumelt: [[ERROR_BB:bb[0-9]+]]
//
// CHECK: bb1([[HIVE:%.*]] : @owned $Hive):
// CHECK: assign [[HIVE]] to [[PB_BOX]]
// CHECK: dealloc_stack [[FOREIGN_ERROR_STACK]]
// CHECK: [[HIVE_COPY:%.*]] = load [copy] [[PB_BOX]]
// CHECK: return [[HIVE_COPY]]
// CHECK: bb2:
// CHECK: [[OPTIONAL_NSERROR:%.*]] = load [take] [[FOREIGN_ERROR_STACK]] : $*Optional<NSError>
// CHECK: [[CONVERT_NSERROR_TO_ERROR_FUNC:%.*]] = function_ref @$s10Foundation22_convertNSErrorToErrorys0E0_pSo0C0CSgF : $@convention(thin) (@guaranteed Optional<NSError>) -> @owned Error
// CHECK: [[ERROR:%.*]] = apply [[CONVERT_NSERROR_TO_ERROR_FUNC]]([[OPTIONAL_NSERROR]]) : $@convention(thin) (@guaranteed Optional<NSError>) -> @owned Error
// CHECK: "willThrow"([[ERROR]] : $Error)
// CHECK: dealloc_stack [[FOREIGN_ERROR_STACK]]
// CHECK: throw [[ERROR]] : $Error
// CHECK: } // end sil function '$sSo4HiveC17objc_factory_initE15otherFlakyQueenABSo3BeeC_tKcfC'
convenience init(otherFlakyQueen other: Bee) throws {
try self.init(flakyQueen: other)
}
}
extension SomeClass {
// CHECK-LABEL: sil hidden [ossa] @$sSo12IAMSomeClassC17objc_factory_initE6doubleABSd_tcfC
// CHECK: bb0([[DOUBLE:%.*]] : $Double,
// CHECK-NOT: value_metatype
// CHECK: [[FNREF:%[0-9]+]] = function_ref @MakeIAMSomeClass
// CHECK: apply [[FNREF]]([[DOUBLE]])
convenience init(double: Double) {
self.init(value: double)
}
}
class SubHive : Hive {
// CHECK-LABEL: sil hidden [ossa] @$s17objc_factory_init7SubHiveC20delegatesToInheritedACyt_tcfC
// CHECK: bb0([[METATYPE:%.*]] : $@thick SubHive.Type):
// CHECK: [[SELF_BOX:%.*]] = alloc_box ${ var SubHive }, let, name "self"
// CHECK: [[MU:%.*]] = mark_uninitialized [delegatingself] [[SELF_BOX]] : ${ var SubHive }
// CHECK: [[LIFETIME:%[^,]+]] = begin_borrow [lexical] [[MU]]
// CHECK: [[PB_BOX:%.*]] = project_box [[LIFETIME]] : ${ var SubHive }, 0
// CHECK: [[UP_METATYPE:%.*]] = upcast [[METATYPE]]
// CHECK: [[OBJC_METATYPE:%.*]] = thick_to_objc_metatype [[UP_METATYPE]]
// CHECK: [[QUEEN:%.*]] = unchecked_ref_cast {{.*}} : $Bee to $Optional<Bee>
// CHECK: [[HIVE_INIT_FN:%.*]] = objc_method [[OBJC_METATYPE]] : $@objc_metatype Hive.Type, #Hive.init!allocator.foreign
// CHECK: apply [[HIVE_INIT_FN]]([[QUEEN]], [[OBJC_METATYPE]]) : $@convention(objc_method) (Optional<Bee>, @objc_metatype Hive.Type) -> @autoreleased Optional<Hive>
// CHECK: destroy_value [[QUEEN]]
// CHECK: } // end sil function '$s17objc_factory_init7SubHiveC20delegatesToInheritedACyt_tcfC'
convenience init(delegatesToInherited: ()) {
self.init(queen: Bee())
}
}
|
apache-2.0
|
e3b92436cce9ab1e8a3c229779b21d93
| 70.872727 | 323 | 0.638882 | 3.387318 | false | false | false | false |
crossroadlabs/Express
|
Express/ViewEngine.swift
|
2
|
1066
|
//===--- ViewEngine.swift -------------------------------------------------===//
//
//Copyright (c) 2015-2016 Daniel Leping (dileping)
//
//This file is part of Swift Express.
//
//Swift Express is free software: you can redistribute it and/or modify
//it under the terms of the GNU Lesser General Public License as published by
//the Free Software Foundation, either version 3 of the License, or
//(at your option) any later version.
//
//Swift Express 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 Lesser General Public License for more details.
//
//You should have received a copy of the GNU Lesser General Public License
//along with Swift Express. If not, see <http://www.gnu.org/licenses/>.
//
//===----------------------------------------------------------------------===//
import Foundation
public protocol ViewEngineType {
func extensions() -> Array<String>
func view(filePath:String) throws -> ViewType
}
|
gpl-3.0
|
8adb2c02a91d6d9f0fbcfecfe651f88a
| 38.518519 | 80 | 0.650094 | 4.737778 | false | false | false | false |
kstaring/swift
|
validation-test/compiler_crashers_fixed/00136-swift-modulefile-getimportedmodules.swift
|
11
|
597
|
// This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -parse
}
func ^(r: l, k) -> k {
? {
h (s : t?) q u {
g let d = s {
p d
}
}
e}
let u : [Int?] = [n{
c v: j t.v == m>(n: o<t>) {
}
}
class r {
typealias n = n
|
apache-2.0
|
d470e51113274e97130315bfdf5f0999
| 24.956522 | 78 | 0.58794 | 3.244565 | false | false | false | false |
CatchChat/Yep
|
Yep/ViewControllers/Register/RegisterPickNameViewController.swift
|
1
|
4865
|
//
// RegisterPickNameViewController.swift
// Yep
//
// Created by NIX on 15/3/16.
// Copyright (c) 2015年 Catch Inc. All rights reserved.
//
import UIKit
import YepKit
import Ruler
import RxSwift
import RxCocoa
final class RegisterPickNameViewController: BaseViewController {
var mobile: String?
var areaCode: String?
private lazy var disposeBag = DisposeBag()
@IBOutlet private weak var pickNamePromptLabel: UILabel!
@IBOutlet private weak var pickNamePromptLabelTopConstraint: NSLayoutConstraint!
@IBOutlet private weak var promptTermsLabel: UILabel!
@IBOutlet private weak var nameTextField: BorderTextField!
@IBOutlet private weak var nameTextFieldTopConstraint: NSLayoutConstraint!
private lazy var nextButton: UIBarButtonItem = {
let button = UIBarButtonItem()
button.title = NSLocalizedString("Next", comment: "")
button.rx_tap
.subscribeNext({ [weak self] in self?.showRegisterPickMobile() })
.addDisposableTo(self.disposeBag)
return button
}()
private var isDirty = false {
willSet {
nextButton.enabled = newValue
promptTermsLabel.alpha = newValue ? 1.0 : 0.5
}
}
deinit {
println("deinit RegisterPickName")
}
override func viewDidLoad() {
super.viewDidLoad()
animatedOnNavigationBar = false
view.backgroundColor = UIColor.yepViewBackgroundColor()
navigationItem.titleView = NavigationTitleLabel(title: NSLocalizedString("Sign Up", comment: ""))
navigationItem.rightBarButtonItem = nextButton
pickNamePromptLabel.text = NSLocalizedString("What's your name?", comment: "")
let text = String.trans_promptTapNextAgreeTerms
let textAttributes: [String: AnyObject] = [
NSFontAttributeName: UIFont.systemFontOfSize(14),
NSForegroundColorAttributeName: UIColor.grayColor(),
]
let attributedText = NSMutableAttributedString(string: text, attributes: textAttributes)
let termsAttributes: [String: AnyObject] = [
NSForegroundColorAttributeName: UIColor.yepTintColor(),
NSUnderlineStyleAttributeName: NSUnderlineStyle.StyleSingle.rawValue,
]
let tapRange = (text as NSString).rangeOfString(NSLocalizedString("terms", comment: ""))
attributedText.addAttributes(termsAttributes, range: tapRange)
promptTermsLabel.attributedText = attributedText
promptTermsLabel.textAlignment = .Center
promptTermsLabel.alpha = 0.5
promptTermsLabel.userInteractionEnabled = true
let tap = UITapGestureRecognizer(target: self, action: #selector(RegisterPickNameViewController.tapTerms(_:)))
promptTermsLabel.addGestureRecognizer(tap)
nameTextField.backgroundColor = UIColor.whiteColor()
nameTextField.textColor = UIColor.yepInputTextColor()
nameTextField.placeholder = " "
nameTextField.delegate = self
nameTextField.rx_text
.map({ !$0.isEmpty })
.subscribeNext({ [weak self] in self?.isDirty = $0 })
.addDisposableTo(disposeBag)
pickNamePromptLabelTopConstraint.constant = Ruler.iPhoneVertical(30, 50, 60, 60).value
nameTextFieldTopConstraint.constant = Ruler.iPhoneVertical(30, 40, 50, 50).value
nextButton.enabled = false
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
nameTextField.becomeFirstResponder()
}
// MARK: Actions
@objc private func tapTerms(sender: UITapGestureRecognizer) {
if let URL = NSURL(string: YepConfig.termsURLString) {
yep_openURL(URL)
}
}
private func showRegisterPickMobile() {
guard let text = nameTextField.text else {
return
}
let nickname = text.trimming(.WhitespaceAndNewline)
YepUserDefaults.nickname.value = nickname
performSegueWithIdentifier("showRegisterPickMobile", sender: nil)
}
// MARK: Navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
guard let identifier = segue.identifier else {
return
}
switch identifier {
case "showRegisterPickMobile":
let vc = segue.destinationViewController as! RegisterPickMobileViewController
vc.mobile = mobile
vc.areaCode = areaCode
default:
break
}
}
}
extension RegisterPickNameViewController: UITextFieldDelegate {
func textFieldShouldReturn(textField: UITextField) -> Bool {
guard let text = textField.text else {
return true
}
if !text.isEmpty {
showRegisterPickMobile()
}
return true
}
}
|
mit
|
fd4ceaa4f85a4c85ffac4f16b23c045f
| 28.834356 | 118 | 0.66605 | 5.403333 | false | false | false | false |
ycaihua/Paranormal
|
Paranormal/Paranormal/Tools/BrushTool.swift
|
3
|
2991
|
import Foundation
import Foundation
public class BrushTool : NSObject, EditorActiveTool {
public var editLayer : Layer?
public var drawingKernel : DrawingKernel?
override init() {
super.init()
}
func lazySetupKernel(size : CGSize) {
if drawingKernel == nil {
drawingKernel = GLDrawingKernel(size: size)
}
}
func initializeEditLayer() {
}
public func mouseDownAtPoint(point : NSPoint, editorViewController: EditorViewController) {
if let currentLayer = editorViewController.currentLayer {
lazySetupKernel(currentLayer.size)
}
editLayer = editorViewController.currentLayer?.createEditLayer()
if let brushOpacity = editorViewController.brushOpacity {
editLayer?.opacity = Float(brushOpacity)
}
initializeEditLayer()
drawingKernel?.startDraw() { [unowned self] (image) -> () in
autoreleasepool {
let data = image.TIFFRepresentation
self.editLayer?.managedObjectContext?.performBlock({ () -> Void in
self.editLayer?.imageData = data
return
})
return
}
return
}
editorViewController.document?.managedObjectContext.undoManager?.beginUndoGrouping()
}
public func mouseDraggedAtPoint(point : NSPoint, editorViewController: EditorViewController) {
if let brushSize = editorViewController.brushSize {
if let color = editorViewController.color {
if let hardness = editorViewController.brushHardness {
let b =
Brush(size: CGFloat(brushSize), color: color, hardness: CGFloat(hardness))
drawingKernel?.addPoint(point, brush: b)
}
}
}
}
public func mouseUpAtPoint(point : NSPoint, editorViewController: EditorViewController) {
if let brushSize = editorViewController.brushSize {
if let color = editorViewController.color {
if let hardness = editorViewController.brushHardness {
let b =
Brush(size: CGFloat(brushSize), color: color, hardness: CGFloat(hardness))
drawingKernel?.addPoint(point, brush: b)
}
}
}
drawingKernel?.stopDraw() {
self.editLayer?.managedObjectContext?.performBlockAndWait({ () -> Void in
if let layer = self.editLayer {
editorViewController.currentLayer?.combineLayerOntoSelf(layer)
}
self.editLayer = nil
editorViewController.document?.managedObjectContext.undoManager?.endUndoGrouping()
return
})
return
}
}
// Call when no longer using the tool.
public func stopUsingTool() {
drawingKernel?.destroy()
}
}
|
mit
|
e919eb5b885b0978fd428650e116116d
| 32.988636 | 98 | 0.587429 | 5.40868 | false | false | false | false |
jpush/jchat-swift
|
JChat/Src/ChatModule/Chat/View/JCUpdateMemberCell.swift
|
1
|
1607
|
//
// JCUpdateMemberCell.swift
// JChat
//
// Created by JIGUANG on 2017/5/11.
// Copyright © 2017年 HXHG. All rights reserved.
//
import UIKit
import JMessage
class JCUpdateMemberCell: UICollectionViewCell {
var avator: UIImage? {
get {
return avatorView.image
}
set {
avatorView.image = newValue
}
}
public override init(frame: CGRect) {
super.init(frame: frame)
_init()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
_init()
}
private var avatorView: UIImageView = UIImageView()
private lazy var defaultUserIcon = UIImage.loadImage("com_icon_user_36")
private func _init() {
avatorView.image = defaultUserIcon
addSubview(avatorView)
addConstraint(_JCLayoutConstraintMake(avatorView, .centerY, .equal, contentView, .centerY))
addConstraint(_JCLayoutConstraintMake(avatorView, .width, .equal, nil, .notAnAttribute, 36))
addConstraint(_JCLayoutConstraintMake(avatorView, .height, .equal, nil, .notAnAttribute, 36))
addConstraint(_JCLayoutConstraintMake(avatorView, .centerX, .equal, contentView, .centerX))
}
func bindDate(user: JMSGUser) {
user.thumbAvatarData { (data, id, error) in
if let data = data {
let image = UIImage(data: data)
self.avatorView.image = image
} else {
self.avatorView.image = self.defaultUserIcon
}
}
}
}
|
mit
|
e368eaf7cfa996697499e6c022cb0b8b
| 26.655172 | 101 | 0.598504 | 4.480447 | false | false | false | false |
plenprojectcompany/plen-Scenography_iOS
|
PLENConnect/Connect/Framework/DragEvent/ActualDragGestureRecognizerTarget.swift
|
1
|
5874
|
//
// ActualDragGestureRecognizerTarget.swift
// PLEN Connect
//
// Created by Trevin Wisaksana on 5/18/17.
// Copyright © 2017 PLEN Project. All rights reserved.
//
import Foundation
import UIKit
class _ActualDragGestureRecognizerTarget: NSObject {
static let _action = Selector(("respondToDragGesture:"))
fileprivate weak var _dragShadow: UIView?
fileprivate var _viewsUnderShadow: [Weak<UIView>] = []
fileprivate var _compositTarget: DragGestureRecognizerTarget
init(compositTarget: DragGestureRecognizerTarget) {
self._compositTarget = compositTarget
super.init()
}
// MARK: Gesture Recognizer
func respondToDragGesture(_ gestureRecognizer: UIGestureRecognizer) {
switch gestureRecognizer.state {
case .began:
// create drag shadow
guard let dragShadow = createDragShadow(gestureRecognizer) else {break}
// display drag shadow
let root = UIViewUtil.root(gestureRecognizer.view!)
root.addSubview(dragShadow)
root.bringSubview(toFront: dragShadow)
// Began
self._dragShadow = dragShadow
_viewsUnderShadow = []
broadcastDragBeganEvent(gestureRecognizer)
// Enterd, Moved
respondToDragGestureChanged(gestureRecognizer)
case .changed:
// Exited, Enterd, Moved
respondToDragGestureChanged(gestureRecognizer)
case .ended:
// Drop
postDropEvent(gestureRecognizer)
// Ended
_viewsUnderShadow = []
broadcastDragBeganEvent(gestureRecognizer)
_dragShadow?.removeFromSuperview()
_dragShadow = nil
default:
break
}
}
fileprivate func respondToDragGestureChanged(_ gestureRecognizer: UIGestureRecognizer) {
_ = updateDragShadow(gestureRecognizer)
// Exited, Entered
guard let dragShadow = _dragShadow else {return}
let root = UIViewUtil.root(dragShadow)
let oldViews = _viewsUnderShadow.flatMap {$0.value}
let newViews = UIViewUtil.find(root) {!$0.contains(dragShadow) && $0.last!.point(inside: gestureRecognizer.location(in: $0.last!), with: nil)}
.reversed()
.flatMap {$0.last}
let exitedViews = oldViews.filter {!newViews.contains($0)}
let enteredViews = newViews.filter {!oldViews.contains($0)}
_viewsUnderShadow = newViews.map {Weak(value: $0)}
postExitedEvent(gestureRecognizer, toViews: exitedViews)
postEnteredEvent(gestureRecognizer, toViews: enteredViews)
// Moved
postMovedEvent(gestureRecognizer)
}
// MARK: - Post Event
func broadcastDragBeganEvent(_ gestureRecognizer: UIGestureRecognizer) {
DragEventCenter.postEventToAllViews(gestureRecognizer: gestureRecognizer, state: .began)
}
func postEnteredEvent(_ gestureRecognizer: UIGestureRecognizer, toViews enteredViews: [UIView]) {
DragEventCenter.postEventToViews(enteredViews, gestureRecognizer: gestureRecognizer, state: .entered)
}
func postMovedEvent(_ gestureRecognizer: UIGestureRecognizer) {
DragEventCenter.postEventToViews(_viewsUnderShadow.flatMap {$0.value},
gestureRecognizer: gestureRecognizer,
state: .moved)
}
func postExitedEvent(_ gestureRecognizer: UIGestureRecognizer, toViews exitedViews: [UIView]) {
DragEventCenter.postEventToViews(exitedViews,
gestureRecognizer: gestureRecognizer,
state: .exited)
}
fileprivate func postDropEvent(_ gestureRecognizer: UIGestureRecognizer) {
let clipData = createClipData(gestureRecognizer)
DragEventCenter.postEventToViews(_viewsUnderShadow.flatMap {$0.value},
gestureRecognizer: gestureRecognizer,
state: .drop(clipData: clipData))
}
func broadcastDragEndedEvent(_ gestureRecognizer: UIGestureRecognizer) {
DragEventCenter.postEventToAllViews(gestureRecognizer: gestureRecognizer, state: .ended)
}
// MARK: - Drag Shdadow
fileprivate func createDragShadow(_ gestureRecognizer: UIGestureRecognizer) -> UIView? {
return _compositTarget.delegate?.dragGestureRecognizerTargetShouldCreateDragShadow(_compositTarget,
gestureRecognizer: gestureRecognizer)
}
fileprivate func updateDragShadow(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
guard let dragShadow = _dragShadow else {return false}
return _compositTarget.delegate?.dragGestureRecognizerTarget(_compositTarget,
gestureRecognizer: gestureRecognizer,
shouldUpdateDragShadow: dragShadow) ?? false
}
fileprivate func createClipData(_ gestureRecognizer: UIGestureRecognizer) -> Any? {
guard let dragShadow = _dragShadow else {return nil}
return _compositTarget.delegate?.dragGestureRecognizerTargetShouldCreateClipData(_compositTarget,
gestureRecognizer: gestureRecognizer,
dragShadow: dragShadow)
}
}
|
mit
|
e6094198d1aa9123290d14e16cfea965
| 38.952381 | 150 | 0.593734 | 5.820614 | false | false | false | false |
lizhihui0215/PCCWFoundationSwift
|
Source/Device+PFS.swift
|
1
|
2294
|
//
// Device+PFS.swift
// PCCWFoundationSwift
//
// Created by 李智慧 on 21/04/2017.
//
//
import DeviceKit
import KeychainAccess
public let keychain = Keychain()
public let device = Device()
extension Device {
public var appVersion: String {
return Bundle.main.infoDictionary!["CFBundleShortVersionString"] as! String
}
public var appName: String{
return Bundle.main.infoDictionary!["CFBundleExecutable"] as! String
}
public var screenSize: CGSize {
return UIScreen.main.bounds.size
}
public var uuid: String {
if let uuid = keychain["uuid"] {
return uuid
}
let uuid = UUID().uuidString
keychain["uuid"] = uuid
return uuid
}
// Return IP address of WiFi interface (en0) as a String, or `nil`
public func getWiFiAddress() -> String? {
var address : String?
// Get list of all interfaces on the local machine:
var ifaddr : UnsafeMutablePointer<ifaddrs>?
guard getifaddrs(&ifaddr) == 0 else { return nil }
guard let firstAddr = ifaddr else { return nil }
// For each interface ...
for ifptr in sequence(first: firstAddr, next: { $0.pointee.ifa_next }) {
let interface = ifptr.pointee
// Check for IPv4 or IPv6 interface:
let addrFamily = interface.ifa_addr.pointee.sa_family
if addrFamily == UInt8(AF_INET) || addrFamily == UInt8(AF_INET6) {
// Check interface name:
let name = String(cString: interface.ifa_name)
if name == "en0" {
// Convert interface address to a human readable string:
var hostname = [CChar](repeating: 0, count: Int(NI_MAXHOST))
getnameinfo(interface.ifa_addr, socklen_t(interface.ifa_addr.pointee.sa_len),
&hostname, socklen_t(hostname.count),
nil, socklen_t(0), NI_NUMERICHOST)
address = String(cString: hostname)
}
}
}
freeifaddrs(ifaddr)
return address
}
}
|
mit
|
88a256bb9e97d5241b92debe1f74b124
| 29.105263 | 97 | 0.541958 | 4.688525 | false | false | false | false |
paidy/paidy-ios
|
PaidyCheckoutSDK/PaidyCheckoutSDK/IntroViewController.swift
|
1
|
3307
|
//
// IntroViewController.swift
// Paidycheckoutsdk
//
// Copyright (c) 2015 Paidy. All rights reserved.
//
import UIKit
class IntroViewController: UIViewController {
@IBOutlet var introText: UILabel!
@IBOutlet var point1Text: UILabel!
@IBOutlet var point2Text: UILabel!
@IBOutlet var point3Text: UILabel!
@IBOutlet var introButton: UIButton!
var authRequest: AuthRequest!
var status: String
// custom init
init(status: String)
{
self.status = status
let frameworkBundle = NSBundle(identifier: "com.paidy.PaidyCheckoutSDK")
super.init(nibName: "IntroViewController", bundle: frameworkBundle)
}
// require init
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
// get authRequest from parent
let paidyCheckoutViewController: PaidyCheckOutViewController = self.parentViewController as! PaidyCheckOutViewController
authRequest = paidyCheckoutViewController.authRequest
// configure intro copy based on subscription
if (authRequest.subscription != nil){
introText.text = "クレジットカード不要の簡単決済!\n購入金額に応じて分割払いも可能。"
point1Text.text = "メールアドレスと携帯電話番号で\n決済手続き完了"
point2Text.text = "1回の注文手続きで\n定期購入受付完了"
point3Text.text = "ご利用金額を翌月10日にコンビニ\nまたは銀行振込でお支払い"
} else {
introText.text = "クレジットカード不要の簡単決済!\n購入金額に応じて分割払いも可能。"
point1Text.text = "メールアドレスと携帯電話番号で\n決済手続き完了"
point2Text.text = "1ヵ月のご利用分をまとめた\n請求書を翌月1日に発行"
point3Text.text = "翌月10日までにコンビニまたは\n銀行振込でお支払い"
}
// set button style
introButton.layer.cornerRadius = 5
introButton.layer.masksToBounds = true
}
override func viewWillAppear(animated: Bool){
super.viewWillAppear(animated)
view.alpha = 0
}
override func viewDidAppear(animated: Bool) {
super.viewWillAppear(true)
if (status == "launch"){
introButton.titleLabel?.text = "次へ"
} else {
introButton.titleLabel?.text = "戻る"
}
UIView.animateWithDuration(0.3, animations: {
self.view.alpha = 1.0
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// next button pressed
@IBAction func introNext(sender: UIButton) {
let paidyCheckoutViewController: PaidyCheckOutViewController = self.parentViewController as! PaidyCheckOutViewController
if (status == "launch") {
paidyCheckoutViewController.router("start", reason: nil)
} else {
paidyCheckoutViewController.closeIntro()
}
}
}
|
mit
|
c7031d6f0c20a4cb304134c3e4da2b01
| 30.641304 | 128 | 0.637582 | 3.620647 | false | false | false | false |
ReiVerdugo/uikit-fundamentals
|
step6.3-bondVillains-tabs-noCollectionView/BondVillains/ViewController.swift
|
1
|
1721
|
//
// ViewController.swift
// BondVillains
//
// Created by Jason on 11/19/14.
// Copyright (c) 2014 Udacity. All rights reserved.
//
import UIKit
// MARK: - ViewController: UIViewController, UITableViewDataSource
class ViewController: UIViewController, UITableViewDataSource {
// MARK: Properties
// Get ahold of some villains, for the table
// This is an array of Villain instances
let allVillains = Villain.allVillains
// MARK: Table View Data Source
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.allVillains.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("VillainCell")!
let villain = self.allVillains[indexPath.row]
// Set the name and image
cell.textLabel?.text = villain.name
cell.imageView?.image = UIImage(named: villain.imageName)
// If the cell has a detail label, we will put the evil scheme in.
if let detailTextLabel = cell.detailTextLabel {
detailTextLabel.text = "Scheme: \(villain.evilScheme)"
}
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let detailController = self.storyboard!.instantiateViewControllerWithIdentifier("VillainDetailViewController") as! VillainDetailViewController
detailController.villain = self.allVillains[indexPath.row]
self.navigationController!.pushViewController(detailController, animated: true)
}
}
|
mit
|
603273f846358b7e1b1cc51fab366f0f
| 32.745098 | 150 | 0.685648 | 5.361371 | false | false | false | false |
googleprojectzero/fuzzilli
|
Sources/Fuzzilli/Mutators/InputMutator.swift
|
1
|
2675
|
// Copyright 2019 Google LLC
//
// 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
//
// https://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.
/// A mutator that changes the input variables of instructions in a program.
public class InputMutator: BaseInstructionMutator {
/// Whether this instance is type aware or not.
/// A type aware InputMutator will attempt to find "compatible" replacement
/// variables, which have roughly the same type as the replaced variable.
public let isTypeAware: Bool
/// The name of this mutator.
public override var name: String {
return isTypeAware ? "InputMutator (type aware)" : "InputMutator"
}
public init(isTypeAware: Bool) {
self.isTypeAware = isTypeAware
var maxSimultaneousMutations = defaultMaxSimultaneousMutations
// A type aware instance can be more aggressive. Based on simple experiments and
// the mutator correctness rates, it can very roughly be twice as aggressive.
if isTypeAware {
maxSimultaneousMutations *= 2
}
super.init(maxSimultaneousMutations: maxSimultaneousMutations)
}
public override func canMutate(_ instr: Instruction) -> Bool {
return instr.numInputs > 0
}
public override func mutate(_ instr: Instruction, _ b: ProgramBuilder) {
var inouts = b.adopt(instr.inouts)
// Replace one input
let selectedInput = Int.random(in: 0..<instr.numInputs)
// Inputs to block end instructions must be taken from the outer scope since the scope
// closed by the instruction is currently still active.
let replacement: Variable
if (isTypeAware) {
let type = b.type(of: inouts[selectedInput]).generalize()
// We are guaranteed to find at least the current input.
replacement = b.randVar(ofType: type, excludeInnermostScope: instr.isBlockEnd)!
} else {
replacement = b.randVar(excludeInnermostScope: instr.isBlockEnd)
}
b.trace("Replacing input \(selectedInput) (\(inouts[selectedInput])) with \(replacement)")
inouts[selectedInput] = replacement
b.append(Instruction(instr.op, inouts: inouts))
}
}
|
apache-2.0
|
429f9672e70fd29376884085428ef7c4
| 42.145161 | 98 | 0.689346 | 4.526227 | false | false | false | false |
qiuncheng/study-for-swift
|
learn-rx-swift/Chocotastic-starter/Chocotastic/Extensions/String+CreditCard.swift
|
3
|
2819
|
/**
* Copyright (c) 2016 Razeware LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
import Foundation
extension String {
func rw_allCharactersAreNumbers() -> Bool {
let nonNumberCharacterSet = NSCharacterSet.decimalDigits.inverted
return (self.rangeOfCharacter(from: nonNumberCharacterSet) == nil)
}
func rw_integerValueOfFirst(characters: Int) -> Int {
guard rw_allCharactersAreNumbers() else {
return NSNotFound
}
if characters > self.characters.count {
return NSNotFound
}
let indexToStopAt = self.index(self.startIndex, offsetBy: characters)
let substring = self.substring(to: indexToStopAt)
guard let integerValue = Int(substring) else {
return NSNotFound
}
return integerValue
}
func rw_isLuhnValid() -> Bool {
//https://www.rosettacode.org/wiki/Luhn_test_of_credit_card_numbers
guard self.rw_allCharactersAreNumbers() else {
//Definitely not valid.
return false
}
let reversed = self.characters.reversed().map { String($0) }
var sum = 0
for (index, element) in reversed.enumerated() {
guard let digit = Int(element) else {
//This is not a number.
return false
}
if index % 2 == 1 {
//Even digit
switch digit {
case 9:
//Just add nine.
sum += 9
default:
//Multiply by 2, then take the remainder when divided by 9 to get addition of digits.
sum += ((digit * 2) % 9)
}
} else {
//Odd digit
sum += digit
}
}
//Valid if divisible by 10
return sum % 10 == 0
}
func rw_removeSpaces() -> String {
return self.replacingOccurrences(of: " ", with: "")
}
}
|
mit
|
7d10a6e8183fa87c523f41395b1c5bc2
| 29.978022 | 95 | 0.658744 | 4.467512 | false | false | false | false |
volythat/HNHelper
|
HNHelper/Helper/HNShare.swift
|
1
|
2756
|
//
// HNShare.swift
//
//
// Created by oneweek on 5/22/17.
// Copyright © 2017 Harry Nguyen. All rights reserved.
//
//import UIKit
//import FBSDKShareKit
//import FacebookCore
//
//class HNShare: NSObject {
// static let shared: HNShare = {
// var instance = HNShare()
// // setup code
//
// return instance
// }()
//
// typealias completed = (_ shared:Bool) -> Void
// var completedShare: completed?
//
// class func shareApp(_ vc : UIViewController){
// if let myWebsite = URL(string: linkItunes) {
// let share = FBSDKShareLinkContent()
// share.contentURL = myWebsite
// share.hashtag = FBSDKHashtag(string: hashTagFb)
//
// let facebookURL = URL(string: "fbauth2://app")
// if(UIApplication.shared.canOpenURL(facebookURL!)){
// FBSDKShareDialog.show(from: vc, with: share, delegate: nil)
// }else{
// let dialog : FBSDKShareDialog = FBSDKShareDialog()
// dialog.fromViewController = vc
// dialog.shareContent = share
// dialog.mode = FBSDKShareDialogMode.feedWeb
// dialog.show()
// }
// }
// }
//
// func shareApp(_ vc: UIViewController, completed:@escaping completed){
// self.completedShare = completed
// if let myWebsite = URL(string: linkItunes) {
// let share = FBSDKShareLinkContent()
// share.contentURL = myWebsite
// share.hashtag = FBSDKHashtag(string: hashTagFb)
//
// let facebookURL = URL(string: "fbauth2://app")
// if(UIApplication.shared.canOpenURL(facebookURL!)){
// FBSDKShareDialog.show(from: vc, with: share, delegate: self)
// }else{
// let dialog : FBSDKShareDialog = FBSDKShareDialog()
// dialog.fromViewController = vc
// dialog.shareContent = share
// dialog.delegate = self
// dialog.mode = FBSDKShareDialogMode.feedWeb
// dialog.show()
// }
// }
// }
//}
//extension HNShare : FBSDKSharingDelegate {
// //MARK: - Delegate
// func sharerDidCancel(_ sharer: FBSDKSharing!) {
// LogD("cancel")
// self.completedShare?(false)
// }
// func sharer(_ sharer: FBSDKSharing!, didFailWithError error: Error!) {
// LogD("didFailWithError = \(error.localizedDescription)")
// self.completedShare?(false)
// }
// func sharer(_ sharer: FBSDKSharing!, didCompleteWithResults results: [AnyHashable : Any]!) {
// LogD("didCompleteWithResults = \(results)")
// self.completedShare?(true)
// }
//}
|
mit
|
be87465bad1162093549669fb82052a8
| 34.320513 | 98 | 0.55971 | 4.039589 | false | false | false | false |
tjw/swift
|
stdlib/public/core/SequenceWrapper.swift
|
4
|
4060
|
//===--- SequenceWrapper.swift - sequence/collection wrapper protocols ----===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// To create a Sequence that forwards requirements to an
// underlying Sequence, have it conform to this protocol.
//
//===----------------------------------------------------------------------===//
/// A type that is just a wrapper over some base Sequence
@_show_in_interface
public // @testable
protocol _SequenceWrapper : Sequence {
associatedtype Base : Sequence where Base.Element == Element
associatedtype Iterator = Base.Iterator
associatedtype SubSequence = Base.SubSequence
var _base: Base { get }
}
extension _SequenceWrapper {
@inlinable // FIXME(sil-serialize-all)
public var underestimatedCount: Int {
return _base.underestimatedCount
}
@inlinable // FIXME(sil-serialize-all)
public func _preprocessingPass<R>(
_ preprocess: () throws -> R
) rethrows -> R? {
return try _base._preprocessingPass(preprocess)
}
}
extension _SequenceWrapper where Iterator == Base.Iterator {
@inlinable // FIXME(sil-serialize-all)
public func makeIterator() -> Iterator {
return self._base.makeIterator()
}
@inlinable // FIXME(sil-serialize-all)
@discardableResult
public func _copyContents(
initializing buf: UnsafeMutableBufferPointer<Element>
) -> (Iterator, UnsafeMutableBufferPointer<Element>.Index) {
return _base._copyContents(initializing: buf)
}
}
extension _SequenceWrapper {
@inlinable // FIXME(sil-serialize-all)
public func map<T>(
_ transform: (Element) throws -> T
) rethrows -> [T] {
return try _base.map(transform)
}
@inlinable // FIXME(sil-serialize-all)
public func filter(
_ isIncluded: (Element) throws -> Bool
) rethrows -> [Element] {
return try _base.filter(isIncluded)
}
@inlinable // FIXME(sil-serialize-all)
public func forEach(_ body: (Element) throws -> Void) rethrows {
return try _base.forEach(body)
}
@inlinable // FIXME(sil-serialize-all)
public func _customContainsEquatableElement(
_ element: Element
) -> Bool? {
return _base._customContainsEquatableElement(element)
}
@inlinable // FIXME(sil-serialize-all)
public func _copyToContiguousArray()
-> ContiguousArray<Element> {
return _base._copyToContiguousArray()
}
}
extension _SequenceWrapper where SubSequence == Base.SubSequence {
@inlinable // FIXME(sil-serialize-all)
public func dropFirst(_ n: Int) -> SubSequence {
return _base.dropFirst(n)
}
@inlinable // FIXME(sil-serialize-all)
public func dropLast(_ n: Int) -> SubSequence {
return _base.dropLast(n)
}
@inlinable // FIXME(sil-serialize-all)
public func prefix(_ maxLength: Int) -> SubSequence {
return _base.prefix(maxLength)
}
@inlinable // FIXME(sil-serialize-all)
public func suffix(_ maxLength: Int) -> SubSequence {
return _base.suffix(maxLength)
}
@inlinable // FIXME(sil-serialize-all)
public func drop(
while predicate: (Element) throws -> Bool
) rethrows -> SubSequence {
return try _base.drop(while: predicate)
}
@inlinable // FIXME(sil-serialize-all)
public func prefix(
while predicate: (Element) throws -> Bool
) rethrows -> SubSequence {
return try _base.prefix(while: predicate)
}
@inlinable // FIXME(sil-serialize-all)
public func split(
maxSplits: Int, omittingEmptySubsequences: Bool,
whereSeparator isSeparator: (Element) throws -> Bool
) rethrows -> [SubSequence] {
return try _base.split(
maxSplits: maxSplits,
omittingEmptySubsequences: omittingEmptySubsequences,
whereSeparator: isSeparator
)
}
}
|
apache-2.0
|
3d74726981612433cb212721ecb44bf5
| 29.074074 | 80 | 0.669704 | 4.408252 | false | false | false | false |
lorentey/swift
|
stdlib/public/Darwin/Accelerate/vDSP_ComplexOperations.swift
|
8
|
21359
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2019 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
extension vDSP {
//===----------------------------------------------------------------------===//
//
// Phase calculation
//
//===----------------------------------------------------------------------===//
/// Populates `result` with the elementwise phase values, in radians, of the supplied complex vector; single-precision.
///
/// - Parameter splitComplex: Single-precision complex input vector.
/// - Parameter result: Single-precision real output vector.
@inlinable
public static func phase<V>(_ splitComplex: DSPSplitComplex,
result: inout V)
where
V: AccelerateMutableBuffer,
V.Element == Float {
let n = vDSP_Length(result.count)
result.withUnsafeMutableBufferPointer { dest in
withUnsafePointer(to: splitComplex) { src in
vDSP_zvphas(src, 1,
dest.baseAddress!, 1,
n)
}
}
}
/// Populates `result` with the elementwise phase values, in radians, of the supplied complex vector; double-precision.
///
/// - Parameter splitComplex: Double-precision complex input vector.
/// - Parameter result: Double-precision real output vector.
@inlinable
public static func phase<V>(_ splitComplex: DSPDoubleSplitComplex,
result: inout V)
where
V: AccelerateMutableBuffer,
V.Element == Double {
let n = vDSP_Length(result.count)
result.withUnsafeMutableBufferPointer { dest in
withUnsafePointer(to: splitComplex) { src in
vDSP_zvphasD(src, 1,
dest.baseAddress!, 1,
n)
}
}
}
//===----------------------------------------------------------------------===//
//
// Complex vector copying
//
//===----------------------------------------------------------------------===//
/// Copies a complex vector; single-precision.
///
/// - Parameter source: Single-precision complex input vector.
/// - Parameter destination: Single-precision real output vector.
@inlinable
public static func copy(_ source: DSPSplitComplex,
to destination: inout DSPSplitComplex,
count: Int) {
let n = vDSP_Length(count)
withUnsafePointer(to: source) { src in
vDSP_zvmov(src, 1,
&destination, 1,
n)
}
}
/// Copies a complex vector; double-precision.
///
/// - Parameter source: Double-precision complex input vector.
/// - Parameter destination: Double-precision real output vector.
@inlinable
public static func copy(_ source: DSPDoubleSplitComplex,
to destination: inout DSPDoubleSplitComplex,
count: Int) {
let n = vDSP_Length(count)
withUnsafePointer(to: source) { src in
vDSP_zvmovD(src, 1,
&destination, 1,
n)
}
}
//===----------------------------------------------------------------------===//
//
// Complex vector conjugate
//
//===----------------------------------------------------------------------===//
/// Populates `result` with the conjugate of `splitComplex`; single-precision.
///
/// - Parameter splitComplex: the `A` in `C[n] = conj(A[n])`.
/// - Parameter result: The `C` in `C[n] = conj(A[n])`.
@inlinable
public static func conjugate(_ splitComplex: DSPSplitComplex,
count: Int,
result: inout DSPSplitComplex) {
withUnsafePointer(to: splitComplex) { a in
vDSP_zvconj(a, 1,
&result, 1,
vDSP_Length(count))
}
}
/// Populates `result` with the conjugate of `splitComplex`; double-precision.
///
/// - Parameter splitComplex: the `A` in `C[n] = conj(A[n])`.
/// - Parameter result: The `C` in `C[n] = conj(A[n])`.
@inlinable
public static func conjugate(_ splitComplex: DSPDoubleSplitComplex,
count: Int,
result: inout DSPDoubleSplitComplex) {
withUnsafePointer(to: splitComplex) { a in
vDSP_zvconjD(a, 1,
&result, 1,
vDSP_Length(count))
}
}
//===----------------------------------------------------------------------===//
//
// Complex vector arithmetic
//
//===----------------------------------------------------------------------===//
/// Populates `result` with the elementwise division of `splitComplex` and `vector`,
/// single-precision.
///
/// - Parameter splitComplex: the `a` in `c[i] = a[i] / b[i]`.
/// - Parameter vector: the `b` in `c[i] = a[i] / b[i]`.
/// - Parameter result: The `c` in `c[i] = a[i] / b[i]`.
@inlinable
public static func divide<U>(_ splitComplex: DSPSplitComplex,
by vector: U,
result: inout DSPSplitComplex)
where
U: AccelerateBuffer,
U.Element == Float {
withUnsafePointer(to: splitComplex) { a in
vector.withUnsafeBufferPointer { b in
vDSP_zrvdiv(a, 1,
b.baseAddress!, 1,
&result, 1,
vDSP_Length(vector.count))
}
}
}
/// Populates `result` with the elementwise division of `splitComplex` and `vector`,
/// double-precision.
///
/// - Parameter splitComplex: the `a` in `c[i] = a[i] / b[i]`.
/// - Parameter vector: the `b` in `c[i] = a[i] / b[i]`.
/// - Parameter result: The `c` in `c[i] = a[i] / b[i]`.
@inlinable
public static func divide<U>(_ splitComplex: DSPDoubleSplitComplex,
by vector: U,
result: inout DSPDoubleSplitComplex)
where
U: AccelerateBuffer,
U.Element == Double {
withUnsafePointer(to: splitComplex) { a in
vector.withUnsafeBufferPointer { b in
vDSP_zrvdivD(a, 1,
b.baseAddress!, 1,
&result, 1,
vDSP_Length(vector.count))
}
}
}
/// Populates `result` with the elementwise product of `splitComplex` and `vector`,
/// single-precision.
///
/// - Parameter splitComplex: the `a` in `c[i] = a[i] * b[i]`.
/// - Parameter vector: the `b` in `c[i] = a[i] * b[i]`.
/// - Parameter result: The `c` in `c[i] = a[i] * b[i]`.
@inlinable
public static func multiply<U>(_ splitComplex: DSPSplitComplex,
by vector: U,
result: inout DSPSplitComplex)
where
U: AccelerateBuffer,
U.Element == Float {
withUnsafePointer(to: splitComplex) { a in
vector.withUnsafeBufferPointer { b in
vDSP_zrvmul(a, 1,
b.baseAddress!, 1,
&result, 1,
vDSP_Length(vector.count))
}
}
}
/// Populates `result` with the elementwise product of `splitComplex` and `vector`,
/// double-precision.
///
/// - Parameter splitComplex: the `a` in `c[i] = a[i] * b[i]`.
/// - Parameter vector: the `b` in `c[i] = a[i] * b[i]`.
/// - Parameter result: The `c` in `c[i] = a[i] * b[i]`.
@inlinable
public static func multiply<U>(_ splitComplex: DSPDoubleSplitComplex,
by vector: U,
result: inout DSPDoubleSplitComplex)
where
U: AccelerateBuffer,
U.Element == Double {
withUnsafePointer(to: splitComplex) { a in
vector.withUnsafeBufferPointer { b in
vDSP_zrvmulD(a, 1,
b.baseAddress!, 1,
&result, 1,
vDSP_Length(vector.count))
}
}
}
/// Populates `result` with the elementwise product of `splitComplexA` and `splitComplexB`,
/// optionally conjugating one of them; single-precision
///
/// - Parameter splitComplexA: The `a` in `c[i] = a[i] * b[i]` or `c[i] = conj(a[i]) * b[i]`.
/// - Parameter splitComplexB: The `b` in `c[i] = a[i] * b[i]` or `c[i] = conj(a[i]) * b[i]`.
/// - Parameter count: The number of elements to process.
/// - Parameter useConjugate: Specifies whether to multiply the complex conjugates of `splitComplexA`.
/// - Parameter result: The `c` in `c[i] = a[i] * b[i]` or `c[i] = conj(a[i]) * b[i]`.
@inlinable
public static func multiply(_ splitComplexA: DSPSplitComplex,
by splitComplexB: DSPSplitComplex,
count: Int,
useConjugate: Bool,
result: inout DSPSplitComplex) {
let conjugate: Int32 = useConjugate ? -1 : 1
withUnsafePointer(to: splitComplexA) { a in
withUnsafePointer(to: splitComplexB) { b in
vDSP_zvmul(a, 1,
b, 1,
&result, 1,
vDSP_Length(count),
conjugate)
}
}
}
/// Populates `result` with the elementwise product of `splitComplexA` and `splitComplexB`,
/// optionally conjugating one of them; double-precision
///
/// - Parameter splitComplexA: The `a` in `c[i] = a[i] * b[i]` or `c[i] = conj(a[i]) * b[i]`.
/// - Parameter splitComplexB: The `b` in `c[i] = a[i] * b[i]` or `c[i] = conj(a[i]) * b[i]`.
/// - Parameter count: The number of elements to process.
/// - Parameter useConjugate: Specifies whether to multiply the complex conjugates of `splitComplexA`.
/// - Parameter result: The `c` in `c[i] = a[i] * b[i]` or `c[i] = conj(a[i]) * b[i]`.
@inlinable
public static func multiply(_ splitComplexA: DSPDoubleSplitComplex,
by splitComplexB: DSPDoubleSplitComplex,
count: Int,
useConjugate: Bool,
result: inout DSPDoubleSplitComplex) {
let conjugate: Int32 = useConjugate ? -1 : 1
withUnsafePointer(to: splitComplexA) { a in
withUnsafePointer(to: splitComplexB) { b in
vDSP_zvmulD(a, 1,
b, 1,
&result, 1,
vDSP_Length(count),
conjugate)
}
}
}
/// Populates `result` with the elementwise sum of `splitComplexA` and `splitComplexB`,
/// single-precision.
///
/// - Parameter splitComplexA: the `a` in `c[i] = a[i] + b[i]`.
/// - Parameter splitComplexB: the `b` in `c[i] = a[i] + b[i]`.
/// - Parameter count: The number of elements to process.
/// - Parameter result: The `c` in `c[i] = a[i] + b[i]`.
@inlinable
public static func add(_ splitComplexA: DSPSplitComplex,
to splitComplexB: DSPSplitComplex,
count: Int,
result: inout DSPSplitComplex) {
withUnsafePointer(to: splitComplexA) { a in
withUnsafePointer(to: splitComplexB) { b in
vDSP_zvadd(a, 1,
b, 1,
&result, 1,
vDSP_Length(count))
}
}
}
/// Populates `result` with the elementwise sum of `splitComplexA` and `splitComplexB`,
/// double-precision.
///
/// - Parameter splitComplexA: the `a` in `c[i] = a[i] + b[i]`.
/// - Parameter splitComplexB: the `b` in `c[i] = a[i] + b[i]`.
/// - Parameter count: The number of elements to process.
/// - Parameter result: The `c` in `c[i] = a[i] + b[i]`.
@inlinable
public static func add(_ splitComplexA: DSPDoubleSplitComplex,
to splitComplexB: DSPDoubleSplitComplex,
count: Int,
result: inout DSPDoubleSplitComplex) {
withUnsafePointer(to: splitComplexA) { a in
withUnsafePointer(to: splitComplexB) { b in
vDSP_zvaddD(a, 1,
b, 1,
&result, 1,
vDSP_Length(count))
}
}
}
/// Populates `result` with the elementwise division of `splitComplexA` and `splitComplexB`,
/// single-precision.
///
/// - Parameter splitComplexA: the `a` in `c[i] = a[i] / b[i]`.
/// - Parameter splitComplexB: the `b` in `c[i] = a[i] / b[i]`.
/// - Parameter count: The number of elements to process.
/// - Parameter result: The `c` in `c[i] = a[i] / b[i]`.
@inlinable
public static func divide(_ splitComplexA: DSPSplitComplex,
by splitComplexB: DSPSplitComplex,
count: Int,
result: inout DSPSplitComplex) {
withUnsafePointer(to: splitComplexA) { a in
withUnsafePointer(to: splitComplexB) { b in
vDSP_zvdiv(b, 1,
a, 1,
&result, 1,
vDSP_Length(count))
}
}
}
/// Populates `result` with the elementwise division of `splitComplexA` and `splitComplexB`,
/// single-precision.
///
/// - Parameter splitComplexA: the `a` in `c[i] = a[i] / b[i]`.
/// - Parameter splitComplexB: the `b` in `c[i] = a[i] / b[i]`.
/// - Parameter count: The number of elements to process.
/// - Parameter result: The `c` in `c[i] = a[i] / b[i]`.
@inlinable
public static func divide(_ splitComplexA: DSPDoubleSplitComplex,
by splitComplexB: DSPDoubleSplitComplex,
count: Int,
result: inout DSPDoubleSplitComplex) {
withUnsafePointer(to: splitComplexA) { a in
withUnsafePointer(to: splitComplexB) { b in
vDSP_zvdivD(b, 1,
a, 1,
&result, 1,
vDSP_Length(count))
}
}
}
/// Populates `result` with the elementwise difference of `splitComplexA` and `splitComplexB`,
/// single-precision.
///
/// - Parameter splitComplexA: the `a` in `c[i] = a[i] - b[i]`.
/// - Parameter splitComplexB: the `b` in `c[i] = a[i] - b[i]`.
/// - Parameter count: The number of elements to process.
/// - Parameter result: The `c` in `c[i] = a[i] - b[i]`.
@inlinable
public static func subtract(_ splitComplexB: DSPSplitComplex,
from splitComplexA: DSPSplitComplex,
count: Int,
result: inout DSPSplitComplex) {
withUnsafePointer(to: splitComplexA) { a in
withUnsafePointer(to: splitComplexB) { b in
vDSP_zvsub(b, 1,
a, 1,
&result, 1,
vDSP_Length(count))
}
}
}
/// Populates `result` with the elementwise difference of `splitComplexA` and `splitComplexB`,
/// double-precision.
///
/// - Parameter splitComplexA: the `a` in `c[i] = a[i] - b[i]`.
/// - Parameter splitComplexB: the `b` in `c[i] = a[i] - b[i]`.
/// - Parameter count: The number of elements to process.
/// - Parameter result: The `c` in `c[i] = a[i] - b[i]`.
@inlinable
public static func subtract(_ splitComplexB: DSPDoubleSplitComplex,
from splitComplexA: DSPDoubleSplitComplex,
count: Int,
result: inout DSPDoubleSplitComplex) {
withUnsafePointer(to: splitComplexA) { a in
withUnsafePointer(to: splitComplexB) { b in
vDSP_zvsubD(b, 1,
a, 1,
&result, 1,
vDSP_Length(count))
}
}
}
//===----------------------------------------------------------------------===//
//
// Complex vector absolute
//
//===----------------------------------------------------------------------===//
/// Populates `result` with the absolute values of `vector`,
/// single-precision.
///
/// - Parameter vector: The input vector.
/// - Parameter result: The output vector.
@inlinable
public static func absolute<V>(_ vector: DSPSplitComplex,
result: inout V)
where
V: AccelerateMutableBuffer,
V.Element == Float {
let n = result.count
result.withUnsafeMutableBufferPointer { r in
withUnsafePointer(to: vector) { v in
vDSP_zvabs(v, 1,
r.baseAddress!, 1,
vDSP_Length(n))
}
}
}
/// Populates `result` with the absolute values of `vector`,
/// double-precision.
///
/// - Parameter vector: The input vector.
/// - Parameter result: The output vector.
@inlinable
public static func absolute<V>(_ vector: DSPDoubleSplitComplex,
result: inout V)
where
V: AccelerateMutableBuffer,
V.Element == Double {
let n = result.count
result.withUnsafeMutableBufferPointer { r in
withUnsafePointer(to: vector) { v in
vDSP_zvabsD(v, 1,
r.baseAddress!, 1,
vDSP_Length(n))
}
}
}
//===----------------------------------------------------------------------===//
//
// Complex squared magnitude
//
//===----------------------------------------------------------------------===//
/// Calculates the squared magnitude of each element in `vector`, writing the result to `result`; single-precision.
///
/// - Parameter splitComplex: Input values.
/// - Parameter result: Output values.
@inlinable
public static func squareMagnitudes<V>(_ splitComplex: DSPSplitComplex,
result: inout V)
where
V : AccelerateMutableBuffer,
V.Element == Float {
let n = vDSP_Length(result.count)
result.withUnsafeMutableBufferPointer { dest in
withUnsafePointer(to: splitComplex) { src in
vDSP_zvmags(src, 1,
dest.baseAddress!, 1,
n)
}
}
}
@inlinable
/// Calculates the squared magnitude of each element in `vector`, writing the result to `result`; double-precision.
///
/// - Parameter splitComplex: Input values.
/// - Parameter result: Output values.
public static func squareMagnitudes<V>(_ splitComplex: DSPDoubleSplitComplex,
result: inout V)
where
V : AccelerateMutableBuffer,
V.Element == Double {
let n = vDSP_Length(result.count)
result.withUnsafeMutableBufferPointer { dest in
withUnsafePointer(to: splitComplex) { src in
vDSP_zvmagsD(src, 1,
dest.baseAddress!, 1,
n)
}
}
}
}
|
apache-2.0
|
ae037cc6a07d37ef84dcffd5d778c825
| 38.335175 | 123 | 0.460228 | 4.922563 | false | false | false | false |
hibu/apptentive-ios
|
Example/iOSExample/FavoritesViewController.swift
|
1
|
1504
|
//
// FavoritesViewController.swift
// ApptentiveExample
//
// Created by Frank Schmitt on 8/6/15.
// Copyright (c) 2015 Apptentive, Inc. All rights reserved.
//
import UIKit
import Apptentive
class FavoritesViewController: PicturesViewController {
@IBOutlet var noFavoritesLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
minimumWidth = 120
self.collectionView!.backgroundView = self.noFavoritesLabel
}
override func configure() {
self.source = manager.favoriteDataSource
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
updateEmpty(animated)
}
private func updateEmpty(animated: Bool) {
let alpha: CGFloat = self.source.numberOfPictures() == 0 ? 1.0 : 0.0
let duration = animated ? 0.1 : 0.0
UIView.animateWithDuration(duration) { () -> Void in
self.noFavoritesLabel.alpha = alpha
}
}
@IBAction override func toggleLike(sender: UIButton) {
if let cell = sender.superview?.superview as? UICollectionViewCell {
if let indexPath = self.collectionView?.indexPathForCell(cell) {
// Will always mean "unlike" in favorites-only view
sender.selected = false
Apptentive.sharedConnection().engage("photo_unliked", withCustomData: ["photo_name": self.source.imageNameAtIndex(indexPath.item)], fromViewController: self)
self.source?.setLiked(indexPath.item, liked: false)
self.collectionView!.deleteItemsAtIndexPaths([indexPath])
self.updateEmpty(true)
}
}
}
}
|
bsd-3-clause
|
148cf9b0a47b81818d6f2b268df4f8da
| 25.857143 | 161 | 0.726064 | 3.886305 | false | false | false | false |
roambotics/swift
|
test/SILGen/subclass_existentials.swift
|
2
|
27209
|
// RUN: %target-swift-emit-silgen -module-name subclass_existentials -Xllvm -sil-full-demangle -parse-as-library -primary-file %s -verify | %FileCheck %s
// RUN: %target-swift-emit-ir -module-name subclass_existentials -parse-as-library -primary-file %s
// Note: we pass -verify above to ensure there are no spurious
// compiler warnings relating to casts.
protocol Q {}
class Base<T> : Q {
required init(classInit: ()) {}
func classSelfReturn() -> Self {
return self
}
static func classSelfReturn() -> Self {
return self.init(classInit: ())
}
}
protocol P {
init(protocolInit: ())
func protocolSelfReturn() -> Self
static func protocolSelfReturn() -> Self
}
class Derived : Base<Int>, P {
required init(protocolInit: ()) {
super.init(classInit: ())
}
required init(classInit: ()) {
super.init(classInit: ())
}
func protocolSelfReturn() -> Self {
return self
}
static func protocolSelfReturn() -> Self {
return self.init(classInit: ())
}
}
protocol R {}
// CHECK-LABEL: sil hidden [ossa] @$s21subclass_existentials11conversions8baseAndP7derived0fE1R0dE5PType0F4Type0fE5RTypeyAA1P_AA4BaseCySiGXc_AA7DerivedCAA1R_ANXcAaI_ALXcXpANmAaO_ANXcXptF : $@convention(thin) (@guaranteed any Base<Int> & P, @guaranteed Derived, @guaranteed any Derived & R, @thick any (Base<Int> & P).Type, @thick Derived.Type, @thick any (Derived & R).Type) -> () {
// CHECK: bb0([[ARG0:%.*]] : @guaranteed $any Base<Int> & P,
func conversions(
baseAndP: Base<Int> & P,
derived: Derived,
derivedAndR: Derived & R,
baseAndPType: (Base<Int> & P).Type,
derivedType: Derived.Type,
derivedAndRType: (Derived & R).Type) {
// Values
// CHECK: [[PAYLOAD:%.*]] = open_existential_ref [[ARG0]] : $any Base<Int> & P
// CHECK: [[REF:%.*]] = copy_value [[PAYLOAD]]
// CHECK: [[BASE:%.*]] = upcast [[REF]] : $@opened("{{.*}}", any Base<Int> & P) Self to $Base<Int>
// CHECK: destroy_value [[BASE]] : $Base<Int>
let _: Base<Int> = baseAndP
// CHECK: [[PAYLOAD:%.*]] = open_existential_ref [[ARG0]] : $any Base<Int> & P
// CHECK: [[RESULT:%.*]] = alloc_stack $any P
// CHECK: [[RESULT_PAYLOAD:%.*]] = init_existential_addr [[RESULT]] : $*any P, $@opened("{{.*}}", any Base<Int> & P) Self
// CHECK: [[REF:%.*]] = copy_value [[PAYLOAD]]
// CHECK: store [[REF]] to [init] [[RESULT_PAYLOAD]]
// CHECK: destroy_addr [[RESULT]] : $*any P
// CHECK: dealloc_stack [[RESULT]] : $*any P
let _: P = baseAndP
// CHECK: [[PAYLOAD:%.*]] = open_existential_ref [[ARG0]] : $any Base<Int> & P
// CHECK: [[RESULT:%.*]] = alloc_stack $any Q
// CHECK: [[RESULT_PAYLOAD:%.*]] = init_existential_addr [[RESULT]] : $*any Q, $@opened("{{.*}}", any Base<Int> & P) Self
// CHECK: [[REF:%.*]] = copy_value [[PAYLOAD]]
// CHECK: store [[REF]] to [init] [[RESULT_PAYLOAD]]
// CHECK: destroy_addr [[RESULT]] : $*any Q
// CHECK: dealloc_stack [[RESULT]] : $*any Q
let _: Q = baseAndP
// CHECK: [[PAYLOAD:%.*]] = open_existential_ref [[ARG2:%.*]] : $any Derived & R
// CHECK: [[REF:%.*]] = copy_value [[PAYLOAD]]
// CHECK: [[RESULT:%.*]] = init_existential_ref [[REF]] : $@opened("{{.*}}", any Derived & R) Self : $@opened("{{.*}}", any Derived & R) Self, $any Base<Int> & P
// CHECK: destroy_value [[RESULT]]
let _: Base<Int> & P = derivedAndR
// Metatypes
// CHECK: [[PAYLOAD:%.*]] = open_existential_metatype %3 : $@thick any (Base<Int> & P).Type to $@thick (@opened("{{.*}}", any Base<Int> & P) Self).Type
// CHECK: [[RESULT:%.*]] = upcast [[PAYLOAD]] : $@thick (@opened("{{.*}}", any Base<Int> & P) Self).Type to $@thick Base<Int>.Type
let _: Base<Int>.Type = baseAndPType
// CHECK: [[PAYLOAD:%.*]] = open_existential_metatype %3 : $@thick any (Base<Int> & P).Type to $@thick (@opened("{{.*}}", any Base<Int> & P) Self).Type
// CHECK: [[RESULT:%.*]] = init_existential_metatype [[PAYLOAD]] : $@thick (@opened("{{.*}}", any Base<Int> & P) Self).Type, $@thick any P.Type
let _: P.Type = baseAndPType
// CHECK: [[PAYLOAD:%.*]] = open_existential_metatype %3 : $@thick any (Base<Int> & P).Type to $@thick (@opened("{{.*}}", any Base<Int> & P) Self).Type
// CHECK: [[RESULT:%.*]] = init_existential_metatype [[PAYLOAD]] : $@thick (@opened("{{.*}}", any Base<Int> & P) Self).Type, $@thick any Q.Type
let _: Q.Type = baseAndPType
// CHECK: [[RESULT:%.*]] = init_existential_metatype %4 : $@thick Derived.Type, $@thick any (Base<Int> & P).Type
let _: (Base<Int> & P).Type = derivedType
// CHECK: [[PAYLOAD:%.*]] = open_existential_metatype %5 : $@thick any (Derived & R).Type to $@thick (@opened("{{.*}}", any Derived & R) Self).Type
// CHECK: [[RESULT:%.*]] = init_existential_metatype [[PAYLOAD]] : $@thick (@opened("{{.*}}", any Derived & R) Self).Type, $@thick any (Base<Int> & P).Type
let _: (Base<Int> & P).Type = derivedAndRType
// CHECK: return
}
// CHECK-LABEL: sil hidden [ossa] @$s21subclass_existentials11methodCalls8baseAndP0eF5PTypeyAA1P_AA4BaseCySiGXc_AaE_AHXcXptF : $@convention(thin) (@guaranteed any Base<Int> & P, @thick any (Base<Int> & P).Type) -> () {
func methodCalls(
baseAndP: Base<Int> & P,
baseAndPType: (Base<Int> & P).Type) {
// CHECK: bb0([[ARG0:%.*]] : @guaranteed $any Base<Int> & P,
// CHECK: [[PAYLOAD:%.*]] = open_existential_ref [[ARG0]] : $any Base<Int> & P to $@opened("{{.*}}", any Base<Int> & P) Self
// CHECK: [[REF:%.*]] = copy_value [[PAYLOAD]] : $@opened("{{.*}}", any Base<Int> & P) Self
// CHECK: [[CLASS_REF:%.*]] = upcast [[REF]] : $@opened("{{.*}}", any Base<Int> & P) Self to $Base<Int>
// CHECK: [[METHOD:%.*]] = class_method [[CLASS_REF]] : $Base<Int>, #Base.classSelfReturn : <T> (Base<T>) -> () -> @dynamic_self Base<T>, $@convention(method) <τ_0_0> (@guaranteed Base<τ_0_0>) -> @owned Base<τ_0_0>
// CHECK: [[RESULT_CLASS_REF:%.*]] = apply [[METHOD]]<Int>([[CLASS_REF]]) : $@convention(method) <τ_0_0> (@guaranteed Base<τ_0_0>) -> @owned Base<τ_0_0>
// CHECK: destroy_value [[CLASS_REF]] : $Base<Int>
// CHECK: [[RESULT_REF:%.*]] = unchecked_ref_cast [[RESULT_CLASS_REF]] : $Base<Int> to $@opened("{{.*}}", any Base<Int> & P) Self
// CHECK: [[RESULT:%.*]] = init_existential_ref [[RESULT_REF]] : $@opened("{{.*}}", any Base<Int> & P) Self, $any Base<Int> & P
// CHECK: destroy_value [[RESULT]] : $any Base<Int> & P
let _: Base<Int> & P = baseAndP.classSelfReturn()
// CHECK: [[PAYLOAD:%.*]] = open_existential_ref [[ARG0]] : $any Base<Int> & P to $@opened("{{.*}}", any Base<Int> & P) Self
// CHECK: [[SELF_BOX:%.*]] = alloc_stack $@opened("{{.*}}", any Base<Int> & P) Self
// CHECK: [[SB:%.*]] = store_borrow [[PAYLOAD]] to [[SELF_BOX]] : $*@opened("{{.*}}", any Base<Int> & P) Self
// CHECK: [[METHOD:%.*]] = witness_method $@opened("{{.*}}", any Base<Int> & P) Self, #P.protocolSelfReturn : <Self where Self : P> (Self) -> () -> Self, [[PAYLOAD]] : $@opened("{{.*}}", any Base<Int> & P) Self : $@convention(witness_method: P) <τ_0_0 where τ_0_0 : P> (@in_guaranteed τ_0_0) -> @out τ_0_0
// CHECK: [[RESULT_BOX:%.*]] = alloc_box
// CHECK: [[RESULT_LIFETIME:%[^,]+]] = begin_borrow [lexical] [[RESULT_BOX]]
// CHECK: [[RESULT_BUF:%.*]] = project_box [[RESULT_LIFETIME]]
// CHECK: apply [[METHOD]]<@opened("{{.*}}", any Base<Int> & P) Self>([[RESULT_BUF]], [[SB]]) : $@convention(witness_method: P) <τ_0_0 where τ_0_0 : P> (@in_guaranteed τ_0_0) -> @out τ_0_0
// end_borrow [[SB]]
// CHECK: dealloc_stack [[SELF_BOX]] : $*@opened("{{.*}}", any Base<Int> & P) Self
// CHECK: [[RESULT_REF:%.*]] = load [take] [[RESULT_BUF]] : $*@opened("{{.*}}", any Base<Int> & P) Self
// CHECK: [[RESULT:%.*]] = init_existential_ref [[RESULT_REF]] : $@opened("{{.*}}", any Base<Int> & P) Self : $@opened("{{.*}}", any Base<Int> & P) Self, $any Base<Int> & P
// CHECK: destroy_value [[RESULT]] : $any Base<Int> & P
// CHECK: end_borrow [[RESULT_LIFETIME]]
// CHECK: dealloc_box [[RESULT_BOX]]
let _: Base<Int> & P = baseAndP.protocolSelfReturn()
// CHECK: [[METATYPE:%.*]] = open_existential_metatype %1 : $@thick any (Base<Int> & P).Type to $@thick (@opened("{{.*}}", any Base<Int> & P) Self).Type
// CHECK: [[METATYPE_REF:%.*]] = upcast [[METATYPE]] : $@thick (@opened("{{.*}}", any Base<Int> & P) Self).Type to $@thick Base<Int>.Type
// CHECK: [[METHOD:%.*]] = function_ref @$s21subclass_existentials4BaseC15classSelfReturnACyxGXDyFZ : $@convention(method) <τ_0_0> (@thick Base<τ_0_0>.Type) -> @owned Base<τ_0_0>
// CHECK: [[RESULT_REF2:%.*]] = apply [[METHOD]]<Int>([[METATYPE_REF]])
// CHECK: [[RESULT_REF:%.*]] = unchecked_ref_cast [[RESULT_REF2]] : $Base<Int> to $@opened("{{.*}}", any Base<Int> & P) Self
// CHECK: [[RESULT:%.*]] = init_existential_ref [[RESULT_REF]] : $@opened("{{.*}}", any Base<Int> & P) Self : $@opened("{{.*}}", any Base<Int> & P) Self, $any Base<Int> & P
// CHECK: destroy_value [[RESULT]]
let _: Base<Int> & P = baseAndPType.classSelfReturn()
// CHECK: [[METATYPE:%.*]] = open_existential_metatype %1 : $@thick any (Base<Int> & P).Type to $@thick (@opened("{{.*}}", any Base<Int> & P) Self).Type
// CHECK: [[METHOD:%.*]] = witness_method $@opened("{{.*}}", any Base<Int> & P) Self, #P.protocolSelfReturn : <Self where Self : P> (Self.Type) -> () -> Self, [[METATYPE]] : $@thick (@opened("{{.*}}", any Base<Int> & P) Self).Type : $@convention(witness_method: P) <τ_0_0 where τ_0_0 : P> (@thick τ_0_0.Type) -> @out τ_0_0
// CHECK: [[RESULT_BOX:%.*]] = alloc_box
// CHECK: [[RESULT_LIFETIME:%[^,]+]] = begin_borrow [lexical] [[RESULT_BOX]]
// CHECK: [[RESULT_BUF:%.*]] = project_box
// CHECK: apply [[METHOD]]<@opened("{{.*}}", any Base<Int> & P) Self>([[RESULT_BUF]], [[METATYPE]]) : $@convention(witness_method: P) <τ_0_0 where τ_0_0 : P> (@thick τ_0_0.Type) -> @out τ_0_0
// CHECK: [[RESULT_REF:%.*]] = load [take] [[RESULT_BUF]] : $*@opened("{{.*}}", any Base<Int> & P) Self
// CHECK: [[RESULT_VALUE:%.*]] = init_existential_ref [[RESULT_REF]] : $@opened("{{.*}}", any Base<Int> & P) Self : $@opened("{{.*}}", any Base<Int> & P) Self, $any Base<Int> & P
// CHECK: destroy_value [[RESULT_VALUE]]
// CHECK: end_borrow [[RESULT_LIFETIME]]
// CHECK: dealloc_box [[RESULT_BOX]]
let _: Base<Int> & P = baseAndPType.protocolSelfReturn()
// Partial applications
let _: () -> (Base<Int> & P) = baseAndP.classSelfReturn
let _: () -> (Base<Int> & P) = baseAndP.protocolSelfReturn
let _: () -> (Base<Int> & P) = baseAndPType.classSelfReturn
let _: () -> (Base<Int> & P) = baseAndPType.protocolSelfReturn
let _: (()) -> (Base<Int> & P) = baseAndPType.init(classInit:)
let _: (()) -> (Base<Int> & P) = baseAndPType.init(protocolInit:)
// CHECK: return
// CHECK-NEXT: }
}
// CHECK-LABEL: sil hidden [ossa] @$s21subclass_existentials29methodCallsOnProtocolMetatypeyyF : $@convention(thin) () -> () {
// CHECK: metatype $@thin (any Base<Int> & P).Type
// CHECK: function_ref @$[[THUNK1_NAME:[_a-zA-Z0-9]+]]
// CHECK: } // end sil function '$s21subclass_existentials29methodCallsOnProtocolMetatypeyyF'
//
// CHECK: sil private [ossa] @$[[THUNK1_NAME]] : $@convention(thin) (@guaranteed any Base<Int> & P) -> @owned @callee_guaranteed () -> @owned any Base<Int> & P {
// CHECK: bb0(%0 : @guaranteed $any Base<Int> & P):
// CHECK: [[THUNK2:%[0-9]+]] = function_ref @$[[THUNK2_NAME:[_a-zA-Z0-9]+]]
// CHECK: [[SELF_COPY:%[0-9]+]] = copy_value %0
// CHECK: [[RESULT:%[0-9]+]] = partial_apply [callee_guaranteed] [[THUNK2]]([[SELF_COPY]])
// CHECK: return [[RESULT]]
// CHECK: } // end sil function '$[[THUNK1_NAME]]'
//
// CHECK: sil private [ossa] @$[[THUNK2_NAME]] : $@convention(thin) (@guaranteed any Base<Int> & P) -> @owned any Base<Int> & P {
// CHECK: bb0(%0 : @guaranteed $any Base<Int> & P):
// CHECK: [[OPENED:%[0-9]+]] = open_existential_ref %0 : $any Base<Int> & P to $[[OPENED_TY:@opened\("[-A-F0-9]+", any Base<Int> & P\) Self]]
// CHECK: [[OPENED_COPY:%[0-9]+]] = copy_value [[OPENED]]
// CHECK: [[CLASS:%[0-9]+]] = upcast [[OPENED_COPY]] : $[[OPENED_TY]] to $Base<Int>
// CHECK: [[METHOD:%[0-9]+]] = class_method [[CLASS]] : $Base<Int>, #Base.classSelfReturn
// CHECK: [[RESULT:%[0-9]+]] = apply [[METHOD]]<Int>([[CLASS]]) : $@convention(method) <τ_0_0> (@guaranteed Base<τ_0_0>) -> @owned Base<τ_0_0>
// CHECK: destroy_value [[CLASS]]
// CHECK: [[TO_OPENED:%[0-9]+]] = unchecked_ref_cast [[RESULT]] : $Base<Int> to $[[OPENED_TY]]
// CHECK: [[ERASED:%[0-9]+]] = init_existential_ref [[TO_OPENED]] : $[[OPENED_TY]]
// CHECK: return [[ERASED]]
// CHECK: } // end sil function '$[[THUNK2_NAME]]'
func methodCallsOnProtocolMetatype() {
let _ = (Base<Int> & P).classSelfReturn
}
protocol PropertyP {
var p: PropertyP & PropertyC { get set }
subscript(key: Int) -> Int { get set }
}
class PropertyC {
var c: PropertyP & PropertyC {
get {
return self as! PropertyP & PropertyC
}
set { }
}
subscript(key: (Int, Int)) -> Int {
get {
return 0
} set { }
}
}
// CHECK-LABEL: sil hidden [ossa] @$s21subclass_existentials16propertyAccessesyyAA9PropertyP_AA0E1CCXcF : $@convention(thin) (@guaranteed any PropertyC & PropertyP) -> () {
func propertyAccesses(_ x: PropertyP & PropertyC) {
var xx = x
xx.p.p = x
xx.c.c = x
propertyAccesses(xx.p)
propertyAccesses(xx.c)
_ = xx[1]
xx[1] = 1
xx[1] += 1
_ = xx[(1, 2)]
xx[(1, 2)] = 1
xx[(1, 2)] += 1
}
// CHECK-LABEL: sil hidden [ossa] @$s21subclass_existentials19functionConversions15returnsBaseAndP0efG5PType0E7Derived0eI4Type0eiG1R0eiG5RTypeyAA1P_AA0F0CySiGXcyc_AaI_ALXcXpycAA0I0CycANmycAA1R_ANXcycAaO_ANXcXpyctF : $@convention(thin) (@guaranteed @callee_guaranteed () -> @owned any Base<Int> & P, @guaranteed @callee_guaranteed () -> @thick any (Base<Int> & P).Type, @guaranteed @callee_guaranteed () -> @owned Derived, @guaranteed @callee_guaranteed () -> @thick Derived.Type, @guaranteed @callee_guaranteed () -> @owned any Derived & R, @guaranteed @callee_guaranteed () -> @thick any (Derived & R).Type) -> () {
func functionConversions(
returnsBaseAndP: @escaping () -> (Base<Int> & P),
returnsBaseAndPType: @escaping () -> (Base<Int> & P).Type,
returnsDerived: @escaping () -> Derived,
returnsDerivedType: @escaping () -> Derived.Type,
returnsDerivedAndR: @escaping () -> Derived & R,
returnsDerivedAndRType: @escaping () -> (Derived & R).Type) {
let _: () -> Base<Int> = returnsBaseAndP
let _: () -> Base<Int>.Type = returnsBaseAndPType
let _: () -> P = returnsBaseAndP
let _: () -> P.Type = returnsBaseAndPType
let _: () -> (Base<Int> & P) = returnsDerived
let _: () -> (Base<Int> & P).Type = returnsDerivedType
let _: () -> Base<Int> = returnsDerivedAndR
let _: () -> Base<Int>.Type = returnsDerivedAndRType
let _: () -> (Base<Int> & P) = returnsDerivedAndR
let _: () -> (Base<Int> & P).Type = returnsDerivedAndRType
let _: () -> P = returnsDerivedAndR
let _: () -> P.Type = returnsDerivedAndRType
// CHECK: return %
// CHECK-NEXT: }
}
// CHECK-LABEL: sil hidden [ossa] @$s21subclass_existentials9downcasts8baseAndP7derived0dE5PType0F4TypeyAA1P_AA4BaseCySiGXc_AA7DerivedCAaG_AJXcXpALmtF : $@convention(thin) (@guaranteed any Base<Int> & P, @guaranteed Derived, @thick any (Base<Int> & P).Type, @thick Derived.Type) -> () {
func downcasts(
baseAndP: Base<Int> & P,
derived: Derived,
baseAndPType: (Base<Int> & P).Type,
derivedType: Derived.Type) {
// CHECK: bb0([[ARG0:%.*]] : @guaranteed $any Base<Int> & P, [[ARG1:%.*]] : @guaranteed $Derived, [[ARG2:%.*]] : $@thick any (Base<Int> & P).Type, [[ARG3:%.*]] : $@thick Derived.Type):
// CHECK: [[COPIED:%.*]] = copy_value [[ARG0]] : $any Base<Int> & P
// CHECK-NEXT: checked_cast_br [[COPIED]] : $any Base<Int> & P to Derived
let _ = baseAndP as? Derived
// CHECK: [[COPIED:%.*]] = copy_value [[ARG0]] : $any Base<Int> & P
// CHECK-NEXT: unconditional_checked_cast [[COPIED]] : $any Base<Int> & P to Derived
let _ = baseAndP as! Derived
// CHECK: [[COPIED:%.*]] = copy_value [[ARG0]] : $any Base<Int> & P
// CHECK-NEXT: checked_cast_br [[COPIED]] : $any Base<Int> & P to any Derived & R
let _ = baseAndP as? (Derived & R)
// CHECK: [[COPIED:%.*]] = copy_value [[ARG0]] : $any Base<Int> & P
// CHECK-NEXT: unconditional_checked_cast [[COPIED]] : $any Base<Int> & P to any Derived & R
let _ = baseAndP as! (Derived & R)
// CHECK: checked_cast_br %3 : $@thick Derived.Type to any (Derived & R).Type
let _ = derivedType as? (Derived & R).Type
// CHECK: unconditional_checked_cast %3 : $@thick Derived.Type to any (Derived & R).Type
let _ = derivedType as! (Derived & R).Type
// CHECK: checked_cast_br %2 : $@thick any (Base<Int> & P).Type to Derived.Type
let _ = baseAndPType as? Derived.Type
// CHECK: unconditional_checked_cast %2 : $@thick any (Base<Int> & P).Type to Derived.Type
let _ = baseAndPType as! Derived.Type
// CHECK: checked_cast_br %2 : $@thick any (Base<Int> & P).Type to any (Derived & R).Type
let _ = baseAndPType as? (Derived & R).Type
// CHECK: unconditional_checked_cast %2 : $@thick any (Base<Int> & P).Type to any (Derived & R).Type
let _ = baseAndPType as! (Derived & R).Type
// CHECK: return
// CHECK-NEXT: }
}
// CHECK-LABEL: sil hidden [ossa] @$s21subclass_existentials16archetypeUpcasts9baseTAndP0E7IntAndP7derivedyq__q0_q1_tAA4BaseCyxGRb_AA1PR_AGySiGRb0_AaIR0_AA7DerivedCRb1_r2_lF : $@convention(thin) <T, BaseTAndP, BaseIntAndP, DerivedT where BaseTAndP : Base<T>, BaseTAndP : P, BaseIntAndP : Base<Int>, BaseIntAndP : P, DerivedT : Derived> (@guaranteed BaseTAndP, @guaranteed BaseIntAndP, @guaranteed DerivedT) -> () {
func archetypeUpcasts<T,
BaseTAndP : Base<T> & P,
BaseIntAndP : Base<Int> & P,
DerivedT : Derived>(
baseTAndP: BaseTAndP,
baseIntAndP : BaseIntAndP,
derived : DerivedT) {
// CHECK: bb0([[ARG0:%.*]] : @guaranteed $BaseTAndP, [[ARG1:%.*]] : @guaranteed $BaseIntAndP, [[ARG2:%.*]] : @guaranteed $DerivedT)
// CHECK: [[COPIED:%.*]] = copy_value [[ARG0]] : $BaseTAndP
// CHECK-NEXT: init_existential_ref [[COPIED]] : $BaseTAndP : $BaseTAndP, $any Base<T> & P
let _: Base<T> & P = baseTAndP
// CHECK: [[COPIED:%.*]] = copy_value [[ARG1]] : $BaseIntAndP
// CHECK-NEXT: init_existential_ref [[COPIED]] : $BaseIntAndP : $BaseIntAndP, $any Base<Int> & P
let _: Base<Int> & P = baseIntAndP
// CHECK: [[COPIED:%.*]] = copy_value [[ARG2]] : $DerivedT
// CHECK-NEXT: init_existential_ref [[COPIED]] : $DerivedT : $DerivedT, $any Base<Int> & P
let _: Base<Int> & P = derived
// CHECK: return
// CHECK-NEXT: }
}
// CHECK-LABEL: sil hidden [ossa] @$s21subclass_existentials18archetypeDowncasts1s1t2pt5baseT0F3Int0f6TAndP_C00fg5AndP_C008derived_C00ji2R_C00fH10P_concrete0fgi2P_K0yx_q_q0_q1_q2_q3_q4_q5_AA1R_AA7DerivedCXcAA1P_AA4BaseCyq_GXcAaQ_ASySiGXctAaQR0_ATRb1_AURb2_ATRb3_AaQR3_AURb4_AaQR4_APRb5_r6_lF : $@convention(thin) <S, T, PT, BaseT, BaseInt, BaseTAndP, BaseIntAndP, DerivedT where PT : P, BaseT : Base<T>, BaseInt : Base<Int>, BaseTAndP : Base<T>, BaseTAndP : P, BaseIntAndP : Base<Int>, BaseIntAndP : P, DerivedT : Derived> (@in_guaranteed S, @in_guaranteed T, @in_guaranteed PT, @guaranteed BaseT, @guaranteed BaseInt, @guaranteed BaseTAndP, @guaranteed BaseIntAndP, @guaranteed DerivedT, @guaranteed any Derived & R, @guaranteed any Base<T> & P, @guaranteed any Base<Int> & P) -> () {
func archetypeDowncasts<S,
T,
PT : P,
BaseT : Base<T>,
BaseInt : Base<Int>,
BaseTAndP : Base<T> & P,
BaseIntAndP : Base<Int> & P,
DerivedT : Derived>(
s: S,
t: T,
pt: PT,
baseT : BaseT,
baseInt : BaseInt,
baseTAndP_archetype: BaseTAndP,
baseIntAndP_archetype : BaseIntAndP,
derived_archetype : DerivedT,
derivedAndR_archetype : Derived & R,
baseTAndP_concrete: Base<T> & P,
baseIntAndP_concrete: Base<Int> & P) {
// CHECK: ([[ARG0:%.*]] : $*S, [[ARG1:%.*]] : $*T, [[ARG2:%.*]] : $*PT, [[ARG3:%.*]] : @guaranteed $BaseT, [[ARG4:%.*]] : @guaranteed $BaseInt, [[ARG5:%.*]] : @guaranteed $BaseTAndP, [[ARG6:%.*]] : @guaranteed $BaseIntAndP, [[ARG7:%.*]] : @guaranteed $DerivedT, [[ARG8:%.*]] : @guaranteed $any Derived & R, [[ARG9:%.*]] : @guaranteed $any Base<T> & P, [[ARG10:%.*]] : @guaranteed $any Base<Int> & P)
// CHECK: [[COPY:%.*]] = alloc_stack $S
// CHECK-NEXT: copy_addr %0 to [init] [[COPY]] : $*S
// CHECK-NEXT: [[RESULT:%.*]] = alloc_stack $any Base<T> & P
// CHECK-NEXT: checked_cast_addr_br take_always S in [[COPY]] : $*S to any Base<T> & P in [[RESULT]] : $*any Base<T> & P
let _ = s as? (Base<T> & P)
// CHECK: [[COPY:%.*]] = alloc_stack $S
// CHECK-NEXT: copy_addr [[ARG0]] to [init] [[COPY]] : $*S
// CHECK-NEXT: [[RESULT:%.*]] = alloc_stack $any Base<T> & P
// CHECK-NEXT: unconditional_checked_cast_addr S in [[COPY]] : $*S to any Base<T> & P in [[RESULT]] : $*any Base<T> & P
let _ = s as! (Base<T> & P)
// CHECK: [[COPY:%.*]] = alloc_stack $S
// CHECK-NEXT: copy_addr [[ARG0]] to [init] [[COPY]] : $*S
// CHECK-NEXT: [[RESULT:%.*]] = alloc_stack $any Base<Int> & P
// CHECK-NEXT: checked_cast_addr_br take_always S in [[COPY]] : $*S to any Base<Int> & P in [[RESULT]] : $*any Base<Int> & P
let _ = s as? (Base<Int> & P)
// CHECK: [[COPY:%.*]] = alloc_stack $S
// CHECK-NEXT: copy_addr [[ARG0]] to [init] [[COPY]] : $*S
// CHECK-NEXT: [[RESULT:%.*]] = alloc_stack $any Base<Int> & P
// CHECK-NEXT: unconditional_checked_cast_addr S in [[COPY]] : $*S to any Base<Int> & P in [[RESULT]] : $*any Base<Int> & P
let _ = s as! (Base<Int> & P)
// CHECK: [[COPIED:%.*]] = copy_value [[ARG5]] : $BaseTAndP
// CHECK-NEXT: checked_cast_br [[COPIED]] : $BaseTAndP to any Derived & R
let _ = baseTAndP_archetype as? (Derived & R)
// CHECK: [[COPIED:%.*]] = copy_value [[ARG5]] : $BaseTAndP
// CHECK-NEXT: unconditional_checked_cast [[COPIED]] : $BaseTAndP to any Derived & R
let _ = baseTAndP_archetype as! (Derived & R)
// CHECK: [[COPIED:%.*]] = copy_value [[ARG9]] : $any Base<T> & P
// CHECK-NEXT: [[COPY:%.*]] = alloc_stack $any Base<T> & P
// CHECK-NEXT: store [[COPIED]] to [init] [[COPY]] : $*any Base<T> & P
// CHECK-NEXT: [[RESULT:%.*]] = alloc_stack $Optional<S>
// CHECK-NEXT: [[PAYLOAD:%.*]] = init_enum_data_addr [[RESULT]] : $*Optional<S>, #Optional.some
// CHECK-NEXT: checked_cast_addr_br take_always any Base<T> & P in [[COPY]] : $*any Base<T> & P to S in [[PAYLOAD]] : $*S
let _ = baseTAndP_concrete as? S
// CHECK: [[COPY:%.*]] = alloc_stack $any Base<T> & P
// CHECK-NEXT: [[COPIED:%.*]] = copy_value [[ARG9]] : $any Base<T> & P
// CHECK-NEXT: store [[COPIED]] to [init] [[COPY]] : $*any Base<T> & P
// CHECK-NEXT: [[RESULT:%.*]] = alloc_stack $S
// CHECK-NEXT: unconditional_checked_cast_addr any Base<T> & P in [[COPY]] : $*any Base<T> & P to S in [[RESULT]] : $*S
let _ = baseTAndP_concrete as! S
// CHECK: [[COPIED:%.*]] = copy_value [[ARG9]] : $any Base<T> & P
// CHECK-NEXT: checked_cast_br [[COPIED]] : $any Base<T> & P to BaseT
let _ = baseTAndP_concrete as? BaseT
// CHECK: [[COPIED:%.*]] = copy_value [[ARG9]] : $any Base<T> & P
// CHECK-NEXT: unconditional_checked_cast [[COPIED]] : $any Base<T> & P to BaseT
let _ = baseTAndP_concrete as! BaseT
// CHECK: [[COPIED:%.*]] = copy_value [[ARG9]] : $any Base<T> & P
// CHECK-NEXT: checked_cast_br [[COPIED]] : $any Base<T> & P to BaseInt
let _ = baseTAndP_concrete as? BaseInt
// CHECK: [[COPIED:%.*]] = copy_value [[ARG9]] : $any Base<T> & P
// CHECK-NEXT: unconditional_checked_cast [[COPIED]] : $any Base<T> & P to BaseInt
let _ = baseTAndP_concrete as! BaseInt
// CHECK: [[COPIED:%.*]] = copy_value [[ARG9]] : $any Base<T> & P
// CHECK-NEXT: checked_cast_br [[COPIED]] : $any Base<T> & P to BaseTAndP
let _ = baseTAndP_concrete as? BaseTAndP
// CHECK: [[COPIED:%.*]] = copy_value [[ARG9]] : $any Base<T> & P
// CHECK-NEXT: unconditional_checked_cast [[COPIED]] : $any Base<T> & P to BaseTAndP
let _ = baseTAndP_concrete as! BaseTAndP
// CHECK: [[COPIED:%.*]] = copy_value [[ARG6]] : $BaseIntAndP
// CHECK-NEXT: checked_cast_br [[COPIED]] : $BaseIntAndP to any Derived & R
let _ = baseIntAndP_archetype as? (Derived & R)
// CHECK: [[COPIED:%.*]] = copy_value [[ARG6]] : $BaseIntAndP
// CHECK-NEXT: unconditional_checked_cast [[COPIED]] : $BaseIntAndP to any Derived & R
let _ = baseIntAndP_archetype as! (Derived & R)
// CHECK: [[COPIED:%.*]] = copy_value [[ARG10]] : $any Base<Int> & P
// CHECK-NEXT: [[COPY:%.*]] = alloc_stack $any Base<Int> & P
// CHECK-NEXT: store [[COPIED]] to [init] [[COPY]] : $*any Base<Int> & P
// CHECK-NEXT: [[RESULT:%.*]] = alloc_stack $Optional<S>
// CHECK-NEXT: [[PAYLOAD:%.*]] = init_enum_data_addr [[RESULT]] : $*Optional<S>, #Optional.some
// CHECK-NEXT: checked_cast_addr_br take_always any Base<Int> & P in [[COPY]] : $*any Base<Int> & P to S in [[PAYLOAD]] : $*S
let _ = baseIntAndP_concrete as? S
// CHECK: [[COPY:%.*]] = alloc_stack $any Base<Int> & P
// CHECK-NEXT: [[COPIED:%.*]] = copy_value [[ARG10]] : $any Base<Int> & P
// CHECK-NEXT: store [[COPIED]] to [init] [[COPY]] : $*any Base<Int> & P
// CHECK-NEXT: [[RESULT:%.*]] = alloc_stack $S
// CHECK-NEXT: unconditional_checked_cast_addr any Base<Int> & P in [[COPY]] : $*any Base<Int> & P to S in [[RESULT]] : $*S
let _ = baseIntAndP_concrete as! S
// CHECK: [[COPIED:%.*]] = copy_value [[ARG10]] : $any Base<Int> & P
// CHECK-NEXT: checked_cast_br [[COPIED]] : $any Base<Int> & P to DerivedT
let _ = baseIntAndP_concrete as? DerivedT
// CHECK: [[COPIED:%.*]] = copy_value [[ARG10]] : $any Base<Int> & P
// CHECK-NEXT: unconditional_checked_cast [[COPIED]] : $any Base<Int> & P to DerivedT
let _ = baseIntAndP_concrete as! DerivedT
// CHECK: [[COPIED:%.*]] = copy_value [[ARG10]] : $any Base<Int> & P
// CHECK-NEXT: checked_cast_br [[COPIED]] : $any Base<Int> & P to BaseT
let _ = baseIntAndP_concrete as? BaseT
// CHECK: [[COPIED:%.*]] = copy_value [[ARG10]] : $any Base<Int> & P
// CHECK-NEXT: unconditional_checked_cast [[COPIED]] : $any Base<Int> & P to BaseT
let _ = baseIntAndP_concrete as! BaseT
// CHECK: [[COPIED:%.*]] = copy_value [[ARG10]] : $any Base<Int> & P
// CHECK-NEXT: checked_cast_br [[COPIED]] : $any Base<Int> & P to BaseInt
let _ = baseIntAndP_concrete as? BaseInt
// CHECK: [[COPIED:%.*]] = copy_value [[ARG10]] : $any Base<Int> & P
// CHECK-NEXT: unconditional_checked_cast [[COPIED]] : $any Base<Int> & P to BaseInt
let _ = baseIntAndP_concrete as! BaseInt
// CHECK: [[COPIED:%.*]] = copy_value [[ARG10]] : $any Base<Int> & P
// CHECK-NEXT: checked_cast_br [[COPIED]] : $any Base<Int> & P to BaseTAndP
let _ = baseIntAndP_concrete as? BaseTAndP
// CHECK: [[COPIED:%.*]] = copy_value [[ARG10]] : $any Base<Int> & P
// CHECK-NEXT: unconditional_checked_cast [[COPIED]] : $any Base<Int> & P to BaseTAndP
let _ = baseIntAndP_concrete as! BaseTAndP
// CHECK: return
// CHECK-NEXT: }
}
|
apache-2.0
|
81a8af7b539ba01c74334f7871cfb3a6
| 52.717391 | 785 | 0.595232 | 3.125331 | false | false | false | false |
davidcairns/DePict
|
DePictLib/DePictLib/Colorer.swift
|
1
|
2550
|
//
// Colorer.swift
// DePictLib
//
// Created by David Cairns on 4/16/15.
// Copyright (c) 2015 David Cairns. All rights reserved.
//
import Foundation
import CoreGraphics
public typealias ColorerFunc = (CGContext) -> ()
public struct Colorer {
public let width, height: Double
public let build: ColorerFunc
}
public func EmptyColorer() -> Colorer {
return Colorer(width: 0.0, height: 0.0) { _ in }
}
private func compose_colorer_builds(_ lhs: @escaping ColorerFunc, rhs: @escaping ColorerFunc) -> ColorerFunc {
return { context in
lhs(context)
rhs(context)
}
}
// Draw on top of each other
public func +(lhs: Colorer, rhs: Colorer) -> Colorer {
return Colorer(width: max(lhs.width, rhs.width), height: max(lhs.height, rhs.height), build: compose_colorer_builds(lhs.build, rhs: rhs.build))
}
// Draw Left next to Right
public func nextTo(_ lhs: Colorer, _ rhs: Colorer, distance: Int = 0) -> Colorer {
return Colorer(width: lhs.width + rhs.width + Double(distance),
height: max(lhs.height, rhs.height),
build: compose_colorer_builds(lhs.build, rhs: Translated(x: Int(lhs.width) + distance, y: 0, colorer: rhs).build))
}
public func |||(lhs: Colorer, rhs: Colorer) -> Colorer {
return nextTo(lhs, rhs)
}
// Draw Left on top of Right
public func onTopOf(_ lhs: Colorer, _ rhs: Colorer, distance: Int = 0) -> Colorer {
return Colorer(width: max(lhs.width, rhs.width),
height: lhs.height + rhs.height + Double(distance),
build: compose_colorer_builds(rhs.build, rhs: Translated(x: 0, y: Int(rhs.height) + distance, colorer: lhs).build))
}
public func ---(lhs: Colorer, rhs: Colorer) -> Colorer {
return onTopOf(lhs, rhs)
}
public typealias ColorerCombiner = ((Colorer, Colorer) -> Colorer)
public func spaced(_ distance: Int = 10) -> ColorerCombiner {
return { lhs, rhs in
return nextTo(lhs, rhs, distance: distance)
}
}
public func stacked(_ distance: Int = 10) -> ColorerCombiner {
return { lhs, rhs in
return onTopOf(lhs, rhs, distance: distance)
}
}
public func Outlined(color: Color, shape: Shape) -> Colorer {
return Colorer(width: shape.width, height: shape.height) { context in
applyPushed(context) {
context.setStrokeColor(colorToCGColor(color))
context.addPath(shape.build())
context.strokePath()
}
}
}
public func Filled(color: Color, shape: Shape) -> Colorer {
return Colorer(width: shape.width, height: shape.height) { context in
applyPushed(context) {
context.setFillColor(colorToCGColor(color))
context.addPath(shape.build())
context.fillPath()
}
}
}
|
mit
|
a150f49fffabac696120cfc46103dd20
| 28.651163 | 144 | 0.697647 | 3.072289 | false | false | false | false |
iOSDevLog/iOSDevLog
|
171. photo-extensions-Filtster/FiltsterPack/CIImageRenderer.swift
|
1
|
2224
|
/*
* 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 CoreImage
import GLKit
public class CIImageRendererView: GLKView {
var renderContext: CIContext
public var image: CIImage! {
didSet {
setNeedsDisplay()
}
}
override public init(frame: CGRect, context: EAGLContext) {
renderContext = CIContext(EAGLContext: context)
super.init(frame: frame, context: context)
enableSetNeedsDisplay = true
}
public required init?(coder aDecoder: NSCoder) {
let eaglContext = EAGLContext(API: .OpenGLES2)
renderContext = CIContext(EAGLContext: eaglContext)
super.init(coder: aDecoder)
context = eaglContext
enableSetNeedsDisplay = true
}
override public func drawRect(rect: CGRect) {
if let image = image {
let imageSize = image.extent.size
var drawFrame = CGRectMake(0, 0, CGFloat(drawableWidth), CGFloat(drawableHeight))
let imageAR = imageSize.width / imageSize.height
let viewAR = drawFrame.width / drawFrame.height
if imageAR > viewAR {
drawFrame.origin.y += (drawFrame.height - drawFrame.width / imageAR) / 2.0
drawFrame.size.height = drawFrame.width / imageAR
} else {
drawFrame.origin.x += (drawFrame.width - drawFrame.height * imageAR) / 2.0
drawFrame.size.width = drawFrame.height * imageAR
}
// clear eagl view to black
glClearColor(0.0, 0.0, 0.0, 1.0);
glClear(0x00004000)
// set the blend mode to "source over" so that CI will use that
glEnable(0x0BE2);
glBlendFunc(1, 0x0303);
renderContext.drawImage(image, inRect: drawFrame, fromRect: image.extent)
}
}
}
|
mit
|
a3fda7cdf0cb878ca960596168657cb6
| 31.705882 | 87 | 0.683453 | 4.080734 | false | false | false | false |
dwsjoquist/ELWebService
|
ELWebServiceTests/MockingTests.swift
|
1
|
4346
|
//
// MockingTests.swift
// ELWebService
//
// Created by Angelo Di Paolo on 3/2/16.
// Copyright © 2016 WalmartLabs. All rights reserved.
//
import XCTest
import ELWebService
// MARK: - Mock Data Task
class MockingTests: XCTestCase {
func test_mockDataTask_changesStateWhenSuspended() {
let task = MockDataTask()
task.resume()
task.suspend()
XCTAssertEqual(task.state, URLSessionTask.State.suspended)
}
func test_mockDataTask_changesStateWhenCancelled() {
let task = MockDataTask()
task.cancel()
XCTAssertEqual(task.state, URLSessionTask.State.canceling)
}
func test_mockDataTask_changesStateWhenResumed() {
let task = MockDataTask()
task.resume()
XCTAssertEqual(task.state, URLSessionTask.State.running)
}
}
// MARK: - Mock Session
extension MockingTests {
func test_mockSession_matchesStubWhenMatcherReturnsTrue() {
struct StubRequest: URLRequestEncodable {
var urlRequestValue: URLRequest {
// using NSURLRequest because its API allows us to initialize an
// empty object to represent a bogus request which is the only
// way to test this code path
return URLRequest(url: URL(string: "https://github.com/")!)
}
}
let session = MockSession()
let response = MockResponse(statusCode: 200)
session.addStub(response) { _ in return true }
let (_, urlResponse, error) = session.stubbedResponse(request: StubRequest())
let httpResponse = urlResponse as? HTTPURLResponse
XCTAssertNotNil(httpResponse)
XCTAssertEqual(httpResponse!.statusCode, 200)
XCTAssertNil(error)
}
func test_mockSession_failsToMatchStubWhenMatcherReturnsFalse() {
struct StubRequest: URLRequestEncodable {
var urlRequestValue: URLRequest {
return URLRequest(url: URL(string: "")!)
}
}
let session = MockSession()
let response = MockResponse(statusCode: 200)
session.addStub(response) { _ in return false }
let (data, urlResponse, error) = session.stubbedResponse(request: StubRequest())
XCTAssertNil(data)
XCTAssertNil(urlResponse)
XCTAssertNil(error)
}
}
// MARK: - Mock Response
extension MockingTests {
func test_mockResponse_initializationWithData() {
let data = Data()
let response = MockResponse(statusCode: 200, data: data)
XCTAssertNotNil(response.data)
XCTAssertEqual(data, response.data)
}
func test_mockResponse_returnsErrorResultWhenRequestURLIsInvalid() {
struct InvalidURLRequestEncodable: URLRequestEncodable {
var urlRequestValue: URLRequest {
// using NSURLRequest because its API allows us to initialize an
// empty object to represent a bogus request which is the only
// way to test this code path
return NSURLRequest() as URLRequest
}
}
let data = Data()
let mockedResponse = MockResponse(statusCode: 200, data: data)
let (responseData, httpResponse, error) = mockedResponse.dataTaskResult(InvalidURLRequestEncodable())
XCTAssertNil(httpResponse)
XCTAssertNil(responseData)
XCTAssertNotNil(error)
}
}
extension MockingTests {
func test_urlResponse_mockableDataTask() {
let url = URL(string: "/test_urlResponse_mockableDataTask")!
let response = URLResponse(url: url, mimeType: nil, expectedContentLength: 0, textEncodingName: nil)
let request = URLRequest(url: url)
let (_, urlResponse, _) = response.dataTaskResult(request)
XCTAssertEqual(urlResponse, response)
}
func test_error_mockableDataTask() {
let error = NSError(domain: "test", code: 500, userInfo: nil)
let request = URLRequest(url: URL(string: "/test_error_mockableDataTask")!)
let (_, _, resultError) = error.dataTaskResult(request)
XCTAssertEqual(resultError as! NSError, error)
}
}
|
mit
|
20b0496687dbeb66220344dd93199518
| 30.485507 | 109 | 0.620483 | 5.105758 | false | true | false | false |
dduan/swift
|
test/SourceKit/CodeComplete/complete_inner.swift
|
4
|
5103
|
class Foo {}
class Base {
init() {}
func base() {}
}
class FooBar {
init() {}
init(x: Foo) {}
static func fooBar() {}
static func fooBaz() {}
func method() {}
let prop: FooBar { return FooBar() }
subscript(x: Foo) -> Foo {}
}
func test001() {
#^TOP_LEVEL_0,fo,foo,foob,foobar^#
}
// RUN: %complete-test %s -no-fuzz -group=none -add-inner-results -tok=TOP_LEVEL_0 | FileCheck %s -check-prefix=TOP_LEVEL_0
// TOP_LEVEL_0-LABEL: Results for filterText: fo [
// TOP_LEVEL_0-NEXT: for
// TOP_LEVEL_0-NEXT: Foo
// TOP_LEVEL_0-NEXT: FooBar
// TOP_LEVEL_0: ]
// TOP_LEVEL_0-LABEL: Results for filterText: foo [
// TOP_LEVEL_0-NEXT: Foo
// TOP_LEVEL_0-NEXT: Foo(
// TOP_LEVEL_0-NEXT: FooBar
// TOP_LEVEL_0-NEXT: Foo()
// TOP_LEVEL_0-NEXT: ]
// TOP_LEVEL_0-LABEL: Results for filterText: foob [
// TOP_LEVEL_0-NEXT: FooBar
// TOP_LEVEL_0-NEXT: ]
// TOP_LEVEL_0-LABEL: Results for filterText: foobar [
// TOP_LEVEL_0-NEXT: FooBar
// TOP_LEVEL_0-NEXT: FooBar.
// TOP_LEVEL_0-NEXT: FooBar(
// TOP_LEVEL_0-NEXT: FooBar()
// TOP_LEVEL_0-NEXT: FooBar(x: Foo)
// TOP_LEVEL_0-NEXT: FooBar.fooBar()
// TOP_LEVEL_0-NEXT: FooBar.fooBaz()
// TOP_LEVEL_0: ]
func test002(abc: FooBar, abd: Base) {
#^TOP_LEVEL_1,ab,abc,abd^#
}
// RUN: %complete-test %s -no-fuzz -group=none -add-inner-results -tok=TOP_LEVEL_1 | FileCheck %s -check-prefix=TOP_LEVEL_1
// TOP_LEVEL_1-LABEL: Results for filterText: ab [
// TOP_LEVEL_1-NEXT: abc
// TOP_LEVEL_1-NEXT: abd
// TOP_LEVEL_1: ]
// TOP_LEVEL_1-LABEL: Results for filterText: abc [
// TOP_LEVEL_1-NEXT: abc
// TOP_LEVEL_1-NEXT: abc.
// TOP_LEVEL_1-NEXT: abc!==
// TOP_LEVEL_1-NEXT: abc===
// TOP_LEVEL_1-NEXT: abc.method()
// TOP_LEVEL_1-NEXT: abc.prop
// TOP_LEVEL_1-NEXT: ]
// TOP_LEVEL_1-LABEL: Results for filterText: abd [
// TOP_LEVEL_1-NEXT: abd
// TOP_LEVEL_1-NEXT: abd.
// TOP_LEVEL_1-NEXT: abd!==
// TOP_LEVEL_1-NEXT: abd===
// TOP_LEVEL_1-NEXT: abd.base()
// TOP_LEVEL_1-NEXT: ]
func test003(x: FooBar) {
x.#^FOOBAR_QUALIFIED,pro,prop,prop.^#
}
// RUN: %complete-test %s -group=none -add-inner-results -tok=FOOBAR_QUALIFIED | FileCheck %s -check-prefix=FOOBAR_QUALIFIED
// FOOBAR_QUALIFIED-LABEL: Results for filterText: pro [
// FOOBAR_QUALIFIED-NEXT: prop
// FOOBAR_QUALIFIED-NEXT: ]
// FOOBAR_QUALIFIED-LABEL: Results for filterText: prop [
// FOOBAR_QUALIFIED-NEXT: prop
// FOOBAR_QUALIFIED-NEXT: prop.
// FOOBAR_QUALIFIED: prop.method()
// FOOBAR_QUALIFIED-NEXT: prop.prop
// FOOBAR_QUALIFIED-NEXT: ]
// Just don't explode. We generally expect to get a new session here.
// FOOBAR_QUALIFIED-LABEL: Results for filterText: prop. [
// FOOBAR_QUALIFIED-NEXT: ]
// RUN: %complete-test %s -group=none -no-inner-results -inner-operators -tok=FOOBAR_QUALIFIED | FileCheck %s -check-prefix=FOOBAR_QUALIFIED_OP
// FOOBAR_QUALIFIED_OP-LABEL: Results for filterText: pro [
// FOOBAR_QUALIFIED_OP-NEXT: prop
// FOOBAR_QUALIFIED_OP-NEXT: ]
// FOOBAR_QUALIFIED_OP-LABEL: Results for filterText: prop [
// FOOBAR_QUALIFIED_OP-NEXT: prop
// FOOBAR_QUALIFIED_OP-NEXT: prop.
// FOOBAR_QUALIFIED_OP: ]
// RUN: %complete-test %s -group=none -add-inner-results -no-inner-operators -tok=FOOBAR_QUALIFIED | FileCheck %s -check-prefix=FOOBAR_QUALIFIED_NOOP
// FOOBAR_QUALIFIED_NOOP-LABEL: Results for filterText: pro [
// FOOBAR_QUALIFIED_NOOP-NEXT: prop
// FOOBAR_QUALIFIED_NOOP-NEXT: ]
// FOOBAR_QUALIFIED_NOOP-LABEL: Results for filterText: prop [
// FOOBAR_QUALIFIED_NOOP-NEXT: prop
// FOOBAR_QUALIFIED_NOOP-NEXT: prop.method()
// FOOBAR_QUALIFIED_NOOP-NEXT: prop.prop
// FOOBAR_QUALIFIED_NOOP-NEXT: ]
// RUN: %complete-test %s -group=none -no-include-exact-match -add-inner-results -no-inner-operators -tok=FOOBAR_QUALIFIED | FileCheck %s -check-prefix=FOOBAR_QUALIFIED_NOEXACT
// FOOBAR_QUALIFIED_NOEXACT-LABEL: Results for filterText: prop [
// FOOBAR_QUALIFIED_NOEXACT-NEXT: prop.method()
// FOOBAR_QUALIFIED_NOEXACT-NEXT: prop.prop
// FOOBAR_QUALIFIED_NOEXACT-NEXT: ]
func test004() {
FooBar#^FOOBAR_POSTFIX^#
}
// RUN: %complete-test %s -group=none -no-inner-results -inner-operators -tok=FOOBAR_POSTFIX | FileCheck %s -check-prefix=FOOBAR_POSTFIX_OP
// FOOBAR_POSTFIX_OP: {{^}}.{{$}}
// FOOBAR_POSTFIX_OP: {{^}}({{$}}
func test005(x: FooBar) {
x#^FOOBAR_INSTANCE_POSTFIX^#
}
// RUN: %complete-test %s -group=none -no-inner-results -inner-operators -tok=FOOBAR_INSTANCE_POSTFIX | FileCheck %s -check-prefix=FOOBAR_INSTANCE_POSTFIX_OP
// FOOBAR_INSTANCE_POSTFIX_OP: .
// FIXME: We should probably just have '[' here - rdar://22702955
// FOOBAR_INSTANCE_POSTFIX_OP: [Foo]
func test005(x: Base?) {
x#^OPTIONAL_POSTFIX^#
}
// RUN: %complete-test %s -group=none -no-inner-results -inner-operators -tok=OPTIONAL_POSTFIX | FileCheck %s -check-prefix=OPTIONAL_POSTFIX_OP
// OPTIONAL_POSTFIX_OP: .
// OPTIONAL_POSTFIX_OP: ?.
// RUN: %complete-test %s -group=none -no-inner-results -inner-operators -tok=KEYWORD_0 | FileCheck %s -check-prefix=KEYWORD_0
func test006() {
#^KEYWORD_0,for^#
}
// KEYWORD_0-NOT: for_
// KEYWORD_0-NOT: fortest
// KEYWORD_0-NOT: for.
|
apache-2.0
|
0c5fa3e72e776cafc423a3e075af3da4
| 34.4375 | 176 | 0.67862 | 2.799232 | false | true | false | false |
alexanderedge/Toolbelt
|
Toolbelt/Toolbelt/Geometry.swift
|
1
|
2950
|
//
// Geometry.swift
// Toolbelt
//
// The MIT License (MIT)
//
// Copyright (c) 02/05/2015 Alexander G Edge
//
// 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 CoreGraphics
extension CGRect {
public init (center: CGPoint, size: CGSize) {
let originX = center.x - (size.width / 2)
let originY = center.y - (size.height / 2)
self.init(origin: CGPoint(x: originX, y: originY), size: size)
}
public var center : CGPoint {
return CGPoint(x: self.midX, y: self.midY)
}
public var diagonal : CGFloat {
return sqrt(pow(self.width,2) + pow(self.height,2))
}
}
public func CGRectMake(_ center : CGPoint, size : CGSize) -> CGRect {
return CGRect(center: center, size: size)
}
public func CGRectGetCenter(_ rect : CGRect) -> CGPoint {
return rect.center
}
public func CGRectDiagonal(_ rect: CGRect) -> CGFloat {
return rect.diagonal
}
// return rect2 that fits inside rect1, resizing and moving if necessary
public func CGRectInsideRect(_ rect1 : CGRect, rect2 : CGRect) -> CGRect {
let width = min(rect1.width, rect2.width);
let height = min(rect1.height, rect2.height);
var xPos = max(rect1.minX, rect2.minX);
var yPos = max(rect1.minY, rect2.minY);
// check right
if ((xPos + width) > rect1.maxX) {
xPos = rect1.maxX - width;
}
// check bottom
if ((yPos + height) > rect1.maxY) {
yPos = rect1.maxY - height;
}
return CGRect(x: xPos, y: yPos, width: width, height: height);
}
protocol Scalable {
func scaleBy(_ scale : CGFloat) -> Self
}
extension CGSize : Scalable {
func scaleBy(_ scale: CGFloat) -> CGSize {
guard scale > 0 else {
fatalError("negative scale factor encountered")
}
return CGSize(width: self.width * scale, height: self.height * scale)
}
}
|
mit
|
b1373734c34bb872230c09c57fc42459
| 30.052632 | 81 | 0.661356 | 3.907285 | false | false | false | false |
Artilles/FloppyCows
|
Floppy Cows/GameOverScene.swift
|
1
|
4790
|
//
// GameOverScene.swift
// Floppy Cows
//
// Created by Jon Bergen on 2014-11-05.
// Copyright (c) 2014 Velocitrix. All rights reserved.
//
import SpriteKit
import Darwin
import AVFoundation
class GameOverScene: SKScene {
var _gameOverText:SKSpriteNode = SKSpriteNode(imageNamed: "gameoverlogo.png")
var _gameOverPic:SKSpriteNode = SKSpriteNode(imageNamed: "alienCows.jpg")
var _playButton:SKSpriteNode = SKSpriteNode(imageNamed: "playagain_button.png")
var _quitButton:SKSpriteNode = SKSpriteNode(imageNamed: "menu2_button.png")
let scoreLabel = SKLabelNode(fontNamed:"ChalkboardSE-Bold")
var soundPlayer:AVAudioPlayer = AVAudioPlayer()
var menuMusicURL:NSURL = NSBundle.mainBundle().URLForResource("menuMusic", withExtension: "mp3")!
var score : Int = 0
override init(size:CGSize) {
super.init(size: size)
self.backgroundColor = SKColor.whiteColor()
initMenu()
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// Menu Initialization
func initMenu()
{
// Add GameOver Picture
_gameOverPic.position = CGPoint(x: self.size.width / 2, y: self.size.height / 2)
_gameOverPic.setScale(2)
_gameOverPic.zPosition = -2
self.addChild(_gameOverPic)
// Add Game Over text
_gameOverText.position = CGPoint(x: (self.size.width / 2) + 3, y: self.size.height / 2 + 250)
_gameOverText.setScale(0.2)
self.addChild(_gameOverText)
// Add Play button
_playButton.position = CGPoint(x: _playButton.size.width / 2, y: 40)
_playButton.setScale(0.8)
self.addChild(_playButton)
// add Menu button
_quitButton.position = CGPoint(x: self.size.width - (_quitButton.size.width / 2), y: 40)
_quitButton.setScale(0.8)
self.addChild(_quitButton)
var mooURL:NSURL = NSBundle.mainBundle().URLForResource("gameover", withExtension: "mp3")!
soundPlayer = AVAudioPlayer(contentsOfURL: mooURL, error: nil)
soundPlayer.prepareToPlay()
soundPlayer.play()
}
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
for touch: AnyObject in touches {
// Reset button touched
if CGRectContainsPoint(_playButton.frame, touch.locationInNode(self)) {
_playButton.texture = SKTexture(imageNamed: "playagain_button_pressed.png")
}
// Back button touched
if CGRectContainsPoint(_quitButton.frame, touch.locationInNode(self)) {
_quitButton.texture = SKTexture(imageNamed: "menu2_button_pressed.png")
}
}
}
override func touchesMoved(touches: NSSet, withEvent event: UIEvent) {
for touch: AnyObject in touches {
if !CGRectContainsPoint(_playButton.frame, touch.locationInNode(self)) {
_playButton.texture = SKTexture(imageNamed: "playagain_button.png")
}
if !CGRectContainsPoint(_quitButton.frame, touch.locationInNode(self)) {
_quitButton.texture = SKTexture(imageNamed: "menu2_button.png")
}
}
}
override func touchesEnded(touches: NSSet, withEvent event: UIEvent) {
for touch: AnyObject in touches {
// Play button touched
if CGRectContainsPoint(_playButton.frame, touch.locationInNode(self)) {
playButtonPressed()
}
// Quit button touched
if CGRectContainsPoint(_quitButton.frame, touch.locationInNode(self)) {
quitButtonPressed()
}
}
}
// Callback event for Play button
func playButtonPressed() {
let scene = GameScene(size: self.size)
scene.scaleMode = .AspectFill
self.view?.presentScene(scene)
}
// Callback event for Quit button
func quitButtonPressed() {
backgroundMusicPlayer = AVAudioPlayer(contentsOfURL: menuMusicURL, error: nil)
backgroundMusicPlayer.play()
let scene = MenuScene(size: self.size)
scene.scaleMode = .AspectFill
self.view?.presentScene(scene)
}
func SetScore(finalScore : Int)
{
score = finalScore
scoreLabel.text = "Final Score: \(finalScore)"
self.addChild(scoreLabel)
scoreLabel.position.x = self.size.width / 2
scoreLabel.position.y = self.size.height - 35
scoreLabel.color = SKColor(red: 1.0, green: 0.0, blue: 0.3, alpha: 1.0)
scoreLabel.colorBlendFactor = 1.0
scoreLabel.zPosition = 100
}
}
|
gpl-2.0
|
6ccd5aff11a71aa24e161ae7fdba84e2
| 34.488889 | 101 | 0.616701 | 4.566254 | false | false | false | false |
brunodlz/Couch
|
Couch/Couch/Core/Networking/TraktAPI.swift
|
1
|
3288
|
import Foundation
public enum HTTPMethod: String {
case get = "GET"
case post = "POST"
}
struct OAuth {
static let url = "https://api.trakt.tv"
static let clientID = "1a611bba8dcd8b33aa53911c92455a1f2cc950dd578a2024e0613cf13fe69b4f"
static let clientSecret = "46b06c01513f9282e803dd9b2a152e4d05a0386635e916727260c1c5c78294ec"
static let redirectURI = "urn:ietf:wg:oauth:2.0:oob"
static let authorization = "\(OAuth.url)/oauth/authorize/"
+ "?client_id=" + OAuth.clientID
+ "&redirect_uri=" + OAuth.redirectURI
+ "&response_type=code"
}
final class TraktAPI {
enum Endpoints {
case token
case profile
case popular
case shows(String)
case summary(String)
case progress(String)
case allSeasons(String)
case episodeDetails(String,Int,Int)
func url() -> String {
switch self {
case .token:
return "\(OAuth.url)/oauth/token"
case .profile:
return "\(OAuth.url)/users/settings"
case .popular:
return "\(OAuth.url)/movies/popular"
case .shows(let user):
return "\(OAuth.url)/users/\(user)/watchlist/shows"
case .summary(let imdb):
return "\(OAuth.url)shows/\(imdb)?extended=full"
case .progress(let imdb):
return "\(OAuth.url)/shows/\(imdb)/progress/watched"
case .allSeasons(let imdb):
return "\(OAuth.url)/shows/\(imdb)/seasons?extended=episodes"
case .episodeDetails(let imdb, let season, let episode):
return "\(OAuth.url)/shows/\(imdb)/seasons/\(season)/episodes/\(episode)?extended=full"
}
}
}
func token() -> URLRequest? {
let endPoint = URL(string: TraktAPI.Endpoints.token.url())
return TraktAPI.to(endPoint, method: .post, authorization: true)
}
func profile() -> URLRequest? {
let endPoint = URL(string: TraktAPI.Endpoints.profile.url())
return TraktAPI.to(endPoint, method: .get, authorization: true)
}
func popular() -> URLRequest? {
let endPoint = URL(string: TraktAPI.Endpoints.popular.url())
return TraktAPI.to(endPoint, method: .get)
}
func shows(_ user: String) -> URLRequest? {
let endPoint = URL(string: TraktAPI.Endpoints.shows(user).url())
return TraktAPI.to(endPoint, method: .get)
}
func progress(_ imdb: String) -> URLRequest? {
let endPoint = URL(string: TraktAPI.Endpoints.progress(imdb).url())
return TraktAPI.to(endPoint, method: .get, authorization: true)
}
func allSeasons(_ imdb: String) -> URLRequest? {
let endPoint = URL(string: TraktAPI.Endpoints.allSeasons(imdb).url())
return TraktAPI.to(endPoint, method: .get)
}
func episodeDetails(_ imdb: String, season: Int, episode: Int) -> URLRequest? {
let endPoint = URL(string: TraktAPI.Endpoints.episodeDetails(imdb, season, episode).url())
return TraktAPI.to(endPoint, method: .get)
}
}
|
mit
|
f7a19ccdfc6378c34c648eb61848a4a9
| 33.978723 | 103 | 0.579988 | 4.099751 | false | false | false | false |
BanyaKrylov/Learn-Swift
|
5.1/HW4.playground/Contents.swift
|
1
|
696
|
import UIKit
//Homework 4
let decimal = 17
let binary = 0b10001
let octal = 0o21
let hexadecimal = 0x11
let exponent = 1.25e2
let hexExponent = 0xFp-2
var number = 1_123_456
var char: Character = "a"
var str: String = "Hello"
let longString = """
Это
многострочный
литерал
"""
var conc = String(number) + String(char) + longString
conc.count
var str2 = "This is String literal"
let char2 = "a"
var num1 = 1, num2 = 2
let concatenation: String = str2 + String(char2) + String(num1 + num2)
print(concatenation)
let w = """
* * *
* * *
* *
"""
print(w)
var day = 21
var month = "January"
var year = 2020
print(String(year) + " " + month + " " + String(day))
|
apache-2.0
|
fefd6b4110b42cb6bd2e5a1d05b51339
| 13.630435 | 70 | 0.649331 | 2.618677 | false | false | false | false |
yonadev/yona-app-ios
|
Yona/Yona/Array.swift
|
1
|
1117
|
//
// Array.swift
// Yona
//
// Created by Chandan on 04/05/16.
// Copyright © 2016 Yona. All rights reserved.
//
import Foundation
extension Array {
func converToDate() -> [ToFromDate]{
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "HH:mm"
var finalZoneArray = [ToFromDate]()
for arr in self {
let bifurcateArray = String(describing: arr).dashRemoval()
finalZoneArray.append(ToFromDate(fromDate: dateFormatter.date(from: bifurcateArray[0])!, toDate: dateFormatter.date(from: bifurcateArray[1])!))
}
return finalZoneArray
}
func convertToString() -> [String] {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "HH:mm"
var finalZoneArray = [String]()
for arr in self {
let bifurcateArray = (arr as! ToFromDate)
finalZoneArray.append("\(dateFormatter.string(from: bifurcateArray.fromDate as Date))-\(dateFormatter.string(from: bifurcateArray.toDate as Date))")
}
return finalZoneArray
}
}
|
mpl-2.0
|
9eff97c37485418f9c935c6c4f9f9bb8
| 30 | 160 | 0.621864 | 4.164179 | false | false | false | false |
laurentVeliscek/AudioKit
|
AudioKit/Common/Nodes/Effects/Filters/Low Pass Filter/AKLowPassFilter.swift
|
2
|
4420
|
//
// AKLowPassFilter.swift
// AudioKit
//
// Created by Aurelius Prochazka, revision history on Github.
// Copyright (c) 2016 Aurelius Prochazka. All rights reserved.
//
import AVFoundation
/// AudioKit version of Apple's LowPassFilter Audio Unit
///
/// - Parameters:
/// - input: Input node to process
/// - cutoffFrequency: Cutoff Frequency (Hz) ranges from 10 to 22050 (Default: 6900)
/// - resonance: Resonance (dB) ranges from -20 to 40 (Default: 0)
///
public class AKLowPassFilter: AKNode, AKToggleable {
private let cd = AudioComponentDescription(
componentType: kAudioUnitType_Effect,
componentSubType: kAudioUnitSubType_LowPassFilter,
componentManufacturer: kAudioUnitManufacturer_Apple,
componentFlags: 0,
componentFlagsMask: 0)
internal var internalEffect = AVAudioUnitEffect()
internal var internalAU: AudioUnit = nil
private var mixer: AKMixer
/// Cutoff Frequency (Hz) ranges from 10 to 22050 (Default: 6900)
public var cutoffFrequency: Double = 6900 {
didSet {
if cutoffFrequency < 10 {
cutoffFrequency = 10
}
if cutoffFrequency > 22050 {
cutoffFrequency = 22050
}
AudioUnitSetParameter(
internalAU,
kLowPassParam_CutoffFrequency,
kAudioUnitScope_Global, 0,
Float(cutoffFrequency), 0)
}
}
/// Resonance (dB) ranges from -20 to 40 (Default: 0)
public var resonance: Double = 0 {
didSet {
if resonance < -20 {
resonance = -20
}
if resonance > 40 {
resonance = 40
}
AudioUnitSetParameter(
internalAU,
kLowPassParam_Resonance,
kAudioUnitScope_Global, 0,
Float(resonance), 0)
}
}
/// Dry/Wet Mix (Default 100)
public var dryWetMix: Double = 100 {
didSet {
if dryWetMix < 0 {
dryWetMix = 0
}
if dryWetMix > 100 {
dryWetMix = 100
}
inputGain?.volume = 1 - dryWetMix / 100
effectGain?.volume = dryWetMix / 100
}
}
private var lastKnownMix: Double = 100
private var inputGain: AKMixer?
private var effectGain: AKMixer?
/// Tells whether the node is processing (ie. started, playing, or active)
public var isStarted = true
// MARK: - Initialization
/// Initialize the low pass filter node
///
/// - Parameters:
/// - input: Input node to process
/// - cutoffFrequency: Cutoff Frequency (Hz) ranges from 10 to 22050 (Default: 6900)
/// - resonance: Resonance (dB) ranges from -20 to 40 (Default: 0)
///
public init(
_ input: AKNode,
cutoffFrequency: Double = 6900,
resonance: Double = 0) {
self.cutoffFrequency = cutoffFrequency
self.resonance = resonance
inputGain = AKMixer(input)
inputGain!.volume = 0
mixer = AKMixer(inputGain!)
effectGain = AKMixer(input)
effectGain!.volume = 1
internalEffect = AVAudioUnitEffect(audioComponentDescription: cd)
super.init()
AudioKit.engine.attachNode(internalEffect)
internalAU = internalEffect.audioUnit
AudioKit.engine.connect((effectGain?.avAudioNode)!, to: internalEffect, format: AudioKit.format)
AudioKit.engine.connect(internalEffect, to: mixer.avAudioNode, format: AudioKit.format)
avAudioNode = mixer.avAudioNode
AudioUnitSetParameter(internalAU, kLowPassParam_CutoffFrequency, kAudioUnitScope_Global, 0, Float(cutoffFrequency), 0)
AudioUnitSetParameter(internalAU, kLowPassParam_Resonance, kAudioUnitScope_Global, 0, Float(resonance), 0)
}
// MARK: - Control
/// Function to start, play, or activate the node, all do the same thing
public func start() {
if isStopped {
dryWetMix = lastKnownMix
isStarted = true
}
}
/// Function to stop or bypass the node, both are equivalent
public func stop() {
if isPlaying {
lastKnownMix = dryWetMix
dryWetMix = 0
isStarted = false
}
}
}
|
mit
|
0f2e6cb317ec697482ddf11a6f9b4563
| 30.126761 | 130 | 0.58914 | 5.230769 | false | false | false | false |
eTilbudsavis/native-ios-eta-sdk
|
Demos/SharedSource/UIViewController+Cycle.swift
|
1
|
2364
|
//
// ┌────┬─┐ ┌─────┐
// │ ──┤ └─┬───┬───┤ ┌──┼─┬─┬───┐
// ├── │ ╷ │ · │ · │ ╵ │ ╵ │ ╷ │
// └────┴─┴─┴───┤ ┌─┴─────┴───┴─┴─┘
// └─┘
//
// Copyright (c) 2019 ShopGun. All rights reserved.
import UIKit
extension UIViewController {
func cycleFromViewController(oldViewController: UIViewController?, toViewController newViewController: UIViewController?, in container: UIView? = nil) {
guard let newViewController = newViewController else {
oldViewController?.willMove(toParent: nil)
oldViewController?.view.removeFromSuperview()
oldViewController?.removeFromParent()
return
}
newViewController.view.translatesAutoresizingMaskIntoConstraints = false
self.addChild(newViewController)
self.addSubview(
subView: newViewController.view,
toView: container ?? self.view
)
newViewController.view.layoutIfNeeded()
guard let oldVC = oldViewController else {
newViewController.didMove(toParent: self)
newViewController.view.alpha = 1
return
}
oldVC.willMove(toParent: nil)
newViewController.view.alpha = 0
UIView.animate(withDuration: 0.2, delay: 0, options: .transitionCrossDissolve, animations: {
newViewController.view.alpha = 1
oldVC.view.alpha = 0
}) { (finished) in
oldVC.view.removeFromSuperview()
oldVC.removeFromParent()
newViewController.didMove(toParent: self)
}
}
private func addSubview(subView: UIView, toView parentView: UIView) {
self.view.layoutIfNeeded()
parentView.addSubview(subView)
NSLayoutConstraint.activate([
subView.topAnchor.constraint(equalTo: parentView.topAnchor),
subView.bottomAnchor.constraint(equalTo: parentView.bottomAnchor),
subView.leadingAnchor.constraint(equalTo: parentView.leadingAnchor),
subView.trailingAnchor.constraint(equalTo: parentView.trailingAnchor)
])
}
}
|
mit
|
f99344ce562e65b570600faf2cad705d
| 34.193548 | 156 | 0.589826 | 5.468672 | false | false | false | false |
raphaelmor/GeoJSON
|
GeoJSON/Geometry/MultiPolygon.swift
|
1
|
3358
|
// MultiPolygon.swift
//
// The MIT License (MIT)
//
// Copyright (c) 2014 Raphaël Mor
//
// 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
public final class MultiPolygon : GeoJSONEncodable {
/// Public polygons
public var polygons: [Polygon] { return _polygons }
/// Prefix used for GeoJSON Encoding
public var prefix: String { return "coordinates" }
/// Private polygons
private var _polygons: [Polygon] = []
/**
Designated initializer for creating a MultiPolygon from a SwiftyJSON object
:param: json The SwiftyJSON Object.
:returns: The created MultiPolygon object.
*/
public init?(json: JSON) {
if let jsonPolygons = json.array {
for jsonPolygon in jsonPolygons {
if let polygon = Polygon(json: jsonPolygon) {
_polygons.append(polygon)
}
else {
return nil
}
}
}
else {
return nil
}
}
/**
Designated initializer for creating a MultiLineString from [LineString]
:param: lineStrings The LineString array.
:returns: The created MultiLineString object.
*/
public init?(polygons: [Polygon]) {
_polygons = polygons
}
/**
Build a object that can be serialized to JSON
:returns: Representation of the MultiPolygon Object
*/
public func json() -> AnyObject {
return _polygons.map { $0.json() }
}
}
/// Array forwarding methods
public extension MultiPolygon {
/// number of polygons
public var count: Int { return polygons.count }
/// subscript to access the Nth polygon
public subscript(index: Int) -> Polygon {
get { return _polygons[index] }
set(newValue) { _polygons[index] = newValue }
}
}
/// MultiPolygon related methods on GeoJSON
public extension GeoJSON {
/// Optional MultiPolygon
public var multiPolygon: MultiPolygon? {
get {
switch type {
case .MultiPolygon:
return object as? MultiPolygon
default:
return nil
}
}
set {
_object = newValue ?? NSNull()
}
}
/**
Convenience initializer for creating a GeoJSON Object from a MultiPolygon
:param: multiPolygon The MultiPolygon object.
:returns: The created GeoJSON object.
*/
convenience public init(multiPolygon: MultiPolygon) {
self.init()
object = multiPolygon
}
}
|
mit
|
3f701d1e36f36578cd2bd2d5eb582134
| 26.752066 | 81 | 0.686923 | 4.298335 | false | false | false | false |
colourful987/JustMakeGame-FlappyBird
|
Code/L07/FlappyBird-End/FlappyBird/GameScene.swift
|
1
|
14407
|
//
// GameScene.swift
// FlappyBird
//
// Created by pmst on 15/10/4.
// Copyright (c) 2015年 pmst. All rights reserved.
//
import SpriteKit
enum Layer: CGFloat {
case Background
case Obstacle
case Foreground
case Player
case UI
}
enum GameState{
case MainMenu
case Tutorial
case Play
case Falling
case ShowingScore
case GameOver
}
struct PhysicsCategory {
static let None: UInt32 = 0
static let Player: UInt32 = 0b1 // 1
static let Obstacle: UInt32 = 0b10 // 2
static let Ground: UInt32 = 0b100 // 4
}
class GameScene: SKScene,SKPhysicsContactDelegate{
// MARK: - 常量
let kGravity:CGFloat = -1500.0
let kImpulse:CGFloat = 400
let kGroundSpeed:CGFloat = 150.0
let kBottomObstacleMinFraction: CGFloat = 0.1
let kBottomObstacleMaxFraction: CGFloat = 0.6
let kGapMultiplier: CGFloat = 3.5
let worldNode = SKNode()
var playableStart:CGFloat = 0
var playableHeight:CGFloat = 0
let player = SKSpriteNode(imageNamed: "Bird0")
var lastUpdateTime :NSTimeInterval = 0
var dt:NSTimeInterval = 0
var playerVelocity = CGPoint.zero
let sombrero = SKSpriteNode(imageNamed: "Sombrero")
var hitGround = false
var hitObstacle = false
var gameState: GameState = .Play
var scoreLabel:SKLabelNode!
var score = 0
// MARK: - 变量
// MARK: - 音乐
let dingAction = SKAction.playSoundFileNamed("ding.wav", waitForCompletion: false)
let flapAction = SKAction.playSoundFileNamed("flapping.wav", waitForCompletion: false)
let whackAction = SKAction.playSoundFileNamed("whack.wav", waitForCompletion: false)
let fallingAction = SKAction.playSoundFileNamed("falling.wav", waitForCompletion: false)
let hitGroundAction = SKAction.playSoundFileNamed("hitGround.wav", waitForCompletion: false)
let popAction = SKAction.playSoundFileNamed("pop.wav", waitForCompletion: false)
let coinAction = SKAction.playSoundFileNamed("coin.wav", waitForCompletion: false)
override func didMoveToView(view: SKView) {
physicsWorld.gravity = CGVector(dx: 0, dy: 0)
physicsWorld.contactDelegate = self
addChild(worldNode)
setupBackground()
setupForeground()
setupPlayer()
setupSomebrero()
startSpawning()
setupLabel()
flapPlayer()
}
// MARK: Setup Method
func setupBackground(){
// 1
let background = SKSpriteNode(imageNamed: "Background")
background.anchorPoint = CGPointMake(0.5, 1)
background.position = CGPointMake(size.width/2.0, size.height)
background.zPosition = Layer.Background.rawValue
worldNode.addChild(background)
// 2
playableStart = size.height - background.size.height
playableHeight = background.size.height
// 新增
let lowerLeft = CGPoint(x: 0, y: playableStart)
let lowerRight = CGPoint(x: size.width, y: playableStart)
// 1
self.physicsBody = SKPhysicsBody(edgeFromPoint: lowerLeft, toPoint: lowerRight)
self.physicsBody?.categoryBitMask = PhysicsCategory.Ground
self.physicsBody?.collisionBitMask = 0
self.physicsBody?.contactTestBitMask = PhysicsCategory.Player
}
func setupForeground() {
for i in 0..<2{
let foreground = SKSpriteNode(imageNamed: "Ground")
foreground.anchorPoint = CGPoint(x: 0, y: 1)
// 改动1
foreground.position = CGPoint(x: CGFloat(i) * size.width, y: playableStart)
foreground.zPosition = Layer.Foreground.rawValue
// 改动2
foreground.name = "foreground"
worldNode.addChild(foreground)
}
}
func setupPlayer(){
player.position = CGPointMake(size.width * 0.2, playableHeight * 0.4 + playableStart)
player.zPosition = Layer.Player.rawValue
let offsetX = player.size.width * player.anchorPoint.x
let offsetY = player.size.height * player.anchorPoint.y
let path = CGPathCreateMutable()
CGPathMoveToPoint(path, nil, 17 - offsetX, 23 - offsetY)
CGPathAddLineToPoint(path, nil, 39 - offsetX, 22 - offsetY)
CGPathAddLineToPoint(path, nil, 38 - offsetX, 10 - offsetY)
CGPathAddLineToPoint(path, nil, 21 - offsetX, 0 - offsetY)
CGPathAddLineToPoint(path, nil, 4 - offsetX, 1 - offsetY)
CGPathAddLineToPoint(path, nil, 3 - offsetX, 15 - offsetY)
CGPathCloseSubpath(path)
player.physicsBody = SKPhysicsBody(polygonFromPath: path)
player.physicsBody?.categoryBitMask = PhysicsCategory.Player
player.physicsBody?.collisionBitMask = 0
player.physicsBody?.contactTestBitMask = PhysicsCategory.Obstacle | PhysicsCategory.Ground
worldNode.addChild(player)
}
func setupSomebrero(){
sombrero.position = CGPointMake(31 - sombrero.size.width/2, 29 - sombrero.size.height/2)
player.addChild(sombrero)
}
func setupLabel() {
scoreLabel = SKLabelNode(fontNamed: "AmericanTypewriter-Bold")
scoreLabel.fontColor = SKColor(red: 101.0/255.0, green: 71.0/255.0, blue: 73.0/255.0, alpha: 1.0)
scoreLabel.position = CGPoint(x: size.width/2, y: size.height - 20)
scoreLabel.text = "0"
scoreLabel.verticalAlignmentMode = .Top
scoreLabel.zPosition = Layer.UI.rawValue
worldNode.addChild(scoreLabel)
}
// MARK: - GamePlay
func createObstacle()->SKSpriteNode{
let sprite = SKSpriteNode(imageNamed: "Cactus")
sprite.zPosition = Layer.Obstacle.rawValue
sprite.userData = NSMutableDictionary()
//========以下为新增内容=========
let offsetX = sprite.size.width * sprite.anchorPoint.x
let offsetY = sprite.size.height * sprite.anchorPoint.y
let path = CGPathCreateMutable()
CGPathMoveToPoint(path, nil, 3 - offsetX, 0 - offsetY)
CGPathAddLineToPoint(path, nil, 5 - offsetX, 309 - offsetY)
CGPathAddLineToPoint(path, nil, 16 - offsetX, 315 - offsetY)
CGPathAddLineToPoint(path, nil, 39 - offsetX, 315 - offsetY)
CGPathAddLineToPoint(path, nil, 51 - offsetX, 306 - offsetY)
CGPathAddLineToPoint(path, nil, 49 - offsetX, 1 - offsetY)
CGPathCloseSubpath(path)
sprite.physicsBody = SKPhysicsBody(polygonFromPath: path)
sprite.physicsBody?.categoryBitMask = PhysicsCategory.Obstacle
sprite.physicsBody?.collisionBitMask = 0
sprite.physicsBody?.contactTestBitMask = PhysicsCategory.Player
return sprite
}
func spawnObstacle(){
//1
let bottomObstacle = createObstacle()
let startX = size.width + bottomObstacle.size.width/2
let bottomObstacleMin = (playableStart - bottomObstacle.size.height/2) + playableHeight * kBottomObstacleMinFraction
let bottomObstacleMax = (playableStart - bottomObstacle.size.height/2) + playableHeight * kBottomObstacleMaxFraction
bottomObstacle.position = CGPointMake(startX, CGFloat.random(min: bottomObstacleMin, max: bottomObstacleMax))
bottomObstacle.name = "BottomObstacle"
worldNode.addChild(bottomObstacle)
let topObstacle = createObstacle()
topObstacle.zRotation = CGFloat(180).degreesToRadians()
topObstacle.position = CGPoint(x: startX, y: bottomObstacle.position.y + bottomObstacle.size.height/2 + topObstacle.size.height/2 + player.size.height * kGapMultiplier)
topObstacle.name = "TopObstacle"
worldNode.addChild(topObstacle)
let moveX = size.width + topObstacle.size.width
let moveDuration = moveX / kGroundSpeed
let sequence = SKAction.sequence([
SKAction.moveByX(-moveX, y: 0, duration: NSTimeInterval(moveDuration)),
SKAction.removeFromParent()
])
topObstacle.runAction(sequence)
bottomObstacle.runAction(sequence)
}
func startSpawning(){
let firstDelay = SKAction.waitForDuration(1.75)
let spawn = SKAction.runBlock(spawnObstacle)
let everyDelay = SKAction.waitForDuration(1.5)
let spawnSequence = SKAction.sequence([
spawn,everyDelay
])
let foreverSpawn = SKAction.repeatActionForever(spawnSequence)
let overallSequence = SKAction.sequence([firstDelay,foreverSpawn])
runAction(overallSequence, withKey: "spawn")
}
func stopSpawning() {
removeActionForKey("spawn")
worldNode.enumerateChildNodesWithName("TopObstacle", usingBlock: { node, stop in
node.removeAllActions()
})
worldNode.enumerateChildNodesWithName("BottomObstacle", usingBlock: { node, stop in
node.removeAllActions()
})
}
func flapPlayer(){
// 发出一次煽动翅膀的声音
runAction(flapAction)
// 重新设定player的速度!!
playerVelocity = CGPointMake(0, kImpulse)
// 使得帽子下上跳动
let moveUp = SKAction.moveByX(0, y: 12, duration: 0.15)
moveUp.timingMode = .EaseInEaseOut
let moveDown = moveUp.reversedAction()
sombrero.runAction(SKAction.sequence([moveUp,moveDown]))
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
switch gameState {
case .MainMenu:
break
case .Tutorial:
break
case .Play:
flapPlayer()
break
case .Falling:
break
case .ShowingScore:
switchToNewGame()
break
case .GameOver:
break
}
}
// MARK: - Updates
override func update(currentTime: CFTimeInterval) {
if lastUpdateTime > 0 {
dt = currentTime - lastUpdateTime
} else {
dt = 0
}
lastUpdateTime = currentTime
switch gameState {
case .MainMenu:
break
case .Tutorial:
break
case .Play:
updateForeground()
updatePlayer()
checkHitObstacle()
checkHitGround()
updateScore()
break
case .Falling:
updatePlayer()
checkHitGround()
break
case .ShowingScore:
break
case .GameOver:
break
}
}
func updatePlayer(){
// 只有Y轴上的重力加速度为-1500
let gravity = CGPoint(x: 0, y: kGravity)
let gravityStep = gravity * CGFloat(dt) //计算dt时间下速度的增量
playerVelocity += gravityStep //计算当前速度
// 位置计算
let velocityStep = playerVelocity * CGFloat(dt) //计算dt时间中下落或上升距离
player.position += velocityStep //计算player的位置
// 倘若Player的Y坐标位置在地面上了就不能再下落了 直接设置其位置的y值为地面的表层坐标
if player.position.y - player.size.height/2 < playableStart {
player.position = CGPoint(x: player.position.x, y: playableStart + player.size.height/2)
}
}
func updateForeground(){
worldNode.enumerateChildNodesWithName("foreground") { (node, stop) -> Void in
if let foreground = node as? SKSpriteNode{
let moveAmt = CGPointMake(-self.kGroundSpeed * CGFloat(self.dt), 0)
foreground.position += moveAmt
if foreground.position.x < -foreground.size.width{
foreground.position += CGPoint(x: foreground.size.width * CGFloat(2), y: 0)
}
}
}
}
func checkHitObstacle() {
if hitObstacle {
hitObstacle = false
switchToFalling()
}
}
func checkHitGround() {
if hitGround {
hitGround = false
playerVelocity = CGPoint.zero
player.zRotation = CGFloat(-90).degreesToRadians()
player.position = CGPoint(x: player.position.x, y: playableStart + player.size.width/2)
runAction(hitGroundAction)
switchToShowScore()
}
}
func updateScore() {
worldNode.enumerateChildNodesWithName("BottomObstacle", usingBlock: { node, stop in
if let obstacle = node as? SKSpriteNode {
if let passed = obstacle.userData?["Passed"] as? NSNumber {
if passed.boolValue {
return
}
}
if self.player.position.x > obstacle.position.x + obstacle.size.width/2 {
self.score++
self.scoreLabel.text = "\(self.score)"
self.runAction(self.coinAction)
obstacle.userData?["Passed"] = NSNumber(bool: true)
}
}
})
}
// MARK: - Game States
func switchToFalling() {
gameState = .Falling
runAction(SKAction.sequence([
whackAction,
SKAction.waitForDuration(0.1),
fallingAction
]))
player.removeAllActions()
stopSpawning()
}
func switchToShowScore() {
gameState = .ShowingScore
player.removeAllActions()
stopSpawning()
}
func switchToNewGame() {
runAction(popAction)
let newScene = GameScene(size: size)
let transition = SKTransition.fadeWithColor(SKColor.blackColor(), duration: 0.5)
view?.presentScene(newScene, transition: transition)
}
// MARK: - Physics
func didBeginContact(contact: SKPhysicsContact) {
let other = contact.bodyA.categoryBitMask == PhysicsCategory.Player ? contact.bodyB : contact.bodyA
if other.categoryBitMask == PhysicsCategory.Ground {
hitGround = true
}
if other.categoryBitMask == PhysicsCategory.Obstacle {
hitObstacle = true
}
}
}
|
mit
|
499079d88262b7f60f124b3ec5d26853
| 31.890698 | 176 | 0.608428 | 4.723781 | false | false | false | false |
KyoheiG3/TableViewDragger
|
TableViewDragger/UIScrollViewExtension.swift
|
1
|
1551
|
//
// UIScrollViewExtension.swift
// Pods
//
// Created by Kyohei Ito on 2015/09/29.
//
//
import UIKit
extension UIScrollView {
enum DraggingDirection {
case up
case down
}
func preferredContentOffset(at point: CGPoint, velocity: CGFloat) -> CGPoint {
let distance = ScrollRects(size: bounds.size).distance(at: point) / velocity
var offset = contentOffset
offset.y += distance
let topOffset = -contentInset.top
let bottomOffset = contentInset.bottom
let height = floor(contentSize.height) - bounds.size.height
if offset.y > height + bottomOffset {
offset.y = height + bottomOffset
} else if offset.y < topOffset {
offset.y = topOffset
}
return offset
}
func draggingDirection(at point: @autoclosure () -> CGPoint) -> DraggingDirection? {
let contentHeight = floor(contentSize.height)
if bounds.size.height >= contentHeight {
return nil
}
let rects = ScrollRects(size: bounds.size)
let point = point()
if rects.topRect.contains(point) {
let topOffset = -contentInset.top
if contentOffset.y > topOffset {
return .up
}
} else if rects.bottomRect.contains(point) {
let bottomOffset = contentHeight + contentInset.bottom - bounds.size.height
if contentOffset.y < bottomOffset {
return .down
}
}
return nil
}
}
|
mit
|
b22e62736b79bf246a39ad70998f569e
| 25.741379 | 88 | 0.586074 | 4.787037 | false | false | false | false |
Fenrikur/ef-app_ios
|
Domain Model/EurofurenceModel/Public/Default Dependency Implementations/Core Data Store/Model Adaptation/LinkEntity+Adaptation.swift
|
1
|
878
|
import Foundation
extension LinkEntity: EntityAdapting {
typealias AdaptedType = LinkCharacteristics
static func makeIdentifyingPredicate(for model: LinkCharacteristics) -> NSPredicate {
return NSPredicate(value: false)
}
func asAdaptedType() -> LinkCharacteristics {
guard let name = name,
let fragmentType = LinkCharacteristics.FragmentType(rawValue: Int(fragmentType)),
let target = target else {
abandonDueToInconsistentState()
}
return LinkCharacteristics(name: name,
fragmentType: fragmentType,
target: target)
}
func consumeAttributes(from value: LinkCharacteristics) {
name = value.name
target = value.target
fragmentType = Int16(Float(value.fragmentType.rawValue))
}
}
|
mit
|
8898ac072d92bd24a776ff1dbe36b68b
| 30.357143 | 95 | 0.627563 | 5.289157 | false | false | false | false |
kean/Nuke
|
Sources/Nuke/ImageResponse.swift
|
1
|
2033
|
// The MIT License (MIT)
//
// Copyright (c) 2015-2022 Alexander Grebenyuk (github.com/kean).
import Foundation
#if !os(macOS)
import UIKit.UIImage
#else
import AppKit.NSImage
#endif
/// An image response that contains a fetched image and some metadata.
public struct ImageResponse: @unchecked Sendable {
/// An image container with an image and associated metadata.
public var container: ImageContainer
#if os(macOS)
/// A convenience computed property that returns an image from the container.
public var image: NSImage { container.image }
#else
/// A convenience computed property that returns an image from the container.
public var image: UIImage { container.image }
#endif
/// Returns `true` if the image in the container is a preview of the image.
public var isPreview: Bool { container.isPreview }
/// The request for which the response was created.
public var request: ImageRequest
/// A response. `nil` unless the resource was fetched from the network or an
/// HTTP cache.
public var urlResponse: URLResponse?
/// Contains a cache type in case the image was returned from one of the
/// pipeline caches (not including any of the HTTP caches if enabled).
public var cacheType: CacheType?
/// Initializes the response with the given image.
public init(container: ImageContainer, request: ImageRequest, urlResponse: URLResponse? = nil, cacheType: CacheType? = nil) {
self.container = container
self.request = request
self.urlResponse = urlResponse
self.cacheType = cacheType
}
/// A cache type.
public enum CacheType: Sendable {
/// Memory cache (see ``ImageCaching``)
case memory
/// Disk cache (see ``DataCaching``)
case disk
}
func map(_ transform: (ImageContainer) throws -> ImageContainer) rethrows -> ImageResponse {
var response = self
response.container = try transform(response.container)
return response
}
}
|
mit
|
3a9b3f073478b3d532f72a59a6c3404e
| 32.327869 | 129 | 0.685686 | 4.7723 | false | false | false | false |
dani-gavrilov/GDPerformanceView-Swift
|
GDPerformanceView-Swift/GDPerformanceMonitoring/PerformanceView.swift
|
1
|
13150
|
//
// Copyright © 2017 Gavrilov Daniil
//
// 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
// MARK: Class Definition
/// Performance view. Displays performance information above status bar. Appearance and output can be changed via properties.
internal class PerformanceView: UIWindow, PerformanceViewConfigurator {
// MARK: Structs
private struct Constants {
static let prefferedHeight: CGFloat = 20.0
static let borderWidth: CGFloat = 1.0
static let cornerRadius: CGFloat = 5.0
static let pointSize: CGFloat = 8.0
static let defaultStatusBarHeight: CGFloat = 20.0
static let safeAreaInsetDifference: CGFloat = 11.0
}
// MARK: Public Properties
/// Allows to change the format of the displayed information.
public var options = PerformanceMonitor.DisplayOptions.default {
didSet {
self.configureStaticInformation()
}
}
public var userInfo = PerformanceMonitor.UserInfo.none {
didSet {
self.configureUserInformation()
}
}
/// Allows to change the appearance of the displayed information.
public var style = PerformanceMonitor.Style.dark {
didSet {
self.configureView(withStyle: self.style)
}
}
/// Allows to add gesture recognizers to the view.
public var interactors: [UIGestureRecognizer]? {
didSet {
self.configureView(withInteractors: self.interactors)
}
}
// MARK: Private Properties
private let monitoringTextLabel = MarginLabel()
private var staticInformation: String?
private var userInformation: String?
// MARK: Init Methods & Superclass Overriders
required internal init() {
super.init(frame: PerformanceView.windowFrame(withPrefferedHeight: Constants.prefferedHeight))
if #available(iOS 13, *) {
self.windowScene = UIApplication.shared.keyWindowScene
}
self.configureWindow()
self.configureMonitoringTextLabel()
self.subscribeToNotifications()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func layoutSubviews() {
super.layoutSubviews()
self.layoutWindow()
}
override func becomeKey() {
self.isHidden = true
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(1)) {
self.showViewAboveStatusBarIfNeeded()
}
}
override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
guard let interactors = self.interactors, interactors.count > 0 else {
return false
}
return super.point(inside: point, with: event)
}
deinit {
NotificationCenter.default.removeObserver(self)
}
}
// MARK: Public Methods
internal extension PerformanceView {
/// Hides monitoring view.
func hide() {
self.monitoringTextLabel.isHidden = true
}
/// Shows monitoring view.
func show() {
self.monitoringTextLabel.isHidden = false
}
/// Updates monitoring label with performance report.
///
/// - Parameter report: Performance report.
func update(withPerformanceReport report: PerformanceReport) {
var monitoringTexts: [String] = []
if self.options.contains(.performance) {
let performance = String(format: "CPU: %.1f%%, FPS: %d", report.cpuUsage, report.fps)
monitoringTexts.append(performance)
}
if self.options.contains(.memory) {
let bytesInMegabyte = 1024.0 * 1024.0
let usedMemory = Double(report.memoryUsage.used) / bytesInMegabyte
let totalMemory = Double(report.memoryUsage.total) / bytesInMegabyte
let memory = String(format: "%.1f of %.0f MB used", usedMemory, totalMemory)
monitoringTexts.append(memory)
}
if let staticInformation = self.staticInformation {
monitoringTexts.append(staticInformation)
}
if let userInformation = self.userInformation {
monitoringTexts.append(userInformation)
}
self.monitoringTextLabel.text = (monitoringTexts.count > 0 ? monitoringTexts.joined(separator: "\n") : nil)
self.showViewAboveStatusBarIfNeeded()
self.layoutMonitoringLabel()
}
}
// MARK: Notifications & Observers
private extension PerformanceView {
func applicationWillChangeStatusBarFrame(notification: Notification) {
self.layoutWindow()
}
}
// MARK: Configurations
private extension PerformanceView {
func configureWindow() {
self.rootViewController = WindowViewController()
self.windowLevel = UIWindow.Level.statusBar + 1.0
self.backgroundColor = .clear
self.clipsToBounds = true
self.isHidden = true
}
func configureMonitoringTextLabel() {
self.monitoringTextLabel.textAlignment = NSTextAlignment.center
self.monitoringTextLabel.numberOfLines = 0
self.monitoringTextLabel.clipsToBounds = true
self.addSubview(self.monitoringTextLabel)
}
func configureStaticInformation() {
var staticInformations: [String] = []
if self.options.contains(.application) {
let applicationVersion = self.applicationVersion()
staticInformations.append(applicationVersion)
}
if self.options.contains(.device) {
let deviceModel = self.deviceModel()
staticInformations.append(deviceModel)
}
if self.options.contains(.system) {
let systemVersion = self.systemVersion()
staticInformations.append(systemVersion)
}
self.staticInformation = (staticInformations.count > 0 ? staticInformations.joined(separator: ", ") : nil)
}
func configureUserInformation() {
var staticInformation: String?
switch self.userInfo {
case .none:
break
case .custom(let string):
staticInformation = string
}
self.userInformation = staticInformation
}
func subscribeToNotifications() {
NotificationCenter.default.addObserver(forName: UIApplication.willChangeStatusBarFrameNotification, object: nil, queue: .main) { [weak self] (notification) in
self?.applicationWillChangeStatusBarFrame(notification: notification)
}
}
func configureView(withStyle style: PerformanceMonitor.Style) {
switch style {
case .dark:
self.monitoringTextLabel.backgroundColor = .black
self.monitoringTextLabel.layer.borderColor = UIColor.white.cgColor
self.monitoringTextLabel.layer.borderWidth = Constants.borderWidth
self.monitoringTextLabel.layer.cornerRadius = Constants.cornerRadius
self.monitoringTextLabel.textColor = .white
self.monitoringTextLabel.font = UIFont.systemFont(ofSize: Constants.pointSize)
case .light:
self.monitoringTextLabel.backgroundColor = .white
self.monitoringTextLabel.layer.borderColor = UIColor.black.cgColor
self.monitoringTextLabel.layer.borderWidth = Constants.borderWidth
self.monitoringTextLabel.layer.cornerRadius = Constants.cornerRadius
self.monitoringTextLabel.textColor = .black
self.monitoringTextLabel.font = UIFont.systemFont(ofSize: Constants.pointSize)
case .custom(let backgroundColor, let borderColor, let borderWidth, let cornerRadius, let textColor, let font):
self.monitoringTextLabel.backgroundColor = backgroundColor
self.monitoringTextLabel.layer.borderColor = borderColor.cgColor
self.monitoringTextLabel.layer.borderWidth = borderWidth
self.monitoringTextLabel.layer.cornerRadius = cornerRadius
self.monitoringTextLabel.textColor = textColor
self.monitoringTextLabel.font = font
}
}
func configureView(withInteractors interactors: [UIGestureRecognizer]?) {
if let recognizers = self.gestureRecognizers {
for recognizer in recognizers {
self.removeGestureRecognizer(recognizer)
}
}
if let recognizers = interactors {
for recognizer in recognizers {
self.addGestureRecognizer(recognizer)
}
}
}
}
// MARK: Layout View
private extension PerformanceView {
func layoutWindow() {
self.frame = PerformanceView.windowFrame(withPrefferedHeight: self.monitoringTextLabel.bounds.height)
self.layoutMonitoringLabel()
}
func layoutMonitoringLabel() {
let windowWidth = self.bounds.width
let windowHeight = self.bounds.height
let labelSize = self.monitoringTextLabel.sizeThatFits(CGSize(width: windowWidth, height: CGFloat.greatestFiniteMagnitude))
if windowHeight != labelSize.height {
self.frame = PerformanceView.windowFrame(withPrefferedHeight: self.monitoringTextLabel.bounds.height)
}
self.monitoringTextLabel.frame = CGRect(x: (windowWidth - labelSize.width) / 2.0, y: (windowHeight - labelSize.height) / 2.0, width: labelSize.width, height: labelSize.height)
}
}
// MARK: Support Methods
private extension PerformanceView {
func showViewAboveStatusBarIfNeeded() {
guard UIApplication.shared.applicationState == UIApplication.State.active, self.canBeVisible(), self.isHidden else {
return
}
self.isHidden = false
}
func applicationVersion() -> String {
var applicationVersion = "<null>"
var applicationBuildNumber = "<null>"
if let infoDictionary = Bundle.main.infoDictionary {
if let versionNumber = infoDictionary["CFBundleShortVersionString"] as? String {
applicationVersion = versionNumber
}
if let buildNumber = infoDictionary["CFBundleVersion"] as? String {
applicationBuildNumber = buildNumber
}
}
return "app v\(applicationVersion) (\(applicationBuildNumber))"
}
func deviceModel() -> String {
var systemInfo = utsname()
uname(&systemInfo)
let machineMirror = Mirror(reflecting: systemInfo.machine)
let model = machineMirror.children.reduce("") { identifier, element in
guard let value = element.value as? Int8, value != 0 else {
return identifier
}
return identifier + String(UnicodeScalar(UInt8(value)))
}
return model
}
func systemVersion() -> String {
let systemName = UIDevice.current.systemName
let systemVersion = UIDevice.current.systemVersion
return "\(systemName) v\(systemVersion)"
}
func canBeVisible() -> Bool {
if let window = UIApplication.shared.keyWindow, window.isKeyWindow, !window.isHidden {
return true
}
return false
}
}
// MARK: Class Methods
private extension PerformanceView {
class func windowFrame(withPrefferedHeight height: CGFloat) -> CGRect {
guard let window = UIApplication.shared.keyWindow else {
return .zero
}
var topInset: CGFloat = 0.0
if #available(iOS 11.0, *), let safeAreaTop = window.rootViewController?.view.safeAreaInsets.top {
if safeAreaTop > 0.0 {
if safeAreaTop > Constants.defaultStatusBarHeight {
topInset = safeAreaTop - Constants.safeAreaInsetDifference
} else {
topInset = safeAreaTop - Constants.defaultStatusBarHeight
}
} else {
topInset = safeAreaTop
}
}
return CGRect(x: 0.0, y: topInset, width: window.bounds.width, height: height)
}
}
|
mit
|
e16ab515510544245e3fb0bf0900aef3
| 35.423823 | 183 | 0.650696 | 5.178811 | false | false | false | false |
PorridgeBear/imvs
|
IMVS/Residue.swift
|
1
|
1469
|
//
// Residue.swift
// IMVS
//
// Created by Allistair Crossley on 13/07/2014.
// Copyright (c) 2014 Allistair Crossley. All rights reserved.
//
import Foundation
/**
* Amino Acid Residue
*
* A protein chain will have somewhere in the range of 50 to 2000 amino acid residues.
* You have to use this term because strictly speaking a peptide chain isn't made up of amino acids.
* When the amino acids combine together, a water molecule is lost. The peptide chain is made up
* from what is left after the water is lost - in other words, is made up of amino acid residues.
* http://www.chemguide.co.uk/organicprops/aminoacids/proteinstruct.html
* C and N terminus
*/
class Residue {
var name: String = ""
var atoms: [Atom] = []
convenience init() {
self.init(name: "NONE")
}
init(name: String) {
self.name = name
}
func addAtom(atom: Atom) {
atoms.append(atom)
}
func getAlphaCarbon() -> Atom? {
for atom in atoms {
if atom.element == "C" && atom.remoteness == "A" {
return atom
}
}
return nil
}
/** TODO - Might not be 100% right grabbing the first O - check */
func getCarbonylOxygen() -> Atom? {
for atom in atoms {
if atom.element == "O" {
return atom
}
}
return nil
}
}
|
mit
|
cf459bc4fc63165338b01a15234992d0
| 22.693548 | 101 | 0.560926 | 3.645161 | false | false | false | false |
StorageKit/StorageKit
|
Tests/Storages/CoreData/TestDoubles/SpyManagedObjectContext.swift
|
1
|
4082
|
//
// SpyManagedObjectContext.swift
// StorageKit
//
// Copyright (c) 2017 StorageKit (https://github.com/StorageKit)
//
// 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 StorageKit
import CoreData
final class SpyManagedObjectContext: ManagedObjectContextType {
// MARK: Static spies
static private(set) var isInitWithConcurrencyTypeCalled = false
static private(set) var initWithConcurrencyTypeArgument: NSManagedObjectContextConcurrencyType?
static private(set) var isPersistentStoreCoordinatorTypeSet = false
static private(set) var persistentStoreCoordinatorTypeSetValue: PersistentStoreCoordinatorType?
// MARK: Not-Static spies
private(set) var isInitWithConcurrencyTypeCalled = false
private(set) var initWithConcurrencyTypeArgument: NSManagedObjectContextConcurrencyType?
private(set) var isContextParentSetCalled = false
private(set) var contextParentSetArgument: ManagedObjectContextType?
private(set) var isSaveCalled = false
private(set) var isPerformCalled = false
var persistentStoreCoordinatorType: PersistentStoreCoordinatorType? {
get {
return nil
}
set {
SpyManagedObjectContext.isPersistentStoreCoordinatorTypeSet = true
SpyManagedObjectContext.persistentStoreCoordinatorTypeSetValue = newValue
}
}
var contextParent: ManagedObjectContextType? {
get {
return contextParentSetArgument
}
set {
isContextParentSetCalled = true
contextParentSetArgument = newValue
}
}
required init(concurrencyType ct: NSManagedObjectContextConcurrencyType) {
SpyManagedObjectContext.isInitWithConcurrencyTypeCalled = true
SpyManagedObjectContext.initWithConcurrencyTypeArgument = ct
isInitWithConcurrencyTypeCalled = true
initWithConcurrencyTypeArgument = ct
}
static func clean() {
SpyManagedObjectContext.isInitWithConcurrencyTypeCalled = false
SpyManagedObjectContext.initWithConcurrencyTypeArgument = nil
SpyManagedObjectContext.isPersistentStoreCoordinatorTypeSet = false
SpyManagedObjectContext.persistentStoreCoordinatorTypeSetValue = nil
}
func save() throws {
isSaveCalled = true
}
func perform(_ block: @escaping () -> Void) {
isPerformCalled = true
block()
}
}
// MARK: - StorageContext
extension SpyManagedObjectContext {
func delete<T: StorageEntityType>(_ entity: T) throws {}
func delete<T: StorageEntityType>(_ entities: [T]) throws {}
func deleteAll<T: StorageEntityType>(_ entityType: T.Type) throws {}
func fetch<T: StorageEntityType>(predicate: NSPredicate?, sortDescriptors: [SortDescriptor]?, completion: @escaping FetchCompletionClosure<T>) {}
func update(transform: @escaping () -> Void) throws {}
func create<T: StorageEntityType>() -> T? { return nil }
func addOrUpdate<T>(_ entity: T) throws { }
}
|
mit
|
88245193399c899fd450416bf05b1309
| 36.449541 | 149 | 0.726115 | 5.134591 | false | false | false | false |
OAuthSwift/OAuthSwift
|
Demo/Common/Storyboards.swift
|
4
|
2870
|
//
// Storyboards.swift
// OAuthSwift
//
// Created by phimage on 23/07/16.
// Copyright © 2016 Dongri Jin. All rights reserved.
//
import Foundation
#if os(iOS)
import UIKit
public typealias OAuthStoryboard = UIStoryboard
public typealias OAuthStoryboardSegue = UIStoryboardSegue
// add missing classes for iOS
extension OAuthStoryboard {
public struct Name {
var rawValue: String
init(_ rawValue: String) {
self.rawValue = rawValue
}
}
public struct SceneIdentifier {
var rawValue: String
init(_ rawValue: String) {
self.rawValue = rawValue
}
}
public convenience init(name: OAuthStoryboard.Name, bundle: Bundle? = nil) {
self.init(name: name.rawValue, bundle: bundle)
}
public func instantiateController(withIdentifier id: OAuthStoryboard.SceneIdentifier) -> UIViewController {
return self.instantiateViewController(withIdentifier: id.rawValue)
}
}
extension UIViewController {
func performSegue(withIdentifier: OAuthStoryboardSegue.Identifier, sender: Any?) {
self.performSegue(withIdentifier: withIdentifier.rawValue, sender: sender)
}
}
extension OAuthStoryboardSegue {
struct Identifier {
var rawValue: String
init(_ rawValue: String) {
self.rawValue = rawValue
}
}
}
extension OAuthStoryboardSegue.Identifier :Equatable {
static func ==(l: OAuthStoryboardSegue.Identifier, r: OAuthStoryboardSegue.Identifier) -> Bool {
return l.rawValue == r.rawValue
}
static func == (l: String, r: OAuthStoryboardSegue.Identifier) -> Bool {
return l == r.rawValue
}
static func == (l: String?, r: OAuthStoryboardSegue.Identifier) -> Bool {
guard let l = l else {
return false
}
return l == r.rawValue
}
}
#elseif os(OSX)
import AppKit
public typealias OAuthStoryboard = NSStoryboard
public typealias OAuthStoryboardSegue = NSStoryboardSegue
#endif
struct Storyboards {
struct Main {
static let identifier = OAuthStoryboard.Name("Storyboard")
static let formIdentifier = OAuthStoryboard.SceneIdentifier("Form")
static let formSegue = OAuthStoryboardSegue.Identifier("form")
static var storyboard: OAuthStoryboard {
return OAuthStoryboard(name: self.identifier, bundle: nil)
}
static func instantiateForm() -> FormViewController {
return self.storyboard.instantiateController(withIdentifier: formIdentifier) as! FormViewController
}
}
}
|
mit
|
22ea9a329fa2b7ce04e7d4b24b311dcd
| 29.2 | 115 | 0.610317 | 5.454373 | false | false | false | false |
dmitrykurochka/CLTokenInputView-Swift
|
CLTokenInputView-Swift/Classes/CLTokenView.swift
|
1
|
7155
|
//
// CLTokenView.swift
// CLTokenInputView
//
// Created by Dmitry Kurochka on 23.08.17.
// Copyright © 2017 Prezentor. All rights reserved.
//
import Foundation
import UIKit
protocol CLTokenViewDelegate: class {
func tokenViewDidRequestDelete(_ tokenView: CLTokenView, replaceWithText replacementText: String?)
func tokenViewDidRequestSelection(_ tokenView: CLTokenView)
func tokenViewDidHandeLongPressure(_ tokenView: CLTokenView)
}
class CLTokenView: UIView, UIKeyInput {
weak var delegate: CLTokenViewDelegate?
var selected: Bool! {
didSet {
if oldValue != selected {
setSelectedNoCheck(selected, animated: false)
}
}
}
var hideUnselectedComma: Bool! {
didSet {
if oldValue != hideUnselectedComma {
updateLabelAttributedText()
}
}
}
var backgroundView: UIView?
var label: UILabel!
var selectedBackgroundView: UIView!
var selectedLabel: UILabel!
var displayText: String!
let paddingX = 4.0
let paddingY = 2.0
// let UNSELECTED_LABEL_FORMAT = "%@, "
// let UNSELECTED_LABEL_NO_COMMA_FORMAT = "%@"
init(frame: CGRect, token: CLToken, font: UIFont?) {
super.init(frame: frame)
var tintColor: UIColor = UIColor(red: 0.08, green: 0.49, blue: 0.98, alpha: 1.0)
tintColor = self.tintColor
label = UILabel(frame: CGRect(x: paddingX, y: paddingY, width: 0.0, height: 0.0))
if font != nil {
label.font = font
}
label.textColor = tintColor
label.backgroundColor = UIColor.clear
addSubview(label)
selectedBackgroundView = UIView(frame: CGRect.zero)
selectedBackgroundView.backgroundColor = tintColor
selectedBackgroundView.layer.cornerRadius = 3.0
addSubview(selectedBackgroundView)
selectedBackgroundView.isHidden = true
selectedLabel = UILabel(frame: CGRect(x: paddingX, y: paddingY, width: 0.0, height: 0.0))
selectedLabel.font = label.font
selectedLabel.textColor = UIColor.white
selectedLabel.backgroundColor = UIColor.clear
addSubview(selectedLabel)
selectedLabel.isHidden = true
selected = false
displayText = token.displayText
hideUnselectedComma = false
updateLabelAttributedText()
selectedLabel.text = token.displayText
let tapSelector = #selector(CLTokenView.handleTapGestureRecognizer(_:))
let tapRecognizer: UITapGestureRecognizer = UITapGestureRecognizer(target: self,
action: tapSelector)
addGestureRecognizer(tapRecognizer)
let longPressSelector = #selector(handleLongPressGestureRecognizer(_:))
let longPressRecognizer = UILongPressGestureRecognizer(target: self,
action: longPressSelector)
addGestureRecognizer(longPressRecognizer)
setNeedsLayout()
}
convenience init(token: CLToken, font: UIFont?) {
self.init(frame: CGRect.zero, token: token, font: font)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override var intrinsicContentSize: CGSize {
let labelIntrinsicSize: CGSize = selectedLabel.intrinsicContentSize
return CGSize(width: Double(labelIntrinsicSize.width)+(2.0*paddingX),
height: Double(labelIntrinsicSize.height)+(2.0*paddingY))
}
override func sizeThatFits(_ size: CGSize) -> CGSize {
let fittingSize = CGSize(width: Double(size.width)-(2.0*paddingX), height:Double(size.height)-(2.0*paddingY))
let labelSize = selectedLabel.sizeThatFits(fittingSize)
return CGSize(width: Double(labelSize.width)+(2.0*paddingX), height:Double(labelSize.height)+(2.0*paddingY))
}
override func tintColorDidChange() {
super.tintColorDidChange()
label.textColor = tintColor
selectedBackgroundView.backgroundColor = tintColor
updateLabelAttributedText()
}
func handleTapGestureRecognizer(_ sender: UIGestureRecognizer) {
delegate?.tokenViewDidRequestSelection(self)
}
func handleLongPressGestureRecognizer(_ sender: UIGestureRecognizer) {
guard sender.state == .began else {return}
delegate?.tokenViewDidHandeLongPressure(self)
}
func setSelected(_ selectedBool: Bool, animated: Bool) {
if selected == selectedBool {
return
}
selected = selectedBool
setSelectedNoCheck(selectedBool, animated: animated)
}
func setSelectedNoCheck(_ selectedBool: Bool, animated: Bool) {
if selectedBool == true && !isFirstResponder {
_ = becomeFirstResponder()
} else if !selectedBool && isFirstResponder {
_ = resignFirstResponder()
}
var selectedAlpha: CGFloat = 0.0
if selectedBool == true {
selectedAlpha = 1.0
}
if animated == true {
if selected == true {
selectedBackgroundView.alpha = 0.0
selectedBackgroundView.isHidden = false
selectedLabel.alpha = 0.0
selectedLabel.isHidden = false
}
UIView.animate(withDuration: 0.25, animations: { [weak self] in
self?.selectedBackgroundView.alpha = selectedAlpha
self?.selectedLabel.alpha = selectedAlpha
}) { [weak self] _ in
if self?.selected == false {
self?.selectedBackgroundView.isHidden = true
self?.selectedLabel.isHidden = true
}
}
} else {
selectedBackgroundView.isHidden = !selected
selectedLabel.isHidden = !selected
}
}
func updateLabelAttributedText() {
var labelString: String
if hideUnselectedComma == true {
labelString = "\(displayText ?? "")"
} else {
labelString = "\(displayText ?? ""),"
}
let attributes: [String:Any] = [NSFontAttributeName: label.font,
NSForegroundColorAttributeName: UIColor.lightGray]
let attrString = NSMutableAttributedString(string: labelString, attributes: attributes)
let tintRange = (labelString as NSString).range(of: displayText)
attrString.setAttributes([NSForegroundColorAttributeName: tintColor], range: tintRange)
label.attributedText = attrString
}
override func layoutSubviews() {
super.layoutSubviews()
let bounds: CGRect = self.bounds
backgroundView?.frame = bounds
selectedBackgroundView.frame = bounds
var labelFrame = bounds.insetBy(dx: CGFloat(paddingX), dy: CGFloat(paddingY))
selectedLabel.frame = labelFrame
labelFrame.size.width += CGFloat(paddingX * 2.0)
label.frame = labelFrame
}
var hasText: Bool {
return true
}
func insertText(_ text: String) {
delegate?.tokenViewDidRequestDelete(self, replaceWithText: text)
}
func deleteBackward() {
delegate?.tokenViewDidRequestDelete(self, replaceWithText: nil)
}
override var canBecomeFirstResponder: Bool {
return true
}
override func resignFirstResponder() -> Bool {
let didResignFirstResponder = super.resignFirstResponder()
setSelected(false, animated: false)
return didResignFirstResponder
}
override func becomeFirstResponder() -> Bool {
let didBecomeFirstResponder = super.becomeFirstResponder()
setSelected(true, animated: false)
return didBecomeFirstResponder
}
}
|
mit
|
54e96aff3842ef9e2dc75ba3b2581225
| 29.57265 | 113 | 0.692899 | 4.753488 | false | false | false | false |
adrfer/swift
|
test/1_stdlib/DictionaryTraps.swift
|
11
|
6518
|
// RUN: rm -rf %t
// RUN: mkdir -p %t
// RUN: %target-build-swift %s -o %t/a.out_Debug
// RUN: %target-build-swift %s -o %t/a.out_Release -O
//
// RUN: %target-run %t/a.out_Debug
// RUN: %target-run %t/a.out_Release
// REQUIRES: executable_test
//
// FIXME: rdar://problem/19648117 Needs splitting objc parts out
// XFAIL: linux
import StdlibUnittest
import Foundation
// Also import modules which are used by StdlibUnittest internally. This
// workaround is needed to link all required libraries in case we compile
// StdlibUnittest with -sil-serialize-all.
import SwiftPrivate
#if _runtime(_ObjC)
import ObjectiveC
#endif
struct NotBridgedKeyTy : Equatable, Hashable {
init(_ value: Int) {
self.value = value
}
var hashValue: Int {
return value
}
var value: Int
}
func == (lhs: NotBridgedKeyTy, rhs: NotBridgedKeyTy) -> Bool {
return lhs.value == rhs.value
}
assert(!_isBridgedToObjectiveC(NotBridgedKeyTy.self))
struct NotBridgedValueTy {}
assert(!_isBridgedToObjectiveC(NotBridgedValueTy.self))
class BridgedVerbatimRefTy : Equatable, Hashable {
init(_ value: Int) {
self.value = value
}
var hashValue: Int {
return value
}
var value: Int
}
func == (lhs: BridgedVerbatimRefTy, rhs: BridgedVerbatimRefTy) -> Bool {
return lhs.value == rhs.value
}
assert(_isBridgedToObjectiveC(BridgedVerbatimRefTy.self))
assert(_isBridgedVerbatimToObjectiveC(BridgedVerbatimRefTy.self))
var DictionaryTraps = TestSuite("DictionaryTraps")
DictionaryTraps.test("sanity") {
// Sanity checks. This code should not trap.
var d = Dictionary<BridgedVerbatimRefTy, BridgedVerbatimRefTy>()
var nsd = d as NSDictionary
}
DictionaryTraps.test("DuplicateKeys1")
.skip(.Custom(
{ _isFastAssertConfiguration() },
reason: "this trap is not guaranteed to happen in -Ounchecked"))
.code {
expectCrashLater()
let d = Dictionary(dictionaryLiteral:
(10, 1010), (20, 1020), (30, 1030), (10, 0))
_blackHole(d)
}
DictionaryTraps.test("DuplicateKeys2")
.skip(.Custom(
{ _isFastAssertConfiguration() },
reason: "this trap is not guaranteed to happen in -Ounchecked"))
.code {
expectCrashLater()
let d = Dictionary(dictionaryLiteral:
(10, 1010), (20, 1020), (30, 1030), (10, 1010))
_blackHole(d)
}
DictionaryTraps.test("DuplicateKeys3")
.skip(.Custom(
{ _isFastAssertConfiguration() },
reason: "this trap is not guaranteed to happen in -Ounchecked"))
.code {
expectCrashLater()
let d = [ 10: 1010, 10: 0 ]
_blackHole(d)
}
DictionaryTraps.test("RemoveInvalidIndex1")
.skip(.Custom(
{ _isFastAssertConfiguration() },
reason: "this trap is not guaranteed to happen in -Ounchecked"))
.code {
var d = Dictionary<Int, Int>()
let index = d.startIndex
expectCrashLater()
d.removeAtIndex(index)
}
DictionaryTraps.test("RemoveInvalidIndex2")
.skip(.Custom(
{ _isFastAssertConfiguration() },
reason: "this trap is not guaranteed to happen in -Ounchecked"))
.code {
var d = Dictionary<Int, Int>()
let index = d.endIndex
expectCrashLater()
d.removeAtIndex(index)
}
DictionaryTraps.test("RemoveInvalidIndex3")
.skip(.Custom(
{ _isFastAssertConfiguration() },
reason: "this trap is not guaranteed to happen in -Ounchecked"))
.code {
var d = [ 10: 1010, 20: 1020, 30: 1030 ]
let index = d.endIndex
expectCrashLater()
d.removeAtIndex(index)
}
DictionaryTraps.test("RemoveInvalidIndex4")
.skip(.Custom(
{ _isFastAssertConfiguration() },
reason: "this trap is not guaranteed to happen in -Ounchecked"))
.code {
var d = [ 10: 1010 ]
let index = d.indexForKey(10)!
d.removeAtIndex(index)
expectEmpty(d[10])
expectCrashLater()
d.removeAtIndex(index)
}
class TestObjCKeyTy : NSObject {
init(_ value: Int) {
self.value = value
}
override func isEqual(object: AnyObject!) -> Bool {
if let other = object {
if let otherObjcKey = other as? TestObjCKeyTy {
return self.value == otherObjcKey.value
}
}
return false
}
override var hash : Int {
return value
}
var value: Int
}
struct TestBridgedKeyTy : Hashable, _ObjectiveCBridgeable {
static func _isBridgedToObjectiveC() -> Bool {
return true
}
init(_ value: Int) { self.value = value }
var hashValue: Int { return value }
static func _getObjectiveCType() -> Any.Type {
return TestObjCKeyTy.self
}
func _bridgeToObjectiveC() -> TestObjCKeyTy {
return TestObjCKeyTy(value)
}
static func _forceBridgeFromObjectiveC(
x: TestObjCKeyTy,
inout result: TestBridgedKeyTy?
) {
result = TestBridgedKeyTy(x.value)
}
static func _conditionallyBridgeFromObjectiveC(
x: TestObjCKeyTy,
inout result: TestBridgedKeyTy?
) -> Bool {
result = TestBridgedKeyTy(x.value)
return true
}
var value: Int
}
func ==(x: TestBridgedKeyTy, y: TestBridgedKeyTy) -> Bool {
return x.value == y.value
}
DictionaryTraps.test("BridgedKeyIsNotNSCopyable1")
.skip(.Custom(
{ _isFastAssertConfiguration() },
reason: "this trap is not guaranteed to happen in -Ounchecked"))
.crashOutputMatches("unrecognized selector sent to instance").code {
// This Dictionary is bridged in O(1).
var d = [ TestObjCKeyTy(10): NSObject() ]
var nsd = d as NSDictionary
expectCrashLater()
nsd.mutableCopy()
}
DictionaryTraps.test("BridgedKeyIsNotNSCopyable2")
.skip(.Custom(
{ _isFastAssertConfiguration() },
reason: "this trap is not guaranteed to happen in -Ounchecked"))
.code {
// This Dictionary is bridged in O(1).
var d = [ TestObjCKeyTy(10): 10 ]
var nsd = d as NSDictionary
expectCrashLater()
nsd.mutableCopy()
}
DictionaryTraps.test("Downcast1") {
let d: Dictionary<NSObject, NSObject> = [ TestObjCKeyTy(10): NSObject(),
NSObject() : NSObject() ]
let d2: Dictionary<TestObjCKeyTy, NSObject> = _dictionaryDownCast(d)
expectCrashLater()
let v1 = d2[TestObjCKeyTy(10)]
let v2 = d2[TestObjCKeyTy(20)]
// This triggers failure.
for (k, v) in d2 { }
}
DictionaryTraps.test("Downcast2")
.skip(.Custom(
{ _isFastAssertConfiguration() },
reason: "this trap is not guaranteed to happen in -Ounchecked"))
.code {
let d: Dictionary<NSObject, NSObject> = [ TestObjCKeyTy(10): NSObject(),
NSObject() : NSObject() ]
expectCrashLater()
let d2: Dictionary<TestBridgedKeyTy, NSObject>
= _dictionaryBridgeFromObjectiveC(d)
let v1 = d2[TestBridgedKeyTy(10)]
}
runAllTests()
|
apache-2.0
|
a08699638e1b9ecc947875f153de19fd
| 24.263566 | 74 | 0.681804 | 3.993873 | false | true | false | false |
XSega/Words
|
Words/Scenes/Trainings/Old/TrainingInteractor.swift
|
1
|
1507
|
//
// MeaningsInteractor.swift
// Words
//
// Created by Sergey Ilyushin on 26/07/2017.
// Copyright © 2017 Sergey Ilyushin. All rights reserved.
//
import Foundation
protocol ITrainingInteractorOutput: class {
func onFetchMeaningsSuccess(meanings: [Meaning])
func onFetchMeaningsFailure(message: String)
}
protocol ITrainingInteractor: class {
func fetchMeanings()
}
class TrainingInteractor: ITrainingInteractor {
var meaningIds = [Int]()
var apiDataManager: IAPIDataManager!
var localDataManager: ILocalDataManager!
weak var presenter: ITrainingInteractorOutput!
func fetchMeanings() {
let ids = meaningIds.randomItems(count: 10)
// Fetch from local storage
//let meanings = localDataManager.fetchMeanings(identifiers: ids)// {
//presenter.onFetchProductsSuccess(meanings: meanings)
// return
//}
// Request from server
let succesHandler = {[unowned self] (meanings: [Meaning]) in
DispatchQueue.main.async {
self.presenter.onFetchMeaningsSuccess(meanings: meanings)
}
}
let errorHandler = {[unowned self] (error: Error) in
DispatchQueue.main.async {
self.presenter.onFetchMeaningsFailure(message: "Error loading")
}
}
apiDataManager.requestMeanings(identifiers: ids, completionHandler: succesHandler, errorHandler: errorHandler)
}
}
|
mit
|
807f2b867de4b9a7a69908c0a0222566
| 27.961538 | 118 | 0.650066 | 4.70625 | false | false | false | false |
jejefcgb/ProjetS9-iOS
|
Projet S9/BeaconsModelBuilder.swift
|
1
|
1456
|
//
// BeaconsModelBuilder.swift
// Projet S9
//
// Created by Jérémie Foucault on 02/01/2015.
// Copyright (c) 2015 Jérémie Foucault. All rights reserved.
//
import Foundation
class BeaconsModelBuilder {
class func buildBeaconsFromJSON(beaconsJson: JSON) {
var beacons: [Beacon] = []
for (index, beaconJson) in beaconsJson {
let id : Int = beaconJson["id"].intValue
let uuid: String = beaconJson["uuid"].stringValue
let major: Int = beaconJson["major"].intValue
let minor: Int = beaconJson["minor"].intValue
let floor_id: Int = beaconJson["floor_id"].intValue
let room_id: Int = beaconJson["room_id"].intValue
let x: CGFloat = CGFloat(beaconJson["coordinates"]["x"].floatValue)
let y: CGFloat = CGFloat(beaconJson["coordinates"]["y"].floatValue)
let coordinates: CGPoint = CGPoint(x: x, y: y)
beacons.append(Beacon(
id: id,
uuid: uuid,
major: major,
minor: minor,
floor_id: floor_id,
room_id: room_id,
coordinates: coordinates
))
}
Beacons.sharedInstance.setData(beacons)
}
}
|
apache-2.0
|
b40a1d5643f166f3634b2ed165b90018
| 31.288889 | 96 | 0.493802 | 4.82392 | false | false | false | false |
Rehsco/StyledOverlay
|
StyledOverlay/StyledBaseOverlay.swift
|
1
|
4750
|
//
// StyledBaseOverlay.swift
// StyledOverlay
//
// Created by Martin Rehder on 22.10.2016.
/*
* Copyright 2016-present Martin Jacob Rehder.
* http://www.rehsco.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 StyledLabel
open class StyledBaseOverlay: UIView {
var styleLayer = CAShapeLayer()
public override init(frame: CGRect) {
super.init(frame: frame)
self.initView()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.initView()
}
open override func layoutSubviews() {
super.layoutSubviews()
self.layoutComponents()
}
func initView() {
self.backgroundColor = .clear
if self.styleLayer.superlayer == nil {
self.layer.insertSublayer(self.styleLayer, at: 0)
}
}
// MARK: - Control Style
/// The view's style.
open var style: ShapeStyle? {
didSet {
self.setNeedsLayout()
}
}
/// Convenience for getting a valid style
open func getStyle() -> ShapeStyle {
return self.style ?? overlayStyleAppearance.style
}
/// The view’s background color.
@IBInspectable open var styleColor: UIColor? {
didSet {
self.setNeedsLayout()
}
}
/// The view's border color.
@IBInspectable open var borderColor: UIColor? {
didSet {
self.setNeedsLayout()
}
}
/// The view's border width.
open var borderWidth: CGFloat? {
didSet {
self.setNeedsLayout()
}
}
/// The view’s background color.
override open var backgroundColor: UIColor? {
didSet {
self.setNeedsLayout()
}
}
/// The controls background insets. These are margins for the inner background.
open var backgroundInsets: UIEdgeInsets? {
didSet {
self.setNeedsLayout()
}
}
// MARK: - Internal View
func marginsForRect(_ rect: CGRect, margins: UIEdgeInsets) -> CGRect {
return CGRect(x: rect.origin.x + margins.left, y: rect.origin.y + margins.top, width: rect.size.width - (margins.left + margins.right), height: rect.size.height - (margins.top + margins.bottom))
}
func layoutComponents() {
self.applyStyle(self.getStyle())
}
func createBorderLayer(_ style: ShapeStyle, layerRect: CGRect) -> CALayer? {
let borderWidth = self.borderWidth ?? overlayStyleAppearance.borderWidth
if borderWidth > 0 {
let bLayer = StyledShapeLayer.createShape(style, bounds: layerRect, color: .clear, borderColor: borderColor ?? overlayStyleAppearance.borderColor, borderWidth: borderWidth)
return bLayer
}
return nil
}
func applyStyle(_ style: ShapeStyle) {
if self.styleLayer.superlayer == nil {
self.layer.addSublayer(styleLayer)
}
let layerRect = self.marginsForRect(bounds, margins: backgroundInsets ?? overlayStyleAppearance.backgroundInsets)
let bgColor: UIColor = self.styleColor ?? backgroundColor ?? overlayStyleAppearance.backgroundColor
let bgsLayer = StyledShapeLayer.createShape(style, bounds: layerRect, color: bgColor)
// Add layer with border, if required
if let bLayer = self.createBorderLayer(style, layerRect: layerRect) {
bgsLayer.addSublayer(bLayer)
}
if styleLayer.superlayer != nil {
layer.replaceSublayer(styleLayer, with: bgsLayer)
}
styleLayer = bgsLayer
styleLayer.frame = layerRect
}
}
|
mit
|
856aabb4a97810b08e348e95974c6e16
| 31.731034 | 202 | 0.644543 | 4.621227 | false | false | false | false |
Rehsco/StyledOverlay
|
StyledOverlay/CloseButtonStyler.swift
|
1
|
2074
|
//
// CloseButtonStyler.swift
// StyledOverlay
//
// Created by Martin Rehder on 08.01.2018.
/*
* Copyright 2018-present Martin Jacob Rehder.
* http://www.rehsco.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 FlexCollections
open class CloseButtonStyler: StyledOverlayCellStyler {
open override func prepareStyle(forCell cell: FlexCollectionViewCell) {
if let baseCell = cell as? FlexBaseCollectionViewCell {
baseCell.flexContentView?.style = self.configuration.closeButtonStyle
baseCell.flexContentView?.styleColor = self.configuration.closeButtonStyleColor
baseCell.style = self.configuration.closeButtonStyle
baseCell.styleColor = self.configuration.closeButtonStyleColor
}
}
open override func applyStyle(toCell cell: FlexCollectionViewCell) {
if let baseCell = cell as? FlexBaseCollectionViewCell {
baseCell.textLabel?.labelTextAlignment = self.configuration.closeButtonTextAlignment
}
}
}
|
mit
|
88f7c82e4dd7494e3116a5dd8e473dcc
| 42.208333 | 96 | 0.744937 | 4.756881 | false | true | false | false |
codelynx/silvershadow
|
Silvershadow/Renderer.swift
|
1
|
1260
|
//
// Renderer.swift
// Silvershadow
//
// Created by Kaz Yoshikawa on 12/12/16.
// Copyright © 2016 Electricwoods LLC. All rights reserved.
//
import MetalKit
extension MTLPixelFormat {
static let `default` : MTLPixelFormat = .bgra8Unorm
}
protocol Renderer: class {
var device: MTLDevice { get }
init(device: MTLDevice)
}
extension Renderer {
var library: MTLLibrary {
return self.device.makeDefaultLibrary()!
}
}
class DictLike<Key : Hashable, Value> {
private var content : [Key: Value] = [:]
subscript(key: Key) -> Value? {
get { return content[key] }
set { content[key] = newValue }
}
}
final class RendererRegistry : DictLike<String, Renderer> { }
func aligned(length: Int, alignment: Int) -> Int {
return length + ((alignment - (length % alignment)) % alignment)
}
final class RenderMap : NSMapTable<MTLDevice, RendererRegistry> {
static let shared = RenderMap.weakToStrongObjects()
}
extension MTLDevice {
func renderer<T: Renderer>() -> T {
let key = NSStringFromClass(T.self)
let registry = RenderMap.shared.object(forKey: self) ?? RendererRegistry()
let renderer = registry[key] ?? T(device: self)
registry[key] = renderer
RenderMap.shared.setObject(registry, forKey: self)
return renderer as! T
}
}
|
mit
|
492c6161ca62e5fc1366b99120e9059d
| 20.338983 | 76 | 0.702939 | 3.421196 | false | false | false | false |
ruipfcosta/SwiftyWalkthrough
|
iOS Example/iOS Example/ProfileViewController.swift
|
1
|
3574
|
//
// ProfileViewController.swift
// iOS Example
//
// Created by Rui Costa on 29/09/2015.
// Copyright © 2015 Rui Costa. All rights reserved.
//
import UIKit
import SwiftyWalkthrough
class ProfileViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var photo: UIImageView!
@IBOutlet weak var nameField: UITextField!
@IBOutlet weak var surnameField: UITextField!
@IBOutlet weak var addressField: UITextField!
static var walkthroughDimColor = UIColor.red.withAlphaComponent(0.7).cgColor
var customWalkthroughView: CustomWalkthroughView? { return walkthroughView as? CustomWalkthroughView }
override func viewDidLoad() {
super.viewDidLoad()
nameField.delegate = self
surnameField.delegate = self
addressField.delegate = self
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
customWalkthroughView?.cutHolesForViewDescriptors([ViewDescriptor(view: photo, extraPaddingX: 20, extraPaddingY: 20, cornerRadius: 80)])
customWalkthroughView?.helpLabel.isHidden = false
customWalkthroughView?.helpLabel.backgroundColor = UIColor.blue
customWalkthroughView?.helpLabel.text = "Ok, lets play with the colors too! Tap the image to start."
customWalkthroughView?.helpLabel.frame = CGRect(x: customWalkthroughView!.center.x - 150, y: customWalkthroughView!.center.y + 60, width: 300, height: 80)
}
@IBAction func onTapImage(_ sender: UITapGestureRecognizer) {
customWalkthroughView?.cutHolesForViews([nameField])
customWalkthroughView?.dimColor = UIColor.blue.withAlphaComponent(0.5).cgColor
customWalkthroughView?.helpLabel.backgroundColor = UIColor.black
customWalkthroughView?.helpLabel.text = "Now tell us your name"
customWalkthroughView?.helpLabel.frame = CGRect(x: customWalkthroughView!.center.x - 150, y: customWalkthroughView!.center.y + 60, width: 300, height: 80)
}
// MARK: - UITextFieldDelegate
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
func textFieldShouldEndEditing(_ textField: UITextField) -> Bool {
if let input = textField.text {
return !input.isEmpty
}
return false
}
func textFieldDidEndEditing(_ textField: UITextField) {
if textField == nameField {
customWalkthroughView?.cutHolesForViews([surnameField])
customWalkthroughView?.helpLabel.text = "... and the surname"
customWalkthroughView?.helpLabel.frame = CGRect(x: customWalkthroughView!.center.x - 150, y: 60, width: 300, height: 80)
} else if textField == surnameField {
customWalkthroughView?.cutHolesForViews([addressField])
customWalkthroughView?.dimColor = ProfileViewController.walkthroughDimColor
customWalkthroughView?.helpLabel.text = "... and finally your address!"
} else if textField == addressField {
customWalkthroughView?.dimColor = HomeViewController.walkthroughDimColor
customWalkthroughView?.removeAllHoles()
customWalkthroughView?.helpLabel.isHidden = true
UserDefaults.standard.set(true, forKey: "profileWalkthroughComplete")
if ongoingWalkthrough {
navigationController?.popToRootViewController(animated: true)
}
}
}
}
|
mit
|
51199bab3855466267b293ca56adddbe
| 40.068966 | 162 | 0.68262 | 5.111588 | false | false | false | false |
akuraru/PureViewIcon
|
PureViewIcon/Views/PVIPlus.swift
|
1
|
1697
|
//
// PVI.swift
//
// Created by akuraru on 2017/02/11.
//
import UIKit
import SnapKit
extension PVIView {
func makePlusConstraints() {
base.snp.makeConstraints { (make) in
make.width.equalToSuperview()
make.height.equalToSuperview()
make.center.equalToSuperview()
}
base.transform = resetTransform()
before.setup(width: 2)
main.setup(width: 2)
after.setup(width: 2)
// before
before.top.alpha = 1
before.left.alpha = 0
before.right.alpha = 0
before.bottom.alpha = 0
before.view.snp.makeConstraints { (make) in
make.center.equalToSuperview()
make.width.equalToSuperview().multipliedBy(20 / 34.0)
make.height.equalToSuperview().multipliedBy(2 / 34.0)
}
before.view.transform = resetTransform()
// main
main.top.alpha = 0
main.left.alpha = 1
main.right.alpha = 0
main.bottom.alpha = 0
main.view.snp.makeConstraints { (make) in
make.center.equalToSuperview()
make.width.equalToSuperview().multipliedBy(2 / 34.0)
make.height.equalToSuperview().multipliedBy(20 / 34.0)
}
main.view.transform = resetTransform()
// after
after.top.alpha = 0
after.left.alpha = 0
after.right.alpha = 0
after.bottom.alpha = 0
after.view.snp.makeConstraints { (make) in
make.center.equalToSuperview()
make.size.equalTo(0)
}
after.view.transform = resetTransform()
}
}
|
mit
|
7621e9208db28bad508938980ab4d6fd
| 26.370968 | 66 | 0.550972 | 4.407792 | false | false | false | false |
PatrickChow/Swift-Awsome
|
News/Network/Plugins/URLAdditionalParametersPlugin.swift
|
1
|
1406
|
//
// Created by Patrick Chow on 2017/7/17.
// Copyright (c) 2017 JIEMIAN. All rights reserved.
import Foundation
import Moya
import Alamofire
import AdSupport
class URLAdditionalParametersPlugin: PluginType {
let encoding: URLEncoding
init(encoding: URLEncoding = URLEncoding.default) {
self.encoding = encoding
}
func prepare(_ request: URLRequest, target: TargetType) -> URLRequest {
/*
每个请求都要在尾部添加4个参数,组成最后的 url
`https://appapi.jiemian.com/v4/1.0/10000/msg/lists.json?dv=iPhone&os=10.3.2&rl=750.0%2A1334.0&vid=BFC22FE7-583D-4AE1-ADDB-578203565D86`
POST 不能添加到 `httpBody` 中,所以这里有个小 trick
*/
// 记录 httpMethod
let method = request.httpMethod
// 修改 httpMethod 保证 post 请求也按 get 形式添加到末尾
var vRequest = request
vRequest.httpMethod = nil
guard var newRequest = try? encoding.encode(vRequest, with: Network.commonParameters) else {
return request
}
newRequest.httpMethod = method
//TODO: 登录状态下,POST要增加参数
guard UserManager.isSignedIn,
let request = try? encoding.encode(newRequest, with: [:])
else {
return newRequest
}
return request
}
}
|
mit
|
8f56e25fa97baf6da3508a41cfed8840
| 28.860465 | 146 | 0.623832 | 3.93865 | false | false | false | false |
loop/ShotsApp
|
Shots-Assets/Spring/DesignableView.swift
|
1
|
1238
|
//
// DesignableView.swift
// Spring
//
// Created by Meng To on 2014-07-04.
// Copyright (c) 2014 Meng To. All rights reserved.
//
import UIKit
@IBDesignable class DesignableView: UIView {
@IBInspectable var borderColor: UIColor = UIColor.clearColor() {
didSet {
layer.borderColor = borderColor.CGColor
}
}
@IBInspectable var borderWidth: CGFloat = 0 {
didSet {
layer.borderWidth = borderWidth
}
}
@IBInspectable var cornerRadius: CGFloat = 0 {
didSet {
layer.cornerRadius = cornerRadius
}
}
@IBInspectable var shadowColor: UIColor = UIColor.clearColor() {
didSet {
layer.shadowColor = shadowColor.CGColor
}
}
@IBInspectable var shadowRadius: CGFloat = 0 {
didSet {
layer.shadowRadius = shadowRadius
layer.shadowOffset = CGSizeMake(1, 1)
layer.shadowRadius = 4
layer.shadowOpacity = 0.8
layer.shadowPath = UIBezierPath(rect: layer.bounds).CGPath
}
}
@IBInspectable var shadowOpacity: CGFloat = 0 {
didSet {
layer.shadowOpacity = Float(shadowOpacity)
}
}
override func awakeFromNib() {
super.awakeFromNib()
}
}
|
mit
|
3e90b87aafa713863c6a3119b90f7bf9
| 21.527273 | 68 | 0.615509 | 4.689394 | false | false | false | false |
pivotframework/pivot
|
PivotFoundation/PivotFoundation/Date.swift
|
1
|
1965
|
import CoreFoundation
public typealias TimeInterval = CFTimeInterval
public class Date {
public init() {
_timeIntervalSinceReferenceDate = CFAbsoluteTimeGetCurrent()
}
public init(timeInterval: TimeInterval) {
_timeIntervalSinceReferenceDate = timeInterval
}
public var timeIntervalSinceReferenceDate: TimeInterval {
get {
return _timeIntervalSinceReferenceDate
}
}
public var timeIntervalSince1970: TimeInterval {
get {
return _timeIntervalSinceReferenceDate + _timeIntervalFromReferenceDateSince1970
}
}
internal let _timeIntervalSinceReferenceDate: TimeInterval
internal let _timeIntervalFromReferenceDateSince1970 = 978307200.0
}
public extension Date {
internal func format(format: String, timeZoneOffset: TimeInterval) -> String {
let currentLocale = CFLocaleCopyCurrent()
let customDateFormatter = CFDateFormatterCreate(kCFAllocatorDefault, currentLocale, CFDateFormatterStyle.NoStyle, CFDateFormatterStyle.NoStyle)
let customDateFormat = CFStringCreateCopy(kCFAllocatorDefault, format);
CFDateFormatterSetFormat(customDateFormatter, customDateFormat)
let timeZone = CFTimeZoneCreateWithTimeIntervalFromGMT(kCFAllocatorDefault, timeZoneOffset)
CFDateFormatterSetProperty(customDateFormatter, kCFDateFormatterTimeZone, timeZone)
return CFDateFormatterCreateStringWithAbsoluteTime(kCFAllocatorDefault, customDateFormatter, _timeIntervalSinceReferenceDate) as String
}
public func format(format: String) -> String {
let timeZoneOffset = CFTimeZoneGetSecondsFromGMT(CFTimeZoneCopySystem(), CFAbsoluteTimeGetCurrent()) as TimeInterval
return self.format(format, timeZoneOffset: timeZoneOffset)
}
public func httpFormat() -> String {
return format("EEE',' dd MMM YYYY HH:mm:ss zzz", timeZoneOffset: 0)
}
}
|
mit
|
52d7dea93b31a59fd7eff5e6f5c416aa
| 38.3 | 151 | 0.736896 | 6.33871 | false | false | false | false |
jorjuela33/OperationKit
|
OperationKit/Operations/Operation.swift
|
1
|
10115
|
//
// Operation.swift
//
// Copyright © 2016. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import CoreData
import UIKit
public let OperationErrorDomainCode = "com.operation.domain.error"
public protocol ObservableOperation {
/// Invoked immediately prior to the `Operation`'s `execute()` method.
func operationDidStart(_ operation: Operation)
/// Invoked when `Operation.produceOperation(_:)` is executed.
func operation(_ operation: Operation, didProduceOperation newOperation: Foundation.Operation)
/// Invoked as an `Operation` finishes, along with any errors produced during
/// execution (or readiness evaluation).
func operationDidFinish(_ operation: Operation, errors: [Error])
}
public protocol OperationStateObserver: ObservableOperation {
/// Invoked when `Operation.resume(_:)` is executed.
func operationDidResume(_ operation: Operation)
/// Invoked when `Operation.suspend(_:)` is executed.
func operationDidSuspend(_ operation: Operation)
}
open class Operation: Foundation.Operation {
fileprivate enum State: Int, Comparable {
/// The initial state of an `Operation`.
case initialized
/// The `Operation` is ready to begin evaluating conditions.
case pending
/// The `Operation` is evaluating conditions.
case evaluatingConditions
/// The `Operation`'s conditions have all been satisfied,
/// and it is ready to execute.
case ready
/// The `Operation` is executing.
case executing
/// Execution of the `Operation` has finished, but it has not yet notified
/// the queue of this.
case finishing
/// The `Operation` has finished executing.
case finished
func canTransitionToState(_ target: State) -> Bool {
switch (self, target) {
case (.initialized, .pending):
return true
case (.pending, .evaluatingConditions):
return true
case (.evaluatingConditions, .ready):
return true
case (.ready, .executing):
return true
case (.ready, .finishing):
return true
case (.executing, .finishing):
return true
case (.finishing, .finished):
return true
case (.pending, .finishing):
return true
default:
return false
}
}
}
private var hasFinishedAlready = false
private var internalErrors: [Error] = []
private var lock = NSLock()
private var _state: State = .initialized
fileprivate var state: State {
get {
lock.lock()
defer { lock.unlock() }
return _state
}
set(newState) {
assert(_state.canTransitionToState(newState))
guard _state != .finished else { return }
willChangeValue(forKey: "state")
lock.lock()
_state = newState
lock.unlock()
didChangeValue(forKey: "state")
}
}
/// The conditions for this operation
fileprivate(set) var conditions: [OperationCondition] = []
/// The observers of the operation
fileprivate(set) var observers = [ObservableOperation]()
override open var isAsynchronous: Bool {
return true
}
/// Wheter the resquest is user initiated or not
open var userInitiated: Bool {
get {
return qualityOfService == .userInitiated
}
set {
assert(state < .executing)
qualityOfService = newValue ? .userInitiated : .default
}
}
override open var isExecuting: Bool {
return state == .executing
}
override open var isFinished: Bool {
return state == .finished
}
override open var isReady: Bool {
switch state {
case .initialized:
return isCancelled
case .pending:
guard !isCancelled else {
return true
}
if super.isReady {
evaluateConditions()
}
return false
case .ready:
return super.isReady || isCancelled
default:
return false
}
}
// MARK: Intance methods
/// Adds a new condition for this operation
public final func addCondition(_ operationCondition: OperationCondition) {
assert(state < .evaluatingConditions)
conditions.append(operationCondition)
}
/// Adds a new observer for the operation
open func addObserver(_ observer: ObservableOperation) {
assert(state < .executing)
observers.append(observer)
}
/// Cancels the current request
///
/// error - The error produced by the request
public final func cancelWithError(_ error: Error) {
internalErrors.append(error)
cancel()
}
/// The entry point of all operations
open func execute() {
finish()
}
/// Finish the current request
///
/// errors - Optional value containing the errors
/// produced by the operation
public final func finish(_ errors: [Error] = []) {
guard hasFinishedAlready == false else { return }
let combinedErrors = internalErrors + errors
hasFinishedAlready = true
state = .finishing
finished(combinedErrors)
for observer in observers {
observer.operationDidFinish(self, errors: combinedErrors)
}
observers.removeAll()
state = .finished
}
/// Should be overriden for the child operations
open func finished(_ errors: [Error]) {
// No op.
}
/// Finish the current request
///
/// error - The error produced by the request
public final func finishWithError(_ error: Error?) {
guard let error = error else {
finish()
return
}
finish([error])
}
/// Notify to the observer when a suboperation is created for this operation
public final func produceOperation(_ operation: Foundation.Operation) {
for observer in observers {
observer.operation(self, didProduceOperation: operation)
}
}
/// Indicates that the Operation can now begin to evaluate readiness conditions,
/// if appropriate.
open func willEnqueue() {
state = .pending
}
// MARK: KVO methods
class func keyPathsForValuesAffectingIsReady() -> Set<NSObject> {
return ["state" as NSObject]
}
class func keyPathsForValuesAffectingIsExecuting() -> Set<NSObject> {
return ["state" as NSObject]
}
class func keyPathsForValuesAffectingIsFinished() -> Set<NSObject> {
return ["state" as NSObject]
}
// MARK: Overrided methods
override final public func main() {
assert(state == .ready)
guard isCancelled == false && internalErrors.isEmpty else {
finish()
return
}
state = .executing
for observer in observers {
observer.operationDidStart(self)
}
execute()
}
override open func start() {
super.start()
if isCancelled {
finish()
}
}
// MARK: Private methods
fileprivate func evaluateConditions() {
assert(state == .pending && !isCancelled)
state = .evaluatingConditions
let conditionGroup = DispatchGroup()
var results = [OperationConditionResult?](repeating: nil, count: conditions.count)
for (index, condition) in conditions.enumerated() {
conditionGroup.enter()
condition.evaluate(for: self) { result in
results[index] = result
conditionGroup.leave()
}
}
conditionGroup.notify(queue: DispatchQueue.global(qos: DispatchQoS.QoSClass.default)) {
self.internalErrors += results.flatMap { $0?.error }
if self.isCancelled {
let error = NSError(domain: OperationErrorDomainCode, code: OperationErrorCode.conditionFailed.rawValue, userInfo: nil)
self.internalErrors.append(error)
}
self.state = .ready
}
}
}
private func <(lhs: Operation.State, rhs: Operation.State) -> Bool {
return lhs.rawValue < rhs.rawValue
}
private func ==(lhs: Operation.State, rhs: Operation.State) -> Bool {
return lhs.rawValue == rhs.rawValue
}
|
mit
|
1ada6618a3901e758869936fd2d96e0b
| 29.191045 | 135 | 0.585426 | 5.362672 | false | false | false | false |
joerocca/GitHawk
|
Local Pods/SwipeCellKit/Example/MailExample/Data.swift
|
7
|
4707
|
//
// Data.swift
//
// Created by Jeremy Koch
// Copyright © 2017 Jeremy Koch. All rights reserved.
//
import Foundation
class Email {
let from: String
let subject: String
let body: String
let date: Date
var unread = false
init(from: String, subject: String, body: String, date: Date) {
self.from = from
self.subject = subject
self.body = body
self.date = date
}
var relativeDateString: String {
if Calendar.current.isDateInToday(date) {
let formatter = DateFormatter()
formatter.timeStyle = .short
return formatter.string(from: date)
} else {
let formatter = DateFormatter()
formatter.dateStyle = .short
formatter.doesRelativeDateFormatting = true
return formatter.string(from: date)
}
}
}
extension Calendar {
static func now(addingDays days: Int) -> Date {
return Date().addingTimeInterval(Double(days) * 60 * 60 * 24)
}
}
let mockEmails: [Email] = [
Email(from: "Realm", subject: "Video: Operators and Strong Opinions with Erica Sadun", body: "Swift operators are flexible and powerful. They’re symbols that behave like functions, adopting a natural mathematical syntax, for example 1 + 2 versus add(1, 2). So why is it so important that you treat them like potential Swift Kryptonite? Erica Sadun discusses why your operators should be few, well-chosen, and heavily used. There’s even a fun interactive quiz! Play along with “Name That Operator!” and learn about an essential Swift best practice.", date: Calendar.now(addingDays: 0)),
Email(from: "The Pragmatic Bookstore", subject: "[Pragmatic Bookstore] Your eBook 'Swift Style' is ready for download", body: "Hello, The gerbils at the Pragmatic Bookstore have just finished hand-crafting your eBook of Swift Style. It's available for download at the following URL:", date: Calendar.now(addingDays: 0)),
Email(from: "Instagram", subject: "mrx, go live and send disappearing photos and videos", body: "Go Live and Send Disappearing Photos and Videos. We recently announced two updates: live video on Instagram Stories and disappearing photos and videos for groups and friends in Instagram Direct.", date: Calendar.now(addingDays: -1)),
Email(from: "Smithsonian Magazine", subject: "Exclusive Sneak Peek Inside | Untold Stories of the Civil War", body: "For the very first time, the Smithsonian showcases the treasures of its Civil War collections in Smithsonian Civil War. This 384-page, hardcover book takes readers inside the museum storerooms and vaults to learn the untold stories behind the Smithsonian's most fascinating and significant pieces, including many previously unseen relics and artifacts. With over 500 photographs and text from forty-nine curators, the Civil War comes alive.", date: Calendar.now(addingDays: -2)),
Email(from: "Apple News", subject: "How to Change Your Personality in 90 Days", body: "How to Change Your Personality. You are not stuck with yourself. New research shows that you can troubleshoot personality traits — in therapy.", date: Calendar.now(addingDays: -3)),
Email(from: "Wordpress", subject: "New WordPress Site", body: "Your new WordPress site has been successfully set up at: http://example.com. You can log in to the administrator account with the following information:", date: Calendar.now(addingDays: -4)),
Email(from: "IFTTT", subject: "See what’s new & notable on IFTTT", body: "See what’s new & notable on IFTTT. To disable these emails, sign in to manage your settings or unsubscribe.", date: Calendar.now(addingDays: -5)),
Email(from: "Westin Vacations", subject: "Your Westin exclusive expires January 11", body: "Last chance to book a captivating 5-day, 4-night vacation in Rancho Mirage for just $389. Learn more. No images? CLICK HERE", date: Calendar.now(addingDays: -6)),
Email(from: "Nugget Markets", subject: "Nugget Markets Weekly Specials Starting February 15, 2017", body: "Scan & Save. For this week’s Secret Special, let’s “brioche” the subject of breakfast. This Friday and Saturday, February 24–25, buy one loaf of Euro Classic Brioche and get one free! This light, soft, hand-braided buttery brioche loaf from France is perfect for an authentic French toast feast. Make Christmas morning extra special with our Signature Recipe for Crème Brûlée French Toast Soufflé!", date: Calendar.now(addingDays: -7)),
Email(from: "GeekDesk", subject: "We have some exciting things happening at GeekDesk!", body: "Wouldn't everyone be so much happier if we all owned GeekDesks?", date: Calendar.now(addingDays: -8))
]
|
mit
|
d7ca0c654c1fbbb95180cc4c4421d397
| 82.535714 | 600 | 0.727661 | 4.029285 | false | false | false | false |
naokits/my-programming-marathon
|
iPhoneSensorDemo/Pods/RxSwift/RxSwift/DataStructures/Bag.swift
|
16
|
7171
|
//
// Bag.swift
// Rx
//
// Created by Krunoslav Zaher on 2/28/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
import Swift
let arrayDictionaryMaxSize = 30
/**
Class that enables using memory allocations as a means to uniquely identify objects.
*/
class Identity {
// weird things have known to happen with Swift
var _forceAllocation: Int32 = 0
}
func hash(_x: Int) -> Int {
var x = _x
x = ((x >> 16) ^ x) &* 0x45d9f3b
x = ((x >> 16) ^ x) &* 0x45d9f3b
x = ((x >> 16) ^ x)
return x;
}
/**
Unique identifier for object added to `Bag`.
*/
public struct BagKey : Hashable {
let uniqueIdentity: Identity?
let key: Int
public var hashValue: Int {
if let uniqueIdentity = uniqueIdentity {
return hash(key) ^ (unsafeAddressOf(uniqueIdentity).hashValue)
}
else {
return hash(key)
}
}
}
/**
Compares two `BagKey`s.
*/
public func == (lhs: BagKey, rhs: BagKey) -> Bool {
return lhs.key == rhs.key && lhs.uniqueIdentity === rhs.uniqueIdentity
}
/**
Data structure that represents a bag of elements typed `T`.
Single element can be stored multiple times.
Time and space complexity of insertion an deletion is O(n).
It is suitable for storing small number of elements.
*/
public struct Bag<T> : CustomDebugStringConvertible {
/**
Type of identifier for inserted elements.
*/
public typealias KeyType = BagKey
private typealias ScopeUniqueTokenType = Int
typealias Entry = (key: BagKey, value: T)
private var _uniqueIdentity: Identity?
private var _nextKey: ScopeUniqueTokenType = 0
// data
// first fill inline variables
private var _key0: BagKey? = nil
private var _value0: T? = nil
private var _key1: BagKey? = nil
private var _value1: T? = nil
// then fill "array dictionary"
private var _pairs = ContiguousArray<Entry>()
// last is sparse dictionary
private var _dictionary: [BagKey : T]? = nil
private var _onlyFastPath = true
/**
Creates new empty `Bag`.
*/
public init() {
}
/**
Inserts `value` into bag.
- parameter element: Element to insert.
- returns: Key that can be used to remove element from bag.
*/
public mutating func insert(element: T) -> BagKey {
_nextKey = _nextKey &+ 1
#if DEBUG
_nextKey = _nextKey % 20
#endif
if _nextKey == 0 {
_uniqueIdentity = Identity()
}
let key = BagKey(uniqueIdentity: _uniqueIdentity, key: _nextKey)
if _key0 == nil {
_key0 = key
_value0 = element
return key
}
_onlyFastPath = false
if _key1 == nil {
_key1 = key
_value1 = element
return key
}
if _dictionary != nil {
_dictionary![key] = element
return key
}
if _pairs.count < arrayDictionaryMaxSize {
_pairs.append(key: key, value: element)
return key
}
if _dictionary == nil {
_dictionary = [:]
}
_dictionary![key] = element
return key
}
/**
- returns: Number of elements in bag.
*/
public var count: Int {
return _pairs.count + (_value0 != nil ? 1 : 0) + (_value1 != nil ? 1 : 0) + (_dictionary?.count ?? 0)
}
/**
Removes all elements from bag and clears capacity.
*/
public mutating func removeAll() {
_key0 = nil
_value0 = nil
_key1 = nil
_value1 = nil
_pairs.removeAll(keepCapacity: false)
_dictionary?.removeAll(keepCapacity: false)
}
/**
Removes element with a specific `key` from bag.
- parameter key: Key that identifies element to remove from bag.
- returns: Element that bag contained, or nil in case element was already removed.
*/
public mutating func removeKey(key: BagKey) -> T? {
if _key0 == key {
_key0 = nil
let value = _value0!
_value0 = nil
return value
}
if _key1 == key {
_key1 = nil
let value = _value1!
_value1 = nil
return value
}
if let existingObject = _dictionary?.removeValueForKey(key) {
return existingObject
}
for i in 0 ..< _pairs.count {
if _pairs[i].key == key {
let value = _pairs[i].value
_pairs.removeAtIndex(i)
return value
}
}
return nil
}
}
extension Bag {
/**
A textual representation of `self`, suitable for debugging.
*/
public var debugDescription : String {
return "\(self.count) elements in Bag"
}
}
// MARK: forEach
extension Bag {
/**
Enumerates elements inside the bag.
- parameter action: Enumeration closure.
*/
public func forEach(@noescape action: (T) -> Void) {
if _onlyFastPath {
if let value0 = _value0 {
action(value0)
}
return
}
let pairs = _pairs
let value0 = _value0
let value1 = _value1
let dictionary = _dictionary
if let value0 = value0 {
action(value0)
}
if let value1 = value1 {
action(value1)
}
for i in 0 ..< pairs.count {
action(pairs[i].value)
}
if dictionary?.count ?? 0 > 0 {
for element in dictionary!.values {
action(element)
}
}
}
}
extension Bag where T: ObserverType {
/**
Dispatches `event` to app observers contained inside bag.
- parameter action: Enumeration closure.
*/
public func on(event: Event<T.E>) {
if _onlyFastPath {
_value0?.on(event)
return
}
let pairs = _pairs
let value0 = _value0
let value1 = _value1
let dictionary = _dictionary
if let value0 = value0 {
value0.on(event)
}
if let value1 = value1 {
value1.on(event)
}
for i in 0 ..< pairs.count {
pairs[i].value.on(event)
}
if dictionary?.count ?? 0 > 0 {
for element in dictionary!.values {
element.on(event)
}
}
}
}
/**
Dispatches `dispose` to all disposables contained inside bag.
*/
public func disposeAllIn(bag: Bag<Disposable>) {
if bag._onlyFastPath {
bag._value0?.dispose()
return
}
let pairs = bag._pairs
let value0 = bag._value0
let value1 = bag._value1
let dictionary = bag._dictionary
if let value0 = value0 {
value0.dispose()
}
if let value1 = value1 {
value1.dispose()
}
for i in 0 ..< pairs.count {
pairs[i].value.dispose()
}
if dictionary?.count ?? 0 > 0 {
for element in dictionary!.values {
element.dispose()
}
}
}
|
mit
|
c8a8e160a69cdf30bf76b6491fef2fe8
| 20.926606 | 109 | 0.537517 | 4.232586 | false | false | false | false |
Bouke/HAP
|
Sources/HAP/Base/Predefined/Characteristics/Characteristic.TargetHeatingCoolingState.swift
|
1
|
2231
|
import Foundation
public extension AnyCharacteristic {
static func targetHeatingCoolingState(
_ value: Enums.TargetHeatingCoolingState = .cool,
permissions: [CharacteristicPermission] = [.read, .write, .events],
description: String? = "Target Heating Cooling State",
format: CharacteristicFormat? = .uint8,
unit: CharacteristicUnit? = nil,
maxLength: Int? = nil,
maxValue: Double? = 3,
minValue: Double? = 0,
minStep: Double? = 1,
validValues: [Double] = [],
validValuesRange: Range<Double>? = nil
) -> AnyCharacteristic {
AnyCharacteristic(
PredefinedCharacteristic.targetHeatingCoolingState(
value,
permissions: permissions,
description: description,
format: format,
unit: unit,
maxLength: maxLength,
maxValue: maxValue,
minValue: minValue,
minStep: minStep,
validValues: validValues,
validValuesRange: validValuesRange) as Characteristic)
}
}
public extension PredefinedCharacteristic {
static func targetHeatingCoolingState(
_ value: Enums.TargetHeatingCoolingState = .cool,
permissions: [CharacteristicPermission] = [.read, .write, .events],
description: String? = "Target Heating Cooling State",
format: CharacteristicFormat? = .uint8,
unit: CharacteristicUnit? = nil,
maxLength: Int? = nil,
maxValue: Double? = 3,
minValue: Double? = 0,
minStep: Double? = 1,
validValues: [Double] = [],
validValuesRange: Range<Double>? = nil
) -> GenericCharacteristic<Enums.TargetHeatingCoolingState> {
GenericCharacteristic<Enums.TargetHeatingCoolingState>(
type: .targetHeatingCoolingState,
value: value,
permissions: permissions,
description: description,
format: format,
unit: unit,
maxLength: maxLength,
maxValue: maxValue,
minValue: minValue,
minStep: minStep,
validValues: validValues,
validValuesRange: validValuesRange)
}
}
|
mit
|
040f4d80ca98b87f3eefa664e812f8b4
| 35.57377 | 75 | 0.606006 | 5.212617 | false | false | false | false |
LYM-mg/MGDS_Swift
|
MGDS_Swift/Pods/IQKeyboardManagerSwift/IQKeyboardManagerSwift/IQKeyboardManager+UITextFieldViewNotification.swift
|
2
|
9941
|
//
// IQKeyboardManager+UITextFieldViewNotification.swift
// https://github.com/hackiftekhar/IQKeyboardManager
// Copyright (c) 2013-20 Iftekhar Qurashi.
//
// 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 - UIKit contains Foundation
import UIKit
// MARK: UITextField/UITextView Notifications
@available(iOSApplicationExtension, unavailable)
internal extension IQKeyboardManager {
private struct AssociatedKeys {
static var textFieldView = "textFieldView"
static var topViewBeginOrigin = "topViewBeginOrigin"
static var rootViewController = "rootViewController"
static var rootViewControllerWhilePopGestureRecognizerActive = "rootViewControllerWhilePopGestureRecognizerActive"
static var topViewBeginOriginWhilePopGestureRecognizerActive = "topViewBeginOriginWhilePopGestureRecognizerActive"
}
/** To save UITextField/UITextView object voa textField/textView notifications. */
weak var textFieldView: UIView? {
get {
return (objc_getAssociatedObject(self, &AssociatedKeys.textFieldView) as? WeakObjectContainer)?.object as? UIView
}
set(newValue) {
objc_setAssociatedObject(self, &AssociatedKeys.textFieldView, WeakObjectContainer(object: newValue), .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
var topViewBeginOrigin: CGPoint {
get {
return objc_getAssociatedObject(self, &AssociatedKeys.topViewBeginOrigin) as? CGPoint ?? IQKeyboardManager.kIQCGPointInvalid
}
set(newValue) {
objc_setAssociatedObject(self, &AssociatedKeys.topViewBeginOrigin, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
/** To save rootViewController */
weak var rootViewController: UIViewController? {
get {
return (objc_getAssociatedObject(self, &AssociatedKeys.rootViewController) as? WeakObjectContainer)?.object as? UIViewController
}
set(newValue) {
objc_setAssociatedObject(self, &AssociatedKeys.rootViewController, WeakObjectContainer(object: newValue), .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
/** To overcome with popGestureRecognizer issue Bug ID: #1361 */
weak var rootViewControllerWhilePopGestureRecognizerActive: UIViewController? {
get {
return (objc_getAssociatedObject(self, &AssociatedKeys.rootViewControllerWhilePopGestureRecognizerActive) as? WeakObjectContainer)?.object as? UIViewController
}
set(newValue) {
objc_setAssociatedObject(self, &AssociatedKeys.rootViewControllerWhilePopGestureRecognizerActive, WeakObjectContainer(object: newValue), .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
var topViewBeginOriginWhilePopGestureRecognizerActive: CGPoint {
get {
return objc_getAssociatedObject(self, &AssociatedKeys.topViewBeginOriginWhilePopGestureRecognizerActive) as? CGPoint ?? IQKeyboardManager.kIQCGPointInvalid
}
set(newValue) {
objc_setAssociatedObject(self, &AssociatedKeys.topViewBeginOriginWhilePopGestureRecognizerActive, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
/** UITextFieldTextDidBeginEditingNotification, UITextViewTextDidBeginEditingNotification. Fetching UITextFieldView object. */
@objc func textFieldViewDidBeginEditing(_ notification: Notification) {
let startTime = CACurrentMediaTime()
showLog("****** \(#function) started ******", indentation: 1)
// Getting object
textFieldView = notification.object as? UIView
if overrideKeyboardAppearance, let textInput = textFieldView as? UITextInput, textInput.keyboardAppearance != keyboardAppearance {
//Setting textField keyboard appearance and reloading inputViews.
if let textFieldView = textFieldView as? UITextField {
textFieldView.keyboardAppearance = keyboardAppearance
} else if let textFieldView = textFieldView as? UITextView {
textFieldView.keyboardAppearance = keyboardAppearance
}
textFieldView?.reloadInputViews()
}
//If autoToolbar enable, then add toolbar on all the UITextField/UITextView's if required.
if privateIsEnableAutoToolbar() {
//UITextView special case. Keyboard Notification is firing before textView notification so we need to resign it first and then again set it as first responder to add toolbar on it.
if let textView = textFieldView as? UIScrollView, textView.responds(to: #selector(getter: UITextView.isEditable)),
textView.inputAccessoryView == nil {
UIView.animate(withDuration: 0.00001, delay: 0, options: animationCurve, animations: { () -> Void in
self.addToolbarIfRequired()
}, completion: { (_) -> Void in
//On textView toolbar didn't appear on first time, so forcing textView to reload it's inputViews.
textView.reloadInputViews()
})
} else {
//Adding toolbar
addToolbarIfRequired()
}
} else {
removeToolbarIfRequired()
}
resignFirstResponderGesture.isEnabled = privateShouldResignOnTouchOutside()
textFieldView?.window?.addGestureRecognizer(resignFirstResponderGesture) // (Enhancement ID: #14)
if privateIsEnabled() == false {
restorePosition()
topViewBeginOrigin = IQKeyboardManager.kIQCGPointInvalid
} else {
if topViewBeginOrigin.equalTo(IQKeyboardManager.kIQCGPointInvalid) { // (Bug ID: #5)
rootViewController = textFieldView?.parentContainerViewController()
if let controller = rootViewController {
if rootViewControllerWhilePopGestureRecognizerActive == controller {
topViewBeginOrigin = topViewBeginOriginWhilePopGestureRecognizerActive
} else {
topViewBeginOrigin = controller.view.frame.origin
}
rootViewControllerWhilePopGestureRecognizerActive = nil
topViewBeginOriginWhilePopGestureRecognizerActive = IQKeyboardManager.kIQCGPointInvalid
self.showLog("Saving \(controller) beginning origin: \(self.topViewBeginOrigin)")
}
}
//If textFieldView is inside ignored responder then do nothing. (Bug ID: #37, #74, #76)
//See notes:- https://developer.apple.com/library/ios/documentation/StringsTextFonts/Conceptual/TextAndWebiPhoneOS/KeyboardManagement/KeyboardManagement.html If it is UIAlertView textField then do not affect anything (Bug ID: #70).
if keyboardShowing,
let textFieldView = textFieldView,
textFieldView.isAlertViewTextField() == false {
// keyboard is already showing. adjust position.
optimizedAdjustPosition()
}
}
let elapsedTime = CACurrentMediaTime() - startTime
showLog("****** \(#function) ended: \(elapsedTime) seconds ******", indentation: -1)
}
/** UITextFieldTextDidEndEditingNotification, UITextViewTextDidEndEditingNotification. Removing fetched object. */
@objc func textFieldViewDidEndEditing(_ notification: Notification) {
let startTime = CACurrentMediaTime()
showLog("****** \(#function) started ******", indentation: 1)
//Removing gesture recognizer (Enhancement ID: #14)
textFieldView?.window?.removeGestureRecognizer(resignFirstResponderGesture)
// We check if there's a change in original frame or not.
if let textView = textFieldView as? UIScrollView, textView.responds(to: #selector(getter: UITextView.isEditable)) {
if isTextViewContentInsetChanged {
self.isTextViewContentInsetChanged = false
if textView.contentInset != self.startingTextViewContentInsets {
self.showLog("Restoring textView.contentInset to: \(self.startingTextViewContentInsets)")
UIView.animate(withDuration: animationDuration, delay: 0, options: animationCurve, animations: { () -> Void in
//Setting textField to it's initial contentInset
textView.contentInset = self.startingTextViewContentInsets
textView.scrollIndicatorInsets = self.startingTextViewScrollIndicatorInsets
}, completion: { (_) -> Void in })
}
}
}
//Setting object to nil
textFieldView = nil
let elapsedTime = CACurrentMediaTime() - startTime
showLog("****** \(#function) ended: \(elapsedTime) seconds ******", indentation: -1)
}
}
|
mit
|
029c74ecbaf032c3add0de20061e4cc5
| 47.024155 | 243 | 0.680817 | 6.236512 | false | false | false | false |
proversity-org/edx-app-ios
|
Source/WebView/DiscoveryHelper.swift
|
1
|
7661
|
//
// DiscoveryHelper.swift
// edX
//
// Created by Salman on 17/07/2018.
// Copyright © 2018 edX. All rights reserved.
//
import UIKit
enum URIString: String {
case appURLScheme = "edxapp"
case pathPlaceHolder = "{path_id}"
case coursePathPrefix = "course/"
}
fileprivate enum URLParameterKeys: String, RawStringExtractable {
case pathId = "path_id";
case courseId = "course_id"
case emailOptIn = "email_opt_in"
}
// Define Your Hosts Here
enum WebviewActions: String {
case courseEnrollment = "enroll"
case courseDetail = "course_info"
case enrolledCourseDetail = "enrolled_course_info"
case enrolledProgramDetail = "enrolled_program_info"
case programDetail = "program_info"
}
class DiscoveryHelper: NSObject {
class func urlAction(from url: URL) -> WebviewActions? {
guard url.isValidAppURLScheme, let url = WebviewActions(rawValue: url.appURLHost) else {
return nil
}
return url
}
@objc class func detailPathID(from url: URL) -> String? {
guard url.isValidAppURLScheme, url.appURLHost == WebviewActions.courseDetail.rawValue, let path = url.queryParameters?[URLParameterKeys.pathId] as? String else {
return nil
}
// the site sends us things of the form "course/<path_id>" we only want the path id
return path.replacingOccurrences(of: URIString.coursePathPrefix.rawValue, with: "")
}
class func parse(url: URL) -> (courseId: String?, emailOptIn: Bool)? {
guard url.isValidAppURLScheme else {
return nil
}
let courseId = url.queryParameters?[URLParameterKeys.courseId] as? String
let emailOptIn = (url.queryParameters?[URLParameterKeys.emailOptIn] as? String).flatMap {Bool($0)}
return (courseId , emailOptIn ?? false)
}
private class func showCourseEnrollmentFailureAlert(controller: UIViewController) {
UIAlertController().showAlert(withTitle: Strings.findCoursesEnrollmentErrorTitle, message: Strings.findCoursesUnableToEnrollErrorDescription(platformName: OEXConfig.shared().platformName()), cancelButtonTitle: Strings.ok, onViewController: controller)
}
class func programDetailURL(from url: URL, config: OEXConfig) -> URL? {
guard url.isValidAppURLScheme, let path = url.queryParameters?[URLParameterKeys.pathId] as? String, let myProgramDetailURL = config.programConfig.programDetailURLTemplate else {
return nil
}
let programDetailUrlString = myProgramDetailURL.replacingOccurrences(of: URIString.pathPlaceHolder.rawValue, with: path)
return URL(string: programDetailUrlString)
}
private class func showMainScreen(with message: String, and courseId: String, from controller: UIViewController) {
OEXRouter.shared().showMyCourses(animated: true, pushingCourseWithID: courseId)
let delay = DispatchTime.now() + Double(Int64(0.5 * TimeInterval(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)
DispatchQueue.main.asyncAfter(deadline: delay) {
postEnrollmentSuccessNotification(message: message, from: controller)
}
}
private class func postEnrollmentSuccessNotification(message: String, from controller: UIViewController) {
NotificationCenter.default.post(name: NSNotification.Name(rawValue: EnrollmentShared.successNotification), object: message)
if controller.isModal() || controller.isRootModal() {
controller.view.window?.rootViewController?.dismiss(animated: true, completion: nil)
}
}
@objc class func enrollInCourse(courseID: String, emailOpt: Bool, from controller: UIViewController) {
let environment = OEXRouter.shared().environment;
environment.analytics.trackCourseEnrollment(courseId: courseID, name: AnalyticsEventName.CourseEnrollmentClicked.rawValue, displayName: AnalyticsDisplayName.EnrolledCourseClicked.rawValue)
guard let _ = OEXSession.shared()?.currentUser else {
OEXRouter.shared().showSignUpScreen(from: controller, completion: {
self.enrollInCourse(courseID: courseID, emailOpt: emailOpt, from: controller)
})
return
}
if let _ = environment.dataManager.enrollmentManager.enrolledCourseWithID(courseID: courseID) {
showMainScreen(with: Strings.findCoursesAlreadyEnrolledMessage, and: courseID, from: controller)
return
}
let request = CourseCatalogAPI.enroll(courseID: courseID)
environment.networkManager.taskForRequest(request) { response in
if response.response?.httpStatusCode.is2xx ?? false {
environment.analytics.trackCourseEnrollment(courseId: courseID, name: AnalyticsEventName.CourseEnrollmentSuccess.rawValue, displayName: AnalyticsDisplayName.EnrolledCourseSuccess.rawValue)
showMainScreen(with: Strings.findCoursesEnrollmentSuccessfulMessage, and: courseID, from: controller)
}
else if response.response?.httpStatusCode.is4xx ?? false {
showCourseEnrollmentFailureAlert(controller: controller)
}
else {
controller.showOverlay(withMessage: Strings.findCoursesEnrollmentErrorDescription)
}
}
}
class func programDetailPathId(from url: URL) -> String? {
guard url.isValidAppURLScheme,
url.appURLHost == WebviewActions.programDetail.rawValue,
let path = url.queryParameters?[URLParameterKeys.pathId] as? String else {
return nil
}
return path
}
}
extension DiscoveryHelper {
private class func enrollInCourse(with url: URL, from controller: UIViewController) {
if let urlData = parse(url: url), let courseId = urlData.courseId {
enrollInCourse(courseID: courseId, emailOpt: urlData.emailOptIn, from: controller)
}
}
class func navigate(to url: URL, from controller: UIViewController, bottomBar: UIView?) -> Bool {
guard let urlAction = urlAction(from: url) else { return false }
let environment = OEXRouter.shared().environment;
switch urlAction {
case .courseEnrollment:
enrollInCourse(with: url, from: controller)
break
case .courseDetail:
guard let courseDetailPath = detailPathID(from: url) else { return false }
environment.router?.showCourseDetails(from: controller, with: courseDetailPath, bottomBar: bottomBar)
break
case .enrolledCourseDetail:
guard let urlData = parse(url: url), let courseId = urlData.courseId else { return false }
environment.router?.showCourseWithID(courseID: courseId, fromController: controller, animated: true)
break
case .enrolledProgramDetail:
guard let programDetailsURL = programDetailURL(from: url, config: environment.config) else { return false }
environment.router?.showProgramDetails(with: programDetailsURL, from: controller)
break
case .programDetail:
guard let pathId = programDetailPathId(from: url) else { return false }
// Setting this view type for Deep Linking
let type = (controller is DegreesViewController) ? ProgramDiscoveryScreen.degree: ProgramDiscoveryScreen.program
environment.router?.showProgramDetail(from: controller, with: pathId, bottomBar: bottomBar, type: type)
break
}
return true
}
}
|
apache-2.0
|
c6b442ba7ad827aee6f570c6dc86da4b
| 44.868263 | 259 | 0.68094 | 4.808537 | false | false | false | false |
lenssss/whereAmI
|
Whereami/Controller/Personal/PublishTourViewController.swift
|
1
|
9585
|
//
// PublishTourViewController.swift
// Whereami
//
// Created by A on 16/4/28.
// Copyright © 2016年 WuQifei. All rights reserved.
//
import UIKit
import SVProgressHUD
import DKImagePickerController
class PublishTourViewController: UIViewController,UITableViewDataSource,UITableViewDelegate {
var tableView:UITableView? = nil
var photoArray:[AnyObject]? = nil
var photoRows:CGFloat? = nil
var textView:UITextView? = nil
var photoList:[AnyObject]? = nil
var assets:[DKAsset]? = nil
var isSuccess:Bool? = false
override func viewDidLoad() {
super.viewDidLoad()
self.setConfig()
self.photoRows = ceil(CGFloat(self.photoArray!.count)/3.0)
self.getPhoto()
self.setUI()
self.registerNotification()
// Do any additional setup after loading the view.
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
SVProgressHUD.dismiss()
}
func getPhoto(){
var array = [UIImage]()
for item in self.photoArray!{
if item.isKindOfClass(UIImage){
array.append(item as! UIImage)
}
}
self.photoArray = array
}
func setUI(){
let backBtn = TheBackBarButton.initWithAction({
let viewControllers = self.navigationController?.viewControllers
let index = (viewControllers?.count)! - 2
let viewController = viewControllers![index]
self.navigationController?.popToViewController(viewController, animated: true)
})
self.navigationItem.leftBarButtonItem = UIBarButtonItem(customView: backBtn)
self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Publish", style: .Done, target: self, action: #selector(self.publishTour))
self.tableView = UITableView()
self.tableView?.dataSource = self
self.tableView?.delegate = self
self.tableView?.separatorStyle = .None
self.view.addSubview(self.tableView!)
self.tableView?.autoPinEdgesToSuperviewEdgesWithInsets(UIEdgeInsetsMake(0, 0, 0, 0))
self.tableView?.registerClass(PublishTourTextViewTableViewCell.self, forCellReuseIdentifier: "PublishTourTextViewTableViewCell")
self.tableView?.registerClass(PublishTourPhotoCollectionTableViewCell.self, forCellReuseIdentifier: "PublishTourPhotoCollectionTableViewCell")
self.tableView?.registerClass(PublishTravelCommonTableViewCell.self, forCellReuseIdentifier: "PublishTravelCommonTableViewCell")
}
func publishTour(){
let currentUser = UserModel.getCurrentUser()
self.photoList = [AnyObject]()
for i in 0...(self.photoArray?.count)!-1 {
let image = self.photoArray![i] as! UIImage
let photoString = UIImageJPEGRepresentation(image, 1.0)
self.photoList!.append(photoString!)
}
var dic = [String:AnyObject]()
dic["userId"] = currentUser?.id
dic["type"] = "jpg"
dic["contents"] = self.photoList
SVProgressHUD.show()
SVProgressHUD.setDefaultMaskType(.Gradient)
SocketManager.sharedInstance.sendMsg("saveMutileImageFile", data: dic, onProto: "saveMutileImageFileed", callBack: { (code, objs) -> Void in
if code == statusCode.Normal.rawValue {
let files = objs[0]["files"] as! [String]
var dic = [String:AnyObject]()
dic["creatorId"] = UserModel.getCurrentUser()?.id
dic["content"] = self.textView?.text
dic["picList"] = files
dic["ginwave"] = LocationManager.sharedInstance.currentLocation
dic["ginwaveDes"] = LocationManager.sharedInstance.geoDes
SocketManager.sharedInstance.sendMsg("createAFeed", data: dic, onProto: "createAFeeded", callBack: { (code, objs) -> Void in
if code == statusCode.Normal.rawValue {
print(objs)
self.runInMainQueue({
SVProgressHUD.showSuccessWithStatus("success")
self.isSuccess = true
self.performSelector(#selector(self.dismiss), withObject: self, afterDelay: 2)
})
}
else{
self.runInMainQueue({
SVProgressHUD.showErrorWithStatus("error")
self.performSelector(#selector(self.dismiss), withObject: self, afterDelay: 2)
})
}
})
}
})
}
func registerNotification(){
NSNotificationCenter.defaultCenter().rac_addObserverForName("didTouchAddButton", object: nil).subscribeNext { (notification) in
let pickerController = DKImagePickerController()
pickerController.navigationBar.setBackgroundImage(UIImage.imageWithColor(UIColor.getNavigationBarColor()), forBarMetrics: UIBarMetrics.Default)
UINavigationBar.appearance().titleTextAttributes = [
NSForegroundColorAttributeName : UIColor.whiteColor()
]
pickerController.maxSelectableCount = 9
pickerController.showsCancelButton = true
pickerController.assetType = .AllPhotos
pickerController.defaultSelectedAssets = self.assets
pickerController.didSelectAssets = { [unowned self] (assets: [DKAsset]) in
print("didSelectAssets")
if assets.count != 0 {
self.assets = assets
}
else{
self.assets = nil
}
}
pickerController.didCancel = { () in
if self.assets != nil {
self.photoArray?.removeAll()
for asset in self.assets! {
asset.fetchFullScreenImageWithCompleteBlock({ (image, info) in
self.photoArray?.append(image!)
if self.photoArray?.count == self.assets?.count {
self.photoRows = ceil(CGFloat(self.photoArray!.count)/3.0)
self.tableView?.reloadData()
}
})
}
}
}
self.presentViewController(pickerController, animated: true, completion: nil)
}
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 2
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0 {
return 2
}
return 1
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if indexPath.section == 0 {
if indexPath.row == 0 {
let cell = tableView.dequeueReusableCellWithIdentifier("PublishTourTextViewTableViewCell", forIndexPath: indexPath) as? PublishTourTextViewTableViewCell
self.textView = cell!.textView
cell!.textView!.becomeFirstResponder()
return cell!
}
else {
let cell = tableView.dequeueReusableCellWithIdentifier("PublishTourPhotoCollectionTableViewCell", forIndexPath: indexPath) as? PublishTourPhotoCollectionTableViewCell
cell!.photoArray = self.photoArray
cell!.updateCollections()
return cell!
}
}
else{
let cell = tableView.dequeueReusableCellWithIdentifier("PublishTravelCommonTableViewCell", forIndexPath: indexPath)
return cell
}
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
if indexPath.section==0 {
if indexPath.row==0 {
return 80
}else {
let screenW = UIScreen.mainScreen().bounds.width
let photoWidth = (screenW-16*2-8*3)/4
let totalHeight = (photoWidth+8)*photoRows!+8
return totalHeight;
}
}
else {
return 44
}
}
func dismiss(){
SVProgressHUD.dismiss()
if isSuccess == true {
NSNotificationCenter.defaultCenter().postNotificationName("publishTour", object: nil)
let index = self.navigationController?.viewControllers.count
let viewController = self.navigationController?.viewControllers[index!-2] as! TourRecordsViewController
self.navigationController?.popToViewController(viewController, animated: true)
}
}
func scrollViewDidScroll(scrollView: UIScrollView) {
self.textView?.resignFirstResponder()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
mit
|
b213f2b565401aa77188edc5513e1f35
| 39.601695 | 182 | 0.596848 | 5.846248 | false | false | false | false |
dcordero/BlurFace
|
BlurFaceSample/BlurFaceSample/ViewController.swift
|
1
|
1560
|
import UIKit
import BlurFace
class ViewController: UIViewController, UINavigationControllerDelegate, UIImagePickerControllerDelegate {
@IBOutlet weak var blurButton: UIButton!
@IBOutlet weak var imageView: UIImageView!
private var blurFace: BlurFace?
// MARK: UIViewController
override func viewDidLoad() {
super.viewDidLoad()
setupImage(UIImage(named: "TheHoff"))
}
// MARK: Actions
@IBAction func loadImageButtonTapped(sender: UIButton) {
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
presentViewController(imagePicker, animated: true, completion: nil)
}
@IBAction func blurButtonTapped(sender: UIButton) {
imageView.image = blurFace!.blurFaces()
}
// MARK: Private
func setupImage(image: UIImage!) {
imageView.image = image
blurButton.enabled = blurImageWithImage(image).hasFaces()
}
func blurImageWithImage(image: UIImage) -> BlurFace {
if let blurFace = blurFace {
blurFace.setImage(image)
}
else {
blurFace = BlurFace(image: image)
}
return blurFace!
}
// MARK: UIImagePickerControllerDelegate
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) {
dismissViewControllerAnimated(true, completion: nil)
setupImage(info[UIImagePickerControllerOriginalImage] as! UIImage)
}
}
|
mit
|
aab59b8f22a3542304f24e999a8cad0c
| 26.857143 | 125 | 0.658333 | 5.454545 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.