repo_name
stringlengths
7
91
path
stringlengths
8
658
copies
stringclasses
125 values
size
stringlengths
3
6
content
stringlengths
118
674k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6.09
99.2
line_max
int64
17
995
alpha_frac
float64
0.3
0.9
ratio
float64
2
9.18
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
wikimedia/wikipedia-ios
Wikipedia/Code/ArticleViewController+SurveyAnnouncements.swift
1
3294
import Foundation extension ArticleViewController { func showSurveyAnnouncementPanel(surveyAnnouncementResult: SurveyAnnouncementsController.SurveyAnnouncementResult, linkState: ArticleAsLivingDocSurveyLinkState) { let currentDate = Date() guard state == .loaded, let surveyEndTime = surveyAnnouncementResult.announcement.endTime, currentDate.isBefore(surveyEndTime), let googleFormattedArticleTitle = articleURL.wmf_title?.googleFormPercentEncodedPageTitle else { return } let didSeeModal: Bool let isInExperiment: Bool switch linkState { case .notInExperiment: didSeeModal = false isInExperiment = false case .inExperimentFailureLoadingEvents, .inExperimentLoadingEvents: assertionFailure("We should not be attempting to show a survey for a user that is still loading or has failed to load events.") return case .inExperimentLoadedEventsDidNotSeeModal: didSeeModal = false isInExperiment = true case .inExperimentLoadedEventsDidSeeModal: didSeeModal = true isInExperiment = true } let newActionURLString = surveyAnnouncementResult.actionURLString .replacingOccurrences(of: "{{articleTitle}}", with: googleFormattedArticleTitle) .replacingOccurrences(of: "{{didSeeModal}}", with: "\(didSeeModal)") .replacingOccurrences(of: "{{isInExperiment}}", with: "\(isInExperiment)") guard let actionURL = URL(string: newActionURLString) else { assertionFailure("Cannot show survey - failure generating actionURL.") return } var vcToPresentSurvey: UIViewController? = self if let presentedNavVC = presentedViewController as? UINavigationController, let livingDocVC = presentedNavVC.viewControllers.first as? ArticleAsLivingDocViewController { vcToPresentSurvey = presentedNavVC.viewControllers.count == 1 ? livingDocVC : nil } vcToPresentSurvey?.wmf_showAnnouncementPanel(announcement: surveyAnnouncementResult.announcement, style: .minimal, primaryButtonTapHandler: { (sender) in self.navigate(to: actionURL, useSafari: true) // dismiss handler is called }, secondaryButtonTapHandler: { (sender) in // dismiss handler is called }, footerLinkAction: { (url) in self.navigate(to: url, useSafari: true) // intentionally don't dismiss }, traceableDismissHandler: { lastAction in switch lastAction { case .tappedBackground, .tappedClose, .tappedSecondary: SurveyAnnouncementsController.shared.markSurveyAnnouncementAnswer(false, campaignIdentifier: surveyAnnouncementResult.campaignIdentifier) case .tappedPrimary: SurveyAnnouncementsController.shared.markSurveyAnnouncementAnswer(true, campaignIdentifier: surveyAnnouncementResult.campaignIdentifier) case .none: assertionFailure("Unexpected lastAction in Panel dismissHandler") break } }, theme: self.theme) } }
mit
0e895624d3918d3ae2f7494056d36260
47.441176
166
0.668488
5.71875
false
false
false
false
bradhilton/Table
Table/StackView/ChildDiff.swift
1
4344
// // ChildDiff.swift // Table // // Created by Bradley Hilton on 10/4/18. // Copyright © 2018 Brad Hilton. All rights reserved. // enum ChildState { case visible case hiding case hidden } protocol ChildAndStateProtocol { associatedtype Child : Hashable var child: Child { get } var state: ChildState { get set } init(child: Child, state: ChildState) } struct ChildAndState<Child : Hashable> : ChildAndStateProtocol { let child: Child var state: ChildState } extension UIView { var childState: ChildState { return isVisible ? isHidden || alpha == 0 ? .hiding : .visible : .hidden } } /* First remove listed children Then insert new children Finally move existing children */ struct ChildDiff<Child : Hashable> { let removeChildren: [Child] let insertNewChildren: [(child: Child, at: Int)] let moveVisibleChildren: [(child: Child, at: Int)] func map<T : Hashable>(_ transform: (Child) -> T) -> ChildDiff<T> { return ChildDiff<T>( removeChildren: removeChildren.map(transform), insertNewChildren: insertNewChildren.map { (child: transform($0.child), at: $0.at) }, moveVisibleChildren: moveVisibleChildren.map { (child: transform($0.child), at: $0.at) } ) } } extension ChildDiff { init(newChildren: [Child], oldChildren: [ChildAndState<Child>]) { var oldChildren = oldChildren let newChildrenSet = Set(newChildren) let newRanks = Dictionary(uniqueKeysWithValues: zip(newChildren, newChildren.indices)) removeChildren = oldChildren.removeToBeInsertedElements(newChildrenSet) insertNewChildren = oldChildren.insert(newChildren) moveVisibleChildren = oldChildren.sort(with: newRanks) } } extension Array where Element : ChildAndStateProtocol { fileprivate mutating func removeToBeInsertedElements(_ newChildren: Set<Element.Child>) -> [Element.Child] { return enumerated().reversed().compactMap { (index, element) in if newChildren.contains(element.child) && element.state == .hidden { remove(at: index) return element.child } else { return nil } } } /// Inserts new children and returns a list of insertions fileprivate mutating func insert(_ newChildren: [Element.Child]) -> [(child: Element.Child, at: Int)] { let indices = Dictionary(uniqueKeysWithValues: enumerated().lazy.map { ($1.child, $0) }) var insertions: [(child: Element.Child, at: Int)] = [] var insertionIndex = 0 for child in newChildren { if let index = indices[child] { insertionIndex = index + insertions.count + 1 } else { insert(Element(child: child, state: .visible), at: insertionIndex) insertions.append((child: child, at: insertionIndex)) insertionIndex += 1 } } return insertions } /// Sorts an array of children and returns a list of insertions fileprivate mutating func sort( with newRanks: [Element.Child: Int] ) -> [(child: Element.Child, at: Int)] { var insertions: [(child: Element.Child, at: Int)] = [] for (index, element) in enumerated() { guard let rank = newRanks[element.child] else { continue } var insertionIndex = index - 1 var insertion: (child: Element.Child, at: Int)? var previousRank: Int? while insertionIndex >= 0 { previousRank = newRanks[self[insertionIndex].child] if let previousRank = previousRank { if rank < previousRank { insertion = (element.child, insertionIndex) } else { break } } insertionIndex -= 1 } if let insertion = insertion { remove(at: index) insert(Element(child: insertion.child, state: .visible), at: insertion.at) insertions.append(insertion) } } return insertions } }
mit
bfcdc67cf2737696ec83aac7fd3f62ff
31.410448
112
0.582086
4.576396
false
false
false
false
stevewight/DetectorKit
DetectorKit/Models/Framers/BaseFramer.swift
1
2580
// // BaseFramer.swift // Sherlock // // Created by Steve on 12/6/16. // Copyright © 2016 Steve Wight. All rights reserved. // import UIKit public class BaseFramer: NSObject { public var shapeColor:UIColor = UIColor.red public var borderWidth:Double = 3.0 var imageView:UIImageView! var coreImage:CIImage! var detector:BaseDetector! var converter:CoordConverter! public init(_ inputImageView:UIImageView) { super.init() imageView = inputImageView coreImage = CIImage(image: imageView.image!) converter = CoordConverter( coreImage.extent.size, imageView.bounds.size ) } public func box() { buildBoxes(features: detector.features()) } internal func buildBoxRotate(features:[CIFeature]) { for feature in features { addBoxRotate(feature: feature) } } internal func buildPulses(features:[CIFeature]) { for feature in features { addPulse(feature: feature) } } internal func buildBoxes(features:[CIFeature]) { for feature in features { addFrame(feature: feature) } } internal func buildRadials(features:[CIFeature]) { for feature in features { addRadial(feature: feature) } } private func addPulse(feature:CIFeature) { let newFrame = converter.convert(feature.bounds) let pulseView = PulseView( frame: newFrame, color: shapeColor.cgColor, width: borderWidth ) imageView.addSubview(pulseView) } private func addBoxRotate(feature:CIFeature) { let newFrame = converter.convert(feature.bounds) let boxRotateView = BoxRotateView( frame: newFrame, color: shapeColor.cgColor, width: borderWidth ) imageView.addSubview(boxRotateView) } private func addFrame(feature:CIFeature) { let newFrame = converter.convert(feature.bounds) let boxView = BoxView( frame: newFrame, color: shapeColor.cgColor, width: borderWidth ) imageView.addSubview(boxView) } private func addRadial(feature:CIFeature) { let newFrame = converter.convert(feature.bounds) let radialView = RadialView( frame: newFrame, color: shapeColor.cgColor, width: borderWidth ) imageView.addSubview(radialView) } }
mit
5efa35ef8027e3654673394147812116
25.316327
56
0.596743
4.680581
false
false
false
false
mozilla-mobile/firefox-ios
Tests/StorageTests/TestSQLiteHistory.swift
2
69268
// 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 @testable import Storage @testable import Client import XCTest class BaseHistoricalBrowserSchema: Schema { var name: String { return "BROWSER" } var version: Int { return -1 } func update(_ db: SQLiteDBConnection, from: Int) -> Bool { fatalError("Should never be called.") } func create(_ db: SQLiteDBConnection) -> Bool { return false } func drop(_ db: SQLiteDBConnection) -> Bool { return false } var supportsPartialIndices: Bool { let v = sqlite3_libversion_number() return v >= 3008000 // 3.8.0. } let oldFaviconsSQL = """ CREATE TABLE IF NOT EXISTS favicons ( id INTEGER PRIMARY KEY AUTOINCREMENT, url TEXT NOT NULL UNIQUE, width INTEGER, height INTEGER, type INTEGER NOT NULL, date REAL NOT NULL ) """ func run(_ db: SQLiteDBConnection, sql: String?, args: Args? = nil) -> Bool { if let sql = sql { do { try db.executeChange(sql, withArgs: args) } catch { return false } } return true } func run(_ db: SQLiteDBConnection, queries: [String?]) -> Bool { for sql in queries { if let sql = sql { if !run(db, sql: sql) { return false } } } return true } func run(_ db: SQLiteDBConnection, queries: [String]) -> Bool { for sql in queries { if !run(db, sql: sql) { return false } } return true } } // Versions of BrowserSchema that we care about: // v6, prior to 001c73ea1903c238be1340950770879b40c41732, July 2015. // This is when we first started caring about database versions. // // v7, 81e22fa6f7446e27526a5a9e8f4623df159936c3. History tiles. // // v8, 02c08ddc6d805d853bbe053884725dc971ef37d7. Favicons. // // v10, 4428c7d181ff4779ab1efb39e857e41bdbf4de67. Mirroring. We skipped v9. // // These tests snapshot the table creation code at each of these points. class BrowserSchemaV6: BaseHistoricalBrowserSchema { override var version: Int { return 6 } func prepopulateRootFolders(_ db: SQLiteDBConnection) -> Bool { let type = 2 // "folder" let root = 0 let titleMobile = String.BookmarksFolderTitleMobile let titleMenu = String.BookmarksFolderTitleMenu let titleToolbar = String.BookmarksFolderTitleToolbar let titleUnsorted = String.BookmarksFolderTitleUnsorted let args: Args = [ root, BookmarkRoots.RootGUID, type, "Root", root, 1, BookmarkRoots.MobileFolderGUID, type, titleMobile, root, 2, BookmarkRoots.MenuFolderGUID, type, titleMenu, root, 3, BookmarkRoots.ToolbarFolderGUID, type, titleToolbar, root, 4, BookmarkRoots.UnfiledFolderGUID, type, titleUnsorted, root, ] let sql = """ INSERT INTO bookmarks (id, guid, type, url, title, parent) VALUES -- Root (?, ?, ?, NULL, ?, ?), -- Mobile (?, ?, ?, NULL, ?, ?), -- Menu (?, ?, ?, NULL, ?, ?), -- Toolbar (?, ?, ?, NULL, ?, ?), -- Unsorted (?, ?, ?, NULL, ?, ?) """ return self.run(db, sql: sql, args: args) } func CreateHistoryTable() -> String { let sql = """ CREATE TABLE IF NOT EXISTS history ( id INTEGER PRIMARY KEY AUTOINCREMENT, -- Not null, but the value might be replaced by the server's. guid TEXT NOT NULL UNIQUE, -- May only be null for deleted records. url TEXT UNIQUE, title TEXT NOT NULL, -- Can be null. Integer milliseconds. server_modified INTEGER, -- Can be null. Client clock. In extremis only. local_modified INTEGER, -- Boolean. Locally deleted. is_deleted TINYINT NOT NULL, -- Boolean. Set when changed or visits added. should_upload TINYINT NOT NULL, domain_id INTEGER REFERENCES domains(id) ON DELETE CASCADE, CONSTRAINT urlOrDeleted CHECK (url IS NOT NULL OR is_deleted = 1) ) """ return sql } func CreateDomainsTable() -> String { let sql = """ CREATE TABLE IF NOT EXISTS domains ( id INTEGER PRIMARY KEY AUTOINCREMENT, domain TEXT NOT NULL UNIQUE, showOnTopSites TINYINT NOT NULL DEFAULT 1 ) """ return sql } func CreateQueueTable() -> String { let sql = """ CREATE TABLE IF NOT EXISTS queue ( url TEXT NOT NULL UNIQUE, title TEXT ) """ return sql } override func create(_ db: SQLiteDBConnection) -> Bool { let visits = """ CREATE TABLE IF NOT EXISTS visits ( id INTEGER PRIMARY KEY AUTOINCREMENT, siteID INTEGER NOT NULL REFERENCES history(id) ON DELETE CASCADE, -- Microseconds since epoch. date REAL NOT NULL, type INTEGER NOT NULL, -- Some visits are local. Some are remote ('mirrored'). This boolean flag is the split. is_local TINYINT NOT NULL, UNIQUE (siteID, date, type) ) """ let indexShouldUpload: String if self.supportsPartialIndices { // There's no point tracking rows that are not flagged for upload. indexShouldUpload = "CREATE INDEX IF NOT EXISTS idx_history_should_upload ON history (should_upload) WHERE should_upload = 1" } else { indexShouldUpload = "CREATE INDEX IF NOT EXISTS idx_history_should_upload ON history (should_upload)" } let indexSiteIDDate = "CREATE INDEX IF NOT EXISTS idx_visits_siteID_is_local_date ON visits (siteID, is_local, date)" let faviconSites = """ CREATE TABLE IF NOT EXISTS favicon_sites ( id INTEGER PRIMARY KEY AUTOINCREMENT, siteID INTEGER NOT NULL REFERENCES history(id) ON DELETE CASCADE, faviconID INTEGER NOT NULL REFERENCES favicons(id) ON DELETE CASCADE, UNIQUE (siteID, faviconID) ) """ let widestFavicons = """ CREATE VIEW IF NOT EXISTS view_favicons_widest AS SELECT favicon_sites.siteID AS siteID, favicons.id AS iconID, favicons.url AS iconURL, favicons.date AS iconDate, favicons.type AS iconType, max(favicons.width) AS iconWidth FROM favicon_sites, favicons WHERE favicon_sites.faviconID = favicons.id GROUP BY siteID """ let historyIDsWithIcon = """ CREATE VIEW IF NOT EXISTS view_history_id_favicon AS SELECT history.id AS id, iconID, iconURL, iconDate, iconType, iconWidth FROM history LEFT OUTER JOIN view_favicons_widest ON history.id = view_favicons_widest.siteID """ let iconForURL = """ CREATE VIEW IF NOT EXISTS view_icon_for_url AS SELECT history.url AS url, icons.iconID AS iconID FROM history, view_favicons_widest AS icons WHERE history.id = icons.siteID """ let bookmarks = """ CREATE TABLE IF NOT EXISTS bookmarks ( id INTEGER PRIMARY KEY AUTOINCREMENT, guid TEXT NOT NULL UNIQUE, type TINYINT NOT NULL, url TEXT, parent INTEGER REFERENCES bookmarks(id) NOT NULL, faviconID INTEGER REFERENCES favicons(id) ON DELETE SET NULL, title TEXT ) """ let queries = [ // This used to be done by FaviconsTable. self.oldFaviconsSQL, CreateDomainsTable(), CreateHistoryTable(), visits, bookmarks, faviconSites, indexShouldUpload, indexSiteIDDate, widestFavicons, historyIDsWithIcon, iconForURL, CreateQueueTable(), ] return self.run(db, queries: queries) && self.prepopulateRootFolders(db) } } class BrowserSchemaV7: BaseHistoricalBrowserSchema { override var version: Int { return 7 } func prepopulateRootFolders(_ db: SQLiteDBConnection) -> Bool { let type = 2 // "folder" let root = 0 let titleMobile = String.BookmarksFolderTitleMobile let titleMenu = String.BookmarksFolderTitleMenu let titleToolbar = String.BookmarksFolderTitleToolbar let titleUnsorted = String.BookmarksFolderTitleUnsorted let args: Args = [ root, BookmarkRoots.RootGUID, type, "Root", root, 1, BookmarkRoots.MobileFolderGUID, type, titleMobile, root, 2, BookmarkRoots.MenuFolderGUID, type, titleMenu, root, 3, BookmarkRoots.ToolbarFolderGUID, type, titleToolbar, root, 4, BookmarkRoots.UnfiledFolderGUID, type, titleUnsorted, root, ] let sql = """ INSERT INTO bookmarks (id, guid, type, url, title, parent) VALUES -- Root (?, ?, ?, NULL, ?, ?), -- Mobile (?, ?, ?, NULL, ?, ?), -- Menu (?, ?, ?, NULL, ?, ?), -- Toolbar (?, ?, ?, NULL, ?, ?), -- Unsorted (?, ?, ?, NULL, ?, ?) """ return self.run(db, sql: sql, args: args) } func getHistoryTableCreationString() -> String { let sql = """ CREATE TABLE IF NOT EXISTS history ( id INTEGER PRIMARY KEY AUTOINCREMENT, -- Not null, but the value might be replaced by the server's. guid TEXT NOT NULL UNIQUE, -- May only be null for deleted records. url TEXT UNIQUE, title TEXT NOT NULL, -- Can be null. Integer milliseconds. server_modified INTEGER, -- Can be null. Client clock. In extremis only. local_modified INTEGER, -- Boolean. Locally deleted. is_deleted TINYINT NOT NULL, -- Boolean. Set when changed or visits added. should_upload TINYINT NOT NULL, domain_id INTEGER REFERENCES domains(id) ON DELETE CASCADE, CONSTRAINT urlOrDeleted CHECK (url IS NOT NULL OR is_deleted = 1) ) """ return sql } func getDomainsTableCreationString() -> String { let sql = """ CREATE TABLE IF NOT EXISTS domains ( id INTEGER PRIMARY KEY AUTOINCREMENT, domain TEXT NOT NULL UNIQUE, showOnTopSites TINYINT NOT NULL DEFAULT 1 ) """ return sql } func getQueueTableCreationString() -> String { let sql = """ CREATE TABLE IF NOT EXISTS queue ( url TEXT NOT NULL UNIQUE, title TEXT ) """ return sql } override func create(_ db: SQLiteDBConnection) -> Bool { // Right now we don't need to track per-visit deletions: Sync can't // represent them! See Bug 1157553 Comment 6. // We flip the should_upload flag on the history item when we add a visit. // If we ever want to support logic like not bothering to sync if we added // and then rapidly removed a visit, then we need an 'is_new' flag on each visit. let visits = """ CREATE TABLE IF NOT EXISTS visits ( id INTEGER PRIMARY KEY AUTOINCREMENT, siteID INTEGER NOT NULL REFERENCES history(id) ON DELETE CASCADE, -- Microseconds since epoch. date REAL NOT NULL, type INTEGER NOT NULL, -- Some visits are local. Some are remote ('mirrored'). This boolean flag is the split. is_local TINYINT NOT NULL, UNIQUE (siteID, date, type) ) """ let indexShouldUpload: String if self.supportsPartialIndices { // There's no point tracking rows that are not flagged for upload. indexShouldUpload = "CREATE INDEX IF NOT EXISTS idx_history_should_upload ON history (should_upload) WHERE should_upload = 1" } else { indexShouldUpload = "CREATE INDEX IF NOT EXISTS idx_history_should_upload ON history (should_upload)" } let indexSiteIDDate = "CREATE INDEX IF NOT EXISTS idx_visits_siteID_is_local_date ON visits (siteID, is_local, date)" let faviconSites = """ CREATE TABLE IF NOT EXISTS favicon_sites ( id INTEGER PRIMARY KEY AUTOINCREMENT, siteID INTEGER NOT NULL REFERENCES history(id) ON DELETE CASCADE, faviconID INTEGER NOT NULL REFERENCES favicons(id) ON DELETE CASCADE, UNIQUE (siteID, faviconID) ) """ let widestFavicons = """ CREATE VIEW IF NOT EXISTS view_favicons_widest AS SELECT favicon_sites.siteID AS siteID, favicons.id AS iconID, favicons.url AS iconURL, favicons.date AS iconDate, favicons.type AS iconType, max(favicons.width) AS iconWidth FROM favicon_sites, favicons WHERE favicon_sites.faviconID = favicons.id GROUP BY siteID """ let historyIDsWithIcon = """ CREATE VIEW IF NOT EXISTS view_history_id_favicon AS SELECT history.id AS id, iconID, iconURL, iconDate, iconType, iconWidth FROM history LEFT OUTER JOIN view_favicons_widest ON history.id = view_favicons_widest.siteID """ let iconForURL = """ CREATE VIEW IF NOT EXISTS view_icon_for_url AS SELECT history.url AS url, icons.iconID AS iconID FROM history, view_favicons_widest AS icons WHERE history.id = icons.siteID """ let bookmarks = """ CREATE TABLE IF NOT EXISTS bookmarks ( id INTEGER PRIMARY KEY AUTOINCREMENT, guid TEXT NOT NULL UNIQUE, type TINYINT NOT NULL, url TEXT, parent INTEGER REFERENCES bookmarks(id) NOT NULL, faviconID INTEGER REFERENCES favicons(id) ON DELETE SET NULL, title TEXT ) """ let queries = [ // This used to be done by FaviconsTable. self.oldFaviconsSQL, getDomainsTableCreationString(), getHistoryTableCreationString(), visits, bookmarks, faviconSites, indexShouldUpload, indexSiteIDDate, widestFavicons, historyIDsWithIcon, iconForURL, getQueueTableCreationString(), ] return self.run(db, queries: queries) && self.prepopulateRootFolders(db) } } class BrowserSchemaV8: BaseHistoricalBrowserSchema { override var version: Int { return 8 } func prepopulateRootFolders(_ db: SQLiteDBConnection) -> Bool { let type = 2 // "folder" let root = 0 let titleMobile = String.BookmarksFolderTitleMobile let titleMenu = String.BookmarksFolderTitleMenu let titleToolbar = String.BookmarksFolderTitleToolbar let titleUnsorted = String.BookmarksFolderTitleUnsorted let args: Args = [ root, BookmarkRoots.RootGUID, type, "Root", root, 1, BookmarkRoots.MobileFolderGUID, type, titleMobile, root, 2, BookmarkRoots.MenuFolderGUID, type, titleMenu, root, 3, BookmarkRoots.ToolbarFolderGUID, type, titleToolbar, root, 4, BookmarkRoots.UnfiledFolderGUID, type, titleUnsorted, root, ] let sql = """ INSERT INTO bookmarks (id, guid, type, url, title, parent) VALUES -- Root (?, ?, ?, NULL, ?, ?), -- Mobile (?, ?, ?, NULL, ?, ?), -- Menu (?, ?, ?, NULL, ?, ?), -- Toolbar (?, ?, ?, NULL, ?, ?), -- Unsorted (?, ?, ?, NULL, ?, ?) """ return self.run(db, sql: sql, args: args) } func getHistoryTableCreationString() -> String { let sql = """ CREATE TABLE IF NOT EXISTS history ( id INTEGER PRIMARY KEY AUTOINCREMENT, -- Not null, but the value might be replaced by the server's. guid TEXT NOT NULL UNIQUE, -- May only be null for deleted records. url TEXT UNIQUE, title TEXT NOT NULL, -- Can be null. Integer milliseconds. server_modified INTEGER, -- Can be null. Client clock. In extremis only. local_modified INTEGER, -- Boolean. Locally deleted. is_deleted TINYINT NOT NULL, -- Boolean. Set when changed or visits added. should_upload TINYINT NOT NULL, domain_id INTEGER REFERENCES domains(id) ON DELETE CASCADE, CONSTRAINT urlOrDeleted CHECK (url IS NOT NULL OR is_deleted = 1) ) """ return sql } func getDomainsTableCreationString() -> String { let sql = """ CREATE TABLE IF NOT EXISTS domains ( id INTEGER PRIMARY KEY AUTOINCREMENT, domain TEXT NOT NULL UNIQUE, showOnTopSites TINYINT NOT NULL DEFAULT 1 ) """ return sql } func getQueueTableCreationString() -> String { let sql = """ CREATE TABLE IF NOT EXISTS queue ( url TEXT NOT NULL UNIQUE, title TEXT ) """ return sql } override func create(_ db: SQLiteDBConnection) -> Bool { let favicons = """ CREATE TABLE IF NOT EXISTS favicons ( id INTEGER PRIMARY KEY AUTOINCREMENT, url TEXT NOT NULL UNIQUE, width INTEGER, height INTEGER, type INTEGER NOT NULL, date REAL NOT NULL ) """ // Right now we don't need to track per-visit deletions: Sync can't // represent them! See Bug 1157553 Comment 6. // We flip the should_upload flag on the history item when we add a visit. // If we ever want to support logic like not bothering to sync if we added // and then rapidly removed a visit, then we need an 'is_new' flag on each visit. let visits = """ CREATE TABLE IF NOT EXISTS visits ( id INTEGER PRIMARY KEY AUTOINCREMENT, siteID INTEGER NOT NULL REFERENCES history(id) ON DELETE CASCADE, -- Microseconds since epoch. date REAL NOT NULL, type INTEGER NOT NULL, -- Some visits are local. Some are remote ('mirrored'). This boolean flag is the split. is_local TINYINT NOT NULL, UNIQUE (siteID, date, type) ) """ let indexShouldUpload: String if self.supportsPartialIndices { // There's no point tracking rows that are not flagged for upload. indexShouldUpload = "CREATE INDEX IF NOT EXISTS idx_history_should_upload ON history (should_upload) WHERE should_upload = 1" } else { indexShouldUpload = "CREATE INDEX IF NOT EXISTS idx_history_should_upload ON history (should_upload)" } let indexSiteIDDate = "CREATE INDEX IF NOT EXISTS idx_visits_siteID_is_local_date ON visits (siteID, is_local, date)" let faviconSites = """ CREATE TABLE IF NOT EXISTS favicon_sites ( id INTEGER PRIMARY KEY AUTOINCREMENT, siteID INTEGER NOT NULL REFERENCES history(id) ON DELETE CASCADE, faviconID INTEGER NOT NULL REFERENCES favicons(id) ON DELETE CASCADE, UNIQUE (siteID, faviconID) ) """ let widestFavicons = """ CREATE VIEW IF NOT EXISTS view_favicons_widest AS SELECT favicon_sites.siteID AS siteID, favicons.id AS iconID, favicons.url AS iconURL, favicons.date AS iconDate, favicons.type AS iconType, max(favicons.width) AS iconWidth FROM favicon_sites, favicons WHERE favicon_sites.faviconID = favicons.id GROUP BY siteID """ let historyIDsWithIcon = """ CREATE VIEW IF NOT EXISTS view_history_id_favicon AS SELECT history.id AS id, iconID, iconURL, iconDate, iconType, iconWidth FROM history LEFT OUTER JOIN view_favicons_widest ON history.id = view_favicons_widest.siteID """ let iconForURL = """ CREATE VIEW IF NOT EXISTS view_icon_for_url AS SELECT history.url AS url, icons.iconID AS iconID FROM history, view_favicons_widest AS icons WHERE history.id = icons.siteID """ let bookmarks = """ CREATE TABLE IF NOT EXISTS bookmarks ( id INTEGER PRIMARY KEY AUTOINCREMENT, guid TEXT NOT NULL UNIQUE, type TINYINT NOT NULL, url TEXT, parent INTEGER REFERENCES bookmarks(id) NOT NULL, faviconID INTEGER REFERENCES favicons(id) ON DELETE SET NULL, title TEXT ) """ let queries: [String] = [ getDomainsTableCreationString(), getHistoryTableCreationString(), favicons, visits, bookmarks, faviconSites, indexShouldUpload, indexSiteIDDate, widestFavicons, historyIDsWithIcon, iconForURL, getQueueTableCreationString(), ] return self.run(db, queries: queries) && self.prepopulateRootFolders(db) } } class BrowserSchemaV10: BaseHistoricalBrowserSchema { override var version: Int { return 10 } func prepopulateRootFolders(_ db: SQLiteDBConnection) -> Bool { let type = 2 // "folder" let root = 0 let titleMobile = String.BookmarksFolderTitleMobile let titleMenu = String.BookmarksFolderTitleMenu let titleToolbar = String.BookmarksFolderTitleToolbar let titleUnsorted = String.BookmarksFolderTitleUnsorted let args: Args = [ root, BookmarkRoots.RootGUID, type, "Root", root, 1, BookmarkRoots.MobileFolderGUID, type, titleMobile, root, 2, BookmarkRoots.MenuFolderGUID, type, titleMenu, root, 3, BookmarkRoots.ToolbarFolderGUID, type, titleToolbar, root, 4, BookmarkRoots.UnfiledFolderGUID, type, titleUnsorted, root, ] let sql = """ INSERT INTO bookmarks (id, guid, type, url, title, parent) VALUES -- Root (?, ?, ?, NULL, ?, ?), -- Mobile (?, ?, ?, NULL, ?, ?), -- Menu (?, ?, ?, NULL, ?, ?), -- Toolbar (?, ?, ?, NULL, ?, ?), -- Unsorted (?, ?, ?, NULL, ?, ?) """ return self.run(db, sql: sql, args: args) } func getHistoryTableCreationString(forVersion version: Int = BrowserSchema.DefaultVersion) -> String { let sql = """ CREATE TABLE IF NOT EXISTS history ( id INTEGER PRIMARY KEY AUTOINCREMENT, -- Not null, but the value might be replaced by the server's. guid TEXT NOT NULL UNIQUE, -- May only be null for deleted records. url TEXT UNIQUE, title TEXT NOT NULL, -- Can be null. Integer milliseconds. server_modified INTEGER, -- Can be null. Client clock. In extremis only. local_modified INTEGER, -- Boolean. Locally deleted. is_deleted TINYINT NOT NULL, -- Boolean. Set when changed or visits added. should_upload TINYINT NOT NULL, domain_id INTEGER REFERENCES domains(id) ON DELETE CASCADE, CONSTRAINT urlOrDeleted CHECK (url IS NOT NULL OR is_deleted = 1) ) """ return sql } func getDomainsTableCreationString() -> String { let sql = """ CREATE TABLE IF NOT EXISTS domains ( id INTEGER PRIMARY KEY AUTOINCREMENT, domain TEXT NOT NULL UNIQUE, showOnTopSites TINYINT NOT NULL DEFAULT 1 ) """ return sql } func getQueueTableCreationString() -> String { let sql = """ CREATE TABLE IF NOT EXISTS queue ( url TEXT NOT NULL UNIQUE, title TEXT ) """ return sql } func getBookmarksMirrorTableCreationString() -> String { // The stupid absence of naming conventions here is thanks to pre-Sync Weave. Sorry. // For now we have the simplest possible schema: everything in one. let sql = """ CREATE TABLE IF NOT EXISTS bookmarksMirror -- Shared fields. ( id INTEGER PRIMARY KEY AUTOINCREMENT , guid TEXT NOT NULL UNIQUE -- Type enum. TODO: BookmarkNodeType needs to be extended. , type TINYINT NOT NULL -- Record/envelope metadata that'll allow us to do merges. -- Milliseconds. , server_modified INTEGER NOT NULL -- Boolean , is_deleted TINYINT NOT NULL DEFAULT 0 -- Boolean, 0 (false) if deleted. , hasDupe TINYINT NOT NULL DEFAULT 0 -- GUID , parentid TEXT , parentName TEXT -- Type-specific fields. These should be NOT NULL in many cases, but we're going -- for a sparse schema, so this'll do for now. Enforce these in the application code. -- LIVEMARKS , feedUri TEXT, siteUri TEXT -- SEPARATORS , pos INT -- FOLDERS, BOOKMARKS, QUERIES , title TEXT, description TEXT -- BOOKMARKS, QUERIES , bmkUri TEXT, tags TEXT, keyword TEXT -- QUERIES , folderName TEXT, queryId TEXT , CONSTRAINT parentidOrDeleted CHECK (parentid IS NOT NULL OR is_deleted = 1) , CONSTRAINT parentNameOrDeleted CHECK (parentName IS NOT NULL OR is_deleted = 1) ) """ return sql } /** * We need to explicitly store what's provided by the server, because we can't rely on * referenced child nodes to exist yet! */ func getBookmarksMirrorStructureTableCreationString() -> String { let sql = """ CREATE TABLE IF NOT EXISTS bookmarksMirrorStructure ( parent TEXT NOT NULL REFERENCES bookmarksMirror(guid) ON DELETE CASCADE, -- Should be the GUID of a child. child TEXT NOT NULL, -- Should advance from 0. idx INTEGER NOT NULL ) """ return sql } override func create(_ db: SQLiteDBConnection) -> Bool { let favicons = """ CREATE TABLE IF NOT EXISTS favicons ( id INTEGER PRIMARY KEY AUTOINCREMENT, url TEXT NOT NULL UNIQUE, width INTEGER, height INTEGER, type INTEGER NOT NULL, date REAL NOT NULL ) """ // Right now we don't need to track per-visit deletions: Sync can't // represent them! See Bug 1157553 Comment 6. // We flip the should_upload flag on the history item when we add a visit. // If we ever want to support logic like not bothering to sync if we added // and then rapidly removed a visit, then we need an 'is_new' flag on each visit. let visits = """ CREATE TABLE IF NOT EXISTS visits ( id INTEGER PRIMARY KEY AUTOINCREMENT, siteID INTEGER NOT NULL REFERENCES history(id) ON DELETE CASCADE, -- Microseconds since epoch. date REAL NOT NULL, type INTEGER NOT NULL, -- Some visits are local. Some are remote ('mirrored'). This boolean flag is the split. is_local TINYINT NOT NULL, UNIQUE (siteID, date, type) ) """ let indexShouldUpload: String if self.supportsPartialIndices { // There's no point tracking rows that are not flagged for upload. indexShouldUpload = "CREATE INDEX IF NOT EXISTS idx_history_should_upload ON history (should_upload) WHERE should_upload = 1" } else { indexShouldUpload = "CREATE INDEX IF NOT EXISTS idx_history_should_upload ON history (should_upload)" } let indexSiteIDDate = "CREATE INDEX IF NOT EXISTS idx_visits_siteID_is_local_date ON visits (siteID, is_local, date)" let faviconSites = """ CREATE TABLE IF NOT EXISTS favicon_sites ( id INTEGER PRIMARY KEY AUTOINCREMENT, siteID INTEGER NOT NULL REFERENCES history(id) ON DELETE CASCADE, faviconID INTEGER NOT NULL REFERENCES favicons(id) ON DELETE CASCADE, UNIQUE (siteID, faviconID) ) """ let widestFavicons = """ CREATE VIEW IF NOT EXISTS view_favicons_widest AS SELECT favicon_sites.siteID AS siteID, favicons.id AS iconID, favicons.url AS iconURL, favicons.date AS iconDate, favicons.type AS iconType, max(favicons.width) AS iconWidth FROM favicon_sites, favicons WHERE favicon_sites.faviconID = favicons.id GROUP BY siteID """ let historyIDsWithIcon = """ CREATE VIEW IF NOT EXISTS view_history_id_favicon AS SELECT history.id AS id, iconID, iconURL, iconDate, iconType, iconWidth FROM history LEFT OUTER JOIN view_favicons_widest ON history.id = view_favicons_widest.siteID """ let iconForURL = """ CREATE VIEW IF NOT EXISTS view_icon_for_url AS SELECT history.url AS url, icons.iconID AS iconID FROM history, view_favicons_widest AS icons WHERE history.id = icons.siteID """ let bookmarks = """ CREATE TABLE IF NOT EXISTS bookmarks ( id INTEGER PRIMARY KEY AUTOINCREMENT, guid TEXT NOT NULL UNIQUE, type TINYINT NOT NULL, url TEXT, parent INTEGER REFERENCES bookmarks(id) NOT NULL, faviconID INTEGER REFERENCES favicons(id) ON DELETE SET NULL, title TEXT ) """ let bookmarksMirror = getBookmarksMirrorTableCreationString() let bookmarksMirrorStructure = getBookmarksMirrorStructureTableCreationString() let indexStructureParentIdx = "CREATE INDEX IF NOT EXISTS idx_bookmarksMirrorStructure_parent_idx ON bookmarksMirrorStructure (parent, idx)" let queries: [String] = [ getDomainsTableCreationString(), getHistoryTableCreationString(), favicons, visits, bookmarks, bookmarksMirror, bookmarksMirrorStructure, indexStructureParentIdx, faviconSites, indexShouldUpload, indexSiteIDDate, widestFavicons, historyIDsWithIcon, iconForURL, getQueueTableCreationString(), ] return self.run(db, queries: queries) && self.prepopulateRootFolders(db) } } class TestSQLiteHistory: XCTestCase { let files = MockFiles() fileprivate func deleteDatabases() { for v in ["6", "7", "8", "10", "6-data"] { do { try files.remove("browser-v\(v).db") } catch {} } do { try files.remove("browser.db") try files.remove("historysynced.db") } catch {} } override func tearDown() { super.tearDown() self.deleteDatabases() } override func setUp() { super.setUp() // Just in case tearDown didn't run or succeed last time! self.deleteDatabases() } // Test that our visit partitioning for frecency is correct. func testHistoryLocalAndRemoteVisits() { let database = BrowserDB(filename: "testHistoryLocalAndRemoteVisits.db", schema: BrowserSchema(), files: files) let prefs = MockProfilePrefs() let history = SQLiteHistory(database: database, prefs: prefs) let siteL = Site(url: "http://url1/", title: "title local only") let siteR = Site(url: "http://url2/", title: "title remote only") let siteB = Site(url: "http://url3/", title: "title local and remote") siteL.guid = "locallocal12" siteR.guid = "remoteremote" siteB.guid = "bothbothboth" let siteVisitL1 = SiteVisit(site: siteL, date: baseInstantInMicros + 1000, type: VisitType.link) let siteVisitL2 = SiteVisit(site: siteL, date: baseInstantInMicros + 2000, type: VisitType.link) let siteVisitR1 = SiteVisit(site: siteR, date: baseInstantInMicros + 1000, type: VisitType.link) let siteVisitR2 = SiteVisit(site: siteR, date: baseInstantInMicros + 2000, type: VisitType.link) let siteVisitR3 = SiteVisit(site: siteR, date: baseInstantInMicros + 3000, type: VisitType.link) let siteVisitBL1 = SiteVisit(site: siteB, date: baseInstantInMicros + 4000, type: VisitType.link) let siteVisitBR1 = SiteVisit(site: siteB, date: baseInstantInMicros + 5000, type: VisitType.link) let deferred = history.clearHistory() >>> { history.addLocalVisit(siteVisitL1) } >>> { history.addLocalVisit(siteVisitL2) } >>> { history.addLocalVisit(siteVisitBL1) } >>> { history.insertOrUpdatePlace(siteL.asPlace(), modified: baseInstantInMillis + 2) } >>> { history.insertOrUpdatePlace(siteR.asPlace(), modified: baseInstantInMillis + 3) } >>> { history.insertOrUpdatePlace(siteB.asPlace(), modified: baseInstantInMillis + 5) } // Do this step twice, so we exercise the dupe-visit handling. >>> { history.storeRemoteVisits([siteVisitR1, siteVisitR2, siteVisitR3], forGUID: siteR.guid!) } >>> { history.storeRemoteVisits([siteVisitR1, siteVisitR2, siteVisitR3], forGUID: siteR.guid!) } >>> { history.storeRemoteVisits([siteVisitBR1], forGUID: siteB.guid!) } >>> { history.getFrecentHistory().getSites(matchingSearchQuery: nil, limit: 3) >>== { (sites: Cursor) -> Success in XCTAssertEqual(3, sites.count) // Two local visits beat a single later remote visit and one later local visit. // Two local visits beat three remote visits. XCTAssertEqual(siteL.guid!, sites[0]!.guid!) XCTAssertEqual(siteB.guid!, sites[1]!.guid!) XCTAssertEqual(siteR.guid!, sites[2]!.guid!) return succeed() } // This marks everything as modified so we can fetch it. >>> history.onRemovedAccount // Now check that we have no duplicate visits. >>> { history.getModifiedHistoryToUpload() >>== { (places) -> Success in if let (_, visits) = places.find({$0.0.guid == siteR.guid!}) { XCTAssertEqual(3, visits.count) } else { XCTFail("Couldn't find site R.") } return succeed() } } } XCTAssertTrue(deferred.value.isSuccess) } func testUpgrades() { let sources: [(Int, Schema)] = [ (6, BrowserSchemaV6()), (7, BrowserSchemaV7()), (8, BrowserSchemaV8()), (10, BrowserSchemaV10()), ] let destination = BrowserSchema() for (version, schema) in sources { var db = BrowserDB(filename: "browser-v\(version).db", schema: schema, files: files) XCTAssertTrue(db.withConnection({ connection -> Int in connection.version }).value.successValue == schema.version, "Creating BrowserSchema at version \(version)") db.forceClose() db = BrowserDB(filename: "browser-v\(version).db", schema: destination, files: files) XCTAssertTrue(db.withConnection({ connection -> Int in connection.version }).value.successValue == destination.version, "Upgrading BrowserSchema from version \(version) to version \(schema.version)") db.forceClose() } } func testUpgradesWithData() { var database = BrowserDB(filename: "browser-v6-data.db", schema: BrowserSchemaV6(), files: files) // Insert some data. let queries = [ "INSERT INTO domains (id, domain) VALUES (1, 'example.com')", "INSERT INTO history (id, guid, url, title, server_modified, local_modified, is_deleted, should_upload, domain_id) VALUES (5, 'guid', 'http://www.example.com', 'title', 5, 10, 0, 1, 1)", "INSERT INTO visits (siteID, date, type, is_local) VALUES (5, 15, 1, 1)", "INSERT INTO favicons (url, width, height, type, date) VALUES ('http://www.example.com/favicon.ico', 10, 10, 1, 20)", "INSERT INTO favicon_sites (siteID, faviconID) VALUES (5, 1)", "INSERT INTO bookmarks (guid, type, url, parent, faviconID, title) VALUES ('guid', 1, 'http://www.example.com', 0, 1, 'title')" ] XCTAssertTrue(database.run(queries).value.isSuccess) // And we can upgrade to the current version. database = BrowserDB(filename: "browser-v6-data.db", schema: BrowserSchema(), files: files) let prefs = MockProfilePrefs() let history = SQLiteHistory(database: database, prefs: prefs) let results = history.getSitesByLastVisit(limit: 10, offset: 0).value.successValue XCTAssertNotNil(results) XCTAssertEqual(results![0]?.url, "http://www.example.com") database.forceClose() } func testDomainUpgrade() { let database = BrowserDB(filename: "testDomainUpgrade.db", schema: BrowserSchema(), files: files) let prefs = MockProfilePrefs() let history = SQLiteHistory(database: database, prefs: prefs) let site = Site(url: "http://www.example.com/test1.4", title: "title one") // Insert something with an invalid domain ID. We have to manually do this since domains are usually hidden. let insertDeferred = database.withConnection { connection -> Void in try connection.executeChange("PRAGMA foreign_keys = OFF") let insert = "INSERT OR REPLACE INTO history (guid, url, title, local_modified, is_deleted, should_upload, domain_id) VALUES (?, ?, ?, ?, ?, ?, ?)" let args: Args = [Bytes.generateGUID(), site.url, site.title, Date.now(), 0, 0, -1] try connection.executeChange(insert, withArgs: args) } XCTAssertTrue(insertDeferred.value.isSuccess) // Now insert it again. This should update the domain. history.addLocalVisit(SiteVisit(site: site, date: Date().toMicrosecondsSince1970(), type: VisitType.link)).succeeded() // domain_id isn't normally exposed, so we manually query to get it. let resultsDeferred = database.withConnection { connection -> Cursor<Int?> in let sql = "SELECT domain_id FROM history WHERE url = ?" let args: Args = [site.url] return connection.executeQuery(sql, factory: { $0[0] as? Int }, withArgs: args) } let results = resultsDeferred.value.successValue! let domain = results[0]! // Unwrap to get the first item from the cursor. XCTAssertNil(domain) } func testDomains() { let database = BrowserDB(filename: "testDomains.db", schema: BrowserSchema(), files: files) let prefs = MockProfilePrefs() let history = SQLiteHistory(database: database, prefs: prefs) let initialGuid = Bytes.generateGUID() let site11 = Site(url: "http://www.example.com/test1.1", title: "title one") let site12 = Site(url: "http://www.example.com/test1.2", title: "title two") let site13 = Place(guid: initialGuid, url: "http://www.example.com/test1.3", title: "title three") let site3 = Site(url: "http://www.example2.com/test1", title: "title three") let expectation = self.expectation(description: "First.") let clearTopSites = "DELETE FROM cached_top_sites" let updateTopSites: [(String, Args?)] = [(clearTopSites, nil), (history.getFrecentHistory().updateTopSitesCacheQuery())] func countTopSites() -> Deferred<Maybe<Cursor<Int>>> { return database.runQuery("SELECT count(*) FROM cached_top_sites", args: nil, factory: { sdrow -> Int in return sdrow[0] as? Int ?? 0 }) } history.clearHistory().bind({ success in return all([ history.addLocalVisit(SiteVisit(site: site11, date: Date().toMicrosecondsSince1970(), type: VisitType.link)), history.addLocalVisit(SiteVisit(site: site12, date: Date().toMicrosecondsSince1970(), type: VisitType.link)), history.addLocalVisit(SiteVisit(site: site3, date: Date().toMicrosecondsSince1970(), type: VisitType.link))]) }).bind({ (results: [Maybe<()>]) in return history.insertOrUpdatePlace(site13, modified: Date().toMicrosecondsSince1970()) }).bind({ guid -> Success in XCTAssertEqual(guid.successValue!, initialGuid, "Guid is correct") return database.run(updateTopSites) }).bind({ success in XCTAssertTrue(success.isSuccess, "update was successful") return countTopSites() }).bind({ (count: Maybe<Cursor<Int>>) -> Success in XCTAssert(count.successValue![0] == 2, "2 sites returned") return history.removeSiteFromTopSites(site11) }).bind({ success -> Success in XCTAssertTrue(success.isSuccess, "Remove was successful") return database.run(updateTopSites) }).bind({ success -> Deferred<Maybe<Cursor<Int>>> in XCTAssertTrue(success.isSuccess, "update was successful") return countTopSites() }) .upon({ (count: Maybe<Cursor<Int>>) in XCTAssert(count.successValue![0] == 1, "1 site returned") expectation.fulfill() }) waitForExpectations(timeout: 10.0) { error in return } } func testHistoryIsSynced() { let database = BrowserDB(filename: "historysynced.db", schema: BrowserSchema(), files: files) let prefs = MockProfilePrefs() let history = SQLiteHistory(database: database, prefs: prefs) let initialGUID = Bytes.generateGUID() let site = Place(guid: initialGUID, url: "http://www.example.com/test1.3", title: "title") XCTAssertFalse(history.hasSyncedHistory().value.successValue ?? true) XCTAssertTrue(history.insertOrUpdatePlace(site, modified: Date.now()).value.isSuccess) XCTAssertTrue(history.hasSyncedHistory().value.successValue ?? false) } // This is a very basic test. Adds an entry, retrieves it, updates it, // and then clears the database. func testHistoryTable() { let database = BrowserDB(filename: "testHistoryTable.db", schema: BrowserSchema(), files: files) let prefs = MockProfilePrefs() let history = SQLiteHistory(database: database, prefs: prefs) let site1 = Site(url: "http://url1/", title: "title one") let site1Changed = Site(url: "http://url1/", title: "title one alt") let siteVisit1 = SiteVisit(site: site1, date: Date().toMicrosecondsSince1970(), type: VisitType.link) let siteVisit2 = SiteVisit(site: site1Changed, date: Date().toMicrosecondsSince1970() + 1000, type: VisitType.bookmark) let site2 = Site(url: "http://url2/", title: "title two") let siteVisit3 = SiteVisit(site: site2, date: Date().toMicrosecondsSince1970() + 2000, type: VisitType.link) let expectation = self.expectation(description: "First.") func done() -> Success { expectation.fulfill() return succeed() } func checkSitesByFrecency(_ f: @escaping (Cursor<Site>) -> Success) -> () -> Success { return { history.getFrecentHistory().getSites(matchingSearchQuery: nil, limit: 10) >>== f } } func checkSitesByDate(_ f: @escaping (Cursor<Site>) -> Success) -> () -> Success { return { history.getSitesByLastVisit(limit: 10, offset: 0) >>== f } } func checkSitesWithFilter(_ filter: String, f: @escaping (Cursor<Site>) -> Success) -> () -> Success { return { history.getFrecentHistory().getSites(matchingSearchQuery: filter, limit: 10) >>== f } } func checkDeletedCount(_ expected: Int) -> () -> Success { return { history.getDeletedHistoryToUpload() >>== { guids in XCTAssertEqual(expected, guids.count) return succeed() } } } history.clearHistory() >>> { history.addLocalVisit(siteVisit1) } >>> checkSitesByFrecency { (sites: Cursor) -> Success in XCTAssertEqual(1, sites.count) XCTAssertEqual(site1.title, sites[0]!.title) XCTAssertEqual(site1.url, sites[0]!.url) sites.close() return succeed() } >>> { history.addLocalVisit(siteVisit2) } >>> checkSitesByFrecency { (sites: Cursor) -> Success in XCTAssertEqual(1, sites.count) XCTAssertEqual(site1Changed.title, sites[0]!.title) XCTAssertEqual(site1Changed.url, sites[0]!.url) sites.close() return succeed() } >>> { history.addLocalVisit(siteVisit3) } >>> checkSitesByFrecency { (sites: Cursor) -> Success in XCTAssertEqual(2, sites.count) // They're in order of frecency. XCTAssertEqual(site1Changed.title, sites[0]!.title) XCTAssertEqual(site2.title, sites[1]!.title) return succeed() } >>> checkSitesByDate { (sites: Cursor<Site>) -> Success in XCTAssertEqual(2, sites.count) // They're in order of date last visited. let first = sites[0]! let second = sites[1]! XCTAssertEqual(site2.title, first.title) XCTAssertEqual(site1Changed.title, second.title) XCTAssertTrue(siteVisit3.date == first.latestVisit!.date) return succeed() } >>> checkSitesWithFilter("two") { (sites: Cursor<Site>) -> Success in XCTAssertEqual(1, sites.count) let first = sites[0]! XCTAssertEqual(site2.title, first.title) return succeed() } >>> checkDeletedCount(0) >>> { history.removeHistoryForURL("http://url2/") } >>> checkDeletedCount(1) >>> checkSitesByFrecency { (sites: Cursor) -> Success in XCTAssertEqual(1, sites.count) // They're in order of frecency. XCTAssertEqual(site1Changed.title, sites[0]!.title) return succeed() } >>> { history.clearHistory() } >>> checkDeletedCount(0) >>> checkSitesByDate { (sites: Cursor<Site>) -> Success in XCTAssertEqual(0, sites.count) return succeed() } >>> checkSitesByFrecency { (sites: Cursor<Site>) -> Success in XCTAssertEqual(0, sites.count) return succeed() } >>> done waitForExpectations(timeout: 10.0) { error in return } } func testRemoveRecentHistory() { let database = BrowserDB(filename: "testRemoveRecentHistory.db", schema: BrowserSchema(), files: files) let prefs = MockProfilePrefs() let history = SQLiteHistory(database: database, prefs: prefs) func delete(date: Date, expectedDeletions: Int) { history.clearHistory().succeeded() let siteL = Site(url: "http://url1/", title: "title local only") let siteR = Site(url: "http://url2/", title: "title remote only") let siteB = Site(url: "http://url3/", title: "title local and remote") siteL.guid = "locallocal12" siteR.guid = "remoteremote" siteB.guid = "bothbothboth" // Site visit uses microsec timestamp let siteVisitL1 = SiteVisit(site: siteL, date: 1_000_000, type: VisitType.link) let siteVisitL2 = SiteVisit(site: siteR, date: 2_000_000, type: VisitType.link) let siteVisitBL1 = SiteVisit(site: siteB, date: 4_000_000, type: VisitType.link) let deferred = history.addLocalVisit(siteVisitL1) >>> { history.addLocalVisit(siteVisitL2) } >>> { history.addLocalVisit(siteVisitBL1) } >>> { history.insertOrUpdatePlace(siteL.asPlace(), modified: baseInstantInMillis + 2) } >>> { history.insertOrUpdatePlace(siteR.asPlace(), modified: baseInstantInMillis + 3) } >>> { history.insertOrUpdatePlace(siteB.asPlace(), modified: baseInstantInMillis + 5) } XCTAssert(deferred.value.isSuccess) history.removeHistoryFromDate(date).succeeded() history.getDeletedHistoryToUpload() >>== { guids in XCTAssertEqual(expectedDeletions, guids.count) } } delete(date: Date(timeIntervalSinceNow: 0), expectedDeletions: 0) delete(date: Date(timeIntervalSince1970: 0), expectedDeletions: 3) delete(date: Date(timeIntervalSince1970: 3), expectedDeletions: 1) } func testRemoveHistoryForUrl() { let database = BrowserDB(filename: "testRemoveHistoryForUrl.db", schema: BrowserSchema(), files: files) let prefs = MockProfilePrefs() let history = SQLiteHistory(database: database, prefs: prefs) history.setTopSitesCacheSize(20) history.clearTopSitesCache().succeeded() history.clearHistory().succeeded() // Lets create some history. This will create 3 sites that will have 4 local and 4 remote visits populateHistoryForFrecencyCalculations(history, siteCount: 3) history.removeHistoryForURL("http://s0ite0.com/foo").succeeded() history.removeHistoryForURL("http://s1ite1.com/foo").succeeded() let deletedResult = history.getDeletedHistoryToUpload().value XCTAssertTrue(deletedResult.isSuccess) let guids = deletedResult.successValue! XCTAssertEqual(2, guids.count) } func testTopSitesFrecencyOrder() { let database = BrowserDB(filename: "testTopSitesFrecencyOrder.db", schema: BrowserSchema(), files: files) let prefs = MockProfilePrefs() let history = SQLiteHistory(database: database, prefs: prefs) history.setTopSitesCacheSize(20) history.clearTopSitesCache().succeeded() history.clearHistory().succeeded() // Lets create some history. This will create 100 sites that will have 4 local and 4 remote visits populateHistoryForFrecencyCalculations(history, siteCount: 100) // Create a new site thats for an existing domain but a different URL. let site = Site(url: "http://s\(5)ite\(5).com/foo-different-url", title: "A \(5) different url") site.guid = "abc\(5)defhi" history.insertOrUpdatePlace(site.asPlace(), modified: baseInstantInMillis - 20000).succeeded() // Don't give it any remote visits. But give it 100 local visits. This should be the new Topsite! for i in 0...100 { addVisitForSite(site, intoHistory: history, from: .local, atTime: advanceTimestamp(baseInstantInMicros, by: 1000000 * i)) } let expectation = self.expectation(description: "First.") func done() -> Success { expectation.fulfill() return succeed() } func loadCache() -> Success { return history.repopulate(invalidateTopSites: true) >>> succeed } func checkTopSitesReturnsResults() -> Success { return history.getTopSitesWithLimit(20) >>== { topSites in XCTAssertEqual(topSites.count, 20) XCTAssertEqual(topSites[0]!.guid, "abc\(5)defhi") return succeed() } } loadCache() >>> checkTopSitesReturnsResults >>> done waitForExpectations(timeout: 10.0) { error in return } } func testTopSitesFiltersGoogle() { let database = BrowserDB(filename: "testTopSitesFiltersGoogle.db", schema: BrowserSchema(), files: files) let prefs = MockProfilePrefs() let history = SQLiteHistory(database: database, prefs: prefs) history.setTopSitesCacheSize(20) history.clearTopSitesCache().succeeded() history.clearHistory().succeeded() // Lets create some history. This will create 100 sites that will have 21 local and 21 remote visits populateHistoryForFrecencyCalculations(history, siteCount: 100) func createTopSite(url: String, guid: String) { let site = Site(url: url, title: "Hi") site.guid = guid history.insertOrUpdatePlace(site.asPlace(), modified: baseInstantInMillis - 20000).succeeded() // Don't give it any remote visits. But give it 100 local visits. This should be the new Topsite! for i in 0...100 { addVisitForSite(site, intoHistory: history, from: .local, atTime: advanceTimestamp(baseInstantInMicros, by: 1000000 * i)) } } createTopSite(url: "http://google.com", guid: "abcgoogle") // should not be a topsite createTopSite(url: "http://www.google.com", guid: "abcgoogle1") // should not be a topsite createTopSite(url: "http://google.co.za", guid: "abcgoogleza") // should not be a topsite createTopSite(url: "http://docs.google.com", guid: "docsgoogle") // should be a topsite let expectation = self.expectation(description: "First.") func done() -> Success { expectation.fulfill() return succeed() } func loadCache() -> Success { return history.repopulate(invalidateTopSites: true) >>> succeed } func checkTopSitesReturnsResults() -> Success { return history.getTopSitesWithLimit(20) >>== { topSites in XCTAssertEqual(topSites[0]?.guid, "docsgoogle") // google docs should be the first topsite // make sure all other google guids are not in the topsites array topSites.forEach { let guid: String = $0!.guid! // type checking is hard XCTAssertNil(["abcgoogle", "abcgoogle1", "abcgoogleza"].firstIndex(of: guid)) } XCTAssertEqual(topSites.count, 20) return succeed() } } loadCache() >>> checkTopSitesReturnsResults >>> done waitForExpectations(timeout: 10.0) { error in return } } func testTopSitesCache() { let database = BrowserDB(filename: "testTopSitesCache.db", schema: BrowserSchema(), files: files) let prefs = MockProfilePrefs() let history = SQLiteHistory(database: database, prefs: prefs) history.setTopSitesCacheSize(20) history.clearTopSitesCache().succeeded() history.clearHistory().succeeded() // Make sure that we get back the top sites populateHistoryForFrecencyCalculations(history, siteCount: 100) // Add extra visits to the 5th site to bubble it to the top of the top sites cache let site = Site(url: "http://s\(5)ite\(5).com/foo", title: "A \(5)") site.guid = "abc\(5)def" for i in 0...20 { addVisitForSite(site, intoHistory: history, from: .local, atTime: advanceTimestamp(baseInstantInMicros, by: 1000000 * i)) } let expectation = self.expectation(description: "First.") func done() -> Success { expectation.fulfill() return succeed() } func loadCache() -> Success { return history.repopulate(invalidateTopSites: true) >>> succeed } func checkTopSitesReturnsResults() -> Success { return history.getTopSitesWithLimit(20) >>== { topSites in XCTAssertEqual(topSites.count, 20) XCTAssertEqual(topSites[0]!.guid, "abc\(5)def") return succeed() } } func invalidateIfNeededDoesntChangeResults() -> Success { return history.repopulate(invalidateTopSites: true) >>> { return history.getTopSitesWithLimit(20) >>== { topSites in XCTAssertEqual(topSites.count, 20) XCTAssertEqual(topSites[0]!.guid, "abc\(5)def") return succeed() } } } func addVisitsToZerothSite() -> Success { let site = Site(url: "http://s\(0)ite\(0).com/foo", title: "A \(0)") site.guid = "abc\(0)def" for i in 0...20 { addVisitForSite(site, intoHistory: history, from: .local, atTime: advanceTimestamp(baseInstantInMicros, by: 1000000 * i)) } return succeed() } func markInvalidation() -> Success { history.setTopSitesNeedsInvalidation() return succeed() } func checkSitesInvalidate() -> Success { history.repopulate(invalidateTopSites: true).succeeded() return history.getTopSitesWithLimit(20) >>== { topSites in XCTAssertEqual(topSites.count, 20) XCTAssertEqual(topSites[0]!.guid, "abc\(5)def") XCTAssertEqual(topSites[1]!.guid, "abc\(0)def") return succeed() } } loadCache() >>> checkTopSitesReturnsResults >>> invalidateIfNeededDoesntChangeResults >>> markInvalidation >>> addVisitsToZerothSite >>> checkSitesInvalidate >>> done waitForExpectations(timeout: 10.0) { error in return } } func testPinnedTopSites() { let database = BrowserDB(filename: "testPinnedTopSites.db", schema: BrowserSchema(), files: files) let prefs = MockProfilePrefs() let history = SQLiteHistory(database: database, prefs: prefs) history.setTopSitesCacheSize(20) history.clearTopSitesCache().succeeded() history.clearHistory().succeeded() // add 2 sites to pinned topsite // get pinned site and make sure it exists in the right order // remove pinned sites // make sure pinned sites dont exist // create pinned sites. let site1 = Site(url: "http://s\(1)ite\(1).com/foo", title: "A \(1)") site1.id = 1 site1.guid = "abc\(1)def" addVisitForSite(site1, intoHistory: history, from: .local, atTime: Date.now()) let site2 = Site(url: "http://s\(2)ite\(2).com/foo", title: "A \(2)") site2.id = 2 site2.guid = "abc\(2)def" addVisitForSite(site2, intoHistory: history, from: .local, atTime: Date.now()) let expectation = self.expectation(description: "First.") func done() -> Success { expectation.fulfill() return succeed() } func addPinnedSites() -> Success { return history.addPinnedTopSite(site1) >>== { sleep(1) // Sleep to prevent intermittent issue with sorting on the timestamp return history.addPinnedTopSite(site2) } } func checkPinnedSites() -> Success { return history.getPinnedTopSites() >>== { pinnedSites in XCTAssertEqual(pinnedSites.count, 2) XCTAssertEqual(pinnedSites[0]!.url, site2.url) XCTAssertEqual(pinnedSites[1]!.url, site1.url, "The older pinned site should be last") return succeed() } } func removePinnedSites() -> Success { return history.removeFromPinnedTopSites(site2) >>== { return history.getPinnedTopSites() >>== { pinnedSites in XCTAssertEqual(pinnedSites.count, 1, "There should only be one pinned site") XCTAssertEqual(pinnedSites[0]!.url, site1.url, "Site2 should be the only pin left") return succeed() } } } func dupePinnedSite() -> Success { return history.addPinnedTopSite(site1) >>== { return history.getPinnedTopSites() >>== { pinnedSites in XCTAssertEqual(pinnedSites.count, 1, "There should not be a dupe") XCTAssertEqual(pinnedSites[0]!.url, site1.url, "Site2 should be the only pin left") return succeed() } } } func removeHistory() -> Success { return history.clearHistory() >>== { return history.getPinnedTopSites() >>== { pinnedSites in XCTAssertEqual(pinnedSites.count, 1, "Pinned sites should exist after a history clear") return succeed() } } } addPinnedSites() >>> checkPinnedSites >>> removePinnedSites >>> dupePinnedSite >>> removeHistory >>> done waitForExpectations(timeout: 10.0) { error in return } } func testPinnedTopSitesDuplicateDomains() { let database = BrowserDB(filename: "testPinnedTopSitesDuplicateDomains.db", schema: BrowserSchema(), files: files) let prefs = MockProfilePrefs() let history = SQLiteHistory(database: database, prefs: prefs) history.setTopSitesCacheSize(20) history.clearTopSitesCache().succeeded() history.clearHistory().succeeded() // create pinned sites with a same domain name let site1 = Site(url: "http://site.com/foo1", title: "A duplicate domain \(1)") site1.id = 1 site1.guid = "abc\(1)def" addVisitForSite(site1, intoHistory: history, from: .local, atTime: Date.now()) let site2 = Site(url: "http://site.com/foo2", title: "A duplicate domain \(2)") site2.id = 2 site2.guid = "abc\(2)def" addVisitForSite(site2, intoHistory: history, from: .local, atTime: Date.now()) let expectation = self.expectation(description: "First.") func done() -> Success { expectation.fulfill() return succeed() } func addPinnedSites() -> Success { return history.addPinnedTopSite(site1) >>== { sleep(1) // Sleep to prevent intermittent issue with sorting on the timestamp return history.addPinnedTopSite(site2) } } func checkPinnedSites() -> Success { return history.getPinnedTopSites() >>== { pinnedSites in XCTAssertEqual(pinnedSites.count, 2) XCTAssertEqual(pinnedSites[0]!.url, site2.url) XCTAssertEqual(pinnedSites[1]!.url, site1.url, "The older pinned site should be last") return succeed() } } func removePinnedSites() -> Success { return history.removeFromPinnedTopSites(site2) >>== { return history.getPinnedTopSites() >>== { pinnedSites in XCTAssertEqual(pinnedSites.count, 1, "There should only be one pinned site") XCTAssertEqual(pinnedSites[0]!.url, site1.url, "Site2 should be the only pin left") return succeed() } } } func removeHistory() -> Success { return history.clearHistory() >>== { return history.getPinnedTopSites() >>== { pinnedSites in XCTAssertEqual(pinnedSites.count, 2, "Pinned sites should exist after a history clear") return succeed() } } } addPinnedSites() >>> checkPinnedSites >>> removeHistory >>> done waitForExpectations(timeout: 10.0) { error in return } } } class TestSQLiteHistoryTransactionUpdate: XCTestCase { func testUpdateInTransaction() { let files = MockFiles() let database = BrowserDB(filename: "testUpdateInTransaction.db", schema: BrowserSchema(), files: files) let prefs = MockProfilePrefs() let history = SQLiteHistory(database: database, prefs: prefs) history.clearHistory().succeeded() let site = Site(url: "http://site.example/foo", title: "AA") site.guid = "abcdefghiabc" history.insertOrUpdatePlace(site.asPlace(), modified: 1234567890).succeeded() let ts: MicrosecondTimestamp = baseInstantInMicros let local = SiteVisit(site: site, date: ts, type: VisitType.link) XCTAssertTrue(history.addLocalVisit(local).value.isSuccess) // Doing it again is a no-op and will not fail. history.insertOrUpdatePlace(site.asPlace(), modified: 1234567890).succeeded() } }
mpl-2.0
2add72d3230cdbf382bb0a56077bf5a2
38.946943
198
0.562814
5.173501
false
false
false
false
mshhmzh/firefox-ios
Utils/TimeConstants.swift
4
3973
/* 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 public typealias Timestamp = UInt64 public typealias MicrosecondTimestamp = UInt64 public let ThreeWeeksInSeconds = 3 * 7 * 24 * 60 * 60 public let OneMonthInMilliseconds = 30 * OneDayInMilliseconds public let OneWeekInMilliseconds = 7 * OneDayInMilliseconds public let OneDayInMilliseconds = 24 * OneHourInMilliseconds public let OneHourInMilliseconds = 60 * OneMinuteInMilliseconds public let OneMinuteInMilliseconds = 60 * OneSecondInMilliseconds public let OneSecondInMilliseconds: UInt64 = 1000 extension NSDate { public class func now() -> Timestamp { return UInt64(1000 * NSDate().timeIntervalSince1970) } public class func nowNumber() -> NSNumber { return NSNumber(unsignedLongLong: now()) } public class func nowMicroseconds() -> MicrosecondTimestamp { return UInt64(1000000 * NSDate().timeIntervalSince1970) } public class func fromTimestamp(timestamp: Timestamp) -> NSDate { return NSDate(timeIntervalSince1970: Double(timestamp) / 1000) } public class func fromMicrosecondTimestamp(microsecondTimestamp: MicrosecondTimestamp) -> NSDate { return NSDate(timeIntervalSince1970: Double(microsecondTimestamp) / 1000000) } public func toRelativeTimeString() -> String { let now = NSDate() let units: NSCalendarUnit = [NSCalendarUnit.Second, NSCalendarUnit.Minute, NSCalendarUnit.Day, NSCalendarUnit.WeekOfYear, NSCalendarUnit.Month, NSCalendarUnit.Year, NSCalendarUnit.Hour] let components = NSCalendar.currentCalendar().components(units, fromDate: self, toDate: now, options: []) if components.year > 0 { return String(format: NSDateFormatter.localizedStringFromDate(self, dateStyle: NSDateFormatterStyle.ShortStyle, timeStyle: NSDateFormatterStyle.ShortStyle)) } if components.month == 1 { return String(format: NSLocalizedString("more than a month ago", comment: "Relative date for dates older than a month and less than two months.")) } if components.month > 1 { return String(format: NSDateFormatter.localizedStringFromDate(self, dateStyle: NSDateFormatterStyle.ShortStyle, timeStyle: NSDateFormatterStyle.ShortStyle)) } if components.weekOfYear > 0 { return String(format: NSLocalizedString("more than a week ago", comment: "Description for a date more than a week ago, but less than a month ago.")) } if components.day == 1 { return String(format: NSLocalizedString("yesterday", comment: "Relative date for yesterday.")) } if components.day > 1 { return String(format: NSLocalizedString("this week", comment: "Relative date for date in past week."), String(components.day)) } if components.hour > 0 || components.minute > 0 { let absoluteTime = NSDateFormatter.localizedStringFromDate(self, dateStyle: NSDateFormatterStyle.NoStyle, timeStyle: NSDateFormatterStyle.ShortStyle) let format = NSLocalizedString("today at %@", comment: "Relative date for date older than a minute.") return String(format: format, absoluteTime) } return String(format: NSLocalizedString("just now", comment: "Relative time for a tab that was visited within the last few moments.")) } } public func decimalSecondsStringToTimestamp(input: String) -> Timestamp? { var double = 0.0 if NSScanner(string: input).scanDouble(&double) { return Timestamp(double * 1000) } return nil } public func millisecondsToDecimalSeconds(input: Timestamp) -> String { let val: Double = Double(input) / 1000 return String(format: "%.2F", val) }
mpl-2.0
6e9022e1806347c0c3e2be9ef730152f
40.821053
193
0.70073
5.074074
false
false
false
false
clarkcb/xsearch
swift/swiftsearch/Sources/swiftsearch/SearchOptions.swift
1
17169
// // SearchOptions.swift // swiftsearch // // Created by Cary Clark on 5/17/15. // Copyright (c) 2015 Cary Clark. All rights reserved. // import Foundation struct SearchOption { let short: String let long: String let desc: String var sortArg: String { (short.isEmpty ? short.lowercased() + "@" : "") + long } } class SearchOptionsXmlParser: NSObject, XMLParserDelegate { var searchOptions = [SearchOption]() let searchOptionNodeName = "searchoption" let longAttributeName = "long" let shortAttributeName = "short" var element = "" var longName = "" var shortName = "" var desc = NSMutableString() func parseFile(_ filepath: String) -> [SearchOption] { if FileManager.default.fileExists(atPath: filepath) { let data: Data? = try? Data(contentsOf: URL(fileURLWithPath: filepath)) let inputStream: InputStream? = InputStream(data: data!) let parser: XMLParser? = XMLParser(stream: inputStream!) if parser != nil { parser!.delegate = self parser!.parse() } } else { print("ERROR: filepath not found: \(filepath)") } return searchOptions } func parser(_: XMLParser, didStartElement elementName: String, namespaceURI _: String?, qualifiedName _: String?, attributes attributeDict: [String: String]) { element = elementName if (elementName as NSString).isEqual(to: searchOptionNodeName) { if attributeDict.index(forKey: longAttributeName) != nil { longName = (attributeDict[longAttributeName]!) } if attributeDict.index(forKey: shortAttributeName) != nil { shortName = (attributeDict[shortAttributeName]!) } desc = NSMutableString() desc = "" } } func parser(_: XMLParser, foundCharacters string: String) { if element == searchOptionNodeName { desc.append(string) } } func parser(_: XMLParser, didEndElement elementName: String, namespaceURI _: String?, qualifiedName _: String?) { if (elementName as NSString).isEqual(to: searchOptionNodeName) { if !desc.isEqual(nil) { let trimmedDesc = desc.trimmingCharacters(in: whitespace as CharacterSet) searchOptions.append(SearchOption(short: shortName, long: longName, desc: trimmedDesc)) } } } } public class SearchOptions { private var searchOptions = [SearchOption]() private var longArgDict: [String: String] = [:] public init() { // setSearchOptionsFromXml() setSearchOptionsFromJson() } private func setSearchOptionsFromXml() { let parser = SearchOptionsXmlParser() searchOptions = parser.parseFile(Config.searchOptionsPath) searchOptions.sort(by: { $0.sortArg < $1.sortArg }) for opt in searchOptions { longArgDict[opt.long] = opt.long if !opt.short.isEmpty { longArgDict[opt.short] = opt.long } } } private func setSearchOptionsFromJson() { do { let searchOptionsUrl = URL(fileURLWithPath: Config.searchOptionsPath) let data = try Data(contentsOf: searchOptionsUrl, options: .mappedIfSafe) if let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] { if let options = json["searchoptions"] as? [[String: Any]] { for so in options { let longArg = so["long"] as! String let shortArg = so.index(forKey: "short") != nil ? so["short"] as! String : "" let desc = so["desc"] as! String searchOptions.append(SearchOption(short: shortArg, long: longArg, desc: desc)) } searchOptions.sort(by: { $0.sortArg < $1.sortArg }) for opt in searchOptions { longArgDict[opt.long] = opt.long if !opt.short.isEmpty { longArgDict[opt.short] = opt.long } } } } } catch let error as NSError { print("Failed to load: \(error.localizedDescription)") } } // this is computed property so that it can reference self private var argActionDict: [String: (String, SearchSettings) -> Void] { [ "encoding": { (str: String, settings: SearchSettings) -> Void in settings.textFileEncoding = str }, "in-archiveext": { (str: String, settings: SearchSettings) -> Void in settings.addInArchiveExtension(str) }, "in-archivefilepattern": { (str: String, settings: SearchSettings) -> Void in settings.addInArchiveFilePattern(str) }, "in-dirpattern": { (str: String, settings: SearchSettings) -> Void in settings.addInDirPattern(str) }, "in-ext": { (str: String, settings: SearchSettings) -> Void in settings.addInExtension(str) }, "in-filepattern": { (str: String, settings: SearchSettings) -> Void in settings.addInFilePattern(str) }, "in-filetype": { (str: String, settings: SearchSettings) -> Void in settings.addInFileType(str) }, "in-linesafterpattern": { (str: String, settings: SearchSettings) -> Void in settings.addInLinesAfterPattern(str) }, "in-linesbeforepattern": { (str: String, settings: SearchSettings) -> Void in settings.addInLinesBeforePattern(str) }, "linesafter": { (str: String, settings: SearchSettings) -> Void in settings.linesAfter = Int(str)! }, "linesaftertopattern": { (str: String, settings: SearchSettings) -> Void in settings.addLinesAfterToPattern(str) }, "linesafteruntilpattern": { (str: String, settings: SearchSettings) -> Void in settings.addLinesAfterUntilPattern(str) }, "linesbefore": { (str: String, settings: SearchSettings) -> Void in settings.linesBefore = Int(str)! }, "maxlinelength": { (str: String, settings: SearchSettings) -> Void in settings.maxLineLength = Int(str)! }, "out-archiveext": { (str: String, settings: SearchSettings) -> Void in settings.addOutArchiveExtension(str) }, "out-archivefilepattern": { (str: String, settings: SearchSettings) -> Void in settings.addOutArchiveFilePattern(str) }, "out-dirpattern": { (str: String, settings: SearchSettings) -> Void in settings.addOutDirPattern(str) }, "out-ext": { (str: String, settings: SearchSettings) -> Void in settings.addOutExtension(str) }, "out-filepattern": { (str: String, settings: SearchSettings) -> Void in settings.addOutFilePattern(str) }, "out-filetype": { (str: String, settings: SearchSettings) -> Void in settings.addOutFileType(str) }, "out-linesafterpattern": { (str: String, settings: SearchSettings) -> Void in settings.addOutLinesAfterPattern(str) }, "out-linesbeforepattern": { (str: String, settings: SearchSettings) -> Void in settings.addOutLinesBeforePattern(str) }, "searchpattern": { (str: String, settings: SearchSettings) -> Void in settings.addSearchPattern(str) }, "settings-file": { (str: String, settings: SearchSettings) -> Void in var error: NSError? self.addSettingsFromFile(str, settings: settings, error: &error) }, ] } private let boolFlagActionDict: [String: (Bool, SearchSettings) -> Void] = [ "allmatches": { (bool: Bool, settings: SearchSettings) -> Void in settings.firstMatch = !bool }, "archivesonly": { (bool: Bool, settings: SearchSettings) -> Void in settings.archivesOnly = bool }, "colorize": { (bool: Bool, settings: SearchSettings) -> Void in settings.colorize = bool }, "debug": { (bool: Bool, settings: SearchSettings) -> Void in settings.debug = bool }, "excludehidden": { (bool: Bool, settings: SearchSettings) -> Void in settings.excludeHidden = bool }, "firstmatch": { (bool: Bool, settings: SearchSettings) -> Void in settings.firstMatch = bool }, "help": { (bool: Bool, settings: SearchSettings) -> Void in settings.printUsage = bool }, "includehidden": { (bool: Bool, settings: SearchSettings) -> Void in settings.excludeHidden = !bool }, "listdirs": { (bool: Bool, settings: SearchSettings) -> Void in settings.listDirs = bool }, "listfiles": { (bool: Bool, settings: SearchSettings) -> Void in settings.listFiles = bool }, "listlines": { (bool: Bool, settings: SearchSettings) -> Void in settings.listLines = bool }, "multilinesearch": { (bool: Bool, settings: SearchSettings) -> Void in settings.multiLineSearch = bool }, "nocolorize": { (bool: Bool, settings: SearchSettings) -> Void in settings.colorize = !bool }, "noprintmatches": { (bool: Bool, settings: SearchSettings) -> Void in settings.printResults = !bool }, "norecursive": { (bool: Bool, settings: SearchSettings) -> Void in settings.recursive = !bool }, "nosearcharchives": { (bool: Bool, settings: SearchSettings) -> Void in settings.searchArchives = !bool }, "printmatches": { (bool: Bool, settings: SearchSettings) -> Void in settings.printResults = bool }, "recursive": { (bool: Bool, settings: SearchSettings) -> Void in settings.recursive = bool }, "searcharchives": { (bool: Bool, settings: SearchSettings) -> Void in settings.searchArchives = bool }, "uniquelines": { (bool: Bool, settings: SearchSettings) -> Void in settings.uniqueLines = bool }, "verbose": { (bool: Bool, settings: SearchSettings) -> Void in settings.verbose = bool }, "version": { (bool: Bool, settings: SearchSettings) -> Void in settings.printVersion = bool }, ] public func settingsFromArgs(_ args: [String], error: NSErrorPointer) -> SearchSettings { var i = 0 let settings = SearchSettings() while i < args.count { var arg = args[i] if arg.hasPrefix("-") { while arg.hasPrefix("-"), arg.lengthOfBytes(using: String.Encoding.utf8) > 1 { arg = String(arg[arg.index(arg.startIndex, offsetBy: 1)...]) } if longArgDict.index(forKey: arg) != nil { let longArg = longArgDict[arg] if argActionDict.index(forKey: longArg!) != nil { if args.count > i + 1 { argActionDict[longArg!]!(args[i + 1], settings) i += 1 } else { setError(error, msg: "Missing argument for option \(arg)") break } } else if boolFlagActionDict.index(forKey: longArg!) != nil { boolFlagActionDict[longArg!]!(true, settings) } else { setError(error, msg: "Invalid option: \(arg)") break } } else { setError(error, msg: "Invalid option: \(arg)") break } } else { settings.startPath = args[i] } i += 1 } return settings } public func settingsFromFile(_ filePath: String, error: NSErrorPointer) -> SearchSettings { let settings = SearchSettings() addSettingsFromFile(filePath, settings: settings, error: error) return settings } public func addSettingsFromFile(_ filePath: String, settings: SearchSettings, error: NSErrorPointer) { do { let fileUrl = URL(fileURLWithPath: filePath) let jsonString = try String(contentsOf: fileUrl, encoding: .utf8) addSettingsFromJson(jsonString, settings: settings, error: error) } catch let error as NSError { print("Failed to load: \(error.localizedDescription)") } } public func settingsFromJson(_ jsonString: String, error: NSErrorPointer) -> SearchSettings { let settings = SearchSettings() addSettingsFromJson(jsonString, settings: settings, error: error) return settings } public func addSettingsFromJson(_ jsonString: String, settings: SearchSettings, error: NSErrorPointer) { do { if let json = try JSONSerialization.jsonObject(with: jsonString.data(using: .utf8)!, options: []) as? [String: Any] { for key in json.keys { if longArgDict.index(forKey: key) != nil { let longArg = longArgDict[key] if argActionDict.index(forKey: longArg!) != nil { let value = json[key] if let string = value as? String { argActionDict[longArg!]!(string, settings) } else if let bool = value as? Bool { argActionDict[longArg!]!(bool.description, settings) } else if let int = value as? Int { argActionDict[longArg!]!(int.description, settings) } else if let stringArray = value as? [String] { for s in stringArray { argActionDict[longArg!]!(s, settings) } } else { setError(error, msg: "Invalid type for \"\(key)\" entry") break } } else if boolFlagActionDict.index(forKey: longArg!) != nil { let value = json[key] if let bool = value as? Bool { boolFlagActionDict[longArg!]!(bool, settings) } else { setError(error, msg: "Invalid type for \"\(key)\" entry") break } } else { setError(error, msg: "Invalid option: \(key)") break } } else if key == "startpath" { let value = json[key] if let string = value as? String { settings.startPath = string } } else { setError(error, msg: "Invalid option: \(key)") break } } } } catch let error as NSError { print("Failed to load: \(error.localizedDescription)") } } public func usage(_ code: Int32 = 0) { logMsg(getUsageString()) exit(code) } func getUsageString() -> String { var str = "\nUsage:\n swiftsearch [options] -s <searchpattern> <startpath>\n\n" str += "Options:\n" let optStrings = searchOptions.map { $0.short.isEmpty ? "--\($0.long)" : "-\($0.short),--\($0.long)" } let optDescs = searchOptions.map(\.desc) let longest = optStrings.map { $0.lengthOfBytes(using: String.Encoding.utf8) }.max()! for i in 0 ..< optStrings.count { var optLine = " \(optStrings[i])" while optLine.lengthOfBytes(using: String.Encoding.utf8) <= longest { optLine += " " } optLine += " \(optDescs[i])\n" str += optLine } return str } }
mit
ab82598a6f0a95fc4ef9124662652dc1
40.773723
108
0.516279
4.832254
false
false
false
false
firebase/firebase-ios-sdk
Firestore/Swift/Tests/Codable/FirestoreEncoderTests.swift
1
21524
/* * 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 * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import Foundation import FirebaseFirestore import FirebaseFirestoreSwift import XCTest class FirestoreEncoderTests: XCTestCase { func testInt() { struct Model: Codable, Equatable { let x: Int } let model = Model(x: 42) let dict = ["x": 42] assertThat(model).roundTrips(to: dict) } func testEmpty() { struct Model: Codable, Equatable {} assertThat(Model()).roundTrips(to: [String: Any]()) } func testString() throws { struct Model: Codable, Equatable { let s: String } assertThat(Model(s: "abc")).roundTrips(to: ["s": "abc"]) } func testOptional() { struct Model: Codable, Equatable { let x: Int let opt: Int? } assertThat(Model(x: 42, opt: nil)).roundTrips(to: ["x": 42]) assertThat(Model(x: 42, opt: 7)).roundTrips(to: ["x": 42, "opt": 7]) assertThat(["x": 42, "opt": 5]).decodes(to: Model(x: 42, opt: 5)) assertThat(["x": 42, "opt": true]).failsDecoding(to: Model.self) assertThat(["x": 42, "opt": "abc"]).failsDecoding(to: Model.self) assertThat(["x": 45.55, "opt": 5]).failsDecoding(to: Model.self) assertThat(["opt": 5]).failsDecoding(to: Model.self) // TODO: - handle encoding keys with nil values // See https://stackoverflow.com/questions/47266862/encode-nil-value-as-null-with-jsonencoder // and https://bugs.swift.org/browse/SR-9232 // XCTAssertTrue(encodedDict.keys.contains("x")) } func testEnum() { enum MyEnum: Codable, Equatable { case num(number: Int) case text(String) case timestamp(Timestamp) private enum CodingKeys: String, CodingKey { case num case text case timestamp } private enum DecodingError: Error { case decoding(String) } init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) if let value = try? values.decode(Int.self, forKey: .num) { self = .num(number: value) return } if let value = try? values.decode(String.self, forKey: .text) { self = .text(value) return } if let value = try? values.decode(Timestamp.self, forKey: .timestamp) { self = .timestamp(value) return } throw DecodingError.decoding("Decoding error: \(dump(values))") } func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) switch self { case let .num(number): try container.encode(number, forKey: .num) case let .text(value): try container.encode(value, forKey: .text) case let .timestamp(stamp): try container.encode(stamp, forKey: .timestamp) } } } struct Model: Codable, Equatable { let x: Int let e: MyEnum } assertThat(Model(x: 42, e: MyEnum.num(number: 4))) .roundTrips(to: ["x": 42, "e": ["num": 4]]) assertThat(Model(x: 43, e: MyEnum.text("abc"))) .roundTrips(to: ["x": 43, "e": ["text": "abc"]]) let timestamp = Timestamp(date: Date()) assertThat(Model(x: 43, e: MyEnum.timestamp(timestamp))) .roundTrips(to: ["x": 43, "e": ["timestamp": timestamp]]) } func testGeoPoint() { struct Model: Codable, Equatable { let p: GeoPoint } let geopoint = GeoPoint(latitude: 1, longitude: -2) assertThat(Model(p: geopoint)).roundTrips(to: ["p": geopoint]) } func testDate() { struct Model: Codable, Equatable { let date: Date } let date = Date(timeIntervalSinceReferenceDate: 0) assertThat(Model(date: date)).roundTrips(to: ["date": Timestamp(date: date)]) } func testTimestampCanDecodeAsDate() { struct EncodingModel: Codable, Equatable { let date: Timestamp } struct DecodingModel: Codable, Equatable { let date: Date } let date = Date(timeIntervalSinceReferenceDate: 0) let timestamp = Timestamp(date: date) assertThat(EncodingModel(date: timestamp)) .encodes(to: ["date": timestamp]) .decodes(to: DecodingModel(date: date)) } func testDocumentReference() { struct Model: Codable, Equatable { let doc: DocumentReference } let d = FSTTestDocRef("abc/xyz") assertThat(Model(doc: d)).roundTrips(to: ["doc": d]) } func testEncodingDocumentReferenceThrowsWithJSONEncoder() { assertThat(FSTTestDocRef("abc/xyz")).failsEncodingWithJSONEncoder() } func testEncodingDocumentReferenceNotEmbeddedThrows() { assertThat(FSTTestDocRef("abc/xyz")).failsEncodingAtTopLevel() } func testTimestamp() { struct Model: Codable, Equatable { let timestamp: Timestamp } let t = Timestamp(date: Date()) assertThat(Model(timestamp: t)).roundTrips(to: ["timestamp": t]) } func testBadValue() { struct Model: Codable, Equatable { let x: Int } assertThat(["x": "abc"]).failsDecoding(to: Model.self) // Wrong type } func testValueTooBig() { struct Model: Codable, Equatable { let x: CChar } assertThat(Model(x: 42)).roundTrips(to: ["x": 42]) assertThat(["x": 12345]).failsDecoding(to: Model.self) // Overflow } // Inspired by https://github.com/firebase/firebase-android-sdk/blob/master/firebase-firestore/src/test/java/com/google/firebase/firestore/util/MapperTest.java func testBeans() { struct Model: Codable, Equatable { let s: String let d: Double let f: Float let l: CLongLong let i: Int let b: Bool let sh: CShort let byte: CChar let uchar: CUnsignedChar let ai: [Int] let si: [String] let caseSensitive: String let casESensitive: String let casESensitivE: String } let model = Model( s: "abc", d: 123, f: -4, l: 1_234_567_890_123, i: -4444, b: false, sh: 123, byte: 45, uchar: 44, ai: [1, 2, 3, 4], si: ["abc", "def"], caseSensitive: "aaa", casESensitive: "bbb", casESensitivE: "ccc" ) let dict = [ "s": "abc", "d": 123, "f": -4, "l": Int64(1_234_567_890_123), "i": -4444, "b": false, "sh": 123, "byte": 45, "uchar": 44, "ai": [1, 2, 3, 4], "si": ["abc", "def"], "caseSensitive": "aaa", "casESensitive": "bbb", "casESensitivE": "ccc", ] as [String: Any] assertThat(model).roundTrips(to: dict) } func testCodingKeysCanCustomizeEncodingAndDecoding() throws { struct Model: Codable, Equatable { var s: String var ms: String = "filler" var d: Double var md: Double = 42.42 // Use CodingKeys to only encode part of the struct. enum CodingKeys: String, CodingKey { case s case d } } assertThat(Model(s: "abc", ms: "dummy", d: 123.3, md: 0)) .encodes(to: ["s": "abc", "d": 123.3]) .decodes(to: Model(s: "abc", ms: "filler", d: 123.3, md: 42.42)) } func testNestedObjects() { struct SecondLevelNestedModel: Codable, Equatable { var age: Int8 var weight: Double } struct NestedModel: Codable, Equatable { var group: String var groupList: [SecondLevelNestedModel] var groupMap: [String: SecondLevelNestedModel] var point: GeoPoint } struct Model: Codable, Equatable { var id: Int64 var group: NestedModel } let model = Model( id: 123, group: NestedModel( group: "g1", groupList: [ SecondLevelNestedModel(age: 20, weight: 80.1), SecondLevelNestedModel(age: 25, weight: 85.1), ], groupMap: [ "name1": SecondLevelNestedModel(age: 30, weight: 64.2), "name2": SecondLevelNestedModel(age: 35, weight: 79.2), ], point: GeoPoint(latitude: 12.0, longitude: 9.1) ) ) let dict = [ "group": [ "group": "g1", "point": GeoPoint(latitude: 12.0, longitude: 9.1), "groupList": [ [ "age": 20, "weight": 80.1, ], [ "age": 25, "weight": 85.1, ], ], "groupMap": [ "name1": [ "age": 30, "weight": 64.2, ], "name2": [ "age": 35, "weight": 79.2, ], ], ], "id": 123, ] as [String: Any] assertThat(model).roundTrips(to: dict) } func testCollapsingNestedObjects() { // The model is flat but the document has a nested Map. struct Model: Codable, Equatable { var id: Int64 var name: String init(id: Int64, name: String) { self.id = id self.name = name } private enum CodingKeys: String, CodingKey { case id case nested } private enum NestedCodingKeys: String, CodingKey { case name } init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) try id = container.decode(Int64.self, forKey: .id) let nestedContainer = try container .nestedContainer(keyedBy: NestedCodingKeys.self, forKey: .nested) try name = nestedContainer.decode(String.self, forKey: .name) } func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(id, forKey: .id) var nestedContainer = container .nestedContainer(keyedBy: NestedCodingKeys.self, forKey: .nested) try nestedContainer.encode(name, forKey: .name) } } assertThat(Model(id: 12345, name: "ModelName")) .roundTrips(to: [ "id": 12345, "nested": ["name": "ModelName"], ]) } class SuperModel: Codable, Equatable { var superPower: Double? = 100.0 var superName: String? = "superName" init(power: Double, name: String) { superPower = power superName = name } static func == (lhs: SuperModel, rhs: SuperModel) -> Bool { return (lhs.superName == rhs.superName) && (lhs.superPower == rhs.superPower) } private enum CodingKeys: String, CodingKey { case superPower case superName } required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) superPower = try container.decode(Double.self, forKey: .superPower) superName = try container.decode(String.self, forKey: .superName) } func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(superPower, forKey: .superPower) try container.encode(superName, forKey: .superName) } } class SubModel: SuperModel { var timestamp: Timestamp? = Timestamp(seconds: 848_483_737, nanoseconds: 23423) init(power: Double, name: String, seconds: Int64, nano: Int32) { super.init(power: power, name: name) timestamp = Timestamp(seconds: seconds, nanoseconds: nano) } static func == (lhs: SubModel, rhs: SubModel) -> Bool { return ((lhs as SuperModel) == (rhs as SuperModel)) && (lhs.timestamp == rhs.timestamp) } private enum CodingKeys: String, CodingKey { case timestamp } required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) timestamp = try container.decode(Timestamp.self, forKey: .timestamp) try super.init(from: container.superDecoder()) } override func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(timestamp, forKey: .timestamp) try super.encode(to: container.superEncoder()) } } func testClassHierarchy() { assertThat(SubModel(power: 100, name: "name", seconds: 123_456_789, nano: 654_321)) .roundTrips(to: [ "super": ["superPower": 100, "superName": "name"], "timestamp": Timestamp(seconds: 123_456_789, nanoseconds: 654_321), ]) } func testEncodingEncodableArrayNotSupported() { struct Model: Codable, Equatable { var name: String } assertThat([Model(name: "1")]).failsToEncode() } func testFieldValuePassthrough() throws { struct Model: Encodable, Equatable { var fieldValue: FieldValue } assertThat(Model(fieldValue: FieldValue.delete())) .encodes(to: ["fieldValue": FieldValue.delete()]) } func testEncodingFieldValueNotEmbeddedThrows() { let ts = FieldValue.serverTimestamp() assertThat(ts).failsEncodingAtTopLevel() } func testServerTimestamp() throws { struct Model: Codable, Equatable { @ServerTimestamp var timestamp: Timestamp? = nil } // Encoding a pending server timestamp assertThat(Model()) .encodes(to: ["timestamp": FieldValue.serverTimestamp()]) // Encoding a resolved server timestamp yields a timestamp; decoding // yields it back. let timestamp = Timestamp(seconds: 123_456_789, nanoseconds: 4321) assertThat(Model(timestamp: timestamp)) .roundTrips(to: ["timestamp": timestamp]) // Decoding a NSNull() leads to nil. assertThat(["timestamp": NSNull()]) .decodes(to: Model(timestamp: nil)) } func testServerTimestampOfDate() throws { struct Model: Codable, Equatable { @ServerTimestamp var date: Date? = nil } // Encoding a pending server timestamp assertThat(Model()) .encodes(to: ["date": FieldValue.serverTimestamp()]) // Encoding a resolved server timestamp yields a timestamp; decoding // yields it back. let timestamp = Timestamp(seconds: 123_456_789, nanoseconds: 0) let date: Date = timestamp.dateValue() assertThat(Model(date: date)) .roundTrips(to: ["date": timestamp]) // Decoding a NSNull() leads to nil. assertThat(["date": NSNull()]) .decodes(to: Model(date: nil)) } func testServerTimestampUserType() throws { struct Model: Codable, Equatable { @ServerTimestamp var timestamp: String? = nil } // Encoding a pending server timestamp assertThat(Model()) .encodes(to: ["timestamp": FieldValue.serverTimestamp()]) // Encoding a resolved server timestamp yields a timestamp; decoding // yields it back. let timestamp = Timestamp(seconds: 1_570_484_031, nanoseconds: 122_999_906) assertThat(Model(timestamp: "2019-10-07T21:33:51.123Z")) .roundTrips(to: ["timestamp": timestamp]) assertThat(Model(timestamp: "Invalid date")) .failsToEncode() } func testExplicitNull() throws { struct Model: Codable, Equatable { @ExplicitNull var name: String? } assertThat(Model(name: nil)) .roundTrips(to: ["name": NSNull()]) assertThat(Model(name: "good name")) .roundTrips(to: ["name": "good name"]) } func testAutomaticallyPopulatesDocumentIDOnDocumentReference() throws { struct Model: Codable, Equatable { var name: String @DocumentID var docId: DocumentReference? } assertThat(["name": "abc"], in: "abc/123") .decodes(to: Model(name: "abc", docId: FSTTestDocRef("abc/123"))) } func testAutomaticallyPopulatesDocumentIDOnString() throws { struct Model: Codable, Equatable { var name: String @DocumentID var docId: String? } assertThat(["name": "abc"], in: "abc/123") .decodes(to: Model(name: "abc", docId: "123")) } func testDocumentIDIgnoredInEncoding() throws { struct Model: Codable, Equatable { var name: String @DocumentID var docId: DocumentReference? } assertThat(Model(name: "abc", docId: FSTTestDocRef("abc/123"))) .encodes(to: ["name": "abc"]) } func testDocumentIDWithJsonEncoderThrows() { assertThat(DocumentID(wrappedValue: FSTTestDocRef("abc/xyz"))) .failsEncodingWithJSONEncoder() } func testDecodingDocumentIDWithConfictingFieldsDoesNotThrow() throws { struct Model: Codable, Equatable { var name: String @DocumentID var docId: DocumentReference? } _ = try Firestore.Decoder().decode( Model.self, from: ["name": "abc", "docId": "Does not cause conflict"], in: FSTTestDocRef("abc/123") ) } } private func assertThat(_ dictionary: [String: Any], in document: String? = nil, file: StaticString = #file, line: UInt = #line) -> DictionarySubject { return DictionarySubject(dictionary, in: document, file: file, line: line) } private func assertThat<X: Equatable & Codable>(_ model: X, file: StaticString = #file, line: UInt = #line) -> CodableSubject<X> { return CodableSubject(model, file: file, line: line) } private func assertThat<X: Equatable & Encodable>(_ model: X, file: StaticString = #file, line: UInt = #line) -> EncodableSubject<X> { return EncodableSubject(model, file: file, line: line) } private class EncodableSubject<X: Equatable & Encodable> { var subject: X var file: StaticString var line: UInt init(_ subject: X, file: StaticString, line: UInt) { self.subject = subject self.file = file self.line = line } @discardableResult func encodes(to expected: [String: Any]) -> DictionarySubject { let encoded = assertEncodes(to: expected) return DictionarySubject(encoded, file: file, line: line) } func failsToEncode() { do { _ = try Firestore.Encoder().encode(subject) } catch { return } XCTFail("Failed to throw") } func failsEncodingWithJSONEncoder() { do { _ = try JSONEncoder().encode(subject) XCTFail("Failed to throw", file: file, line: line) } catch FirestoreEncodingError.encodingIsNotSupported { return } catch { XCTFail("Unrecognized error: \(error)", file: file, line: line) } } func failsEncodingAtTopLevel() { do { _ = try Firestore.Encoder().encode(subject) XCTFail("Failed to throw", file: file, line: line) } catch EncodingError.invalidValue(_, _) { return } catch { XCTFail("Unrecognized error: \(error)", file: file, line: line) } } private func assertEncodes(to expected: [String: Any]) -> [String: Any] { do { let enc = try Firestore.Encoder().encode(subject) XCTAssertEqual(enc as NSDictionary, expected as NSDictionary, file: file, line: line) return enc } catch { XCTFail("Failed to encode \(X.self): error: \(error)") return ["": -1] } } } private class CodableSubject<X: Equatable & Codable>: EncodableSubject<X> { func roundTrips(to expected: [String: Any]) { let reverseSubject = encodes(to: expected) reverseSubject.decodes(to: subject) } } private class DictionarySubject { var subject: [String: Any] var document: DocumentReference? var file: StaticString var line: UInt init(_ subject: [String: Any], in documentName: String? = nil, file: StaticString, line: UInt) { self.subject = subject if let documentName = documentName { document = FSTTestDocRef(documentName) } self.file = file self.line = line } func decodes<X: Equatable & Codable>(to expected: X) -> Void { do { let decoded = try Firestore.Decoder().decode(X.self, from: subject, in: document) XCTAssertEqual(decoded, expected) } catch { XCTFail("Failed to decode \(X.self): \(error)", file: file, line: line) } } func failsDecoding<X: Equatable & Codable>(to _: X.Type) -> Void { XCTAssertThrowsError(try Firestore.Decoder().decode(X.self, from: subject), file: file, line: line) } } enum DateError: Error { case invalidDate(String) } // Extends Strings to allow them to be wrapped with @ServerTimestamp. Resolved // server timestamps will be stored in an ISO 8601 date format. // // This example exists outside the main implementation to show that users can // extend @ServerTimestamp with arbitrary types. extension String: ServerTimestampWrappable { static let formatter: DateFormatter = { let formatter = DateFormatter() formatter.calendar = Calendar(identifier: .iso8601) formatter.locale = Locale(identifier: "en_US_POSIX") formatter.timeZone = TimeZone(secondsFromGMT: 0) formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSXXXXX" return formatter }() public static func wrap(_ timestamp: Timestamp) throws -> Self { return formatter.string(from: timestamp.dateValue()) } public static func unwrap(_ value: Self) throws -> Timestamp { let date = formatter.date(from: value) if let date = date { return Timestamp(date: date) } else { throw DateError.invalidDate(value) } } }
apache-2.0
9683a0dc25d20425ad3be9e44a9cc527
28.647383
161
0.62284
4.016421
false
true
false
false
ninewine/SaturnTimer
SaturnTimer/View/ActionButton/AnimatableGearLayer.swift
1
1314
// // AnimatableGearLayer.swift // SaturnTimer // // Created by Tidy Nine on 2/26/16. // Copyright © 2016 Tidy Nine. All rights reserved. // import UIKit class AnimatableGearLayer: AnimatableLayer { fileprivate let _gear: CAShapeLayer = CAShapeLayer () required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } init(frame: CGRect) { super.init() _gear.frame = frame _gear.position = CGPoint(x: frame.width * 0.5, y: frame.height * 0.5) _gear.path = _ActionButtonLayerPath.gearPath.cgPath _gear.strokeColor = HelperColor.lightGrayColor.cgColor _gear.fillColor = UIColor.clear.cgColor _gear.colorType = ShapeLayerColorType.stroke _gear.strokeEnd = 0.0 addSublayer(_gear) } override func layersNeedToBeHighlighted() -> [CAShapeLayer]? { return [_gear] } override func transitionIn(_ completion: (() -> ())?) { _gear.pathStokeAnimationFrom(nil, to: 1.0, duration: transitionDuration, type: .end) { () -> Void in if let block = completion { block() } } } override func transitionOut(_ completion: (() -> ())?) { _gear.pathStokeAnimationFrom(nil, to: 0.0, duration: transitionDuration, type: .end) { () -> Void in if let block = completion { block () } } } }
mit
125005ae9115ff2759050d33df79ca17
25.26
104
0.638995
3.762178
false
false
false
false
agilie/AGCircularPicker
Example/AGCircularPicker/MultiPickerViewController.swift
1
3471
// // MultiPickerViewController.swift // AGCircularPicker // // Created by Sergii Avilov on 6/23/17. // Copyright © 2017 CocoaPods. All rights reserved. // import UIKit import AGCircularPicker class MultiPickerViewController: UIViewController { @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var circularPicker: AGCircularPicker! override func viewDidLoad() { super.viewDidLoad() let hourColor1 = UIColor.rgb_color(r: 0, g: 237, b: 233) let hourColor2 = UIColor.rgb_color(r: 0, g: 135, b: 217) let hourColor3 = UIColor.rgb_color(r: 138, g: 28, b: 195) let hourTitleOption = AGCircularPickerTitleOption(title: "hours") let hourValueOption = AGCircularPickerValueOption(minValue: 0, maxValue: 23, rounds: 2, initialValue: 15) let hourColorOption = AGCircularPickerColorOption(gradientColors: [hourColor1, hourColor2, hourColor3], gradientAngle: 20) let hourOption = AGCircularPickerOption(valueOption: hourValueOption, titleOption: hourTitleOption, colorOption: hourColorOption) let minuteColor1 = UIColor.rgb_color(r: 255, g: 141, b: 0) let minuteColor2 = UIColor.rgb_color(r: 255, g: 0, b: 88) let minuteColor3 = UIColor.rgb_color(r: 146, g: 0, b: 132) let minuteColorOption = AGCircularPickerColorOption(gradientColors: [minuteColor1, minuteColor2, minuteColor3], gradientAngle: -20) let minuteTitleOption = AGCircularPickerTitleOption(title: "minutes") let minuteValueOption = AGCircularPickerValueOption(minValue: 0, maxValue: 59) let minuteOption = AGCircularPickerOption(valueOption: minuteValueOption, titleOption: minuteTitleOption, colorOption: minuteColorOption) let secondTitleOption = AGCircularPickerTitleOption(title: "seconds") let secondColorOption = AGCircularPickerColorOption(gradientColors: [hourColor3, hourColor2, hourColor1]) let secondOption = AGCircularPickerOption(valueOption: minuteValueOption, titleOption: secondTitleOption, colorOption: secondColorOption) circularPicker.options = [hourOption, minuteOption, secondOption] circularPicker.delegate = self } @IBAction func close(_ sender: Any) { navigationController?.popViewController(animated: true) } } extension MultiPickerViewController: AGCircularPickerDelegate { func didChangeValues(_ values: Array<AGColorValue>, selectedIndex: Int) { let valueComponents = values.map { return String(format: "%02d", $0.value) } let fullString = valueComponents.joined(separator: ":") let attributedString = NSMutableAttributedString(string:fullString) let fullRange = (fullString as NSString).range(of: fullString) attributedString.addAttribute(NSForegroundColorAttributeName, value: UIColor.white.withAlphaComponent(0.5), range: fullRange) attributedString.addAttribute(NSFontAttributeName, value: UIFont.systemFont(ofSize: 28, weight: UIFontWeightBold), range: fullRange) let range = NSMakeRange(selectedIndex * 2 + selectedIndex, 2) attributedString.addAttribute(NSForegroundColorAttributeName, value: values[selectedIndex].color, range: range) attributedString.addAttribute(NSFontAttributeName, value: UIFont.systemFont(ofSize: 35, weight: UIFontWeightBlack), range: range) titleLabel.attributedText = attributedString } }
mit
335652a7f229633aea3a0d130853c07e
52.384615
145
0.726225
4.454429
false
false
false
false
JimiHFord/Exploding-Monkeys
ExplodingMonkeys/ExplodingMonkeys/GameViewController.swift
1
4526
// // GameViewController.swift // ExplodingMonkeys // // Created by James Ford on 6/2/15. // Copyright (c) 2015 JWorks. All rights reserved. // import UIKit import SpriteKit extension SKNode { class func unarchiveFromFile(file : String) -> SKNode? { if let path = NSBundle.mainBundle().pathForResource(file, ofType: "sks") { var sceneData = NSData(contentsOfFile: path, options: .DataReadingMappedIfSafe, error: nil)! var archiver = NSKeyedUnarchiver(forReadingWithData: sceneData) archiver.setClass(self.classForKeyedUnarchiver(), forClassName: "SKScene") let scene = archiver.decodeObjectForKey(NSKeyedArchiveRootObjectKey) as! GameScene archiver.finishDecoding() return scene } else { return nil } } } class GameViewController: UIViewController { var currentGame: GameScene! @IBOutlet weak var angleSlider: UISlider! @IBOutlet weak var angleLabel: UILabel! @IBOutlet weak var velocitySlider: UISlider! @IBOutlet weak var velocityLabel: UILabel! @IBOutlet weak var launchButton: UIButton! @IBOutlet weak var playerLabel: UILabel! let defaultAngle = 45.0 let defaultVelocity = 125.0 var currentPlayer: Int = 1 var player1values = (45, 125) var player2values = (45, 125) override func viewDidLoad() { super.viewDidLoad() if let scene = GameScene.unarchiveFromFile("GameScene") as? GameScene { // Configure the view. let skView = self.view as! SKView skView.showsFPS = true skView.showsNodeCount = true /* Sprite Kit applies additional optimizations to improve rendering performance */ skView.ignoresSiblingOrder = true /* Set the scale mode to scale to fit the window */ scene.scaleMode = .AspectFill skView.presentScene(scene) scene.viewController = self currentGame = scene } } override func shouldAutorotate() -> Bool { return true } override func supportedInterfaceOrientations() -> Int { if UIDevice.currentDevice().userInterfaceIdiom == .Phone { return Int(UIInterfaceOrientationMask.AllButUpsideDown.rawValue) } else { return Int(UIInterfaceOrientationMask.All.rawValue) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Release any cached data, images, etc that aren't in use. } override func prefersStatusBarHidden() -> Bool { return true } @IBAction func angleChanged(sender: UISlider!) { updateAngleText() } func updateAngleText() { angleLabel.text = "\(Int(angleSlider.value))°" } @IBAction func velocityChanged(sender: UISlider!) { updateVelocityText() } func updateVelocityText() { velocityLabel.text = "\(Int(velocitySlider.value))/250" } @IBAction func launch(sender: AnyObject) { angleSlider.hidden = true angleLabel.hidden = true velocitySlider.hidden = true velocityLabel.hidden = true launchButton.hidden = true playerLabel.hidden = true var values = (Int(angleSlider.value), Int(velocitySlider.value)) if currentPlayer == 1 { player1values = values } else { player2values = values } currentGame.launch(angle: Int(angleSlider.value), velocity: Int(velocitySlider.value)) } func setCurrentGame(scene: GameScene, first: Int) { self.currentGame = scene currentPlayer = first } func setPlayerNumber(number: Int) { if number == 1 { playerLabel.text = "<<< PLAYER ONE" angleSlider.value = Float(player1values.0) velocitySlider.value = Float(player1values.1) } else { playerLabel.text = "PLAYER TWO >>>" angleSlider.value = Float(player2values.0) velocitySlider.value = Float(player2values.1) } updateAngleText() updateVelocityText() currentPlayer = number angleSlider.hidden = false angleLabel.hidden = false velocitySlider.hidden = false velocityLabel.hidden = false launchButton.hidden = false playerLabel.hidden = false } }
mit
b3005fa479f55237af5e637652d4e2f4
29.993151
104
0.615028
5.011074
false
false
false
false
mort3m/xcassets-generator
main.swift
1
5361
#!/usr/bin/swift //.xcassets Generator import Foundation ‚ //let args = ["", "directory", "images.xcassets"] let args = Process.arguments let fileManager = NSFileManager() var inputDirectory: String? var outputAssetDirectory: String? //Helper methods func isDirectory(path: String) -> Bool { var isDir: ObjCBool = false if fileManager.fileExistsAtPath(path, isDirectory: &isDir) { return Bool(isDir) } return false } func checkArgs(args: [String]) -> Bool { if args.count == 3 { if isDirectory(args[1]) && args[2].hasSuffix(".xcassets") { inputDirectory = args[1] outputAssetDirectory = args[2] return true } } return false } func createDir(path: String) { do { try fileManager.createDirectoryAtPath(path, withIntermediateDirectories: false, attributes: nil) } catch _ as NSError { } } func copyFile(from: String, to: String) { do { try fileManager.copyItemAtPath(from, toPath: to) } catch _ as NSError { } } func infoJson() -> NSData { let json = [ "info": [ "version": 1, "author": "mort3m" ] ] return try! NSJSONSerialization.dataWithJSONObject(json, options: .PrettyPrinted) } func generateJSON(dir: String) -> NSData? { do { let files = try fileManager.contentsOfDirectoryAtPath(dir) var json = [String : AnyObject]() var imagesJson = [AnyObject]() for file in files { if file.hasSuffix(".png") { let name = (file as NSString).lastPathComponent //get scale - crap. var scale = "1x" if let scaleAt = file.rangeOfString("@") { var scaleRange = scaleAt scaleRange.endIndex = scaleRange.endIndex.advancedBy(2) scaleRange.startIndex = scaleRange.startIndex.advancedBy(1) scale = file.substringWithRange(scaleRange) } let imageJson: [String: AnyObject] = [ "idiom": "universal", "scale": scale, "filename": name ] imagesJson.append(imageJson) } } json["images"] = imagesJson json["info"] = [ "version" : 1, "author" : "mort3m" ] return try NSJSONSerialization.dataWithJSONObject(json, options: .PrettyPrinted) } catch _ as NSError { } return nil } //Entry Point if checkArgs(args) { //\u{001B}[0;36m print("") print("\u{001B}[0;36m [info] \u{001B}[0;37m started.") //Create xcassets folder createDir(outputAssetDirectory!) do { try infoJson().writeToFile("\(outputAssetDirectory!)/Contents.json", options: .AtomicWrite) } catch { } var enumerator: NSDirectoryEnumerator = fileManager.enumeratorAtPath(inputDirectory!)! var images = [String:[(old: String, new: String)]]() //Create subfolders while let element = enumerator.nextObject() as? String { if element.hasSuffix(".png") { // checks the extension var filename = (element as NSString).lastPathComponent var imageset = filename imageset = imageset.stringByReplacingOccurrencesOfString(".png", withString: "") imageset = imageset.characters.split{$0 == "@"}.map(String.init)[0] imageset += ".imageset" var filePath = (element as NSString).stringByDeletingLastPathComponent if images[filename] == nil { images[filename] = [(old: element, new: "\(filePath)/\(imageset)/\(filename)")] createDir("\(outputAssetDirectory!)/\(filePath)/\(imageset)") } else { images[filename]!.append((old: element, new: "\(filePath)/\(imageset)/\(filename)")) } } else if isDirectory("\(inputDirectory!)/\(element)") { createDir("\(outputAssetDirectory!)/\(element)") } } //copy images for imageName in images.keys { for imagePath in images[imageName]! { let output = "\(outputAssetDirectory!)/\(imagePath.new)" let input = "\(inputDirectory!)/\(imagePath.old)" copyFile(input, to: output) } } //Generate JSON per Folder enumerator = fileManager.enumeratorAtPath(outputAssetDirectory!)! while let element = enumerator.nextObject() as? String { if element.hasSuffix(".imageset") { do { if let json = generateJSON("\(outputAssetDirectory!)/\(element)") { try json.writeToFile("\(outputAssetDirectory!)/\(element)/Contents.json", options: .AtomicWrite) } } catch { } } else { do { try infoJson().writeToFile("\(outputAssetDirectory!)/\(element)/Contents.json", options: .AtomicWrite) } catch { } } } print("\u{001B}[0;32m [done] \u{001B}[0;37m moved \(images.count) images.") print("") } else { print("\u{001B}[0;31m [error] \u{001B}[0;37m Usage: ./generator.swift \"dir\" \".xcasset file\"") }
mit
1eb09f48ceb433449d2dd50ba4996c57
30.523529
118
0.554581
4.627807
false
false
false
false
vczhou/twitter_feed
TwitterDemo/DetailTweetViewController.swift
1
5482
// // DetailTweetViewController.swift // TwitterDemo // // Created by Victoria Zhou on 2/27/17. // Copyright © 2017 Victoria Zhou. All rights reserved. // import UIKit class DetailTweetViewController: UIViewController { @IBOutlet weak var profImageView: UIImageView! @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var handleLabel: UILabel! @IBOutlet weak var tweetLabel: UILabel! @IBOutlet weak var timestampLabel: UILabel! @IBOutlet weak var retweetCountLabel: UILabel! @IBOutlet weak var favoriteCountLabel: UILabel! @IBOutlet weak var replyButton: UIButton! @IBOutlet weak var retweetButton: UIButton! @IBOutlet weak var favButton: UIButton! var tweet: Tweet! override func viewDidLoad() { super.viewDidLoad() let tweeter = tweet.user! profImageView.setImageWith((tweeter.profileUrl)!) nameLabel.text = tweeter.name handleLabel.text = "@\(tweeter.screenname!)" timestampLabel.text = tweet.timestamp?.description tweetLabel.text = tweet.text retweetCountLabel.text = "\(tweet.retweetCount)" favoriteCountLabel.text = "\(tweet.favoriteCount)" if (tweet.favorited) { favButton.setBackgroundImage(#imageLiteral(resourceName: "favor-icon-red"), for: .normal) } else { favButton.setBackgroundImage(#imageLiteral(resourceName: "favor-icon"), for: .normal) } favButton.setTitle("", for: .normal) if(tweet.retweeted){ retweetButton.setBackgroundImage(#imageLiteral(resourceName: "retweet-icon-green"), for: .normal) } else { retweetButton.setBackgroundImage(#imageLiteral(resourceName: "retweet-icon"), for: .normal) } retweetButton.setTitle("", for: .normal) replyButton.setBackgroundImage(#imageLiteral(resourceName: "reply-icon"), for: .normal) replyButton.setTitle("", for: .normal) // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func onReplyButton(_ sender: Any) { performSegue(withIdentifier: "compose", sender: self) } @IBAction func onRetweetButton(_ sender: Any) { if(!tweet.retweeted) { TwitterClient.sharedInstance.retweet(id: tweet.id!, success: { (t: Tweet) in self.retweetButton.setBackgroundImage(#imageLiteral(resourceName: "retweet-icon-green"), for: .normal) self.tweet.retweetCount += 1 self.retweetCountLabel.text = "\(self.tweet.retweetCount)" }, failure: {(error: Error) -> () in print(error.localizedDescription) }) self.tweet.retweeted = true } else { TwitterClient.sharedInstance.unretweet(id: tweet.id!, success: { (t: Tweet) in self.retweetButton.setBackgroundImage(#imageLiteral(resourceName: "retweet-icon"), for: .normal) self.tweet.retweetCount -= 1 self.retweetCountLabel.text = "\(self.tweet.retweetCount)" }, failure: {(error: Error) -> () in print(error.localizedDescription) }) self.tweet.retweeted = false } } @IBAction func onFavButton(_ sender: Any) { if(!tweet.favorited) { TwitterClient.sharedInstance.favorite(id: tweet.id!, success: { (b: NSDictionary) in self.favButton.setBackgroundImage(#imageLiteral(resourceName: "favor-icon-red"), for: .normal) self.tweet.favoriteCount += 1 self.favoriteCountLabel.text = "\(self.tweet.favoriteCount)" self.tweet.favorited = true }) { (error: Error) in print(error.localizedDescription) } } else { TwitterClient.sharedInstance.unfavorite(id: tweet.id!, success: { (b: NSDictionary) in self.favButton.setBackgroundImage(#imageLiteral(resourceName: "favor-icon"), for: .normal) self.tweet.favoriteCount -= 1 self.favoriteCountLabel.text = "\(self.tweet.favoriteCount)" self.tweet.favorited = false }) { (error: Error) in print(error.localizedDescription) } } } // 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. print("Prepare for segue called") print(segue.identifier ?? "no identifier") if (segue.identifier == "compose"){ print("Hello ") let destination = segue.destination as! ComposeTweetViewController destination.isReply = true destination.replyText = "@\(tweet.user!.screenname!)" } if (segue.identifier == "userDetail") { print("Hello hello") let cell = sender as! TweetCell let destination = segue.destination as! ProfileViewController destination.user = cell.tweet.user } } }
apache-2.0
3278e4249677e4370c4a9a5e81c875f5
39.007299
118
0.615399
4.969175
false
false
false
false
rmirabelli/UofD-Fall2017
TextInAndOut/TextInAndOut/LoginViewController.swift
1
1643
// // LoginViewController.swift // TextInAndOut // // Created by Russell Mirabelli on 10/24/17. // Copyright © 2017 Russell Mirabelli. All rights reserved. // import UIKit class LoginViewController: UIViewController { @IBOutlet weak var nameTextField: UITextField! @IBOutlet weak var passwordTextField: UITextField! override func viewDidLoad() { super.viewDidLoad() nameTextField.delegate = self if let username = UserDefaults.standard.string(forKey: "username") { nameTextField.text = username } } @IBAction func goButtonTapped(_ sender: Any) { print(nameTextField.text ?? "no name") print(passwordTextField.text ?? "no password") UserDefaults.standard.set(nameTextField.text ?? "", forKey: "username") UserDefaults.standard.synchronize() } } extension LoginViewController: UITextFieldDelegate { func textFieldDidBeginEditing(_ textField: UITextField) { print("begin") } // handling return button should be in "textFieldShouldReturn". func textFieldShouldReturn(_ textField: UITextField) -> Bool { if textField == nameTextField { passwordTextField.becomeFirstResponder() } if textField == passwordTextField && !(nameTextField.text?.isEmpty ?? false) { passwordTextField.resignFirstResponder() } return true } func textFieldShouldEndEditing(_ textField: UITextField) -> Bool { return true } func textFieldDidEndEditing(_ textField: UITextField) { } }
mit
210f6a9486613ffd0d4e04c05dad2adc
26.366667
86
0.641291
5.383607
false
false
false
false
sarahspins/Loop
Loop/Models/MLabService.swift
2
4029
// // mLabService.swift // Loop // // Created by Nate Racklyeft on 7/3/16. // Copyright © 2016 Nathan Racklyeft. All rights reserved. // import Foundation private let mLabAPIHost = NSURL(string: "https://api.mongolab.com/api/1/databases")! struct MLabService: ServiceAuthentication { var credentials: [ServiceCredential] let title: String = NSLocalizedString("mLab", comment: "The title of the mLab service") init(databaseName: String?, APIKey: String?) { credentials = [ ServiceCredential( title: NSLocalizedString("Database", comment: "The title of the mLab database name credential"), placeholder: "nightscoutdb", isSecret: false, keyboardType: .ASCIICapable, value: databaseName ), ServiceCredential( title: NSLocalizedString("API Key", comment: "The title of the mLab API Key credential"), placeholder: nil, isSecret: false, keyboardType: .ASCIICapable, value: APIKey ) ] if databaseName != nil && APIKey != nil { isAuthorized = true } } var databaseName: String? { return credentials[0].value } var APIKey: String? { return credentials[1].value } private(set) var isAuthorized: Bool = false mutating func verify(completion: (success: Bool, error: ErrorType?) -> Void) { guard let APIURL = APIURLForCollection("") else { completion(success: false, error: nil) return } NSURLSession.sharedSession().dataTaskWithURL(APIURL) { (_, response, error) in var error: ErrorType? = error if error == nil, let response = response as? NSHTTPURLResponse where response.statusCode >= 300 { error = LoopError.ConnectionError } self.isAuthorized = error == nil completion(success: self.isAuthorized, error: error) }.resume() } mutating func reset() { credentials[0].value = nil credentials[1].value = nil isAuthorized = false } private func APIURLForCollection(collection: String) -> NSURL? { guard let databaseName = databaseName, APIKey = APIKey else { return nil } let APIURL = mLabAPIHost.URLByAppendingPathComponent("\(databaseName)/collections").URLByAppendingPathComponent(collection) let components = NSURLComponents(URL: APIURL, resolvingAgainstBaseURL: true)! var items = components.queryItems ?? [] items.append(NSURLQueryItem(name: "apiKey", value: APIKey)) components.queryItems = items return components.URL } func uploadTaskWithData(data: NSData, inCollection collection: String) -> NSURLSessionTask? { guard let URL = APIURLForCollection(collection) else { return nil } let request = NSMutableURLRequest(URL: URL) request.HTTPMethod = "POST" request.setValue("application/json", forHTTPHeaderField: "Content-Type") return NSURLSession.sharedSession().uploadTaskWithRequest(request, fromData: data) } } extension KeychainManager { func setMLabDatabaseName(databaseName: String?, APIKey: String?) throws { let credentials: InternetCredentials? if let username = databaseName, password = APIKey { credentials = InternetCredentials(username: username, password: password, URL: mLabAPIHost) } else { credentials = nil } try replaceInternetCredentials(credentials, forURL: mLabAPIHost) } func getMLabCredentials() -> (databaseName: String, APIKey: String)? { do { let credentials = try getInternetCredentials(URL: mLabAPIHost) return (databaseName: credentials.username, APIKey: credentials.password) } catch { return nil } } }
apache-2.0
213a1492f23614bc2769fa5f41da760f
30.46875
131
0.618669
5.041302
false
false
false
false
GreatfeatServices/gf-mobile-app
olivin-esguerra/ios-exam/Pods/RxSwift/RxSwift/Observables/Implementations/RefCount.swift
57
2536
// // RefCount.swift // RxSwift // // Created by Krunoslav Zaher on 3/5/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import Foundation class RefCountSink<CO: ConnectableObservableType, O: ObserverType> : Sink<O> , ObserverType where CO.E == O.E { typealias Element = O.E typealias Parent = RefCount<CO> private let _parent: Parent init(parent: Parent, observer: O, cancel: Cancelable) { _parent = parent super.init(observer: observer, cancel: cancel) } func run() -> Disposable { let subscription = _parent._source.subscribeSafe(self) _parent._lock.lock(); defer { _parent._lock.unlock() } // { if _parent._count == 0 { _parent._count = 1 _parent._connectableSubscription = _parent._source.connect() } else { _parent._count = _parent._count + 1 } // } return Disposables.create { subscription.dispose() self._parent._lock.lock(); defer { self._parent._lock.unlock() } // { if self._parent._count == 1 { self._parent._connectableSubscription!.dispose() self._parent._count = 0 self._parent._connectableSubscription = nil } else if self._parent._count > 1 { self._parent._count = self._parent._count - 1 } else { rxFatalError("Something went wrong with RefCount disposing mechanism") } // } } } func on(_ event: Event<Element>) { switch event { case .next: forwardOn(event) case .error, .completed: forwardOn(event) dispose() } } } class RefCount<CO: ConnectableObservableType>: Producer<CO.E> { fileprivate let _lock = NSRecursiveLock() // state fileprivate var _count = 0 fileprivate var _connectableSubscription = nil as Disposable? fileprivate let _source: CO init(source: CO) { _source = source } override func run<O: ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == CO.E { let sink = RefCountSink(parent: self, observer: observer, cancel: cancel) let subscription = sink.run() return (sink: sink, subscription: subscription) } }
apache-2.0
282941ced8ec8ad8115a3891092870d4
29.178571
141
0.542406
4.617486
false
false
false
false
adolfrank/Swift_practise
17-day/17-day/TestTableViewController.swift
1
3235
// // TestTableViewController.swift // 17-day // // Created by Hongbo Yu on 16/4/18. // Copyright © 2016年 Frank. All rights reserved. // import UIKit class TestTableViewController: UITableViewController { 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. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 0 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return 0 } /* override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) // Configure the cell... return cell } */ /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false 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 false if you do not want the item to be re-orderable. return true } */ /* // 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
c2e7052e0b1dc67fd44c8b5b1b78a1b0
32.666667
157
0.686262
5.543739
false
false
false
false
nifti/CinchKit
CinchKit/Client/CinchClient+Notifications.swift
1
1108
// // CinchClient+Notifications.swift // CinchKit // // Created by Ryan Fitzgerald on 5/12/15. // Copyright (c) 2015 cinch. All rights reserved. // extension CinchClient { public func fetchNotifications(atURL url : NSURL, queue: dispatch_queue_t? = nil, completionHandler : (CNHNotificationsResponse?, NSError?) -> ()) { let serializer = NotificationsResponseSerializer() request(.GET, url, queue: queue, serializer: serializer, completionHandler: completionHandler) } public func sendNotification(params: [String: AnyObject], queue: dispatch_queue_t? = nil, completionHandler : ((String?, NSError?) -> ())?) { let serializer = EmptyResponseSerializer() if let notifications = self.rootResources?["notifications"] { authorizedRequest(.POST, notifications.href, parameters: params, queue: queue, serializer: serializer, completionHandler: completionHandler) } else { dispatch_async(queue ?? dispatch_get_main_queue(), { completionHandler?(nil, self.clientNotConnectedError()) }) } } }
mit
012c7d86e9d600126b8248b59636f5cf
40.037037
152
0.672383
4.635983
false
false
false
false
nifti/CinchKit
CinchKit/Models/PollModel.swift
1
5250
// // PollModel.swift // CinchKit // // Created by Ryan Fitzgerald on 1/26/15. // Copyright (c) 2015 cinch. All rights reserved. // import Foundation public enum PictureVersion : String { case Small = "small", Medium = "medium", Large = "large", Original = "original" } public enum AccountRole : String { case Admin = "admin", User = "user" } public enum CNHPurchaseProduct: String { case BumpPoll = "com.clutchretail.cinch.bump" } public enum CNHLeaderMovement: String { case Up = "up", Down = "down" } public struct CNHAccount { public let id: String public let href: String public let name: String public let username: String? public let email: String? public let pictures: [PictureVersion : NSURL]? public let bio: String? public let website: String? public let shareLink: String? public let instagramId: String? public let instagramName: String? public let facebookId: String? public let facebookName: String? public let twitterId: String? public let twitterName: String? public let links : [String : NSURL]? public let roles : [AccountRole]? } public struct CNHAccountStats { public let id: String // public let href: String public let totalUnread: Int public let totalPollsCreated: Int public let totalVotes: Int public let totalFollowing: Int public let totalFollowers: Int public let totalGroups: Int } public struct CNHPoll { public let id: String public let href: String public let topic: String public let type: String public let shortLink: NSURL? public let votesTotal: Int public let messagesTotal: Int public let isPublic : Bool public let categoryId : String public let created : NSDate public let updated : NSDate public let displayAt : NSDate public let author : CNHAccount? public let candidates : [CNHPollCandidate] public let comments : [CNHComment]? public let links : [String : NSURL]? public let recentVoters : [CNHAccount]? } public struct CNHPollCandidate { public let id: String public let href: String public let image: String public let votes : Int public let created : NSDate public let voters : [String]? public let type : String public let option : String? public let images : [PictureVersion : NSURL]? } public struct CNHApiLink { public let id : String? public let href : NSURL public let type : String? } public struct CNHPollsResponse { public let selfLink : CNHApiLink public let nextLink : CNHApiLink? public let polls : [CNHPoll]? } public struct CNHCategory { public let id: String public let name: String public let hideWhenCreating: Bool public let links : [String : NSURL]? public let icons : [NSURL]? public let position : Int } public struct CNHVote { public let id: String? public let photoURL : NSURL? // public let href: String public let created : NSDate public let updated : NSDate public let account : CNHAccount? } public struct CNHVotesResponse { public let selfLink : CNHApiLink public let nextLink : CNHApiLink? public let votes : [CNHVote]? } public struct CNHFollowersResponse { public let selfLink : CNHApiLink public let nextLink : CNHApiLink? public let followers : [CNHAccount]? } public enum CNHCommentType : String { case Picture = "picture", Comment = "comment" } public struct CNHComment { public let id: String public let href : NSURL public let created : NSDate public let message : String public let author : CNHAccount? public let type : CNHCommentType public let links : [String : NSURL]? } public struct CNHCommentsResponse { public let selfLink : CNHApiLink public let nextLink : CNHApiLink? public let comments : [CNHComment]? } public struct CNHNotification { public let id: String public let href : NSURL public let created : NSDate public let action : String public let senderAccount : CNHAccount? public let recipientAccount : CNHAccount? public let resourcePoll : CNHPoll? public let resourceAccount : CNHAccount? public let resourceCategory : CNHCategory? public let extraCategory : CNHCategory? public let extraCandidate : CNHPollCandidate? public let extraAccount : CNHAccount? } public struct CNHNotificationsResponse { public let selfLink : CNHApiLink public let nextLink : CNHApiLink? public let notifications : [CNHNotification]? } public struct CNHPhoto { public let id: String public let href: String public let width: Float public let height: Float } public struct CNHPurchase { public let id: String public let product: CNHPurchaseProduct public let transactionId: String public let account: CNHAccount public let poll: CNHPoll? } public struct CNHLeaderAccount { public let account: CNHAccount public let rank: Int? public let votesTotal: Int public let movement: CNHLeaderMovement } public struct CNHLeaderboardResponse { public let selfLink: CNHApiLink public let nextLink: CNHApiLink? public let leaders: [CNHLeaderAccount]? }
mit
6d4aad62c352a35be7136d67df58a23c
24.362319
83
0.698476
4.019908
false
false
false
false
cozkurt/coframework
COFramework/COFramework/Swift/Components/UIStyling/AppearanceImageView.swift
1
2083
// // AppearanceImageView.swift // COLibrary // // Created by Cenker Ozkurt on 07/14/16. // Copyright (c) 2015 Cenker Ozkurt. All rights reserved. // import UIKit @IBDesignable public class AppearanceImageView: UIImageView { @IBInspectable public var appearanceId: String? { didSet { if self.appearanceId != "" { AppearanceController.sharedInstance.customizeImageView(self) } } } @IBInspectable public var useDefaultTint: Bool = false { didSet { self.tintColor = AppearanceController.sharedInstance.color("default.image.tint") self.setImageWithAlwaysTemplate() } } @IBInspectable public var imageName: String? { didSet { self.image = self.localizedImage(imageName ?? "") } } override public func prepareForInterfaceBuilder() { let bundle = Bundle(for: type(of: self)) self.image = self.localizedImage(imageName ?? "", bundle: bundle) } public func localizedImage(_ imageName: String, bundle: Bundle? = nil) -> UIImage? { let id = Locale.current.identifier let localizedName = id == "en" ? imageName : "\(imageName)_\(id)" if let bundle = bundle { if let image = UIImage(named: localizedName, in: bundle, compatibleWith: self.traitCollection) { return image } } else { if let image = UIImage(systemName: localizedName) { return image } if let image = UIImage(named: localizedName) { return image } } return UIImage(systemName: imageName) ?? UIImage(named: imageName) } public func setImageWithAlwaysTemplate(name: String) { self.image = self.localizedImage(name)?.withRenderingMode(.alwaysTemplate) } public func setImageWithAlwaysTemplate() { if useDefaultTint { self.image = self.image?.withRenderingMode(.alwaysTemplate) } } }
gpl-3.0
68094f26e33908d78abae40cb82dcd0c
27.930556
108
0.591935
4.959524
false
false
false
false
odigeoteam/TableViewKit
TableViewKit/ObservableArray.swift
1
6146
import Foundation enum ArrayChanges<Element> { case inserts([Int], [Element]) case deletes([Int], [Element]) case updates([Int]) case moves([(Int, Int)]) case beginUpdates(from: [Element], to: [Element]) case endUpdates(from: [Element], to: [Element]) } /// An observable array. It will notify any kind of changes. public class ObservableArray<T>: RandomAccessCollection, ExpressibleByArrayLiteral { /// The type of the elements of an array literal. public typealias Element = T var array: [T] var callback: ((ArrayChanges<T>) -> Void)? /// Creates an empty `ObservableArray` public required init() { self.array = [] } /// Creates an `ObservableArray` with the contents of `array` /// /// - parameter array: The initial content public init(array: [T]) { self.array = array } /// Creates an instance initialized with the given elements. /// /// - parameter elements: An array of elements public required init(arrayLiteral elements: Element...) { self.array = elements } /// Returns an iterator over the elements of the collection. public func makeIterator() -> Array<T>.Iterator { return array.makeIterator() } /// The position of the first element in a nonempty collection. public var startIndex: Int { return array.startIndex } /// The position of the last element in a nonempty collection. public var endIndex: Int { return array.endIndex } /// Returns the position immediately after the given index. /// /// - parameter i: A valid index of the collection. i must be less than endIndex. /// /// - returns: The index value immediately after i. public func index(after index: Int) -> Int { return array.index(after: index) } /// A Boolean value indicating whether the collection is empty. public var isEmpty: Bool { return array.isEmpty } /// The number of elements in the collection. public var count: Int { return array.count } /// Accesses the element at the specified position. /// /// - parameter index: public subscript(index: Int) -> T { get { return array[index] } set { replaceSubrange(index..<index + 1, with: [newValue]) } } /// Replace its content with a new array /// /// - parameter array: The new array public func replace(with array: [T], shouldPerformDiff: Bool = true) { guard shouldPerformDiff else { self.array = array return } let diff = Array.diff(between: self.array, and: array, where: compare) self.array = array notifyChanges(with: diff) } /// Replaces the specified subrange of elements with the given collection. /// /// - parameter subrange: The subrange that must be replaced /// - parameter newElements: The new elements that must be replaced // swiftlint:disable:next line_length public func replaceSubrange<C>(_ subrange: Range<Int>, with newElements: C) where C: Collection, C.Iterator.Element == T { let temp = Array(newElements) var diff = Array.diff(between: self.array, and: temp, subrange: subrange, where: compare) self.array.replaceSubrange(subrange, with: newElements) diff.toElements = self.array notifyChanges(with: diff) } /// Append `newElement` to the array. public func append(contentsOf newElements: [T]) { insert(contentsOf: newElements, at: array.count) } /// Append `newElement` to the array. public func append(_ newElement: T) { replaceSubrange(array.count..<array.count, with: [newElement]) } /// Insert `newElement` at index `i`. public func insert(_ newElement: T, at index: Int) { replaceSubrange(index..<index, with: [newElement]) } /// Insert elements `newElements` at index `i`. public func insert(contentsOf newElements: [T], at index: Int) { replaceSubrange(index..<index, with: newElements) } /// Remove and return the element at index i. @discardableResult public func remove(at index: Int) -> T { let element = array[index] replaceSubrange(index..<index + 1, with: []) return element } /// Removes the specified number of elements from the beginning of the collection. public func removeFirst(_ n: Int) { replaceSubrange(0..<n, with: []) } /// Remove an element from the end of the array in O(1). @discardableResult public func removeFirst() -> T { let element = array[0] replaceSubrange(0..<1, with: []) return element } /// Removes the specified number of elements from the end of the collection. public func removeLast(_ n: Int) { replaceSubrange((array.count - n)..<array.count, with: []) } /// Remove an element from the end of the array in O(1). @discardableResult public func removeLast() -> T { let element = array[array.count - 1] replaceSubrange(array.count - 1..<array.count, with: []) return element } /// Remove all elements from the array. public func removeAll() { replaceSubrange(0..<array.count, with: []) } private func compare(lhs: T, rhs: T) -> Bool { if let lhs = lhs as? AnyEquatable { return lhs.equals(rhs) } return false } private func notifyChanges(with diff: Diff<T>) { callback?(.beginUpdates(from: diff.fromElements, to: diff.toElements)) if !diff.moves.isEmpty { callback?(.moves(diff.moves)) } if !diff.deletes.isEmpty { callback?(.deletes(diff.deletes, diff.deletesElement)) } if !diff.inserts.isEmpty { callback?(.inserts(diff.inserts, diff.insertsElement)) } callback?(.endUpdates(from: diff.fromElements, to: diff.toElements)) } }
mit
74871f37b28b4d6295605fc0f138ab19
30.84456
126
0.609014
4.552593
false
false
false
false
jasnig/DouYuTVMutate
DouYuTVMutate/DouYuTV/Home/ViewModel/RecommendViewModel.swift
1
4467
// // RecommendViewModel.swift // DouYuTVMutate // // Created by ZeroJ on 16/8/6. // Copyright © 2016年 ZeroJ. All rights reserved. // import UIKit import RxSwift class RecommendViewModel: BaseViewModel { /// 是否加载完毕 private(set) var isLoadFinished: Observable<Bool> var isBeginLoad: Variable<Bool> = Variable(false) var pptData: [ScrollPhotoModel] { return pptDataVariable.value ?? [] } var data: [TagModel] { return dataVariable.value ?? [] } private var pptDataVariable: Variable<([ScrollPhotoModel]?)> = Variable(nil) private var dataVariable: Variable<[TagModel]?> = Variable(nil) override init() { /// 两次请求都完成才标识结束 !!!! 强大的功能之一 isLoadFinished = Observable.combineLatest(pptDataVariable.asObservable(), dataVariable.asObservable()) {ppt, data in return ppt != nil && data != nil } super.init() isBeginLoad.asObservable().subscribeNext { (begin) in if begin { self.loadData() self.loadScrollPhotoData() } } .addDisposableTo(disposeBag) } func loadData() { let url: String = URL.recommondURL + String.getNowTimeString() NetworkTool.GET(url, successHandler: {[weak self] (result) in if let resultJSON = result { if let data = Mapper<TagModel>().map(resultJSON)?.data { guard let `self` = self else { return } self.dataVariable.value = data } } }) { (error) in } } func loadScrollPhotoData() { let url: String = URL.slideURL + String.getNowTimeString() NetworkTool.GET(url, successHandler: {[weak self] (result) in if let resultJSON = result { if let data = Mapper<ScrollPhotoModel>().map(resultJSON)?.data { guard let `self` = self else { return } self.pptDataVariable.value = data } } }) { (error) in } } } class RecommendViewModel1: BaseViewModel { /// 是否加载完毕 var pptData: [ScrollPhotoModel] = [] var data: [TagModel] = [] typealias Handler = (loadState: LoadState) -> Void func loadDataWithHandler(handler: Handler) { let url: String = URL.recommondURL + String.getNowTimeString() NetworkTool.GET(url, successHandler: {[weak self] (result) in if let resultJSON = result { if let data = Mapper<TagModel>().map(resultJSON)?.data { guard let `self` = self else { return } self.data = data /// 加载pptData self.loadPPTViewDataWithHandler(handler) } else { handler(loadState: LoadState.failure(errorMessage: "数据解析错误")) } } else { handler(loadState: .failure(errorMessage: "服务器返回的错误")) } }) { (error) in handler(loadState: .failure(errorMessage: "网络错误")) } } private func loadPPTViewDataWithHandler(handler: Handler) { let url: String = URL.slideURL + String.getNowTimeString() NetworkTool.GET(url, successHandler: {[weak self] (result) in if let resultJSON = result { if let data = Mapper<ScrollPhotoModel>().map(resultJSON)?.data { guard let `self` = self else { return } self.pptData = data handler(loadState: .success) } else { handler(loadState: LoadState.failure(errorMessage: "数据解析错误")) } } else { handler(loadState: .failure(errorMessage: "服务器返回的错误")) } }) { (error) in handler(loadState: .failure(errorMessage: "网络错误")) } } }
mit
c4d63c3ff3c8027ed388e7a0d7198863
28.435374
124
0.495839
4.955326
false
false
false
false
creatubbles/ctb-api-swift
CreatubblesAPIClient/Sources/CreationUploadSession/CreationUploadSessionPublicData.swift
1
2444
// // CreationUploadSessionPublicData.swift // CreatubblesAPIClient // // Copyright (c) 2017 Creatubbles Pte. Ltd. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import UIKit @objc open class CreationUploadSessionPublicData: NSObject { public enum Status: Equatable { case inProgress // completed successfully case completed // cancelled by user case cancelled // failed due to error case failed } open let identifier: String open let creationData: NewCreationData open let creation: Creation? open let error: Error? open let status: Status init(creationUploadSession: CreationUploadSession) { identifier = creationUploadSession.localIdentifier creation = creationUploadSession.creation creationData = creationUploadSession.creationData error = creationUploadSession.error if creationUploadSession.isFailed { status = .failed } else if creationUploadSession.isAlreadyFinished { status = .completed } else if creationUploadSession.isCancelled { status = .cancelled } else { status = .inProgress } } open func includesSubmittingToGallery(withIdentifier galleryIdentifier: String) -> Bool { return creationData.galleryIds?.contains(galleryIdentifier) ?? false } }
mit
7eea2bae48432ab79bdbfe2af8f71e4d
36.030303
93
0.709083
4.927419
false
false
false
false
ShanghaiTimes/Swift-Radio-Pro
SwiftRadio/InfoDetailViewController.swift
2
2991
// // InfoDetailViewController.swift // Swift Radio // // Created by Matthew Fecher on 7/9/15. // Copyright (c) 2015 MatthewFecher.com. All rights reserved. // import UIKit class InfoDetailViewController: UIViewController { @IBOutlet weak var stationImageView: UIImageView! @IBOutlet weak var stationNameLabel: UILabel! @IBOutlet weak var stationDescLabel: UILabel! @IBOutlet weak var stationLongDescTextView: UITextView! @IBOutlet weak var okayButton: UIButton! var currentStation: RadioStation! var downloadTask: NSURLSessionDownloadTask? //***************************************************************** // MARK: - ViewDidLoad //***************************************************************** override func viewDidLoad() { super.viewDidLoad() setupStationText() setupStationLogo() } deinit { // Be a good citizen. downloadTask?.cancel() downloadTask = nil } //***************************************************************** // MARK: - UI Helpers //***************************************************************** func setupStationText() { // Display Station Name & Short Desc stationNameLabel.text = currentStation.stationName stationDescLabel.text = currentStation.stationDesc // Display Station Long Desc if currentStation.stationLongDesc == "" { loadDefaultText() } else { stationLongDescTextView.text = currentStation.stationLongDesc } } func loadDefaultText() { // Add your own default ext stationLongDescTextView.text = "You are listening to Swift Radio. This is a sweet open source project. Tell your friends, swiftly!" } func setupStationLogo() { // Display Station Image/Logo let imageURL = currentStation.stationImageURL if imageURL.rangeOfString("http") != nil { // Get station image from the web, iOS should cache the image if let url = NSURL(string: currentStation.stationImageURL) { downloadTask = stationImageView.loadImageWithURL(url) { _ in } } } else if imageURL != "" { // Get local station image stationImageView.image = UIImage(named: imageURL) } else { // Use default image if station image not found stationImageView.image = UIImage(named: "stationImage") } // Apply shadow to Station Image stationImageView.applyShadow() } //***************************************************************** // MARK: - IBActions //***************************************************************** @IBAction func okayButtonPressed(sender: UIButton) { navigationController?.popViewControllerAnimated(true) } }
mit
aaa20f8b63aeaf94c0336bad426b13b0
30.819149
139
0.525911
5.899408
false
false
false
false
ben-ng/swift
validation-test/compiler_crashers_fixed/27456-swift-abstractclosureexpr-setparams.swift
1
2562
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck } class b typealias e let end = " \ ( { {} class d protocol a T { struct Q<T{class B<T where f={ if true { class C(object1: a{ struct d=true { let end = " ) struct Q<T {c d<T> : Any) }class c{ typealias b let a {} struct c{ enum S<T where B<h:b a : d<T> : d<T NSObject { var f=true { } protocol A { struct d<T{ class C{ if true as S<T> func a() let f={ } enum B{ } class a {{ protocol A { var _=(object1 : d<T T{ for c d<T where f={ func g<T T> if true { class a { class d<T where class A{struct d< func<T where B : d { } protocol A:{struct e.b }} class c{ protocol A{ func g:A{class { protocol P{}class d<h:{} enum B{ enum S<T{class C if true { let a : whe if true {c e=e=""" class c{ protocol a {var e }struct D : a ifruct var e=(object1 : a { class C{ struct d<T where B : whe class a : d<T {class B enum B class C{ let end = " \ () { class c{{typealias b var f={ let end = D> ) { class a T NSObject { struct D : a func g:{ func a(object1 : = D> : d<T NSObject { struct B:A? { class C struct B func " ) func T{ func g: d<T where g<T where g:e:C( func g:b func g: T) { enum S struct Q<T {class B{ struct B protocol A { class B< T where B<T NSObject { } }} struct e() }protocol a T {} class c{ typealias e={ if true { class c{let f={} class A<T) { func g<T : T> {class C class c{ { class c{} } enum S<T{ }protocol b func a{} a { var _=(object1: a() } { class b if true {c d<T where T> : d<T where B { } "[1 let:A:A{class A{ } a : Any) func g:C { struct B{ class a"\ (object1 : = " ) } func T) {{let end = B class A{} } struct e:e.b func a class d<T where var f={ func<T NSObject { if true { { for c e={ struct B{ struct d<T{ func T> ) { struct c{ enum B } protocol A { enum B{ { protocol P{ protocol P{ } if true{} for c e="[1 func a( for c d var f {{ let end = " ) class d=true {let f=" protocol A? { func T> enum S<T where B : A{} { } struct B< T { class C{ } let f: d } struct Q<l where g:A{ class d<T where g<h:{ { func T{ }protocol P{ a : a( enum k protocol P{ struct B }class a T where B : a if true{ {} class A{ }class a {var d { { enum B struct d if true { class A{class d< var b ="[1 func a if true {} class c{ var e(object1: a<T where B<T where B : Any
apache-2.0
ae86cd9c184f4bbfe14441e84f1fb8b3
12.206186
79
0.627244
2.407895
false
false
false
false
adrfer/swift
validation-test/compiler_crashers_fixed/01031-getselftypeforcontainer.swift
3
432
// RUN: not %target-swift-frontend %s -parse // Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing protocol b : C { } let start = b, let t.c { typealias d>(n: b { protocol C = 0] = """\())] = c: e? = T) -> A { } protocol A : a { } protocol a { func e: b { } func c(() -> Any) { } protocol A { } typealias d : e: C {
apache-2.0
dd5e7e7386aa2a0716478d83adf778ca
18.636364
87
0.615741
2.958904
false
true
false
false
paymentez/paymentez-ios
PaymentSDK/PaymentResponse.swift
1
2386
// // PaymentResponse.swift // PaymentSDKSample // // Created by Gustavo Sotelo on 04/05/16. // Copyright © 2016 Payment. All rights reserved. // import Foundation fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l < r case (nil, _?): return true default: return false } } fileprivate func > <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l > r default: return rhs < lhs } } enum PaymentSDKTypeAddError:Int { case unauthorized = 0 case insuficientParams = 1 case invalidFormat = 2 case operationNotAllowed = 3 case invalidConfiguration = 4 } enum PaymentSDKDebitStatus { case authorized } class PaymentDebitResponse { var transactionId = "" var status:PaymentSDKDebitStatus? var statusDetail = "" var paymentDate:Date? var amount = 0.0 var carrierData:[String:Any]? var cardData:[String:Any]? } @objcMembers open class PaymentSDKError:NSObject { open var code = 500 open var descriptionData = "Internal Error" open var help:String? open var type:String? init(code:Int, description:String, help:String?, type:String?) { self.code = code self.descriptionData = description self.help = help self.type = type } fileprivate func convertStringToDictionary(_ text: String!) -> [String:Any]? { if let data = text.data(using: String.Encoding.utf8, allowLossyConversion: false) { do { let json = try JSONSerialization.jsonObject(with: data, options: [.allowFragments, .mutableContainers]) as? [String:Any] return json } catch let error as NSError { print (error) print("Something went wrong with Params") } } return nil } static func createError(_ err:NSError) -> PaymentSDKError { return PaymentSDKError(code: 500, description: err.localizedDescription, help: err.debugDescription, type:nil) } @objc public static func createError(_ code:Int, description:String, help:String?, type:String?) -> PaymentSDKError { return PaymentSDKError(code: code, description: description, help: help, type:type) } }
mit
042840dc352e90687337a7e9b80e7df6
22.85
136
0.619706
4.147826
false
false
false
false
Carthage/PrettyColors
Tests/PrettyColorsTests.swift
1
9914
import PrettyColors import Foundation import XCTest class PrettyColorsTests: XCTestCase { override func setUp() { super.setUp() } override func tearDown() { super.tearDown() } func test_basics() { let redText: String = Color.Wrap(foreground: .Red).wrap("A red piece of text.") println(redText) Color.Wrap(foreground: .Yellow, style: .Bold) Color.Wrap(foreground: .Green, background: .Black, style: .Bold, .Underlined) // 8-bit (256) color support Color.Wrap(foreground: 114) Color.Wrap(foreground: 114, style: .Bold) } func test_problem_SingleStyleParameter() { /* As of `swift-600.0.57.3`, the following statement errors: «Extra argument 'style' in call» */ // Color.Wrap(style: .Bold) /* Removing the supposedly "extra" argument 'style' errors: «'().Type' does not have a member named 'Bold'» */ // Color.Wrap(.Bold) /* The true problem appears to be the ambiguity between the two functions of the form `init(foreground:background:style:)`. */ // Workarounds: Color.Wrap(foreground: nil as UInt8?, style: .Bold) Color.Wrap(foreground: nil as Color.Named.Color?, style: .Bold) [StyleParameter.Bold] as Color.Wrap Color.Wrap(styles: .Bold) // Multiple Color.Wrap(styles: .Bold, .Blink) } func test_problem_TypeInference() { // As of `swift-600.0.57.3`, this doesn't get type-inferred properly. /* Color.Wrap( parameters: [ Color.Named(foreground: .Green), Color.EightBit(foreground: 114), StyleParameter.Bold ] ) */ // Workarounds: Color.Wrap( parameters: [ Color.Named(foreground: .Green), Color.EightBit(foreground: 114), StyleParameter.Bold ] as [Color.Wrap.Element] ) Color.Wrap( parameters: [ Color.Named(foreground: .Green), Color.EightBit(foreground: 114), StyleParameter.Bold ] as [Parameter] ) [ Color.Named(foreground: .Green), Color.EightBit(foreground: 114), StyleParameter.Bold ] as Color.Wrap } func testImmutableFilterOrMap() { let redBold = Color.Wrap(foreground: .Red, style: .Bold) let redItalic = Color.Wrap(foreground: .Red, style: .Italic) XCTAssert( redBold == redItalic .filter { $0 != StyleParameter.Italic } + [ StyleParameter.Bold ] ) XCTAssert( redBold == Color.Wrap( parameters: redItalic .map { (parameter: Parameter) in return parameter == StyleParameter.Italic ? StyleParameter.Bold : parameter } ) ) } func testEmptyWrap() { XCTAssert( Color.Wrap(parameters: []).code.enable == "", "Wrap with no parameters wrapping an empty string should return an empty SelectGraphicRendition." ) XCTAssert( Color.Wrap(parameters: []).wrap("") == "", "Wrap with no parameters wrapping an empty string should return an empty string." ) } func testMulti() { var multi = [ Color.EightBit(foreground: 227), Color.Named(foreground: .Green, brightness: .NonBright) ] as Color.Wrap XCTAssert( multi.code.enable == ECMA48.controlSequenceIntroducer + "38;5;227" + ";" + "32" + "m" ) XCTAssert( multi.code.disable == ECMA48.controlSequenceIntroducer + "0" + "m" ) } func testLetWorkflow() { let redOnBlack = Color.Wrap(foreground: .Red, background: .Black) let boldRedOnBlack: Color.Wrap = redOnBlack + [ StyleParameter.Bold ] as Color.Wrap XCTAssert( boldRedOnBlack == Color.Wrap(foreground: .Red, background: .Black, style: .Bold) ) XCTAssert( [ boldRedOnBlack, Color.Wrap(foreground: .Red, background: .Black, style: .Bold) ].reduce(true) { (previous, value) in return previous && value.parameters.reduce(true) { (previous, value) in let enable = value.code.enable return previous && ( value == Color.Named(foreground: .Red) as Parameter || value == Color.Named(background: .Black) as Parameter || value == StyleParameter.Bold ) } } == true ) } func testAppendStyleParameter() { let red = Color.Wrap(foreground: .Red) let _ = { (wrap: Color.Wrap) -> Void in var formerlyRed = wrap formerlyRed.append(StyleParameter.Bold) XCTAssert( formerlyRed == Color.Wrap(foreground: .Red, style: .Bold) ) }(red) let _ = { (wrap: Color.Wrap) -> Void in var formerlyRed = wrap formerlyRed.append(style: .Bold) XCTAssert( formerlyRed == Color.Wrap(foreground: .Red, style: .Bold) ) }(red) XCTAssert( red + Color.Wrap(styles: .Bold) == Color.Wrap(foreground: .Red, style: .Bold) ) // Multiple let _ = { (wrap: Color.Wrap) -> Void in var formerlyRed = wrap formerlyRed.append(StyleParameter.Bold) formerlyRed.append(StyleParameter.Italic) XCTAssert( formerlyRed == Color.Wrap(foreground: .Red, style: .Bold, .Italic) ) }(red) let _ = { (wrap: Color.Wrap) -> Void in var formerlyRed = wrap formerlyRed.append(style: .Bold, .Italic) XCTAssert( formerlyRed == Color.Wrap(foreground: .Red, style: .Bold, .Italic) ) }(red) XCTAssert( red + Color.Wrap(styles: .Bold, .Italic) == Color.Wrap(foreground: .Red, style: .Bold, .Italic) ) } func testMutableAppend() { var formerlyRed = Color.Wrap(foreground: .Red) let redBlackBackground = Color.Wrap(foreground: .Red, background: .Black) formerlyRed.append( Color.Named(background: .Black) ) XCTAssert( formerlyRed == redBlackBackground ) } //------------------------------------------------------------------------------ // MARK: - Foreground/Background //------------------------------------------------------------------------------ func testSetForeground() { var formerlyRed = Color.Wrap(foreground: .Red) formerlyRed.foreground = Color.EightBit(foreground: 227) // A nice yellow XCTAssert( formerlyRed == Color.Wrap(foreground: 227) ) } func testSetForegroundToNil() { var formerlyRed = Color.Wrap(foreground: .Red) formerlyRed.foreground = nil XCTAssert( formerlyRed == Color.Wrap(foreground: nil as UInt8?) ) } func testSetForegroundToParameter() { var formerlyRed = Color.Wrap(foreground: .Red) formerlyRed.foreground = StyleParameter.Bold XCTAssert( formerlyRed == [StyleParameter.Bold] as Color.Wrap ) } func testTransformForeground() { var formerlyRed = Color.Wrap(foreground: .Red) formerlyRed.foreground { (color: ColorType) -> ColorType in return Color.EightBit(foreground: 227) // A nice yellow } XCTAssert( formerlyRed == Color.Wrap(foreground: 227) ) } func testTransformForeground2() { var formerlyRed = Color.Wrap(foreground: 124) formerlyRed.foreground { (var color: ColorType) -> ColorType in if let color = color as? Color.EightBit { var soonYellow = color soonYellow.color += (227-124) return soonYellow } else { return color } } XCTAssert( formerlyRed == Color.Wrap(foreground: 227) ) } func testTransformForegroundWithVar() { var formerlyRed = Color.Wrap(foreground: .Red) formerlyRed.foreground { (var color: ColorType) -> ColorType in if let namedColor = color as? Color.Named { var soonYellow = namedColor soonYellow.color = .Yellow return soonYellow } else { return color } } XCTAssert( formerlyRed == Color.Wrap(foreground: .Yellow) ) } func testTransformForegroundToBright() { var formerlyRed = Color.Wrap(foreground: .Red) formerlyRed.foreground { (var color: ColorType) -> ColorType in var clone = color as Color.Named clone.brightness.toggle() return clone } let brightRed = [ Color.Named(foreground: .Red, brightness: .Bright) ] as Color.Wrap XCTAssert( formerlyRed == brightRed ) } func testComputedVariableForegroundEquality() { XCTAssert( Color.Named(foreground: .Red) == Color.Wrap(foreground: .Red).foreground! as Color.Named ) } func testEightBitForegroundBackgroundDifference() { let one = Color.EightBit(foreground: 114) let two = Color.EightBit(background: 114) let difference = one.code.enable.reduce( two.code.enable.reduce(0 as UInt8) { return $0.0 + $0.1 } ) { return $0.0 - $0.1 } XCTAssert( difference == 10 ) } func testNamedForegroundBackgroundDifference() { let one = Color.Named(foreground: .Green) let two = Color.Named(background: .Green) let difference = one.code.enable.reduce( two.code.enable.reduce(0 as UInt8) { return $0.0 + $0.1 } ) { return $0.0 - $0.1 } XCTAssert( difference == 10 ) } func testNamedBrightnessDifference() { let one = Color.Named(foreground: .Green) let two = Color.Named(foreground: .Green, brightness: .Bright) let difference = one.code.enable.reduce( two.code.enable.reduce(0 as UInt8) { return $0.0 + $0.1 } ) { return $0.0 - $0.1 } XCTAssert( difference == 60 ) } //------------------------------------------------------------------------------ // MARK: - Zap //------------------------------------------------------------------------------ func testZapAllStyleParameters() { let red = Color.Named(foreground: .Red) let niceColor = Color.EightBit(foreground: 114) let iterables: Array<Array<Parameter>> = [ [red], [niceColor], ] for parameters in iterables { let wrap = Color.Wrap(parameters: parameters) for i in stride(from: 1 as UInt8, through: 55, by: 1) { if let parameter = StyleParameter(rawValue: i) { for wrapAndSuffix in [ (wrap, "normal"), (wrap + [ StyleParameter.Bold ] as Color.Wrap, "bold"), (wrap + [ StyleParameter.Italic ] as Color.Wrap, "italic"), (wrap + [ StyleParameter.Underlined ] as Color.Wrap, "underlined") ] { let wrap = (wrapAndSuffix.0 + [parameter] as Color.Wrap) let suffix = wrapAndSuffix.1 let string = "• " + wrap.wrap("__|øat·•ªº^∆©|__") + " " + NSString(format: "%02d", i) + " + " + suffix println(string) } } } } } }
mit
cb2c0c3b96ba90ee1ccc7a727f93da02
24.778646
100
0.637236
3.28325
false
true
false
false
kostiakoval/ExSwift
ExSwiftTests/ExSwiftTests.swift
1
2233
// // ExSwiftTests.swift // ExSwift // // Created by pNre on 07/06/14. // Copyright (c) 2014 pNre. All rights reserved. // import XCTest class ExSwiftTests: XCTestCase { func testAfter () { let f = ExSwift.after(2, { () -> Bool in return true }) XCTAssertNil(f()) XCTAssertNil(f()) XCTAssertTrue(f()!) var called = false let g = ExSwift.after(2, { called = true }) g() g() g() XCTAssertTrue(called) } func testOnce () { // Test execution var test = false let f = Ex.once { test = !test } f() f() XCTAssertTrue(test) // Test return value var seq = [1, 2, 3, 4].generate() let g = Ex.once { Void -> Int in return seq.next()! } XCTAssertEqual(g(), 1) XCTAssertEqual(g(), 1) } func testPartial () { let add = { (params: Int...) -> Int in return params.reduce(0, { return $0 + $1 }) } let add5 = ExSwift.partial(add, 5) XCTAssertEqual(15, add5(10)) XCTAssertEqual(8, add5(1, 2)) } func testBind () { let concat = { (params: String...) -> String in return params.implode(" ")! } let helloWorld = ExSwift.bind(concat, "Hello", "World") XCTAssertEqual(helloWorld(), "Hello World") } func testCached () { var calls = 0 // Slow Fibonacci var fib: ((Int...) -> Int)! fib = { (params: Int...) -> Int in let n = params[0] calls++ if n <= 1 { return n } return fib(n - 1) + fib(n - 2) } let fibonacci = Ex.cached(fib) // This one is computed (fib is called 465 times) fibonacci(12) XCTAssertEqual(465, calls) // The results is taken from the cache (fib is not called) fibonacci(12) XCTAssertEqual(465, calls) } }
bsd-2-clause
41b444ee120c9925799fa582ccdf6bbe
20.066038
66
0.438424
4.448207
false
true
false
false
mvader/advent-of-code
2020/22/02.swift
1
1685
import Foundation struct Deck: Hashable { var cards: [Int] init(_ initialCards: [Int]) { cards = initialCards } mutating func draw() -> Int { return cards.removeFirst() } mutating func put(_ cards: Int...) { self.cards.append(contentsOf: cards) } func score() -> Int { var score = 0 for (i, card) in cards.enumerated() { score += (cards.count - i) * card } return score } } func parseDeck(_ input: String) -> Deck { return Deck(input.components(separatedBy: "\n").dropFirst().map { Int($0)! }) } struct State: Hashable { let deck1: Int let deck2: Int } func playRecursiveCombat(_ p1: inout Deck, _ p2: inout Deck) -> (Int, Int) { var seenDecks = Set<State>() while !p1.cards.isEmpty && !p2.cards.isEmpty { let state = State(deck1: p1.score(), deck2: p2.score()) if seenDecks.contains(state) { return (1, 0) } seenDecks.update(with: state) let (card1, card2) = (p1.draw(), p2.draw()) var firstWon = false if card1 <= p1.cards.count && card2 <= p2.cards.count { var deck1 = Deck([Int](p1.cards[0..<card1])) var deck2 = Deck([Int](p2.cards[0..<card2])) let (firstScore, _) = playRecursiveCombat(&deck1, &deck2) firstWon = firstScore > 0 } else if card1 > card2 { firstWon = true } if firstWon { p1.put(card1, card2) } else { p2.put(card2, card1) } } return (p1.score(), p2.score()) } let input = try String(contentsOfFile: "./input.txt", encoding: .utf8) let decks = input.components(separatedBy: "\n\n").map(parseDeck) var (player1, player2) = (decks[0], decks[1]) print(playRecursiveCombat(&player1, &player2))
mit
9bf3f22749031c2bd919034aa5b2da2d
23.071429
79
0.607122
3.086081
false
false
false
false
guglielmino/Marty-Quiz
jurassic Marty/Libs/PASImageView.swift
1
10379
// // PASImageView.swift // PASImageView // // Created by Pierre Abi-aad on 09/06/2014. // Copyright (c) 2014 Pierre Abi-aad. All rights reserved. // import UIKit import QuartzCore let spm_identifier = "spm.imagecache.tg" let kLineWidth :CGFloat = 3.0 func rad(degrees : Float) -> Float { return ((degrees) / Float((180.0/M_PI))) } class SPMImageCache : NSObject { var cachePath = String() let fileManager = NSFileManager.defaultManager() override init() { let paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.CachesDirectory, NSSearchPathDomainMask.UserDomainMask, true) let rootCachePath : AnyObject = paths[0] cachePath = rootCachePath.stringByAppendingPathComponent(spm_identifier) if !fileManager.fileExistsAtPath(cachePath) { fileManager.createDirectoryAtPath(cachePath, withIntermediateDirectories: false, attributes: nil, error: nil) } super.init() } func image(image: UIImage, URL: NSURL) { var imageData :NSData = NSData() let fileExtension = URL.pathExtension if fileExtension == "png" { imageData = UIImagePNGRepresentation(image) } else if fileExtension == "jpg" || fileExtension == "jpeg" { imageData = UIImageJPEGRepresentation(image, 1.0) } imageData.writeToFile(self.cachePath.stringByAppendingPathComponent(String(format: "%u.%@", URL.hash, fileExtension!)), atomically: true) } func imageForURL(URL: NSURL) -> UIImage? { let fileExtension = URL.pathExtension let path = self.cachePath.stringByAppendingPathComponent(String(format: "%u.%@", URL.hash, fileExtension!)) if self.fileManager.fileExistsAtPath(path) { return UIImage(data: NSData(contentsOfFile: path)!) } return nil } } class PASImageView : UIView, NSURLSessionDownloadDelegate { var cacheEnabled = true var placeHolderImage = UIImage() var backgroundProgressColor = UIColor.blackColor() var progressColor = UIColor.redColor() var backgroundLayer = CAShapeLayer() var progressLayer = CAShapeLayer() var containerImageView = UIImageView() var progressContainer = UIView() var cache = SPMImageCache() var delegate :PASImageViewDelegate? required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } convenience init(frame: CGRect, delegate: PASImageViewDelegate) { self.init(frame: frame) self.delegate = delegate } convenience override init() { self.init(frame: CGRectZero) } override init(frame: CGRect) { super.init(frame: frame) self.layer.masksToBounds = false self.clipsToBounds = true updatePaths() backgroundLayer.strokeColor = backgroundProgressColor.CGColor backgroundLayer.fillColor = UIColor.clearColor().CGColor backgroundLayer.lineWidth = kLineWidth progressLayer.strokeColor = progressColor.CGColor progressLayer.fillColor = backgroundLayer.fillColor progressLayer.lineWidth = backgroundLayer.lineWidth progressLayer.strokeEnd = 0.0 progressContainer = UIView() progressContainer.layer.masksToBounds = false progressContainer.clipsToBounds = true progressContainer.backgroundColor = UIColor.clearColor() containerImageView = UIImageView() containerImageView.layer.masksToBounds = false containerImageView.clipsToBounds = true containerImageView.contentMode = UIViewContentMode.ScaleAspectFill progressContainer.layer.addSublayer(backgroundLayer) progressContainer.layer.addSublayer(progressLayer) self.addSubview(containerImageView) self.addSubview(progressContainer) self.addGestureRecognizer(UITapGestureRecognizer(target: self, action: "handleSingleTap:")) setConstraints() } func updatePaths() { let arcCenter = CGPoint(x: CGRectGetMidX(self.bounds), y: CGRectGetMidY(self.bounds)) let radius = Float(min(CGRectGetMidX(self.bounds) - 1, CGRectGetMidY(self.bounds)-1)) let circlePath = UIBezierPath(arcCenter: arcCenter, radius: CGFloat(radius), startAngle: CGFloat(-rad(Float(90))), endAngle: CGFloat(rad(360-90)), clockwise: true) backgroundLayer.path = circlePath.CGPath progressLayer.path = backgroundLayer.path } func setConstraints() { // containerImageView containerImageView.setTranslatesAutoresizingMaskIntoConstraints(false) self.addConstraint(NSLayoutConstraint(item: containerImageView, attribute: .Width, relatedBy: .Equal, toItem: self, attribute: .Width, multiplier: 1, constant: -2)) self.addConstraint(NSLayoutConstraint(item: containerImageView, attribute: .Height, relatedBy: .Equal, toItem: self, attribute: .Height, multiplier: 1, constant: -2)) self.addConstraint(NSLayoutConstraint(item: containerImageView, attribute: .CenterX, relatedBy: .Equal, toItem: self, attribute: .CenterX, multiplier: 1, constant: 0)) self.addConstraint(NSLayoutConstraint(item: containerImageView, attribute: .CenterY, relatedBy: .Equal, toItem: self, attribute: .CenterY, multiplier: 1, constant: 0)) // progressContainer progressContainer.setTranslatesAutoresizingMaskIntoConstraints(false) self.addConstraint(NSLayoutConstraint(item: progressContainer, attribute: .Width, relatedBy: .Equal, toItem: self, attribute: .Width, multiplier: 1, constant: 0)) self.addConstraint(NSLayoutConstraint(item: progressContainer, attribute: .Height, relatedBy: .Equal, toItem: self, attribute: .Height, multiplier: 1, constant: 0)) self.addConstraint(NSLayoutConstraint(item: progressContainer, attribute: .CenterX, relatedBy: .Equal, toItem: self, attribute: .CenterX, multiplier: 1, constant: 0)) self.addConstraint(NSLayoutConstraint(item: progressContainer, attribute: .CenterY, relatedBy: .Equal, toItem: self, attribute: .CenterY, multiplier: 1, constant: 0)) } override func layoutSubviews() { self.layer.cornerRadius = self.bounds.width/2.0 progressContainer.layer.cornerRadius = self.bounds.width/2.0 containerImageView.layer.cornerRadius = self.bounds.width/2.0 updatePaths() } func handleSingleTap(gesture: UIGestureRecognizer) { delegate?.PAImageView(didTapped: self) } func backgroundProgressColor(color: UIColor) { backgroundProgressColor = color backgroundLayer.strokeColor = self.backgroundProgressColor.CGColor } func progressColor(color: UIColor) { progressColor = color progressLayer.strokeColor = self.progressColor.CGColor } func placeHolderImage(image: UIImage) { placeHolderImage = image if containerImageView.image == nil { containerImageView.image = image } } func imageURL(URL: NSURL) { let urlRequest = NSURLRequest(URL: URL) var cachedImage = (cacheEnabled) ? cache.imageForURL(URL) : nil if (cachedImage != nil) { updateImage(cachedImage!, animated: false) } else { let session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration(), delegate: self, delegateQueue: nil) let downloadTask = session.downloadTaskWithRequest(urlRequest) downloadTask.resume() } } func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didFinishDownloadingToURL location: NSURL) { let image = UIImage(data: NSData(contentsOfURL: location)!) dispatch_async(dispatch_get_main_queue(), { self.updateImage(image! , animated: true) }) if cacheEnabled { if let url = downloadTask.response?.URL { cache.image(image!, URL: url) } } } func URLSession(session: NSURLSession!, downloadTask: NSURLSessionDownloadTask!, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) { let progress: CGFloat = CGFloat(totalBytesWritten)/CGFloat(totalBytesExpectedToWrite) dispatch_async(dispatch_get_main_queue(), { self.progressLayer.strokeEnd = progress self.backgroundLayer.strokeStart = progress }) } func updateImage(image: UIImage, animated: Bool) { let duration = (animated) ? 0.3 : 0.0 let delay = (animated) ? 0.1 : 0.0 containerImageView.transform = CGAffineTransformMakeScale(0, 0) containerImageView.alpha = 0.0 containerImageView.image = image UIView.animateWithDuration(duration, animations: { self.progressContainer.transform = CGAffineTransformMakeScale(1.1, 1.1) self.progressContainer.alpha = 0.0 UIView.animateWithDuration(duration, delay: delay, options: UIViewAnimationOptions.CurveEaseOut, animations: { self.containerImageView.transform = CGAffineTransformIdentity self.containerImageView.alpha = 1.0 }, completion: nil) }, completion: { finished in self.progressLayer.strokeColor = self.backgroundProgressColor.CGColor UIView.animateWithDuration(duration, animations: { self.progressContainer.transform = CGAffineTransformIdentity self.progressContainer.alpha = 1.0 }) }) } } protocol PASImageViewDelegate { func PAImageView(didTapped imageView: PASImageView) }
mit
5ef9e213edf640567826750582c8864f
39.862205
180
0.64062
5.322564
false
false
false
false
wordpress-mobile/WordPress-iOS
WordPress/Classes/ViewRelated/Site Creation/Site Intent/SiteIntentViewController.swift
1
8134
import UIKit class SiteIntentViewController: CollapsableHeaderViewController { private let selection: SiteIntentStep.SiteIntentSelection private let tableView: UITableView private var availableVerticals: [SiteIntentVertical] = SiteIntentData.defaultVerticals { didSet { contentSizeWillChange() } } private let searchBar: UISearchBar = { let searchBar = UISearchBar() searchBar.translatesAutoresizingMaskIntoConstraints = false WPStyleGuide.configureSearchBar(searchBar, backgroundColor: .clear, returnKeyType: .search) searchBar.setImage(UIImage(), for: .search, state: .normal) return searchBar }() override var separatorStyle: SeparatorStyle { return .hidden } override var alwaysResetHeaderOnRotation: Bool { // the default behavior works on iPad, so let's not override it WPDeviceIdentification.isiPhone() } init(_ selection: @escaping SiteIntentStep.SiteIntentSelection) { self.selection = selection tableView = UITableView(frame: .zero, style: .plain) super.init( scrollableView: tableView, mainTitle: Strings.mainTitle, navigationBarTitle: Strings.navigationBarTitle, prompt: Strings.prompt, primaryActionTitle: Strings.primaryAction, accessoryView: searchBar ) tableView.dataSource = self searchBar.delegate = self } // MARK: UIViewController required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() configureNavigationBar() configureTable() largeTitleView.numberOfLines = Metrics.largeTitleLines SiteCreationAnalyticsHelper.trackSiteIntentViewed() } override func viewDidLayoutSubviews() { searchBar.placeholder = Strings.searchTextFieldPlaceholder } override func estimatedContentSize() -> CGSize { let visibleCells = CGFloat(availableVerticals.count) let height = visibleCells * IntentCell.estimatedSize.height return CGSize(width: view.frame.width, height: height) } // MARK: UI Setup private func configureNavigationBar() { // Title navigationItem.backButtonTitle = Strings.backButtonTitle // Skip button navigationItem.rightBarButtonItem = UIBarButtonItem(title: Strings.skipButtonTitle, style: .done, target: self, action: #selector(skipButtonTapped)) // Cancel button navigationItem.leftBarButtonItem = UIBarButtonItem(title: Strings.cancelButtonTitle, style: .done, target: self, action: #selector(closeButtonTapped)) navigationItem.leftBarButtonItem?.accessibilityIdentifier = "site-intent-cancel-button" } private func configureTable() { let cellName = IntentCell.cellReuseIdentifier() let nib = UINib(nibName: cellName, bundle: nil) tableView.register(nib, forCellReuseIdentifier: cellName) tableView.register(InlineErrorRetryTableViewCell.self, forCellReuseIdentifier: InlineErrorRetryTableViewCell.cellReuseIdentifier()) tableView.cellLayoutMarginsFollowReadableWidth = true tableView.backgroundColor = .basicBackground tableView.accessibilityIdentifier = "Site Intent Table" } // MARK: Actions @objc private func skipButtonTapped(_ sender: Any) { SiteCreationAnalyticsHelper.trackSiteIntentSkipped() selection(nil) } @objc private func closeButtonTapped(_ sender: Any) { SiteCreationAnalyticsHelper.trackSiteIntentCanceled() dismiss(animated: true) } } // MARK: Constants extension SiteIntentViewController { private enum Strings { static let mainTitle = NSLocalizedString("What's your website about?", comment: "Select the site's intent. Title") static let navigationBarTitle = NSLocalizedString("Site Topic", comment: "Title of the navigation bar, shown when the large title is hidden.") static let prompt = NSLocalizedString("Choose a topic from the list below or type your own.", comment: "Select the site's intent. Subtitle") static let primaryAction = NSLocalizedString("Continue", comment: "Button to progress to the next step") static let backButtonTitle = NSLocalizedString("Topic", comment: "Shortened version of the main title to be used in back navigation") static let skipButtonTitle = NSLocalizedString("Skip", comment: "Continue without making a selection") static let cancelButtonTitle = NSLocalizedString("Cancel", comment: "Cancel site creation") static let searchTextFieldPlaceholder = NSLocalizedString("E.g. Fashion, Poetry, Politics", comment: "Placeholder text for the search field int the Site Intent screen.") static let continueButtonTitle = NSLocalizedString("Continue", comment: "Title of the continue button for the Site Intent screen.") } private enum Metrics { static let largeTitleLines = 2 static let continueButtonPadding: CGFloat = 16 static let continueButtonBottomOffset: CGFloat = 12 static let continueButtonHeight: CGFloat = 44 } } // MARK: UITableViewDataSource extension SiteIntentViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return availableVerticals.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { return configureIntentCell(tableView, cellForRowAt: indexPath) } func configureIntentCell(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let cell = tableView.dequeueReusableCell(withIdentifier: IntentCell.cellReuseIdentifier()) as? IntentCell else { assertionFailure("This is a programming error - IntentCell has not been properly registered!") return UITableViewCell() } let vertical = availableVerticals[indexPath.row] cell.model = vertical return cell } } // MARK: UITableViewDelegate extension SiteIntentViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) let vertical = availableVerticals[indexPath.row] SiteCreationAnalyticsHelper.trackSiteIntentSelected(vertical) selection(vertical) } } // MARK: Search Bar Delegate extension SiteIntentViewController: UISearchBarDelegate { func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) { // do not unfilter already filtered content, when navigating back to this page SiteCreationAnalyticsHelper.trackSiteIntentSearchFocused() guard availableVerticals == SiteIntentData.defaultVerticals else { return } availableVerticals = SiteIntentData.allVerticals tableView.reloadData() tableView.scrollVerticallyToView(searchBar.searchTextField, animated: true) } func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { availableVerticals = SiteIntentData.filterVerticals(with: searchText) tableView.reloadData() } }
gpl-2.0
e40259e5475dfdfaae59b0631459b47e
39.467662
177
0.648267
6.05659
false
false
false
false
wordpress-mobile/WordPress-iOS
WordPress/WordPressTest/ReaderTrackerTests.swift
2
1873
import UIKit import XCTest import Nimble @testable import WordPress class ReaderTrackerTests: XCTestCase { /// Return 20s as the time spent in Reader /// func testTrackTimeSpentInMainReader() { let nowMock = DateMock(startTime: Date(), endTime: Date() + 20) let tracker = ReaderTracker(now: nowMock.now) tracker.start(.main) tracker.stop(.main) expect(tracker.data()).to(equal([ "time_in_main_reader": 20, "time_in_reader_filtered_list": 0, "time_in_reader_post": 0 ])) } /// Return 16s as the time spent in filtered list /// func testTrackTimeSpentInFilteredList() { let nowMock = DateMock(startTime: Date(), endTime: Date() + 15.5) let tracker = ReaderTracker(now: nowMock.now) tracker.start(.filteredList) tracker.stop(.filteredList) expect(tracker.data()).to(equal([ "time_in_main_reader": 0, "time_in_reader_filtered_list": 16, "time_in_reader_post": 0 ])) } /// Return 60s as the time spent in post /// func testTrackTimeSpentInPost() { let nowMock = DateMock(startTime: Date(), endTime: Date() + 60) let tracker = ReaderTracker(now: nowMock.now) tracker.start(.readerPost) tracker.stop(.readerPost) expect(tracker.data()).to(equal([ "time_in_main_reader": 0, "time_in_reader_filtered_list": 0, "time_in_reader_post": 60 ])) } } private class DateMock { private let startTime: Date private let endTime: Date var called = 0 init(startTime: Date, endTime: Date) { self.startTime = startTime self.endTime = endTime } func now() -> Date { called += 1 return called == 1 ? startTime : endTime } }
gpl-2.0
eeecd2c32efc8d7c1c5b68244b1d8328
24.657534
73
0.58142
3.96822
false
true
false
false
Miridescen/M_365key
365KEY_swift/365KEY_swift/MainController/Class/UserCenter/controller/subController/SKChangePhoneNumberViewController.swift
1
7960
// // SKChangePhoneNumberViewController.swift // 365KEY_swift // // Created by 牟松 on 2016/12/14. // Copyright © 2016年 DoNews. All rights reserved. // import UIKit class SKChangePhoneNumberViewController: UIViewController { var navBar: UINavigationBar? var navItem: UINavigationItem? var titleName: String? var newPhoneNumTF: UITextField? var captachTF: UITextField? var fatchCapeachBtn: UIButton? var userShared: SKUserShared? override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.white addSubView() } } extension SKChangePhoneNumberViewController { func addSubView() { navBar = UINavigationBar(frame: CGRect(x: 0, y: 0, width: SKScreenWidth, height: 64)) navBar?.isTranslucent = false navBar?.barTintColor = UIColor().mainColor navBar?.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.white] view.addSubview(navBar!) navItem = UINavigationItem() navItem?.title = "修改\(title!)" navItem?.leftBarButtonItem = UIBarButtonItem(SK_barButtonItem: "取消", tragtic: self, action: #selector(navLeftBarButtonDidClick)) navItem?.rightBarButtonItem = UIBarButtonItem(SK_barButtonItem: "保存", tragtic: self, action: #selector(navRightBarButtonDidClick)) navBar?.items = [navItem!] newPhoneNumTF = UITextField(frame: CGRect(x: 40, y: 26+64, width: SKScreenWidth-80, height: 40)) newPhoneNumTF?.placeholder = "新\(title!)" newPhoneNumTF?.textAlignment = .center newPhoneNumTF?.borderStyle = .roundedRect newPhoneNumTF?.keyboardType = .numberPad newPhoneNumTF?.delegate = self view.addSubview(newPhoneNumTF!) captachTF = UITextField(frame: CGRect(x: 40, y: 26+64+10+40, width: SKScreenWidth-80, height: 40)) captachTF?.placeholder = "验证码" captachTF?.textAlignment = .center captachTF?.borderStyle = .roundedRect captachTF?.delegate = self view.addSubview(captachTF!) fatchCapeachBtn = UIButton(frame: CGRect(x: SKScreenWidth-80-66, y: 0, width: 66, height: 40)) fatchCapeachBtn?.setTitle("获取", for: .normal) fatchCapeachBtn?.setTitleColor(UIColor.white, for: .normal) fatchCapeachBtn?.setBackgroundImage(UIImage(named: "bg_huoqu"), for: .normal) fatchCapeachBtn?.addTarget(self, action: #selector(fatchCapeachBtnDidClick), for: .touchUpInside) captachTF?.addSubview(fatchCapeachBtn!) } @objc private func fatchCapeachBtnDidClick(button: UIButton){ if checkPhoneNum(string: (newPhoneNumTF?.text)!) { NSURLConnection.connection.checkPhoneNumIsUsed(with: (newPhoneNumTF?.text)!){ isSuccess in if isSuccess { // 倒计时 var timeout: Int = 60 let queue = DispatchQueue.global() let source = DispatchSource.makeTimerSource(flags: [], queue: queue) source.scheduleRepeating(deadline: .now(), interval: DispatchTimeInterval.seconds(1), leeway: DispatchTimeInterval.milliseconds(100)) source.setEventHandler{ timeout -= 1 if timeout <= 0 { source.cancel() DispatchQueue.main.async { button.setTitle("获取", for: .normal) button.isUserInteractionEnabled = true } } else { button.isUserInteractionEnabled = false DispatchQueue.main.async { UIView.beginAnimations(nil, context: nil) UIView.setAnimationDuration(1) button.setTitle("\(timeout)秒", for: .normal) UIView.commitAnimations() } } } source.resume() // 发送请求 NSURLConnection.connection.registerFatchCaptcha(with: (self.newPhoneNumTF?.text)!){isSuccess,codeNum in switch codeNum! { case 0:{ SKProgressHUD.setSuccessString(with: "验证码发送成功") }() case 1:{ SKProgressHUD.setErrorString(with: "手机号已被注册") }() default:{ SKProgressHUD.setErrorString(with: "验证码发送失败") }() } } } else { SKProgressHUD.setErrorString(with: "该手机号已被注册") } } } } @objc private func navLeftBarButtonDidClick(){ _ = navigationController?.popViewController(animated: true) } @objc private func navRightBarButtonDidClick(){ if checkEmptyString(string: newPhoneNumTF?.text) || checkEmptyString(string: captachTF?.text) { var params = [String: AnyObject]() params["uid"] = userShared?.uid as AnyObject if checkPhoneNum(string: (newPhoneNumTF?.text)!) { params["phone"] = newPhoneNumTF?.text as AnyObject?; } else { return } NSURLConnection.connection.chengeUserInfo(params: params, completion: { (bool, codeNum) in if bool { if codeNum == 0{ NSURLConnection.connection.userInfoRequest(compeltion: { (bool) in }) _ = self.navigationController?.popViewController(animated: true) SKProgressHUD.setSuccessString(with: "修改\(self.title!)成功") } else if codeNum == -11 { SKProgressHUD.setErrorString(with: "新电话和原电话相同") } else { SKProgressHUD.setErrorString(with: "修改电话失败") } } else { SKProgressHUD.setErrorString(with: "修改电话失败") } }) } else { SKProgressHUD.setErrorString(with: "信息不能为空") } } func checkEmptyString(string: String?) -> Bool { if string?.isEmpty == true || string?.characters.count == 0 || string == "" { return false } else { return true } } func checkPhoneNum(string: String) -> Bool { if string.isEmpty || string.characters.count == 0 { SKProgressHUD.setErrorString(with: "新电话不能为空") return false } let phoneRegex = "^1(3[0-9]|5[0-9]|7[0-9]|8[0-9])\\d{8}$" let phonePred = NSPredicate(format: "SELF MATCHES %@", phoneRegex) let isPhoneNum: Bool = phonePred.evaluate(with: string) if !isPhoneNum { SKProgressHUD.setErrorString(with: "新电话格式不正确") return false } return true } } extension SKChangePhoneNumberViewController: UITextFieldDelegate{ func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return true } }
apache-2.0
023231e0f70d32d90bc9960782af3fed
36.84878
153
0.523521
5.183033
false
false
false
false
lucasmpaim/GuizionCardView
guizion-card-view/Classes/Cards.swift
1
2346
// // Cards.swift // Pods // // Created by Guizion Labs on 07/07/16. // // import Foundation public enum CardTypes: String { case Diners = "Diners Club" case Visa = "Visa" case Mastercard = "MasterCard" case JCB = "JCB" case AmericanExpress = "American Express" case LaserCardServices = "Laser Card Services Ltd." case ChinaUnionPay = "China UnionPay" case Maestro = "Maestro (MasterCard)" case Discover = "Discover" case NotRecognized = "Not Recognized" case None = "None" } /** <key>numberColor</key> <string>#D7D7D7</string> <key>nameColor</key> <string>#D4D4D4</string> <key>expirationColor</key> <string>#D4D4D4</string> <key>ccvColor</key> <string>#4B4B4B</string> */ public struct CardInfo { var pattern: NSRegularExpression? var frontImage: String? var backImage: String? var name: String? var group: String? var mask: String? var numberColor: String? var nameColor: String? var expirationColor: String? var ccvColor: String? init(dictionary: Dictionary<String, String>) { self.pattern = try! NSRegularExpression(pattern: dictionary["pattern"]!, options: [.caseInsensitive]) self.frontImage = dictionary["imageFront"] self.backImage = dictionary["imageBack"] self.name = dictionary["companyName"] self.group = dictionary["numberGrouping"] if let groupMask = group { let groups = groupMask.split(separator: ",") var mask = "" groups.forEach { let groupSize = Int($0)! for _ in 0..<groupSize {mask += "#"} mask += " " } self.mask = mask } self.numberColor = dictionary["numberColor"] self.nameColor = dictionary["nameColor"] self.expirationColor = dictionary["expirationColor"] self.ccvColor = dictionary["ccvColor"] } } public struct CreditCard { let cardType: CardTypes let card: CardInfo? init() { self.cardType = .None self.card = nil } init(type: CardTypes) { self.cardType = type self.card = nil } init(type: CardTypes, card: CardInfo) { self.cardType = type self.card = card } }
mit
0186c6293aa7aa9e18dba9f58fb343a8
22.46
109
0.58994
3.923077
false
false
false
false
jcavar/refresher
PullToRefreshDemo/PacmanAnimator.swift
1
4138
// // PacmanAnimator.swift // // Copyright (c) 2014 Josip Cavar // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import Foundation import Refresher import QuartzCore import UIKit class PacmanAnimator: UIView, PullToRefreshViewDelegate { private let layerLoader = CAShapeLayer() private let layerSeparator = CAShapeLayer() override init(frame: CGRect) { super.init(frame: frame) layerLoader.lineWidth = 8 layerLoader.strokeColor = UIColor(red: 0, green: 0.7, blue: 1, alpha: 1).cgColor layerLoader.strokeEnd = 0 layerLoader.fillColor = UIColor.clear.cgColor layerSeparator.lineWidth = 8 layerSeparator.strokeColor = UIColor(red: 0.7, green: 0.7, blue: 0.7, alpha: 1).cgColor layerSeparator.fillColor = UIColor.clear.cgColor } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func pullToRefresh(_ view: PullToRefreshView, progressDidChange progress: CGFloat) { layerLoader.strokeEnd = progress } func pullToRefresh(_ view: PullToRefreshView, stateDidChange state: PullToRefreshViewState) { } func pullToRefreshAnimationDidEnd(_ view: PullToRefreshView) { layerLoader.removeAllAnimations() } func pullToRefreshAnimationDidStart(_ view: PullToRefreshView) { let pathAnimationEnd = CABasicAnimation(keyPath: "strokeEnd") pathAnimationEnd.duration = 0.5 pathAnimationEnd.repeatCount = 100 pathAnimationEnd.autoreverses = true pathAnimationEnd.fromValue = 1 pathAnimationEnd.toValue = 0.8 layerLoader.add(pathAnimationEnd, forKey: "strokeEndAnimation") let pathAnimationStart = CABasicAnimation(keyPath: "strokeStart") pathAnimationStart.duration = 0.5 pathAnimationStart.repeatCount = 100 pathAnimationStart.autoreverses = true pathAnimationStart.fromValue = 0 pathAnimationStart.toValue = 0.2 layerLoader.add(pathAnimationStart, forKey: "strokeStartAnimation") } override func layoutSubviews() { super.layoutSubviews() if let superview = superview { if layerSeparator.superlayer == nil { superview.layer.addSublayer(layerSeparator) } if layerLoader.superlayer == nil { superview.layer.addSublayer(layerLoader) } let center = CGPoint(x: 30, y: superview.frame.size.height / 2) let bezierPathLoader = UIBezierPath(arcCenter: center, radius: CGFloat(10), startAngle: CGFloat(0), endAngle: CGFloat(2 * Double.pi), clockwise: true) let bezierPathSeparator = UIBezierPath() bezierPathSeparator.move(to: CGPoint(x: 0, y: superview.frame.height - 1)) bezierPathSeparator.addLine(to: CGPoint(x: superview.frame.width, y: superview.frame.height - 1)) layerLoader.path = bezierPathLoader.cgPath layerSeparator.path = bezierPathLoader.cgPath } } }
mit
a9a403e9b970121affb2ad5d58c9b30c
40.38
162
0.689222
5.052503
false
false
false
false
Sadmansamee/quran-ios
Pods/GenericDataSources/Sources/DelegatedGeneralCollectionView.swift
1
7409
// // DelegatedGeneralCollectionView.swift // GenericDataSource // // Created by Mohamed Afifi on 3/20/16. // Copyright © 2016 mohamede1945. All rights reserved. // import UIKit protocol GeneralCollectionViewMapping { func globalSectionForLocalSection(_ localSection: Int) -> Int func localIndexPathForGlobalIndexPath(_ globalIndexPath: IndexPath) -> IndexPath func globalIndexPathForLocalIndexPath(_ localIndexPath: IndexPath) -> IndexPath var delegate: GeneralCollectionView? { get } } @objc class DelegatedGeneralCollectionView: NSObject, GeneralCollectionView { let mapping: GeneralCollectionViewMapping var delegate: GeneralCollectionView { guard let delegate = mapping.delegate else { fatalError("Couldn't call \(#function) of \(self) with a nil delegate. This is usually because you didn't set your UITableView/UICollection to ds_reusableViewDelegate for the GenericDataSource.") } return delegate } init(mapping: GeneralCollectionViewMapping) { self.mapping = mapping } // MARK:- Scroll View var ds_scrollView: UIScrollView { return delegate.ds_scrollView } // MARK:- Register, dequeue func ds_register(_ cellClass: AnyClass?, forCellWithReuseIdentifier identifier: String) { delegate.ds_register(cellClass, forCellWithReuseIdentifier: identifier) } func ds_register(_ nib: UINib?, forCellWithReuseIdentifier identifier: String) { delegate.ds_register(nib, forCellWithReuseIdentifier: identifier) } func ds_dequeueReusableCell(withIdentifier identifier: String, for indexPath: IndexPath) -> ReusableCell { let globalIndexPath = ds_globalIndexPathForLocalIndexPath(indexPath) return delegate.ds_dequeueReusableCell(withIdentifier: identifier, for: globalIndexPath) } // MARK:- Numbers func ds_numberOfSections() -> Int { return delegate.ds_numberOfSections() } func ds_numberOfItems(inSection section: Int) -> Int { let globalSection = ds_globalSectionForLocalSection(section) return delegate.ds_numberOfItems(inSection: globalSection) } // MARK:- Manpulate items and sections func ds_reloadData() { delegate.ds_reloadData() } func ds_performBatchUpdates(_ updates: (() -> Void)?, completion: ((Bool) -> Void)?) { delegate.ds_performBatchUpdates(updates, completion: completion) } func ds_insertSections(_ sections: IndexSet, with animation: UITableViewRowAnimation) { let globalSections = ds_globalSectionSetForLocalSectionSet(sections) delegate.ds_insertSections(globalSections, with: animation) } func ds_deleteSections(_ sections: IndexSet, with animation: UITableViewRowAnimation) { let globalSections = ds_globalSectionSetForLocalSectionSet(sections) delegate.ds_deleteSections(globalSections, with: animation) } func ds_reloadSections(_ sections: IndexSet, with animation: UITableViewRowAnimation) { let globalSections = ds_globalSectionSetForLocalSectionSet(sections) delegate.ds_reloadSections(globalSections, with: animation) } func ds_moveSection(_ section: Int, toSection newSection: Int) { let globalSection = ds_globalSectionForLocalSection(section) let globalNewSection = ds_globalSectionForLocalSection(newSection) delegate.ds_moveSection(globalSection, toSection: globalNewSection) } func ds_insertItems(at indexPaths: [IndexPath], with animation: UITableViewRowAnimation) { let globalIndexPaths = ds_globalIndexPathsForLocalIndexPaths(indexPaths) delegate.ds_insertItems(at: globalIndexPaths, with: animation) } func ds_deleteItems(at indexPaths: [IndexPath], with animation: UITableViewRowAnimation) { let globalIndexPaths = ds_globalIndexPathsForLocalIndexPaths(indexPaths) delegate.ds_deleteItems(at: globalIndexPaths, with: animation) } func ds_reloadItems(at indexPaths: [IndexPath], with animation: UITableViewRowAnimation) { let globalIndexPaths = ds_globalIndexPathsForLocalIndexPaths(indexPaths) delegate.ds_reloadItems(at: globalIndexPaths, with: animation) } func ds_moveItem(at indexPath: IndexPath, to newIndexPath: IndexPath) { let globalIndexPath = ds_globalIndexPathForLocalIndexPath(indexPath) let globalNewIndexPath = ds_globalIndexPathForLocalIndexPath(newIndexPath) delegate.ds_moveItem(at: globalIndexPath, to: globalNewIndexPath) } // MARK:- Scroll func ds_scrollToItem(at indexPath: IndexPath, at scrollPosition: UICollectionViewScrollPosition, animated: Bool) { let globalIndexPath = ds_globalIndexPathForLocalIndexPath(indexPath) delegate.ds_scrollToItem(at: globalIndexPath, at: scrollPosition, animated: animated) } // MARK:- Select/Deselect func ds_selectItem(at indexPath: IndexPath?, animated: Bool, scrollPosition: UICollectionViewScrollPosition) { let globalIndexPath: IndexPath? if let indexPath = indexPath { globalIndexPath = ds_globalIndexPathForLocalIndexPath(indexPath) } else { globalIndexPath = nil } delegate.ds_selectItem(at: globalIndexPath, animated: animated, scrollPosition: scrollPosition) } func ds_deselectItem(at indexPath: IndexPath, animated: Bool) { let globalIndexPath = ds_globalIndexPathForLocalIndexPath(indexPath) delegate.ds_deselectItem(at: globalIndexPath, animated: animated) } // MARK:- IndexPaths, Cells func ds_indexPath(for cell: ReusableCell) -> IndexPath? { if let indexPath = delegate.ds_indexPath(for: cell) { return ds_localIndexPathForGlobalIndexPath(indexPath) } return nil } func ds_indexPathForItem(at point: CGPoint) -> IndexPath? { if let indexPath = delegate.ds_indexPathForItem(at: point) { return ds_localIndexPathForGlobalIndexPath(indexPath) } return nil } func ds_indexPathsForVisibleItems() -> [IndexPath] { let indexPaths = delegate.ds_indexPathsForVisibleItems() return ds_localIndexPathsForGlobalIndexPaths(indexPaths) } func ds_indexPathsForSelectedItems() -> [IndexPath] { let indexPaths = delegate.ds_indexPathsForSelectedItems() return ds_localIndexPathsForGlobalIndexPaths(indexPaths) } func ds_visibleCells() -> [ReusableCell] { return delegate.ds_visibleCells() } func ds_cellForItem(at indexPath: IndexPath) -> ReusableCell? { let globalIndexPath = ds_globalIndexPathForLocalIndexPath(indexPath) return delegate.ds_cellForItem(at: globalIndexPath) } // MARK: - Local, Global func ds_localIndexPathForGlobalIndexPath(_ globalIndexPath: IndexPath) -> IndexPath { return mapping.localIndexPathForGlobalIndexPath(globalIndexPath) } func ds_globalIndexPathForLocalIndexPath(_ localIndexPath: IndexPath) -> IndexPath { return mapping.globalIndexPathForLocalIndexPath(localIndexPath) } func ds_globalSectionForLocalSection(_ localSection: Int) -> Int { return mapping.globalSectionForLocalSection(localSection) } }
mit
e81f2803296cf2f6060a36ec999aa51d
36.989744
207
0.707613
5.499629
false
false
false
false
tgyhlsb/RxSwiftExt
Source/RxSwift/retryWithBehavior.swift
5
4514
// // retryWithBehavior.swift // Pods // // Created by Anton Efimenko on 17.07.16. // Copyright © 2016 RxSwift Community. All rights reserved. // import Foundation import RxSwift /** Specifies how observable sequence will be repeated in case of an error - Immediate: Will be immediatelly repeated specified number of times - Delayed: Will be repeated after specified delay specified number of times - ExponentialDelayed: Will be repeated specified number of times. Delay will be incremented by multiplier after each iteration (multiplier = 0.5 means 50% increment) - CustomTimerDelayed: Will be repeated specified number of times. Delay will be calculated by custom closure */ public enum RepeatBehavior { case immediate (maxCount: UInt) case delayed (maxCount: UInt, time: Double) case exponentialDelayed (maxCount: UInt, initial: Double, multiplier: Double) case customTimerDelayed (maxCount: UInt, delayCalculator: (UInt) -> Double) } public typealias RetryPredicate = (Error) -> Bool extension RepeatBehavior { /** Extracts maxCount and calculates delay for current RepeatBehavior - parameter currentAttempt: Number of current attempt - returns: Tuple with maxCount and calculated delay for provided attempt */ func calculateConditions(_ currentRepetition: UInt) -> (maxCount: UInt, delay: Double) { switch self { case .immediate(let max): // if Immediate, return 0.0 as delay return (maxCount: max, delay: 0.0) case .delayed(let max, let time): // return specified delay return (maxCount: max, delay: time) case .exponentialDelayed(let max, let initial, let multiplier): // if it's first attempt, simply use initial delay, otherwise calculate delay let delay = currentRepetition == 1 ? initial : initial * pow(1 + multiplier, Double(currentRepetition - 1)) return (maxCount: max, delay: delay) case .customTimerDelayed(let max, let delayCalculator): // calculate delay using provided calculator return (maxCount: max, delay: delayCalculator(currentRepetition)) } } } extension ObservableType { /** Repeats the source observable sequence using given behavior in case of an error or until it successfully terminated - parameter behavior: Behavior that will be used in case of an error - parameter scheduler: Schedular that will be used for delaying subscription after error - parameter shouldRetry: Custom optional closure for checking error (if returns true, repeat will be performed) - returns: Observable sequence that will be automatically repeat if error occurred */ public func retry(_ behavior: RepeatBehavior, scheduler: SchedulerType = MainScheduler.instance, shouldRetry: RetryPredicate? = nil) -> Observable<E> { return retry(1, behavior: behavior, scheduler: scheduler, shouldRetry: shouldRetry) } /** Repeats the source observable sequence using given behavior in case of an error or until it successfully terminated - parameter currentAttempt: Number of current attempt - parameter behavior: Behavior that will be used in case of an error - parameter scheduler: Schedular that will be used for delaying subscription after error - parameter shouldRetry: Custom optional closure for checking error (if returns true, repeat will be performed) - returns: Observable sequence that will be automatically repeat if error occurred */ internal func retry(_ currentAttempt: UInt, behavior: RepeatBehavior, scheduler: SchedulerType = MainScheduler.instance, shouldRetry: RetryPredicate? = nil) -> Observable<E> { guard currentAttempt > 0 else { return Observable.empty() } // calculate conditions for bahavior let conditions = behavior.calculateConditions(currentAttempt) return catchError { error -> Observable<E> in // return error if exceeds maximum amount of retries guard conditions.maxCount > currentAttempt else { return Observable.error(error) } if let shouldRetry = shouldRetry, !shouldRetry(error) { // also return error if predicate says so return Observable.error(error) } guard conditions.delay > 0.0 else { // if there is no delay, simply retry return self.retry(currentAttempt + 1, behavior: behavior, scheduler: scheduler, shouldRetry: shouldRetry) } // otherwise retry after specified delay return Observable<Void>.just(()).delaySubscription(conditions.delay, scheduler: scheduler).flatMapLatest { self.retry(currentAttempt + 1, behavior: behavior, scheduler: scheduler, shouldRetry: shouldRetry) } } } }
mit
f2e9172784e450a607547faf9562f15f
42.815534
157
0.755373
4.437561
false
false
false
false
Rochester-Ting/DouyuTVDemo
RRDouyuTV/RRDouyuTV/Classes/Main(主界面)/View/PageContentView.swift
1
4866
// // PageContentView.swift // RRDouyuTV // // Created by 丁瑞瑞 on 11/10/16. // Copyright © 2016年 Rochester. All rights reserved. // import UIKit protocol PageContentViewDelegate : class { func pageContentView(_ pageContentView : PageContentView,progress:CGFloat,sourceIndex: Int,targetIndex : Int) } private let contentCellId = "contentCellId" class PageContentView: UIView { open var childVC : [UIViewController] open var parentVC : UIViewController open var startOffsetX : CGFloat open var isForbidDelegate : Bool = false weak var delegate : PageContentViewDelegate? // MARK:- 懒加载collectionView open lazy var collectionView : UICollectionView = { let layout = UICollectionViewFlowLayout() layout.itemSize = self.bounds.size layout.minimumLineSpacing = 0 layout.minimumInteritemSpacing = 0 layout.scrollDirection = .horizontal let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout) collectionView.isPagingEnabled = true collectionView.bounces = false collectionView.showsHorizontalScrollIndicator = false collectionView.delegate = self collectionView.dataSource = self collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: contentCellId) return collectionView }() init(frame: CGRect, childVC:[UIViewController] ,parentVC:UIViewController) { self.childVC = childVC self.parentVC = parentVC self.startOffsetX = 0 super.init(frame: frame) // MARK:- 设置UI setUpUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension PageContentView{ public func setUpUI(){ for vc in childVC { parentVC .addChildViewController(vc) } addSubview(collectionView) collectionView.frame = self.bounds } } // MARK:- 遵守数据源方法 extension PageContentView : UICollectionViewDataSource{ func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return childVC.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { //创建cell let cell = collectionView.dequeueReusableCell(withReuseIdentifier: contentCellId, for: indexPath) for childVC in cell.contentView.subviews { childVC.removeFromSuperview() } //取出对应的vc let vc = childVC[indexPath.item] //设置vc的frame vc.view.frame = cell.bounds cell.contentView.addSubview(vc.view) return cell } } // MARK:- 遵守代理方法 extension PageContentView : UICollectionViewDelegate{ func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { isForbidDelegate = false startOffsetX = scrollView.contentOffset.x } func scrollViewDidScroll(_ scrollView: UIScrollView) { if isForbidDelegate { return } // 获取滑动的比例 var progress : CGFloat = 0 // 获取当前的label的tag var sourceIndex : Int = 0 // 获取目标label的tag var targetIndex : Int = 0 let scrollViewW = scrollView.frame.width if startOffsetX < scrollView.contentOffset.x { // 左划 progress = scrollView.contentOffset.x / scrollViewW - floor(scrollView.contentOffset.x / scrollViewW) sourceIndex = Int(scrollView.contentOffset.x / scrollViewW) targetIndex = sourceIndex + 1 if targetIndex >= childVC.count { targetIndex = childVC.count - 1 } // MARK:- 如果划过去以后改变当前的label和目标的label if (scrollView.contentOffset.x - startOffsetX) == scrollViewW { progress = 1 targetIndex = sourceIndex } }else{ //右划 progress = 1 - (scrollView.contentOffset.x / scrollViewW - floor(scrollView.contentOffset.x / scrollViewW)) targetIndex = Int(scrollView.contentOffset.x / scrollViewW) sourceIndex = targetIndex + 1 if sourceIndex > childVC.count { sourceIndex = childVC.count - 1 } } delegate?.pageContentView(self, progress: progress, sourceIndex: sourceIndex, targetIndex: targetIndex) } } // MARK:- 对外暴露的方法 extension PageContentView{ func setCurrentIndex(_ currentIndex : Int){ isForbidDelegate = true let offSet = kScreenW * CGFloat(currentIndex) collectionView.setContentOffset(CGPoint(x:offSet, y:0), animated: true) } }
mit
707565a5e0d98922c4c338e1147f4ae0
35.51938
121
0.652303
5.39016
false
false
false
false
blg-andreasbraun/ProcedureKit
Sources/ProcedureQueue.swift
2
10110
// // ProcedureKit // // Copyright © 2016 ProcedureKit. All rights reserved. // import Foundation public protocol OperationQueueDelegate: class { /** The operation queue will add a new operation. This is for information only, the delegate cannot affect whether the operation is added, or other control flow. - paramter queue: the `OperationQueue`. - paramter operation: the `Operation` instance about to be added. */ func operationQueue(_ queue: OperationQueue, willAddOperation operation: Operation) /** An operation will finish on the queue. - parameter queue: the `OperationQueue`. - parameter operation: the `Operation` instance which finished. - parameter errors: an array of `Error`s. */ func operationQueue(_ queue: OperationQueue, willFinishOperation operation: Operation) /** An operation did finish on the queue. - parameter queue: the `OperationQueue`. - parameter operation: the `Operation` instance which finished. - parameter errors: an array of `Error`s. */ func operationQueue(_ queue: OperationQueue, didFinishOperation operation: Operation) } public extension OperationQueueDelegate { func operationQueue(_ queue: OperationQueue, willAddOperation operation: Operation) { /* default no-op */ } func operationQueue(_ queue: OperationQueue, willFinishOperation operation: Operation) { /* default no-op */ } } /** A protocol which the `OperationQueue`'s delegate must conform to. The delegate is informed when the queue is about to add an operation/procedure, and when they finish. Because it is a delegate protocol, conforming types must be classes, as the queue weakly owns it. */ public protocol ProcedureQueueDelegate: OperationQueueDelegate { /** The procedure queue will add a new operation. This is for information only, the delegate cannot affect whether the operation is added, or other control flow. - paramter queue: the `ProcedureQueue`. - paramter operation: the `Operation` instance about to be added. */ func procedureQueue(_ queue: ProcedureQueue, willAddOperation operation: Operation) /** The procedure queue did add a new operation. This is for information only. - paramter queue: the `ProcedureQueue`. - paramter operation: the `Operation` instance which was added. */ func procedureQueue(_ queue: ProcedureQueue, didAddOperation operation: Operation) /** An operation will finish on the queue. - parameter queue: the `ProcedureQueue`. - parameter operation: the `Operation` instance which finished. - parameter errors: an array of `Error`s. */ func procedureQueue(_ queue: ProcedureQueue, willFinishOperation operation: Operation, withErrors errors: [Error]) /** An operation has finished on the queue. - parameter queue: the `ProcedureQueue`. - parameter operation: the `Operation` instance which finished. - parameter errors: an array of `Error`s. */ func procedureQueue(_ queue: ProcedureQueue, didFinishOperation operation: Operation, withErrors errors: [Error]) /** The operation queue will add a new operation via produceOperation(). This is for information only, the delegate cannot affect whether the operation is added, or other control flow. - paramter queue: the `ProcedureQueue`. - paramter operation: the `Operation` instance about to be added. */ func procedureQueue(_ queue: ProcedureQueue, willProduceOperation operation: Operation) } public extension ProcedureQueueDelegate { func procedureQueue(_ queue: ProcedureQueue, willAddOperation operation: Operation) { /* default no-op */ } func procedureQueue(_ queue: ProcedureQueue, didAddOperation operation: Operation) { /* default no-op */ } func procedureQueue(_ queue: ProcedureQueue, willProduceOperation operation: Operation) { /* default no-op */ } } /** An `OperationQueue` subclass which supports the features of ProcedureKit. All functionality is achieved via the overridden functionality of `addOperation`. */ open class ProcedureQueue: OperationQueue { private class MainProcedureQueue: ProcedureQueue { override init() { super.init() underlyingQueue = DispatchQueue.main maxConcurrentOperationCount = 1 } } private static let sharedMainQueue = MainProcedureQueue() /** Override OperationQueue's main to return the main queue as an ProcedureQueue - returns: The main queue */ open override class var main: ProcedureQueue { return sharedMainQueue } /** The queue's delegate, helpful for reporting activity. - parameter delegate: a weak `ProcedureQueueDelegate?` */ open weak var delegate: ProcedureQueueDelegate? = nil // swiftlint:disable function_body_length // swiftlint:disable cyclomatic_complexity /** Adds the operation to the queue. Subclasses which override this method must call this implementation as it is critical to how ProcedureKit function. - parameter op: an `Operation` instance. */ open func add(operation: Operation) { defer { super.addOperation(operation) delegate?.procedureQueue(self, didAddOperation: operation) } guard let procedure = operation as? Procedure else { operation.addCompletionBlock { [weak self, weak operation] in if let queue = self, let operation = operation { queue.delegate?.operationQueue(queue, didFinishOperation: operation) } } delegate?.operationQueue(self, willAddOperation: operation) return } procedure.log.verbose(message: "Adding to queue") /// Add an observer to invoke the will finish delegate method procedure.addWillFinishBlockObserver { [weak self] procedure, errors in if let queue = self { queue.delegate?.procedureQueue(queue, willFinishOperation: procedure, withErrors: errors) } } /// Add an observer to invoke the did finish delegate method procedure.addDidFinishBlockObserver { [weak self] procedure, errors in if let queue = self { queue.delegate?.procedureQueue(queue, didFinishOperation: procedure, withErrors: errors) } } /// Process any conditions if procedure.conditions.count > 0 { /// Check for mutual exclusion conditions let manager = ExclusivityManager.sharedInstance let mutuallyExclusiveConditions = procedure.conditions.filter { $0.isMutuallyExclusive } var previousMutuallyExclusiveOperations = Set<Operation>() for condition in mutuallyExclusiveConditions { let category = "\(condition.category)" if let previous = manager.add(procedure: procedure, category: category) { previousMutuallyExclusiveOperations.insert(previous) } } // Create the condition evaluator let evaluator = procedure.evaluateConditions() // Get the condition dependencies let indirectDependencies = procedure.indirectDependencies // If there are dependencies if indirectDependencies.count > 0 { // Filter out the indirect dependencies which have already been added to the queue let indirectDependenciesToProcess = indirectDependencies.filter { !self.operations.contains($0) } // Check to see if there are any which need processing if indirectDependenciesToProcess.count > 0 { // Iterate through the indirect dependencies indirectDependenciesToProcess.forEach { // Indirect dependencies are executed after // any previous mutually exclusive operation(s) $0.add(dependencies: previousMutuallyExclusiveOperations) // Indirect dependencies are executed after // all direct dependencies $0.add(dependencies: procedure.directDependencies) // Only evaluate conditions after all indirect // dependencies have finished evaluator.addDependency($0) } // Add indirect dependencies add(operations: indirectDependenciesToProcess) } } // Add the evaluator addOperation(evaluator) } // Indicate to the operation that it is to be enqueued procedure.willEnqueue(on: self) delegate?.procedureQueue(self, willAddOperation: procedure) } // swiftlint:enable cyclomatic_complexity // swiftlint:enable function_body_length /** Adds the operations to the queue. - parameter ops: an array of `NSOperation` instances. - parameter wait: a Bool flag which is ignored. */ open override func addOperations(_ ops: [Operation], waitUntilFinished wait: Bool) { ops.forEach { addOperation($0) } } /// Overrides and wraps the Swift 3 interface open override func addOperation(_ operation: Operation) { add(operation: operation) } } /// Public extensions on OperationQueue public extension OperationQueue { /** Add operations to the queue as an array - parameters ops: a array of `NSOperation` instances. */ func add<S>(operations: S) where S: Sequence, S.Iterator.Element: Operation { addOperations(Array(operations), waitUntilFinished: false) } /** Add operations to the queue as a variadic parameter - parameters ops: a variadic array of `NSOperation` instances. */ func add(operations: Operation...) { add(operations: operations) } }
mit
d50be3a035b2423e453e26a649bf7fc3
34.470175
118
0.659907
5.482104
false
false
false
false
yeziahehe/Gank
Pods/Kingfisher/Sources/General/KingfisherManager.swift
1
20125
// // KingfisherManager.swift // Kingfisher // // Created by Wei Wang on 15/4/6. // // Copyright (c) 2019 Wei Wang <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation /// The downloading progress block type. /// The parameter value is the `receivedSize` of current response. /// The second parameter is the total expected data length from response's "Content-Length" header. /// If the expected length is not available, this block will not be called. public typealias DownloadProgressBlock = ((_ receivedSize: Int64, _ totalSize: Int64) -> Void) /// Represents the result of a Kingfisher retrieving image task. public struct RetrieveImageResult { /// Gets the image object of this result. public let image: Image /// Gets the cache source of the image. It indicates from which layer of cache this image is retrieved. /// If the image is just downloaded from network, `.none` will be returned. public let cacheType: CacheType /// The `Source` from which the retrieve task begins. public let source: Source } /// Main manager class of Kingfisher. It connects Kingfisher downloader and cache, /// to provide a set of convenience methods to use Kingfisher for tasks. /// You can use this class to retrieve an image via a specified URL from web or cache. public class KingfisherManager { /// Represents a shared manager used across Kingfisher. /// Use this instance for getting or storing images with Kingfisher. public static let shared = KingfisherManager() // Mark: Public Properties /// The `ImageCache` used by this manager. It is `ImageCache.default` by default. /// If a cache is specified in `KingfisherManager.defaultOptions`, the value in `defaultOptions` will be /// used instead. public var cache: ImageCache /// The `ImageDownloader` used by this manager. It is `ImageDownloader.default` by default. /// If a downloader is specified in `KingfisherManager.defaultOptions`, the value in `defaultOptions` will be /// used instead. public var downloader: ImageDownloader /// Default options used by the manager. This option will be used in /// Kingfisher manager related methods, as well as all view extension methods. /// You can also passing other options for each image task by sending an `options` parameter /// to Kingfisher's APIs. The per image options will overwrite the default ones, /// if the option exists in both. public var defaultOptions = KingfisherOptionsInfo.empty // Use `defaultOptions` to overwrite the `downloader` and `cache`. private var currentDefaultOptions: KingfisherOptionsInfo { return [.downloader(downloader), .targetCache(cache)] + defaultOptions } private let processingQueue: CallbackQueue private convenience init() { self.init(downloader: .default, cache: .default) } init(downloader: ImageDownloader, cache: ImageCache) { self.downloader = downloader self.cache = cache let processQueueName = "com.onevcat.Kingfisher.KingfisherManager.processQueue.\(UUID().uuidString)" processingQueue = .dispatch(DispatchQueue(label: processQueueName)) } // Mark: Getting Images /// Gets an image from a given resource. /// /// - Parameters: /// - resource: The `Resource` object defines data information like key or URL. /// - options: Options to use when creating the animated image. /// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an /// `expectedContentLength`, this block will not be called. `progressBlock` is always called in /// main queue. /// - completionHandler: Called when the image retrieved and set finished. This completion handler will be invoked /// from the `options.callbackQueue`. If not specified, the main queue will be used. /// - Returns: A task represents the image downloading. If there is a download task starts for `.network` resource, /// the started `DownloadTask` is returned. Otherwise, `nil` is returned. /// /// - Note: /// This method will first check whether the requested `resource` is already in cache or not. If cached, /// it returns `nil` and invoke the `completionHandler` after the cached image retrieved. Otherwise, it /// will download the `resource`, store it in cache, then call `completionHandler`. /// @discardableResult public func retrieveImage( with resource: Resource, options: KingfisherOptionsInfo? = nil, progressBlock: DownloadProgressBlock? = nil, completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)?) -> DownloadTask? { let source = Source.network(resource) return retrieveImage( with: source, options: options, progressBlock: progressBlock, completionHandler: completionHandler ) } /// Gets an image from a given resource. /// /// - Parameters: /// - source: The `Source` object defines data information from network or a data provider. /// - options: Options to use when creating the animated image. /// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an /// `expectedContentLength`, this block will not be called. `progressBlock` is always called in /// main queue. /// - completionHandler: Called when the image retrieved and set finished. This completion handler will be invoked /// from the `options.callbackQueue`. If not specified, the main queue will be used. /// - Returns: A task represents the image downloading. If there is a download task starts for `.network` resource, /// the started `DownloadTask` is returned. Otherwise, `nil` is returned. /// /// - Note: /// This method will first check whether the requested `source` is already in cache or not. If cached, /// it returns `nil` and invoke the `completionHandler` after the cached image retrieved. Otherwise, it /// will try to load the `source`, store it in cache, then call `completionHandler`. /// public func retrieveImage( with source: Source, options: KingfisherOptionsInfo? = nil, progressBlock: DownloadProgressBlock? = nil, completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)?) -> DownloadTask? { let options = currentDefaultOptions + (options ?? .empty) return retrieveImage( with: source, options: KingfisherParsedOptionsInfo(options), progressBlock: progressBlock, completionHandler: completionHandler) } func retrieveImage( with source: Source, options: KingfisherParsedOptionsInfo, progressBlock: DownloadProgressBlock? = nil, completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)?) -> DownloadTask? { if options.forceRefresh { return loadAndCacheImage( source: source, options: options, progressBlock: progressBlock, completionHandler: completionHandler) } else { let loadedFromCache = retrieveImageFromCache( source: source, options: options, completionHandler: completionHandler) if loadedFromCache { return nil } if options.onlyFromCache { let error = KingfisherError.cacheError(reason: .imageNotExisting(key: source.cacheKey)) completionHandler?(.failure(error)) return nil } return loadAndCacheImage( source: source, options: options, progressBlock: progressBlock, completionHandler: completionHandler) } } func provideImage( provider: ImageDataProvider, options: KingfisherParsedOptionsInfo, completionHandler: ((Result<ImageLoadingResult, KingfisherError>) -> Void)?) { guard let completionHandler = completionHandler else { return } provider.data { result in switch result { case .success(let data): (options.processingQueue ?? self.processingQueue).execute { let processor = options.processor let processingItem = ImageProcessItem.data(data) guard let image = processor.process(item: processingItem, options: options) else { options.callbackQueue.execute { let error = KingfisherError.processorError( reason: .processingFailed(processor: processor, item: processingItem)) completionHandler(.failure(error)) } return } options.callbackQueue.execute { let result = ImageLoadingResult(image: image, url: nil, originalData: data) completionHandler(.success(result)) } } case .failure(let error): options.callbackQueue.execute { let error = KingfisherError.imageSettingError( reason: .dataProviderError(provider: provider, error: error)) completionHandler(.failure(error)) } } } } @discardableResult func loadAndCacheImage( source: Source, options: KingfisherParsedOptionsInfo, progressBlock: DownloadProgressBlock? = nil, completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)?) -> DownloadTask? { func cacheImage(_ result: Result<ImageLoadingResult, KingfisherError>) { switch result { case .success(let value): // Add image to cache. let targetCache = options.targetCache ?? self.cache targetCache.store( value.image, original: value.originalData, forKey: source.cacheKey, options: options, toDisk: !options.cacheMemoryOnly) { _ in if options.waitForCache { let result = RetrieveImageResult(image: value.image, cacheType: .none, source: source) completionHandler?(.success(result)) } } // Add original image to cache if necessary. let needToCacheOriginalImage = options.cacheOriginalImage && options.processor != DefaultImageProcessor.default if needToCacheOriginalImage { let originalCache = options.originalCache ?? targetCache originalCache.storeToDisk( value.originalData, forKey: source.cacheKey, processorIdentifier: DefaultImageProcessor.default.identifier, expiration: options.diskCacheExpiration) } if !options.waitForCache { let result = RetrieveImageResult(image: value.image, cacheType: .none, source: source) completionHandler?(.success(result)) } case .failure(let error): completionHandler?(.failure(error)) } } switch source { case .network(let resource): let downloader = options.downloader ?? self.downloader return downloader.downloadImage( with: resource.downloadURL, options: options, progressBlock: progressBlock, completionHandler: cacheImage) case .provider(let provider): provideImage(provider: provider, options: options, completionHandler: cacheImage) return nil } } /// Retrieves image from memory or disk cache. /// /// - Parameters: /// - source: The target source from which to get image. /// - key: The key to use when caching the image. /// - url: Image request URL. This is not used when retrieving image from cache. It is just used for /// `RetrieveImageResult` callback compatibility. /// - options: Options on how to get the image from image cache. /// - completionHandler: Called when the image retrieving finishes, either with succeeded /// `RetrieveImageResult` or an error. /// - Returns: `true` if the requested image or the original image before being processed is existing in cache. /// Otherwise, this method returns `false`. /// /// - Note: /// The image retrieving could happen in either memory cache or disk cache. The `.processor` option in /// `options` will be considered when searching in the cache. If no processed image is found, Kingfisher /// will try to check whether an original version of that image is existing or not. If there is already an /// original, Kingfisher retrieves it from cache and processes it. Then, the processed image will be store /// back to cache for later use. func retrieveImageFromCache( source: Source, options: KingfisherParsedOptionsInfo, completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)?) -> Bool { // 1. Check whether the image was already in target cache. If so, just get it. let targetCache = options.targetCache ?? cache let key = source.cacheKey let targetImageCached = targetCache.imageCachedType( forKey: key, processorIdentifier: options.processor.identifier) let validCache = targetImageCached.cached && (options.fromMemoryCacheOrRefresh == false || targetImageCached == .memory) if validCache { targetCache.retrieveImage(forKey: key, options: options) { result in guard let completionHandler = completionHandler else { return } options.callbackQueue.execute { result.match( onSuccess: { cacheResult in let value: Result<RetrieveImageResult, KingfisherError> if let image = cacheResult.image { value = result.map { RetrieveImageResult(image: image, cacheType: $0.cacheType, source: source) } } else { value = .failure(KingfisherError.cacheError(reason: .imageNotExisting(key: key))) } completionHandler(value) }, onFailure: { _ in completionHandler(.failure(KingfisherError.cacheError(reason: .imageNotExisting(key: key)))) } ) } } return true } // 2. Check whether the original image exists. If so, get it, process it, save to storage and return. let originalCache = options.originalCache ?? targetCache // No need to store the same file in the same cache again. if originalCache === targetCache && options.processor == DefaultImageProcessor.default { return false } // Check whether the unprocessed image existing or not. let originalImageCached = originalCache.imageCachedType( forKey: key, processorIdentifier: DefaultImageProcessor.default.identifier).cached if originalImageCached { // Now we are ready to get found the original image from cache. We need the unprocessed image, so remove // any processor from options first. var optionsWithoutProcessor = options optionsWithoutProcessor.processor = DefaultImageProcessor.default originalCache.retrieveImage(forKey: key, options: optionsWithoutProcessor) { result in result.match( onSuccess: { cacheResult in guard let image = cacheResult.image else { return } let processor = options.processor (options.processingQueue ?? self.processingQueue).execute { let item = ImageProcessItem.image(image) guard let processedImage = processor.process(item: item, options: options) else { let error = KingfisherError.processorError( reason: .processingFailed(processor: processor, item: item)) options.callbackQueue.execute { completionHandler?(.failure(error)) } return } var cacheOptions = options cacheOptions.callbackQueue = .untouch targetCache.store( processedImage, forKey: key, options: cacheOptions, toDisk: !options.cacheMemoryOnly) { _ in if options.waitForCache { let value = RetrieveImageResult(image: processedImage, cacheType: .none, source: source) options.callbackQueue.execute { completionHandler?(.success(value)) } } } if !options.waitForCache { let value = RetrieveImageResult(image: processedImage, cacheType: .none, source: source) options.callbackQueue.execute { completionHandler?(.success(value)) } } } }, onFailure: { _ in // This should not happen actually, since we already confirmed `originalImageCached` is `true`. // Just in case... options.callbackQueue.execute { completionHandler?(.failure(KingfisherError.cacheError(reason: .imageNotExisting(key: key)))) } } ) } return true } return false } }
gpl-3.0
96ac04a8ff0e25637355fd6d6e32ef4f
47.377404
124
0.596571
5.823206
false
false
false
false
GitTennis/SuccessFramework
Templates/_BusinessAppSwift_/_BusinessAppSwift_/Core/BaseTableViewController.swift
2
5070
// // BaseTableViewController.swift // _BusinessAppSwift_ // // Created by Gytenis Mikulenas on 06/11/16. // Copyright © 2016 Gytenis Mikulėnas // https://github.com/GitTennis/SuccessFramework // // 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. All rights reserved. // import UIKit class BaseTableViewController: UITableViewController, GenericViewControllerProtocol, GenericDetailsViewControllerProtocol, KeyboardControlDelegate { var context: Any? var viewLoader: ViewLoaderProtocol? var crashManager: CrashManagerProtocol? var analyticsManager: AnalyticsManagerProtocol? var messageBarManager: MessageBarManagerProtocol? var viewControllerFactory: ViewControllerFactoryProtocol? var reachabilityManager: ReachabilityManagerProtocol? var localizationManager: LocalizationManagerProtocol? var userManager: UserManagerProtocol? var keyboardControls: KeyboardControlProtocol? deinit { let center: NotificationCenter = NotificationCenter.default center.removeObserver(self) self.reachabilityManager?.removeServiceObserver(observer: self as ReachabilityManagerObserver) } override func viewDidLoad() { super.viewDidLoad() // Add navigation bar if self.isModal() { let navigatioBar = self.viewLoader?.addDefaultModalNavigationBar(viewController: self) navigatioBar?.delegate = self } else { let navigatioBar = self.viewLoader?.addDefaultNavigationBar(viewController: self) navigatioBar?.delegate = self } // Prepare for functional tests self.viewLoader?.prepareAccesibility(viewController: self) // Add language change observing self.localizationManager?.addServiceObserver(observer: self, notificationType: LocalizationManagerNotificationType.didChangeLang, callback: { [weak self] (success, result, context, error) in DDLogDebug(log: className(object: self) + ": prepareUI") self?.prepareUI() DDLogDebug(log: className(object: self) + ": loadModel") self?.loadModel() }, context: nil) //Adding environment switch buttons for DEBUG only #if DEBUG //self.addNetworkSwitches() #endif } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) DDLogDebug(log: className(object: self) + ": viewWillAppear") // Enable user interaction self.view.isUserInteractionEnabled = true // Log current screen self.crashManager?.logScreenAction(log: className(object: self)) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) super.viewWillDisappear(animated) DDLogDebug(log: className(object: self) + ": viewWillDisappear") // Disable user interaction self.view.isUserInteractionEnabled = false } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() DDLogDebug(log: className(object: self) + ": didReceiveMemoryWarning") } // MARK: GenericViewControllerProtocol func prepareUI() { // ... } func renderUI() { // ... } func loadModel() { self.renderUI() } // MARK: KeyboardControlDelegate func didPressGo() { } // MARK: ViewControllerModelDelegate func modelHasChangedWithData(data: Any?, context: Any?) { // Override // ... } func modelHasFailedToChangeDataWithError(error: Error, context: Any?) { // Override // ... } }
mit
205f2a7ac906ba7612122f5eda57120c
30.874214
198
0.642265
5.550931
false
false
false
false
edc1591/human-to-gpx
human-to-gpx/main.swift
1
1612
// // main.swift // human-to-gpx // // Created by Evan Coleman on 12/13/15. // Copyright © 2015 Evan Coleman. All rights reserved. // import Foundation let opts = Args.parsed.flags let directory = opts["d"] let file = opts["f"] let output = opts["o"] if directory == nil && file == nil { print("Usage:".f.Blue) print(" Specify a Human JSON file: -f <path>".f.Magenta) print(" Specify a Human archive folder to get information about its contents: -d <path>".f.Magenta) print(" Optionally specify an output directory with (otherwise the current directory is used): -o <path>".f.Magenta) exit(0) } else if directory != nil && file != nil { print("You can only specify an archive directory or file path. Not both.".f.Red) exit(0) } // MARK: Main Stuff if let d = directory { var archive = Archive(path: d) let description = archive.description() print("\(description)") } else if let f = file { var activity = Activity(path: f) guard let gpxString = activity.gpx else { exit(0) } var outputDirectory = NSFileManager.defaultManager().currentDirectoryPath as NSString if let o = output { outputDirectory = o } let outputPath = outputDirectory.stringByAppendingPathComponent(((f as NSString).stringByDeletingPathExtension as NSString).lastPathComponent) + ".gpx" do { try gpxString.writeToFile(outputPath, atomically: true, encoding: NSUTF8StringEncoding) print("File successfully saved to \(outputPath)".f.Green) } catch { print("\(error)".f.Red) } }
mit
39fa6b7896589beee03ebb6d90917b59
27.767857
155
0.651769
4.057935
false
false
false
false
tierriminator/Lolang
Sources/lolc/main.swift
1
6048
import Foundation import Lib import LLVM import PathKit import struct PathKit.Path import FileUtils #if os(Linux) import GlibcVersion #endif /// prints the usage information to stderr and exits with exit code -1 func printUsage() -> Never{ let usage = """ Usage: lolc <source> [options]\n OPTIONS: -o <path>\tspecify destination file -l\t\t\toutput LLVM IR -a\t\t\toutput assembly file -b\t\t\toutput object file -O<char>\tOptimization level. [-O0, -O1, -O2, -O3] (default: -O2) """ fail(usage) } /// prints message to stderr and exits with exit code -1 /// -parameter message: the message that should be printed to stderr func fail(_ message: String) -> Never { print(message, to: &errStream) exit(-1) } /// prints message to stdout and exits with exit code 0 /// -parameter message: the message that should be printed to stdout func exitGracefully(_ message: String? = nil) -> Never { if let msg = message { print(msg) } exit(0) } let arguments = CommandLine.arguments if arguments.count == 1 { printUsage() } // parameters that can be changed through commandline arguments var outFile = "" var emitIR = false var optimization = "-O2" var assembly = false var object = false // process commandline arguments // check source file let sourceStr = arguments[1] let sourcePath = Path(sourceStr).absolute() if !sourcePath.isFile { fail("The given source path is no file: \(sourceStr)") } if !sourcePath.exists { fail("The given source path does not exist: \(sourceStr)") } if !sourcePath.isReadable { fail("The file at the given source cannot be read: \(sourceStr)") } let sourceName = sourcePath.lastComponentWithoutExtension let sourceDir = sourcePath.parent() // process remaining arguments var i = 2 while i < arguments.count { if arguments[i] == "-o" { i += 1 var outPath = Path(arguments[i]) if outPath.isDirectory { if !outPath.exists { fail("The given output directory does not exist: \(arguments[i])") } if !outPath.isWritable { fail("No write is allowed to the given output directory: \(arguments[i])") } outPath = outPath + Path(sourceName) } outFile = outPath.absolute().string } else if arguments[i] == "-l" { emitIR = true } else if arguments[i].hasPrefix("-O") && arguments[i].count == 3 { if let lvl = Int(arguments[i].suffix(1)) { if lvl >= 0 && lvl <= 3 { optimization = arguments[i] } else { printUsage() } } else { printUsage() } } else if arguments[i] == "-a" { assembly = true } else if arguments[i] == "-b" { object = true } else { printUsage() } i+=1 } // load source file let code: String do { /// the lolang code that should be compiled code = try File.read(atPath: sourcePath.absolute().string) } catch { fail("Could not load source file \(sourcePath): \(error)") } // parse let p = Parser(code) let ast: AST do { if let _ast = try p.parse() { ast = _ast } else { exitGracefully() } } catch { print(error) let syntaxError = error as! SyntaxError fail(syntaxError.localizedDescription) } // generate IR let module = compile(ast) // store IR let irOutName = "\(sourceName).ll" let irOutPath = sourceDir + Path(irOutName) let irOut: String if emitIR && outFile != "" { irOut = outFile } else { irOut = irOutPath.absolute().string } do { try module.print(to: irOut) } catch { fail("Could not write to \(irOut): \(error)") } if emitIR { // stop here if IR should be emitted exitGracefully() } // generate assembly or object file let objOutName = "\(sourceName).o" let objOutPath = sourceDir + Path(objOutName) let asmOutName = "\(sourceName).s" let asmOutPath = sourceDir + Path(asmOutName) let objOut: String let asmOut: String if outFile != "" && (assembly || object) { objOut = outFile asmOut = outFile } else { objOut = objOutPath.absolute().string asmOut = asmOutPath.absolute().string } let fileType = assembly ? "asm" : "obj" /// the output path of the compiled file let compiledOut = assembly ? asmOut : objOut // execute llc on generated IR let llcProc = Process() llcProc.launchPath = "/usr/bin/env" llcProc.arguments = ["llc", irOut, "-o", compiledOut, "-filetype", fileType, optimization] llcProc.launch() llcProc.waitUntilExit() if llcProc.terminationStatus != 0 { fail("Could not compile IR, llc exited with code \(llcProc.terminationStatus)") } // remove IR file do { try FileManager.default.removeItem(at: URL(fileURLWithPath: irOut)) } catch { fail("Could not remove IR file \(irOut): \(error)") } if object || assembly { // stop here if object or assembly file should be emitted exitGracefully() } // link and generate executable if outFile == "" { let outFilePath = sourceDir + Path(sourceName) outFile = outFilePath.absolute().string } let ldProc = Process() ldProc.launchPath = "/usr/bin/env" ldProc.arguments = ["ld", "-o", outFile, objOut] #if os(Linux) /* On linux the correct dynamic linker is not necesseraly detected by 'ld', therefore we have to indicate the dynamic linker provided by glibc. */ // find glibc version let glibcVersion = String(cString: gnu_get_libc_version()!) ldProc.arguments!.append(contentsOf: ["-l:crt1.o", "-l:crti.o", "-l:crtn.o", "-L/usr/lib", "--dynamic-linker", "/lib/ld-\(glibcVersion).so", "-lc"]) #else ldProc.arguments!.append(contentsOf: ["-lcrt1.o", "-lc"]) #endif ldProc.launch() ldProc.waitUntilExit() if ldProc.terminationStatus != 0 { fail("Could not link, ld exited with code \(ldProc.terminationStatus)") } // remove obj file do { try FileManager.default.removeItem(at: URL(fileURLWithPath: objOut)) } catch { fail("Could not remove object file \(objOut): \(error)") }
mit
72fac3db516bc41c3492563efd55d2f8
26.870968
152
0.640873
3.65659
false
false
false
false
rcasanovan/MarvelApp
Marvel App/Marvel App/UI/Character Detail/View/Cell/MComicTableViewCell.swift
1
1720
// // MComicTableViewCell.swift // Marvel App // // Created by Ricardo Casanova on 20/2/16. // Copyright © 2016 Marvel. All rights reserved. // import UIKit //__ Pods import Haneke class MComicTableViewCell: UITableViewCell, DVATableViewCellProtocol { //__ IBOutlets @IBOutlet weak fileprivate var comicNameLabel : UILabel? @IBOutlet weak fileprivate var comicDesciptionLabel : UILabel? @IBOutlet weak fileprivate var comicImageView : UIImageView? override func awakeFromNib() { super.awakeFromNib() self.selectionStyle = UITableViewCellSelectionStyle.none } override func prepareForReuse() { self.comicImageView?.image = nil; if let label = self.comicNameLabel { label.text = "" } if let label = self.comicDesciptionLabel { label.text = "" } } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) } //__ DVATableViewModelProtocol method func bind(withModel viewModel: DVATableViewModelProtocol!) { let model : MComicCellViewModel = (viewModel as? MComicCellViewModel)! if let label = self.comicNameLabel { label.text = model.comicName } if let label = self.comicDesciptionLabel { label.text = model.comicDescription } self.comicImageView?.contentMode = UIViewContentMode.scaleAspectFill; self.comicImageView?.clipsToBounds = true; let URL = Foundation.URL(string:model.comicUrlImage! + "/portrait_medium." + model.comicUrlImageExtension!) comicImageView?.hnk_setImageFromURL(URL!) } }
apache-2.0
d243cd5d377c274ab9ca95c9c975339f
30.833333
115
0.657941
4.788301
false
false
false
false
ZeldaIV/TDC2015-FP
Pods/SwiftWebSocket/Source/WebSocket.swift
4
57798
/* * SwiftWebSocket (websocket.swift) * * Copyright (C) 2015 ONcast, LLC. All Rights Reserved. * Created by Josh Baker ([email protected]) * * This software may be modified and distributed under the terms * of the MIT license. See the LICENSE file for details. * */ import Foundation private let windowBufferSize = 0x2000 private class Payload { var ptr : UnsafeMutablePointer<UInt8> var cap : Int var len : Int init(){ len = 0 cap = windowBufferSize ptr = UnsafeMutablePointer<UInt8>(malloc(cap)) } deinit{ free(ptr) } var count : Int { get { return len } set { if newValue > cap { while cap < newValue { cap *= 2 } ptr = UnsafeMutablePointer<UInt8>(realloc(ptr, cap)) } len = newValue } } func append(bytes: UnsafePointer<UInt8>, length: Int){ let prevLen = len count = len+length memcpy(ptr+prevLen, bytes, length) } var array : [UInt8] { get { var array = [UInt8](count: count, repeatedValue: 0) memcpy(&array, ptr, count) return array } set { count = 0 append(newValue, length: newValue.count) } } var nsdata : NSData { get { return NSData(bytes: ptr, length: count) } set { count = 0 append(UnsafePointer<UInt8>(newValue.bytes), length: newValue.length) } } var buffer : UnsafeBufferPointer<UInt8> { get { return UnsafeBufferPointer<UInt8>(start: ptr, count: count) } set { count = 0 append(newValue.baseAddress, length: newValue.count) } } } private enum OpCode : UInt8, CustomStringConvertible { case Continue = 0x0, Text = 0x1, Binary = 0x2, Close = 0x8, Ping = 0x9, Pong = 0xA var isControl : Bool { switch self { case .Close, .Ping, .Pong: return true default: return false } } var description : String { switch self { case Continue: return "Continue" case Text: return "Text" case Binary: return "Binary" case Close: return "Close" case Ping: return "Ping" case Pong: return "Pong" } } } /// The WebSocketEvents struct is used by the events property and manages the events for the WebSocket connection. public struct WebSocketEvents { /// An event to be called when the WebSocket connection's readyState changes to .Open; this indicates that the connection is ready to send and receive data. public var open : ()->() = {} /// An event to be called when the WebSocket connection's readyState changes to .Closed. public var close : (code : Int, reason : String, wasClean : Bool)->() = {(code, reason, wasClean) in} /// An event to be called when an error occurs. public var error : (error : ErrorType)->() = {(error) in} /// An event to be called when a message is received from the server. public var message : (data : Any)->() = {(data) in} /// An event to be called when a pong is received from the server. public var pong : (data : Any)->() = {(data) in} /// An event to be called when the WebSocket process has ended; this event is guarenteed to be called once and can be used as an alternative to the "close" or "error" events. public var end : (code : Int, reason : String, wasClean : Bool, error : ErrorType?)->() = {(code, reason, wasClean, error) in} } /// The WebSocketBinaryType enum is used by the binaryType property and indicates the type of binary data being transmitted by the WebSocket connection. public enum WebSocketBinaryType : CustomStringConvertible { /// The WebSocket should transmit [UInt8] objects. case UInt8Array /// The WebSocket should transmit NSData objects. case NSData /// The WebSocket should transmit UnsafeBufferPointer<UInt8> objects. This buffer is only valid during the scope of the message event. Use at your own risk. case UInt8UnsafeBufferPointer public var description : String { switch self { case UInt8Array: return "UInt8Array" case NSData: return "NSData" case UInt8UnsafeBufferPointer: return "UInt8UnsafeBufferPointer" } } } /// The WebSocketReadyState enum is used by the readyState property to describe the status of the WebSocket connection. public enum WebSocketReadyState : Int, CustomStringConvertible { /// The connection is not yet open. case Connecting = 0 /// The connection is open and ready to communicate. case Open = 1 /// The connection is in the process of closing. case Closing = 2 /// The connection is closed or couldn't be opened. case Closed = 3 private var isClosed : Bool { switch self { case .Closing, .Closed: return true default: return false } } /// Returns a string that represents the ReadyState value. public var description : String { switch self { case Connecting: return "Connecting" case Open: return "Open" case Closing: return "Closing" case Closed: return "Closed" } } } private let defaultMaxWindowBits = 15 /// The WebSocketCompression struct is used by the compression property and manages the compression options for the WebSocket connection. public struct WebSocketCompression { /// Used to accept compressed messages from the server. Default is true. public var on = false /// request no context takeover. public var noContextTakeover = false /// request max window bits. public var maxWindowBits = defaultMaxWindowBits } /// The WebSocketService options are used by the services property and manages the underlying socket services. public struct WebSocketService : OptionSetType { public typealias RawValue = UInt var value: UInt = 0 init(_ value: UInt) { self.value = value } public init(rawValue value: UInt) { self.value = value } public init(nilLiteral: ()) { self.value = 0 } public static var allZeros: WebSocketService { return self.init(0) } static func fromMask(raw: UInt) -> WebSocketService { return self.init(raw) } public var rawValue: UInt { return self.value } /// No services. static var None: WebSocketService { return self.init(0) } /// Allow socket to handle VoIP. static var VoIP: WebSocketService { return self.init(1 << 0) } /// Allow socket to handle video. static var Video: WebSocketService { return self.init(1 << 1) } /// Allow socket to run in background. static var Background: WebSocketService { return self.init(1 << 2) } /// Allow socket to handle voice. static var Voice: WebSocketService { return self.init(1 << 3) } } private let atEndDetails = "streamStatus.atEnd" public enum WebSocketError : ErrorType, CustomStringConvertible { case Memory case NeedMoreInput case InvalidHeader case InvalidAddress case Network(String) case LibraryError(String) case PayloadError(String) case ProtocolError(String) case InvalidResponse(String) case InvalidCompressionOptions(String) public var description : String { switch self { case .Memory: return "Memory" case .NeedMoreInput: return "NeedMoreInput" case .InvalidAddress: return "InvalidAddress" case .InvalidHeader: return "InvalidHeader" case let .InvalidResponse(details): return "InvalidResponse(\(details))" case let .InvalidCompressionOptions(details): return "InvalidCompressionOptions(\(details))" case let .LibraryError(details): return "LibraryError(\(details))" case let .ProtocolError(details): return "ProtocolError(\(details))" case let .PayloadError(details): return "PayloadError(\(details))" case let .Network(details): return "Network(\(details))" } } public var details : String { switch self { case .InvalidResponse(let details): return details case .InvalidCompressionOptions(let details): return details case .LibraryError(let details): return details case .ProtocolError(let details): return details case .PayloadError(let details): return details case .Network(let details): return details default: return "" } } } private class UTF8 { var text : String = "" var count : UInt32 = 0 // number of bytes var procd : UInt32 = 0 // number of bytes processed var codepoint : UInt32 = 0 // the actual codepoint var bcount = 0 init() { text = "" } func append(byte : UInt8) throws { if count == 0 { if byte <= 0x7F { text.append(UnicodeScalar(byte)) return } if byte == 0xC0 || byte == 0xC1 { throw WebSocketError.PayloadError("invalid codepoint: invalid byte") } if byte >> 5 & 0x7 == 0x6 { count = 2 } else if byte >> 4 & 0xF == 0xE { count = 3 } else if byte >> 3 & 0x1F == 0x1E { count = 4 } else { throw WebSocketError.PayloadError("invalid codepoint: frames") } procd = 1 codepoint = (UInt32(byte) & (0xFF >> count)) << ((count-1) * 6) return } if byte >> 6 & 0x3 != 0x2 { throw WebSocketError.PayloadError("invalid codepoint: signature") } codepoint += UInt32(byte & 0x3F) << ((count-procd-1) * 6) if codepoint > 0x10FFFF || (codepoint >= 0xD800 && codepoint <= 0xDFFF) { throw WebSocketError.PayloadError("invalid codepoint: out of bounds") } procd++ if procd == count { if codepoint <= 0x7FF && count > 2 { throw WebSocketError.PayloadError("invalid codepoint: overlong") } if codepoint <= 0xFFFF && count > 3 { throw WebSocketError.PayloadError("invalid codepoint: overlong") } procd = 0 count = 0 text.append(UnicodeScalar(codepoint)) } return } func append(bytes : UnsafePointer<UInt8>, length : Int) throws { if length == 0 { return } if count == 0 { var ascii = true for var i = 0; i < length; i++ { if bytes[i] > 0x7F { ascii = false break } } if ascii { text += NSString(bytes: bytes, length: length, encoding: NSASCIIStringEncoding) as! String bcount += length return } } for var i = 0; i < length; i++ { try append(bytes[i]) } bcount += length } var completed : Bool { return count == 0 } static func bytes(string : String) -> [UInt8]{ let data = string.dataUsingEncoding(NSUTF8StringEncoding)! return [UInt8](UnsafeBufferPointer<UInt8>(start: UnsafePointer<UInt8>(data.bytes), count: data.length)) } static func string(bytes : [UInt8]) -> String{ if let str = NSString(bytes: bytes, length: bytes.count, encoding: NSUTF8StringEncoding) { return str as String } return "" } } private class Frame { var inflate = false var code = OpCode.Continue var utf8 = UTF8() var payload = Payload() var statusCode = UInt16(0) var finished = true static func makeClose(statusCode: UInt16, reason: String) -> Frame { let f = Frame() f.code = .Close f.statusCode = statusCode f.utf8.text = reason return f } func copy() -> Frame { let f = Frame() f.code = code f.utf8.text = utf8.text f.payload.buffer = payload.buffer f.statusCode = statusCode f.finished = finished f.inflate = inflate return f } } private class Delegate : NSObject, NSStreamDelegate { @objc func stream(aStream: NSStream, handleEvent eventCode: NSStreamEvent){ manager.signal() } } @asmname("zlibVersion") private func zlibVersion() -> COpaquePointer @asmname("deflateInit2_") private func deflateInit2(strm : UnsafeMutablePointer<Void>, level : CInt, method : CInt, windowBits : CInt, memLevel : CInt, strategy : CInt, version : COpaquePointer, stream_size : CInt) -> CInt @asmname("deflateInit_") private func deflateInit(strm : UnsafeMutablePointer<Void>, level : CInt, version : COpaquePointer, stream_size : CInt) -> CInt @asmname("deflateEnd") private func deflateEnd(strm : UnsafeMutablePointer<Void>) -> CInt @asmname("deflate") private func deflate(strm : UnsafeMutablePointer<Void>, flush : CInt) -> CInt @asmname("inflateInit2_") private func inflateInit2(strm : UnsafeMutablePointer<Void>, windowBits : CInt, version : COpaquePointer, stream_size : CInt) -> CInt @asmname("inflateInit_") private func inflateInit(strm : UnsafeMutablePointer<Void>, version : COpaquePointer, stream_size : CInt) -> CInt @asmname("inflate") private func inflateG(strm : UnsafeMutablePointer<Void>, flush : CInt) -> CInt @asmname("inflateEnd") private func inflateEndG(strm : UnsafeMutablePointer<Void>) -> CInt private func zerror(res : CInt) -> ErrorType? { var err = "" switch res { case 0: return nil case 1: err = "stream end" case 2: err = "need dict" case -1: err = "errno" case -2: err = "stream error" case -3: err = "data error" case -4: err = "mem error" case -5: err = "buf error" case -6: err = "version error" default: err = "undefined error" } return WebSocketError.PayloadError("zlib: \(err): \(res)") } private struct z_stream { var next_in : UnsafePointer<UInt8> = nil var avail_in : CUnsignedInt = 0 var total_in : CUnsignedLong = 0 var next_out : UnsafeMutablePointer<UInt8> = nil var avail_out : CUnsignedInt = 0 var total_out : CUnsignedLong = 0 var msg : UnsafePointer<CChar> = nil var state : COpaquePointer = nil var zalloc : COpaquePointer = nil var zfree : COpaquePointer = nil var opaque : COpaquePointer = nil var data_type : CInt = 0 var adler : CUnsignedLong = 0 var reserved : CUnsignedLong = 0 } private class Inflater { var windowBits = 0 var strm = z_stream() var tInput = [[UInt8]]() var inflateEnd : [UInt8] = [0x00, 0x00, 0xFF, 0xFF] var bufferSize = windowBufferSize var buffer = UnsafeMutablePointer<UInt8>(malloc(windowBufferSize)) init?(windowBits : Int){ if buffer == nil { return nil } self.windowBits = windowBits let ret = inflateInit2(&strm, windowBits: -CInt(windowBits), version: zlibVersion(), stream_size: CInt(sizeof(z_stream))) if ret != 0 { return nil } } deinit{ inflateEndG(&strm) free(buffer) } func inflate(bufin : UnsafePointer<UInt8>, length : Int, final : Bool) throws -> (p : UnsafeMutablePointer<UInt8>, n : Int){ var buf = buffer var bufsiz = bufferSize var buflen = 0 for var i = 0; i < 2; i++ { if i == 0 { strm.avail_in = CUnsignedInt(length) strm.next_in = UnsafePointer<UInt8>(bufin) } else { if !final { break } strm.avail_in = CUnsignedInt(inflateEnd.count) strm.next_in = UnsafePointer<UInt8>(inflateEnd) } for ;; { strm.avail_out = CUnsignedInt(bufsiz) strm.next_out = buf inflateG(&strm, flush: 0) let have = bufsiz - Int(strm.avail_out) bufsiz -= have buflen += have if strm.avail_out != 0{ break } if bufsiz == 0 { bufferSize *= 2 let nbuf = UnsafeMutablePointer<UInt8>(realloc(buffer, bufferSize)) if nbuf == nil { throw WebSocketError.PayloadError("memory") } buffer = nbuf buf = buffer+Int(buflen) bufsiz = bufferSize - buflen } } } return (buffer, buflen) } } private class Deflater { var windowBits = 0 var memLevel = 0 var strm = z_stream() var bufferSize = windowBufferSize var buffer = UnsafeMutablePointer<UInt8>(malloc(windowBufferSize)) init?(windowBits : Int, memLevel : Int){ if buffer == nil { return nil } self.windowBits = windowBits self.memLevel = memLevel let ret = deflateInit2(&strm, level: 6, method: 8, windowBits: -CInt(windowBits), memLevel: CInt(memLevel), strategy: 0, version: zlibVersion(), stream_size: CInt(sizeof(z_stream))) if ret != 0 { return nil } } deinit{ deflateEnd(&strm) free(buffer) } func deflate(bufin : UnsafePointer<UInt8>, length : Int, final : Bool) -> (p : UnsafeMutablePointer<UInt8>, n : Int, err : NSError?){ return (nil, 0, nil) } } /// WebSocket objects are bidirectional network streams that communicate over HTTP. RFC 6455. public class WebSocket: Hashable { private var id : Int private var mutex = pthread_mutex_t() private var cond = pthread_cond_t() private let request : NSURLRequest! private let subProtocols : [String]! private var frames : [Frame] = [] private var delegate : Delegate private var inflater : Inflater! private var deflater : Deflater! private var outputBytes : UnsafeMutablePointer<UInt8> private var outputBytesSize : Int = 0 private var outputBytesStart : Int = 0 private var outputBytesLength : Int = 0 private var inputBytes : UnsafeMutablePointer<UInt8> private var inputBytesSize : Int = 0 private var inputBytesStart : Int = 0 private var inputBytesLength : Int = 0 private var _eventQueue : dispatch_queue_t? = dispatch_get_main_queue() private var _subProtocol = "" private var _compression = WebSocketCompression() private var _services = WebSocketService.None private var _event = WebSocketEvents() private var _binaryType = WebSocketBinaryType.UInt8Array private var _readyState = WebSocketReadyState.Connecting private var _networkTimeout = NSTimeInterval(-1) /// The URL as resolved by the constructor. This is always an absolute URL. Read only. public var url : String { return request.URL!.description } /// A string indicating the name of the sub-protocol the server selected; this will be one of the strings specified in the protocols parameter when creating the WebSocket object. public var subProtocol : String { get { return privateSubProtocol } } private var privateSubProtocol : String { get { lock(); defer { unlock() }; return _subProtocol } set { lock(); defer { unlock() }; _subProtocol = newValue } } /// The compression options of the WebSocket. public var compression : WebSocketCompression { get { lock(); defer { unlock() }; return _compression } set { lock(); defer { unlock() }; _compression = newValue } } /// The services of the WebSocket. public var services : WebSocketService { get { lock(); defer { unlock() }; return _services } set { lock(); defer { unlock() }; _services = newValue } } /// The events of the WebSocket. public var event : WebSocketEvents { get { lock(); defer { unlock() }; return _event } set { lock(); defer { unlock() }; _event = newValue } } /// The queue for firing off events. default is main_queue public var eventQueue : dispatch_queue_t? { get { lock(); defer { unlock() }; return _eventQueue; } set { lock(); defer { unlock() }; _eventQueue = newValue } } /// A WebSocketBinaryType value indicating the type of binary data being transmitted by the connection. Default is .UInt8Array. public var binaryType : WebSocketBinaryType { get { lock(); defer { unlock() }; return _binaryType } set { lock(); defer { unlock() }; _binaryType = newValue } } /// The current state of the connection; this is one of the WebSocketReadyState constants. Read only. public var readyState : WebSocketReadyState { get { return privateReadyState } } private var privateReadyState : WebSocketReadyState { get { lock(); defer { unlock() }; return _readyState } set { lock(); defer { unlock() }; _readyState = newValue } } public var hashValue: Int { return id } /// Create a WebSocket connection to a URL; this should be the URL to which the WebSocket server will respond. public convenience init(_ url: String){ self.init(request: NSURLRequest(URL: NSURL(string: url)!), subProtocols: []) } /// Create a WebSocket connection to a URL; this should be the URL to which the WebSocket server will respond. Also include a list of protocols. public convenience init(_ url: String, subProtocols : [String]){ self.init(request: NSURLRequest(URL: NSURL(string: url)!), subProtocols: subProtocols) } /// Create a WebSocket connection to a URL; this should be the URL to which the WebSocket server will respond. Also include a protocol. public convenience init(_ url: String, subProtocol : String){ self.init(request: NSURLRequest(URL: NSURL(string: url)!), subProtocols: [subProtocol]) } /// Create a WebSocket connection from an NSURLRequest; Also include a list of protocols. public init(request: NSURLRequest, subProtocols : [String] = []){ pthread_mutex_init(&mutex, nil) pthread_cond_init(&cond, nil) self.id = manager.nextId() self.request = request self.subProtocols = subProtocols self.outputBytes = UnsafeMutablePointer<UInt8>.alloc(windowBufferSize) self.outputBytesSize = windowBufferSize self.inputBytes = UnsafeMutablePointer<UInt8>.alloc(windowBufferSize) self.inputBytesSize = windowBufferSize self.delegate = Delegate() dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0), dispatch_get_main_queue()){ manager.add(self) } } deinit{ if outputBytes != nil { free(outputBytes) } if inputBytes != nil { free(inputBytes) } pthread_cond_init(&cond, nil) pthread_mutex_init(&mutex, nil) } @inline(__always) private func lock(){ pthread_mutex_lock(&mutex) } @inline(__always) private func unlock(){ pthread_mutex_unlock(&mutex) } private var dirty : Bool { lock() defer { unlock() } if exit { return false } if stage != .ReadResponse && stage != .HandleFrames { return true } if rd.streamStatus != .Open || wr.streamStatus != .Open { return true } if rd.streamError != nil || wr.streamError != nil { return true } if rd.hasBytesAvailable || frames.count > 0 || inputBytesLength > 0 || outputBytesLength > 0 { return true } return false } private enum Stage : Int { case OpenConn case ReadResponse case HandleFrames case CloseConn case End } private var stage = Stage.OpenConn private var rd : NSInputStream! private var wr : NSOutputStream! private var atEnd = false private var closeCode = UInt16(0) private var closeReason = "" private var closeClean = false private var closeFinal = false private var finalError : ErrorType? private var exit = false private func step(){ if exit { return } do { try stepBuffers() try stepStreamErrors() switch stage { case .OpenConn: try openConn() stage = .ReadResponse case .ReadResponse: try readResponse() privateReadyState = .Open fire { self.event.open() } stage = .HandleFrames case .HandleFrames: try stepOutputFrames() if closeFinal { privateReadyState == .Closing stage = .CloseConn return } let frame = try readFrame() switch frame.code { case .Text: fire { self.event.message(data: frame.utf8.text) } case .Binary: fire { switch self.binaryType { case .UInt8Array: self.event.message(data: frame.payload.array) case .NSData: self.event.message(data: frame.payload.nsdata) case .UInt8UnsafeBufferPointer: self.event.message(data: frame.payload.buffer) } } case .Ping: let nframe = frame.copy() nframe.code = .Pong lock() frames += [nframe] unlock() case .Pong: fire { switch self.binaryType { case .UInt8Array: self.event.pong(data: frame.payload.array) case .NSData: self.event.pong(data: frame.payload.nsdata) case .UInt8UnsafeBufferPointer: self.event.pong(data: frame.payload.buffer) } } case .Close: lock() frames += [frame] unlock() default: break } case .CloseConn: if let error = finalError { self.event.error(error: error) } privateReadyState == .Closed if rd != nil { closeConn() fire { self.event.close(code: Int(self.closeCode), reason: self.closeReason, wasClean: self.closeFinal) } } stage = .End case .End: fire { self.event.end(code: Int(self.closeCode), reason: self.closeReason, wasClean: self.closeClean, error: self.finalError) } exit = true manager.remove(self) } } catch WebSocketError.NeedMoreInput { } catch { if finalError != nil { return } finalError = error if stage == .OpenConn || stage == .ReadResponse { stage = .CloseConn } else { var frame : Frame? if let error = error as? WebSocketError{ switch error { case .Network(let details): if details == atEndDetails{ stage = .CloseConn frame = Frame.makeClose(1006, reason: "Abnormal Closure") atEnd = true finalError = nil } case .ProtocolError: frame = Frame.makeClose(1002, reason: "Protocol error") case .PayloadError: frame = Frame.makeClose(1007, reason: "Payload error") default: break } } if frame == nil { frame = Frame.makeClose(1006, reason: "Abnormal Closure") } if let frame = frame { if frame.statusCode == 1007 { self.lock() self.frames = [frame] self.unlock() manager.signal() } else { dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0), dispatch_get_main_queue()){ self.lock() self.frames += [frame] self.unlock() manager.signal() } } } } } } private func stepBuffers() throws { if rd != nil { if rd.streamStatus == NSStreamStatus.AtEnd { if atEnd { return; } throw WebSocketError.Network(atEndDetails) } while rd.hasBytesAvailable { var size = inputBytesSize while size-(inputBytesStart+inputBytesLength) < windowBufferSize { size *= 2 } if size > inputBytesSize { let ptr = UnsafeMutablePointer<UInt8>(realloc(inputBytes, size)) if ptr == nil { throw WebSocketError.Memory } inputBytes = ptr inputBytesSize = size } let n = rd.read(inputBytes+inputBytesStart+inputBytesLength, maxLength: inputBytesSize-inputBytesStart-inputBytesLength) if n > 0 { inputBytesLength += n } } } if wr != nil && wr.hasSpaceAvailable && outputBytesLength > 0 { let n = wr.write(outputBytes+outputBytesStart, maxLength: outputBytesLength) if n > 0 { outputBytesLength -= n if outputBytesLength == 0 { outputBytesStart = 0 } else { outputBytesStart += n } } } } private func stepStreamErrors() throws { if finalError == nil { if let error = rd?.streamError { throw WebSocketError.Network(error.localizedDescription) } if let error = wr?.streamError { throw WebSocketError.Network(error.localizedDescription) } } } private func stepOutputFrames() throws { lock() defer { frames = [] unlock() } if !closeFinal { for frame in frames { try writeFrame(frame) if frame.code == .Close { closeCode = frame.statusCode closeReason = frame.utf8.text closeFinal = true return } } } } @inline(__always) private func fire(block: ()->()){ if let queue = eventQueue { dispatch_sync(queue) { block() } } else { block() } } private var readStateSaved = false private var readStateFrame : Frame? private var readStateFinished = false private var leaderFrame : Frame? private func readFrame() throws -> Frame { var frame : Frame var finished : Bool if !readStateSaved { if leaderFrame != nil { frame = leaderFrame! finished = false leaderFrame = nil } else { frame = try readFrameFragment(nil) finished = frame.finished } if frame.code == .Continue{ throw WebSocketError.ProtocolError("leader frame cannot be a continue frame") } if !finished { readStateSaved = true readStateFrame = frame readStateFinished = finished throw WebSocketError.NeedMoreInput } } else { frame = readStateFrame! finished = readStateFinished if !finished { let cf = try readFrameFragment(frame) finished = cf.finished if cf.code != .Continue { if !cf.code.isControl { throw WebSocketError.ProtocolError("only ping frames can be interlaced with fragments") } leaderFrame = frame return cf } if !finished { readStateSaved = true readStateFrame = frame readStateFinished = finished throw WebSocketError.NeedMoreInput } } } if !frame.utf8.completed { throw WebSocketError.PayloadError("incomplete utf8") } readStateSaved = false readStateFrame = nil readStateFinished = false return frame } private func closeConn() { rd.removeFromRunLoop(NSRunLoop.mainRunLoop(), forMode: NSDefaultRunLoopMode) wr.removeFromRunLoop(NSRunLoop.mainRunLoop(), forMode: NSDefaultRunLoopMode) rd.delegate = nil wr.delegate = nil rd.close() wr.close() } private func openConn() throws { let req = request.mutableCopy() as! NSMutableURLRequest req.setValue("websocket", forHTTPHeaderField: "Upgrade") req.setValue("Upgrade", forHTTPHeaderField: "Connection") req.setValue("SwiftWebSocket", forHTTPHeaderField: "User-Agent") req.setValue("13", forHTTPHeaderField: "Sec-WebSocket-Version") if req.URL == nil || req.URL!.host == nil{ throw WebSocketError.InvalidAddress } if req.URL!.port == nil || req.URL!.port!.integerValue == 80 || req.URL!.port!.integerValue == 443 { req.setValue(req.URL!.host!, forHTTPHeaderField: "Host") } else { req.setValue("\(req.URL!.host!):\(req.URL!.port!.integerValue)", forHTTPHeaderField: "Host") } req.setValue(req.URL!.absoluteString, forHTTPHeaderField: "Origin") if subProtocols.count > 0 { req.setValue(subProtocols.joinWithSeparator(";"), forHTTPHeaderField: "Sec-WebSocket-Protocol") } if req.URL!.scheme != "wss" && req.URL!.scheme != "ws" { throw WebSocketError.InvalidAddress } if compression.on { var val = "permessage-deflate" if compression.noContextTakeover { val += "; client_no_context_takeover; server_no_context_takeover" } val += "; client_max_window_bits" if compression.maxWindowBits != 0 { val += "; server_max_window_bits=\(compression.maxWindowBits)" } req.setValue(val, forHTTPHeaderField: "Sec-WebSocket-Extensions") } var security = TCPConnSecurity.None let port : Int if req.URL!.port != nil { port = req.URL!.port!.integerValue } else if req.URL!.scheme == "wss" { port = 443 security = .NegoticatedSSL } else { port = 80 security = .None } var path = CFURLCopyPath(req.URL!) as String if path == "" { path = "/" } if let q = req.URL!.query { if q != "" { path += "?" + q } } var reqs = "GET \(path) HTTP/1.1\r\n" for key in req.allHTTPHeaderFields!.keys { if let val = req.valueForHTTPHeaderField(key) { reqs += "\(key): \(val)\r\n" } } var keyb = [UInt32](count: 4, repeatedValue: 0) for var i = 0; i < 4; i++ { keyb[i] = arc4random() } let rkey = NSData(bytes: keyb, length: 16).base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0)) reqs += "Sec-WebSocket-Key: \(rkey)\r\n" reqs += "\r\n" var header = [UInt8]() for b in reqs.utf8 { header += [b] } let addr = ["\(req.URL!.host!)", "\(port)"] if addr.count != 2 || Int(addr[1]) == nil { throw WebSocketError.InvalidAddress } var (rdo, wro) : (NSInputStream?, NSOutputStream?) NSStream.getStreamsToHostWithName(addr[0], port: Int(addr[1])!, inputStream: &rdo, outputStream: &wro) (rd, wr) = (rdo!, wro!) let securityLevel : String switch security { case .None: securityLevel = NSStreamSocketSecurityLevelNone case .NegoticatedSSL: securityLevel = NSStreamSocketSecurityLevelNegotiatedSSL } rd.setProperty(securityLevel, forKey: NSStreamSocketSecurityLevelKey) wr.setProperty(securityLevel, forKey: NSStreamSocketSecurityLevelKey) if services.contains(.VoIP) { rd.setProperty(NSStreamNetworkServiceTypeVoIP, forKey: NSStreamNetworkServiceType) wr.setProperty(NSStreamNetworkServiceTypeVoIP, forKey: NSStreamNetworkServiceType) } if services.contains(.Video) { rd.setProperty(NSStreamNetworkServiceTypeVideo, forKey: NSStreamNetworkServiceType) wr.setProperty(NSStreamNetworkServiceTypeVideo, forKey: NSStreamNetworkServiceType) } if services.contains(.Background) { rd.setProperty(NSStreamNetworkServiceTypeBackground, forKey: NSStreamNetworkServiceType) wr.setProperty(NSStreamNetworkServiceTypeBackground, forKey: NSStreamNetworkServiceType) } if services.contains(.Voice) { rd.setProperty(NSStreamNetworkServiceTypeVoice, forKey: NSStreamNetworkServiceType) wr.setProperty(NSStreamNetworkServiceTypeVoice, forKey: NSStreamNetworkServiceType) } rd.delegate = delegate wr.delegate = delegate rd.scheduleInRunLoop(NSRunLoop.mainRunLoop(), forMode: NSDefaultRunLoopMode) wr.scheduleInRunLoop(NSRunLoop.mainRunLoop(), forMode: NSDefaultRunLoopMode) rd.open() wr.open() try write(header, length: header.count) } private func write(bytes: UnsafePointer<UInt8>, length: Int) throws { if outputBytesStart+outputBytesLength+length > outputBytesSize { var size = outputBytesSize while outputBytesStart+outputBytesLength+length > size { size *= 2 } let ptr = UnsafeMutablePointer<UInt8>(realloc(outputBytes, size)) if ptr == nil { throw WebSocketError.Memory } outputBytes = ptr outputBytesSize = size } memcpy(outputBytes+outputBytesStart+outputBytesLength, bytes, length) outputBytesLength += length } private func readResponse() throws { let end : [UInt8] = [ 0x0D, 0x0A, 0x0D, 0x0A ] let ptr = UnsafeMutablePointer<UInt8>(memmem(inputBytes+inputBytesStart, inputBytesLength, end, 4)) if ptr == nil { throw WebSocketError.NeedMoreInput } let buffer = inputBytes+inputBytesStart let bufferCount = ptr-(inputBytes+inputBytesStart) let string = NSString(bytesNoCopy: buffer, length: bufferCount, encoding: NSUTF8StringEncoding, freeWhenDone: false) as? String if string == nil { throw WebSocketError.InvalidHeader } let header = string! var needsCompression = false var serverMaxWindowBits = 15 let clientMaxWindowBits = 15 var key = "" let trim : (String)->(String) = { (text) in return text.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())} let eqval : (String,String)->(String) = { (line, del) in return trim(line.componentsSeparatedByString(del)[1]) } let lines = header.componentsSeparatedByString("\r\n") for var i = 0; i < lines.count; i++ { let line = trim(lines[i]) if i == 0 { if !line.hasPrefix("HTTP/1.1 101"){ throw WebSocketError.InvalidResponse(line) } } else if line != "" { var value = "" if line.hasPrefix("\t") || line.hasPrefix(" ") { value = trim(line) } else { key = "" if let r = line.rangeOfString(":") { key = trim(line.substringToIndex(r.startIndex)) value = trim(line.substringFromIndex(r.endIndex)) } } switch key { case "Sec-WebSocket-SubProtocol": privateSubProtocol = value case "Sec-WebSocket-Extensions": let parts = value.componentsSeparatedByString(";") for p in parts { let part = trim(p) if part == "permessage-deflate" { needsCompression = true } else if part.hasPrefix("server_max_window_bits="){ if let i = Int(eqval(line, "=")) { serverMaxWindowBits = i } } } default: break } } } if needsCompression { if serverMaxWindowBits < 8 || serverMaxWindowBits > 15 { throw WebSocketError.InvalidCompressionOptions("server_max_window_bits") } if serverMaxWindowBits < 8 || serverMaxWindowBits > 15 { throw WebSocketError.InvalidCompressionOptions("client_max_window_bits") } inflater = Inflater(windowBits: serverMaxWindowBits) if inflater == nil { throw WebSocketError.InvalidCompressionOptions("inflater init") } deflater = Deflater(windowBits: clientMaxWindowBits, memLevel: 8) if deflater == nil { throw WebSocketError.InvalidCompressionOptions("deflater init") } } inputBytesLength -= bufferCount+4 if inputBytesLength == 0 { inputBytesStart = 0 } else { inputBytesStart += bufferCount+4 } } private class ByteReader { var start : UnsafePointer<UInt8> var end : UnsafePointer<UInt8> var bytes : UnsafePointer<UInt8> init(bytes: UnsafePointer<UInt8>, length: Int){ self.bytes = bytes start = bytes end = bytes+length } func readByte() throws -> UInt8 { if bytes >= end { throw WebSocketError.NeedMoreInput } let b = bytes.memory bytes++ return b } var length : Int { return end - bytes } var position : Int { get { return bytes - start } set { bytes = start + newValue } } } private var fragStateSaved = false private var fragStatePosition = 0 private var fragStateInflate = false private var fragStateLen = 0 private var fragStateFin = false private var fragStateCode = OpCode.Continue private var fragStateLeaderCode = OpCode.Continue private var fragStateUTF8 = UTF8() private var fragStatePayload = Payload() private var fragStateStatusCode = UInt16(0) private var fragStateHeaderLen = 0 private var buffer = [UInt8](count: windowBufferSize, repeatedValue: 0) private var reusedPayload = Payload() private func readFrameFragment(var leader : Frame?) throws -> Frame { var inflate : Bool var len : Int var fin = false var code : OpCode var leaderCode : OpCode var utf8 : UTF8 var payload : Payload var statusCode : UInt16 var headerLen : Int let reader = ByteReader(bytes: inputBytes+inputBytesStart, length: inputBytesLength) if fragStateSaved { // load state reader.position += fragStatePosition inflate = fragStateInflate len = fragStateLen fin = fragStateFin code = fragStateCode leaderCode = fragStateLeaderCode utf8 = fragStateUTF8 payload = fragStatePayload statusCode = fragStateStatusCode headerLen = fragStateHeaderLen fragStateSaved = false } else { var b = try reader.readByte() fin = b >> 7 & 0x1 == 0x1 let rsv1 = b >> 6 & 0x1 == 0x1 let rsv2 = b >> 5 & 0x1 == 0x1 let rsv3 = b >> 4 & 0x1 == 0x1 if inflater != nil && (rsv1 || (leader != nil && leader!.inflate)) { inflate = true } else if rsv1 || rsv2 || rsv3 { throw WebSocketError.ProtocolError("invalid extension") } else { inflate = false } code = OpCode.Binary if let c = OpCode(rawValue: (b & 0xF)){ code = c } else { throw WebSocketError.ProtocolError("invalid opcode") } if !fin && code.isControl { throw WebSocketError.ProtocolError("unfinished control frame") } b = try reader.readByte() if b >> 7 & 0x1 == 0x1 { throw WebSocketError.ProtocolError("server sent masked frame") } var len64 = Int64(b & 0x7F) var bcount = 0 if b & 0x7F == 126 { bcount = 2 } else if len64 == 127 { bcount = 8 } if bcount != 0 { if code.isControl { throw WebSocketError.ProtocolError("invalid payload size for control frame") } len64 = 0 for var i = bcount-1; i >= 0; i-- { b = try reader.readByte() len64 += Int64(b) << Int64(i*8) } } len = Int(len64) if code == .Continue { if code.isControl { throw WebSocketError.ProtocolError("control frame cannot have the 'continue' opcode") } if leader == nil { throw WebSocketError.ProtocolError("continue frame is missing it's leader") } } if code.isControl { if leader != nil { leader = nil } if inflate { throw WebSocketError.ProtocolError("control frame cannot be compressed") } } statusCode = 0 if leader != nil { leaderCode = leader!.code utf8 = leader!.utf8 payload = leader!.payload } else { leaderCode = code utf8 = UTF8() payload = reusedPayload payload.count = 0 } if leaderCode == .Close { if len == 1 { throw WebSocketError.ProtocolError("invalid payload size for close frame") } if len >= 2 { let b1 = try reader.readByte() let b2 = try reader.readByte() statusCode = (UInt16(b1) << 8) + UInt16(b2) len -= 2 if statusCode < 1000 || statusCode > 4999 || (statusCode >= 1004 && statusCode <= 1006) || (statusCode >= 1012 && statusCode <= 2999) { throw WebSocketError.ProtocolError("invalid status code for close frame") } } } headerLen = reader.position } let rlen : Int let rfin : Bool let chopped : Bool if reader.length+reader.position-headerLen < len { rlen = reader.length rfin = false chopped = true } else { rlen = len-reader.position+headerLen rfin = fin chopped = false } let bytes : UnsafeMutablePointer<UInt8> let bytesLen : Int if inflate { (bytes, bytesLen) = try inflater!.inflate(reader.bytes, length: rlen, final: rfin) } else { (bytes, bytesLen) = (UnsafeMutablePointer<UInt8>(reader.bytes), rlen) } reader.bytes += rlen if leaderCode == .Text || leaderCode == .Close { try utf8.append(bytes, length: bytesLen) } else { payload.append(bytes, length: bytesLen) } if chopped { // save state fragStateHeaderLen = headerLen fragStateStatusCode = statusCode fragStatePayload = payload fragStateUTF8 = utf8 fragStateLeaderCode = leaderCode fragStateCode = code fragStateFin = fin fragStateLen = len fragStateInflate = inflate fragStatePosition = reader.position fragStateSaved = true throw WebSocketError.NeedMoreInput } inputBytesLength -= reader.position if inputBytesLength == 0 { inputBytesStart = 0 } else { inputBytesStart += reader.position } let f = Frame() (f.code, f.payload, f.utf8, f.statusCode, f.inflate, f.finished) = (code, payload, utf8, statusCode, inflate, fin) return f } private var head = [UInt8](count: 0xFF, repeatedValue: 0) private func writeFrame(f : Frame) throws { if !f.finished{ throw WebSocketError.LibraryError("cannot send unfinished frames") } var hlen = 0 let b : UInt8 = 0x80 var deflate = false if deflater != nil { if f.code == .Binary || f.code == .Text { deflate = true // b |= 0x40 } } head[hlen++] = b | f.code.rawValue var payloadBytes : [UInt8] var payloadLen = 0 if f.utf8.text != "" { payloadBytes = UTF8.bytes(f.utf8.text) } else { payloadBytes = f.payload.array } payloadLen += payloadBytes.count if deflate { } var usingStatusCode = false if f.statusCode != 0 && payloadLen != 0 { payloadLen += 2 usingStatusCode = true } if payloadLen < 126 { head[hlen++] = 0x80 | UInt8(payloadLen) } else if payloadLen <= 0xFFFF { head[hlen++] = 0x80 | 126 for var i = 1; i >= 0; i-- { head[hlen++] = UInt8((UInt16(payloadLen) >> UInt16(i*8)) & 0xFF) } } else { head[hlen++] = UInt8((0x1 << 7) + 127) for var i = 7; i >= 0; i-- { head[hlen++] = UInt8((UInt64(payloadLen) >> UInt64(i*8)) & 0xFF) } } let r = arc4random() var maskBytes : [UInt8] = [UInt8(r >> 0 & 0xFF), UInt8(r >> 8 & 0xFF), UInt8(r >> 16 & 0xFF), UInt8(r >> 24 & 0xFF)] for var i = 0; i < 4; i++ { head[hlen++] = maskBytes[i] } if payloadLen > 0 { if usingStatusCode { var sc = [UInt8(f.statusCode >> 8 & 0xFF), UInt8(f.statusCode >> 0 & 0xFF)] for var i = 0; i < 2; i++ { sc[i] ^= maskBytes[i % 4] } head[hlen++] = sc[0] head[hlen++] = sc[1] for var i = 2; i < payloadLen; i++ { payloadBytes[i-2] ^= maskBytes[i % 4] } } else { for var i = 0; i < payloadLen; i++ { payloadBytes[i] ^= maskBytes[i % 4] } } } try write(head, length: hlen) try write(payloadBytes, length: payloadBytes.count) } /** Closes the WebSocket connection or connection attempt, if any. If the connection is already closed or in the state of closing, this method does nothing. :param: code An integer indicating the status code explaining why the connection is being closed. If this parameter is not specified, a default value of 1000 (indicating a normal closure) is assumed. :param: reason A human-readable string explaining why the connection is closing. This string must be no longer than 123 bytes of UTF-8 text (not characters). */ public func close(code : Int = 1000, reason : String = "Normal Closure") { let f = Frame() f.code = .Close f.statusCode = UInt16(truncatingBitPattern: code) f.utf8.text = reason sendFrame(f) } private func sendFrame(f : Frame) { lock() frames += [f] unlock() manager.signal() } /** Transmits message to the server over the WebSocket connection. :param: message The data to be sent to the server. */ public func send(message : Any) { let f = Frame() if let message = message as? String { f.code = .Text f.utf8.text = message } else if let message = message as? [UInt8] { f.code = .Binary f.payload.array = message } else if let message = message as? UnsafeBufferPointer<UInt8> { f.code = .Binary f.payload.append(message.baseAddress, length: message.count) } else if let message = message as? NSData { f.code = .Binary f.payload.nsdata = message } else { f.code = .Text f.utf8.text = "\(message)" } sendFrame(f) } /** Transmits a ping to the server over the WebSocket connection. */ public func ping() { let f = Frame() f.code = .Ping sendFrame(f) } /** Transmits a ping to the server over the WebSocket connection. :param: optional message The data to be sent to the server. */ public func ping(message : Any){ let f = Frame() f.code = .Ping if let message = message as? String { f.payload.array = UTF8.bytes(message) } else if let message = message as? [UInt8] { f.payload.array = message } else if let message = message as? UnsafeBufferPointer<UInt8> { f.payload.append(message.baseAddress, length: message.count) } else if let message = message as? NSData { f.payload.nsdata = message } else { f.utf8.text = "\(message)" } sendFrame(f) } } public func ==(lhs: WebSocket, rhs: WebSocket) -> Bool { return lhs.id == rhs.id } private enum TCPConnSecurity { case None case NegoticatedSSL } // Manager class is used to minimize the number of dispatches and cycle through network events // using fewers threads. Helps tremendously with lowing system resources when many conncurrent // sockets are opened. private class Manager { var once = dispatch_once_t() var mutex = pthread_mutex_t() var cond = pthread_cond_t() var websockets = Set<WebSocket>() var _nextId = 0 init(){ pthread_mutex_init(&mutex, nil) pthread_cond_init(&cond, nil) dispatch_async(dispatch_queue_create("SwiftWebSocket", nil)) { var wss : [WebSocket] = [] for ;; { var wait = true wss.removeAll() pthread_mutex_lock(&self.mutex) for ws in self.websockets { wss.append(ws) } for ws in wss { if ws.dirty { pthread_mutex_unlock(&self.mutex) ws.step() pthread_mutex_lock(&self.mutex) wait = false } } if wait { pthread_cond_wait(&self.cond, &self.mutex) } pthread_mutex_unlock(&self.mutex) } } } func signal(){ pthread_mutex_lock(&mutex) pthread_cond_signal(&cond) pthread_mutex_unlock(&mutex) } func add(websocket: WebSocket) { pthread_mutex_lock(&mutex) websockets.insert(websocket) pthread_cond_signal(&cond) pthread_mutex_unlock(&mutex) } func remove(websocket: WebSocket) { pthread_mutex_lock(&mutex) websockets.remove(websocket) pthread_cond_signal(&cond) pthread_mutex_unlock(&mutex) } func nextId() -> Int { pthread_mutex_lock(&mutex) defer { pthread_mutex_unlock(&mutex) } return ++_nextId } } private let manager = Manager()
mit
90ef8daaaf8412f4ab06544b43a759ed
36.216999
222
0.546334
5.005889
false
false
false
false
Piwigo/Piwigo-Mobile
piwigo/Settings/Cells/SwitchTableViewCell.swift
1
1129
// // SwitchTableViewCell.swift // piwigo // // Created by Spencer Baker on 3/24/15. // Copyright (c) 2015 bakercrew. All rights reserved. // // Converted to Swift 5 by Eddy Lelièvre-Berna on 12/04/2020. // import UIKit typealias CellSwitchBlock = (Bool) -> Void class SwitchTableViewCell: UITableViewCell { @IBOutlet weak var switchName: UILabel! @IBOutlet weak var cellSwitch: UISwitch! var cellSwitchBlock: CellSwitchBlock? func configure(with title:String) { // Background color and aspect backgroundColor = .piwigoColorCellBackground() // Switch name switchName.font = .piwigoFontNormal() switchName.textColor = .piwigoColorLeftLabel() switchName.text = title // Switch appearance and action cellSwitch.thumbTintColor = .piwigoColorThumb() cellSwitch.onTintColor = .piwigoColorOrange() } @IBAction func switchChanged(_ sender: Any) { (cellSwitchBlock ?? {_ in return})(cellSwitch.isOn) } override func prepareForReuse() { super.prepareForReuse() switchName.text = "" } }
mit
13f6d72675ca4cc9f6ddb981d40c0881
24.066667
62
0.664007
4.47619
false
false
false
false
digitwolf/SwiftFerrySkill
Sources/Ferry/Domain/TerminalService.swift
1
3545
// // TerminalService.swift // Kitura-Starter // // Created by Babych, Ruslan on 2/16/17. // // import Foundation import SwiftyJSON public class TerminalService : WSDOTService { public override init() { super.init(key: "2d1dbff1-4218-4e8b-b832-e6599db7919b") } func terminalbasics(completionHandler: @escaping ([TerminalBasics]) -> Void) { self.get(path: "terminals", method: "terminalbasics", completionHandler: { json in var result: [TerminalBasics] = [] for obj in json.arrayValue { result.append(TerminalBasics(obj)) } completionHandler(result) }) } func terminallocations(completionHandler: @escaping ([TerminalLocations]) -> Void) { self.get(path: "terminals", method: "terminallocations", completionHandler: { json in var result: [TerminalLocations] = [] for obj in json.arrayValue { result.append(TerminalLocations(obj)) } completionHandler(result) }) } func terminallocations(terminalID: String, completionHandler: @escaping ([TerminalLocations]) -> Void) { self.get(path: "terminals", method: "terminallocations/\(terminalID)", completionHandler: { json in var result: [TerminalLocations] = [] for obj in json.arrayValue { result.append(TerminalLocations(obj)) } completionHandler(result) }) } func terminalwaittimes(completionHandler: @escaping (TerminalWaitTimes) -> Void) { self.get(path: "terminals", method: "terminalwaittimes", completionHandler: { json in var result: TerminalWaitTimes = TerminalWaitTimes() result = TerminalWaitTimes.init(json) completionHandler(result) }) } func terminalwaittimes(terminalID: String, completionHandler: @escaping (TerminalWaitTimes) -> Void) { self.get(path: "terminals", method: "terminalwaittimes/\(terminalID)", completionHandler: { json in var result: TerminalWaitTimes = TerminalWaitTimes() result = TerminalWaitTimes.init(json) completionHandler(result) }) } func terminalsailingspace (terminalID: String, completionHandler: @escaping (TerminalSailingSpace) -> Void) { self.get(path: "terminals", method: "terminalsailingspace/\(terminalID)", completionHandler: { json in var result: TerminalSailingSpace = TerminalSailingSpace() result = TerminalSailingSpace.init(json) completionHandler(result) }) } // provides helpful information for terminal commuters (including parking notes, vehicle-specific tips, etc). A TerminalID, or unique terminal identifier, may be optionally passed to retrieve a specific terminal. func terminaltransports (terminalID: String, completionHandler: @escaping (JSON) -> Void) { self.get(path: "terminals", method: "terminaltransports/\(terminalID)", completionHandler: completionHandler) } }
apache-2.0
b0b013faa4db6242d032724aa8401ccf
35.546392
216
0.565585
5.122832
false
false
false
false
practicalswift/swift
test/SILGen/optional_lvalue.swift
12
7342
// RUN: %target-swift-emit-silgen -module-name optional_lvalue %s | %FileCheck %s // CHECK-LABEL: sil hidden [ossa] @$s15optional_lvalue07assign_a1_B0yySiSgz_SitF // CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] %0 : $*Optional<Int> // CHECK: [[FILESTR:%.*]] = string_literal utf8 " // CHECK-NEXT: [[FILESIZ:%.*]] = integer_literal $Builtin.Word, // CHECK-NEXT: [[FILEASC:%.*]] = integer_literal $Builtin.Int1, // CHECK-NEXT: [[LINE:%.*]] = integer_literal $Builtin.Word, // CHECK-NEXT: [[COLUMN:%.*]] = integer_literal $Builtin.Word, // CHECK-NEXT: [[IMPLICIT:%.*]] = integer_literal $Builtin.Int1, 0 // CHECK: [[PRECOND:%.*]] = function_ref @$ss30_diagnoseUnexpectedNilOptional{{[_0-9a-zA-Z]*}}F // CHECK: apply [[PRECOND]]([[FILESTR]], [[FILESIZ]], [[FILEASC]], [[LINE]], [[IMPLICIT]]) // CHECK: [[PAYLOAD:%.*]] = unchecked_take_enum_data_addr [[WRITE]] : $*Optional<Int>, #Optional.some!enumelt.1 // CHECK: assign {{%.*}} to [[PAYLOAD]] func assign_optional_lvalue(_ x: inout Int?, _ y: Int) { x! = y } // CHECK-LABEL: sil hidden [ossa] @$s15optional_lvalue011assign_iuo_B0yySiSgz_SitF // CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] %0 : $*Optional<Int> // CHECK: [[FILESTR:%.*]] = string_literal utf8 " // CHECK-NEXT: [[FILESIZ:%.*]] = integer_literal $Builtin.Word, // CHECK-NEXT: [[FILEASC:%.*]] = integer_literal $Builtin.Int1, // CHECK-NEXT: [[LINE:%.*]] = integer_literal $Builtin.Word, // CHECK-NEXT: [[COLUMN:%.*]] = integer_literal $Builtin.Word, // CHECK-NEXT: [[IMPLICIT:%.*]] = integer_literal $Builtin.Int1, 0 // CHECK: [[PRECOND:%.*]] = function_ref @$ss30_diagnoseUnexpectedNilOptional{{[_0-9a-zA-Z]*}}F // CHECK: apply [[PRECOND]]([[FILESTR]], [[FILESIZ]], [[FILEASC]], [[LINE]], [[IMPLICIT]]) // CHECK: [[PAYLOAD:%.*]] = unchecked_take_enum_data_addr [[WRITE]] : $*Optional<Int>, #Optional.some!enumelt.1 // CHECK: assign {{%.*}} to [[PAYLOAD]] func assign_iuo_lvalue(_ x: inout Int!, _ y: Int) { x! = y } struct S { var x: Int var computed: Int { get {} set {} } } // CHECK-LABEL: sil hidden [ossa] @$s15optional_lvalue011assign_iuo_B9_implicityyAA1SVSgz_SitF // CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] %0 : $*Optional<S> // CHECK: [[FILESTR:%.*]] = string_literal utf8 " // CHECK-NEXT: [[FILESIZ:%.*]] = integer_literal $Builtin.Word, // CHECK-NEXT: [[FILEASC:%.*]] = integer_literal $Builtin.Int1, // CHECK-NEXT: [[LINE:%.*]] = integer_literal $Builtin.Word, // CHECK-NEXT: [[COLUMN:%.*]] = integer_literal $Builtin.Word, // CHECK-NEXT: [[IMPLICIT:%.*]] = integer_literal $Builtin.Int1, -1 // CHECK: [[PRECOND:%.*]] = function_ref @$ss30_diagnoseUnexpectedNilOptional{{[_0-9a-zA-Z]*}}F // CHECK: apply [[PRECOND]]([[FILESTR]], [[FILESIZ]], [[FILEASC]], [[LINE]], [[IMPLICIT]]) // CHECK: [[SOME:%.*]] = unchecked_take_enum_data_addr [[WRITE]] // CHECK: [[X:%.*]] = struct_element_addr [[SOME]] func assign_iuo_lvalue_implicit(_ s: inout S!, _ y: Int) { s.x = y } struct Struct<T> { var value: T? } // CHECK-LABEL: sil hidden [ossa] @$s15optional_lvalue07assign_a1_B13_reabstractedyyAA6StructVyS2icGz_S2ictF // CHECK: [[REABSTRACT:%.*]] = function_ref @$sS2iIegyd_S2iIegnr_TR // CHECK: [[REABSTRACTED:%.*]] = partial_apply [callee_guaranteed] [[REABSTRACT]] // CHECK: assign [[REABSTRACTED]] to {{%.*}} : $*@callee_guaranteed (@in_guaranteed Int) -> @out Int func assign_optional_lvalue_reabstracted(_ x: inout Struct<(Int) -> Int>, _ y: @escaping (Int) -> Int) { x.value! = y } // CHECK-LABEL: sil hidden [ossa] @$s15optional_lvalue07assign_a1_B9_computedySiAA1SVSgz_SitF // CHECK: function_ref @$s15optional_lvalue1SV8computedSivs // CHECK: function_ref @$s15optional_lvalue1SV8computedSivg func assign_optional_lvalue_computed(_ x: inout S?, _ y: Int) -> Int { x!.computed = y return x!.computed } func generate_int() -> Int { return 0 } // CHECK-LABEL: sil hidden [ossa] @$s15optional_lvalue013assign_bound_a1_B0yySiSgzF // CHECK: [[HASVALUE:%.*]] = select_enum_addr {{%.*}} // CHECK: cond_br [[HASVALUE]], [[SOME:bb[0-9]+]], [[NONE:bb[0-9]+]] // // CHECK: [[SOME]]: // CHECK: [[PAYLOAD:%.*]] = unchecked_take_enum_data_addr // CHECK: [[FN:%.*]] = function_ref // CHECK: [[T0:%.*]] = apply [[FN]]() // CHECK: assign [[T0]] to [[PAYLOAD]] func assign_bound_optional_lvalue(_ x: inout Int?) { x? = generate_int() } struct ComputedOptional { var computedOptional : Int? { get {} set {} } } // CHECK-LABEL: sil hidden [ossa] @$s15optional_lvalue013assign_bound_a10_computed_B0yyAA16ComputedOptionalVzF // CHECK: [[SELF:%.*]] = begin_access [modify] [unknown] %0 : $*ComputedOptional // CHECK: [[TEMP:%.*]] = alloc_stack $Optional<Int> // CHECK: [[T0:%.*]] = load [trivial] [[SELF]] : $*ComputedOptional // CHECK: [[GETTER:%.*]] = function_ref @$s15optional_lvalue16ComputedOptionalV08computedD0SiSgvg // CHECK: [[VALUE:%.*]] = apply [[GETTER]]([[T0]]) // CHECK: store [[VALUE]] to [trivial] [[TEMP]] : $*Optional<Int> // CHECK: select_enum_addr [[TEMP]] : $*Optional<Int> // CHECK: cond_br // CHECK: [[VALUE_ADDR:%.*]] = unchecked_take_enum_data_addr [[TEMP]] : $*Optional<Int> // CHECK: [[GENERATOR:%.*]] = function_ref @$s15optional_lvalue12generate_intSiyF // CHECK: [[VALUE:%.*]] = apply [[GENERATOR]]() // CHECK: assign [[VALUE]] to [[VALUE_ADDR]] : $*Int // CHECK: [[OPTVALUE:%.*]] = load [trivial] [[TEMP]] : $*Optional<Int> // CHECK: [[SETTER:%.*]] = function_ref @$s15optional_lvalue16ComputedOptionalV08computedD0SiSgvs // CHECK: apply [[SETTER]]([[OPTVALUE]], [[SELF]]) // CHECK: end_access [[SELF]] // CHECK: dealloc_stack [[TEMP]] func assign_bound_optional_computed_lvalue(_ co: inout ComputedOptional) { co.computedOptional? = generate_int() } // CHECK-LABEL: sil hidden [ossa] @$s15optional_lvalue014assign_forced_a10_computed_B0yyAA16ComputedOptionalVzF // CHECK: [[GENERATOR:%.*]] = function_ref @$s15optional_lvalue12generate_intSiyF // CHECK: [[VALUE:%.*]] = apply [[GENERATOR]]() // CHECK: [[SELF:%.*]] = begin_access [modify] [unknown] %0 : $*ComputedOptional // CHECK: [[TEMP:%.*]] = alloc_stack $Optional<Int> // CHECK: [[T0:%.*]] = load [trivial] [[SELF]] : $*ComputedOptional // CHECK: [[GETTER:%.*]] = function_ref @$s15optional_lvalue16ComputedOptionalV08computedD0SiSgvg // CHECK: [[OPTVALUE:%.*]] = apply [[GETTER]]([[T0]]) // CHECK: store [[OPTVALUE]] to [trivial] [[TEMP]] // CHECK: switch_enum_addr [[TEMP]] // CHECK: [[VALUE_ADDR:%.*]] = unchecked_take_enum_data_addr [[TEMP]] : $*Optional<Int> // CHECK: assign [[VALUE]] to [[VALUE_ADDR]] : $*Int // CHECK: [[OPTVALUE:%.*]] = load [trivial] [[TEMP]] : $*Optional<Int> // CHECK: [[SETTER:%.*]] = function_ref @$s15optional_lvalue16ComputedOptionalV08computedD0SiSgvs // CHECK: apply [[SETTER]]([[OPTVALUE]], [[SELF]]) // CHECK: end_access [[SELF]] // CHECK: dealloc_stack [[TEMP]] func assign_forced_optional_computed_lvalue(_ co: inout ComputedOptional) { co.computedOptional! = generate_int() }
apache-2.0
631c19c7f17ba8a4e218917753e6c05d
49.634483
119
0.601743
3.313177
false
false
false
false
fthomasmorel/insapp-iOS
Insapp/EditUserViewController.swift
1
4210
// // EditUserViewController.swift // Insapp // // Created by Florent THOMAS-MOREL on 9/13/16. // Copyright © 2016 Florent THOMAS-MOREL. All rights reserved. // import Foundation import UIKit class EditUserViewController: UIViewController { @IBOutlet weak var keyboardHeightConstraint: NSLayoutConstraint! @IBOutlet weak var saveButton: UIButton! var settingViewController:EditUserTableViewController? var user:User? override func viewDidLoad() { super.viewDidLoad() self.settingViewController = self.childViewControllers.last as? EditUserTableViewController } override func viewWillAppear(_ animated: Bool) { self.hideNavBar() self.notifyGoogleAnalytics() self.settingViewController?.avatarImageView.image = user?.avatar() self.settingViewController?.usernameTextField.text = "@\(user!.username!)" self.settingViewController?.nameTextField.text = user!.name self.settingViewController?.emailTextField.text = user!.email self.settingViewController?.descriptionTextView.text = user!.desc self.settingViewController?.promotionTextField.text = user!.promotion self.settingViewController?.genderTextField.text = convertGender[user!.gender!] NotificationCenter.default.addObserver(self, selector: #selector(EditUserViewController.keyboardWillShow(_:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(EditUserViewController.keyboardWillHide(_:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil) self.lightStatusBar() } override func viewWillDisappear(_ animated: Bool) { NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillShow, object: self.view.window) NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillHide, object: self.view.window) } func keyboardWillShow(_ notification: NSNotification) { let userInfo:NSDictionary = notification.userInfo! as NSDictionary let keyboardFrame = (userInfo.value(forKey: UIKeyboardFrameEndUserInfoKey) as! NSValue).cgRectValue self.keyboardHeightConstraint.constant = keyboardFrame.height } func keyboardWillHide(_ notification: NSNotification) { self.keyboardHeightConstraint.constant = 0 } @IBAction func dismissAction(_ sender: AnyObject) { self.settingViewController?.view.resignFirstResponder() self.settingViewController?.view.endEditing(true) self.dismiss(animated: true, completion: nil) } @IBAction func saveAction(_ sender: AnyObject) { if let field = self.checkForm() { field.textColor = UIColor.red }else{ self.startLoading() APIManager.update(user: self.user!, controller: self, completion: { (opt_user) in guard let _ = opt_user else { return } self.stopLoading() self.dismissAction(self) }) } } func checkForm() -> Optional<UITextField> { guard let name = self.settingViewController!.nameTextField.text else { return self.settingViewController!.nameTextField } let promotion = self.settingViewController!.promotionTextField.text let gender = self.settingViewController!.genderTextField.text let email = self.settingViewController!.emailTextField.text user?.name = name.replacingOccurrences(of: "\u{00a0}", with: " ") user?.email = email user?.promotion = promotion user?.gender = convertGender[gender!] user?.desc = "" let characters = NSMutableCharacterSet.alphanumeric() characters.addCharacters(in: NSRange(location: 0x1F300, length: 0x1F700 - 0x1F300)) if var description = self.settingViewController?.descriptionTextView.text, let _ = description.rangeOfCharacter(from: characters as CharacterSet) { description.condenseNewLine() user?.desc = description } return nil } }
mit
b3ba58a54114dddf28f07b739ad6116e
41.94898
177
0.690188
5.222084
false
false
false
false
HarukaMa/iina
iina/Parameter.swift
1
654
// // Parameter.swift // iina // // Created by lhc on 8/7/16. // Copyright © 2016年 lhc. All rights reserved. // import Cocoa class Parameter: NSObject { static let basicParameter = [ "profile": "pseudo-gui", "quiet": "", ] static func defaultParameter() -> [String] { var p = basicParameter p["vd-lavc-threads"] = String(ProcessInfo.processInfo.processorCount) p["cache"] = "8192" return parameterFormatter(p) } private static func parameterFormatter(_ dic: [String: String]) -> [String] { var result: [String] = [] for (k, v) in dic { result.append("--\(k)=\(v)") } return result } }
gpl-3.0
4f024b173f63a823401ccc4e7e8797f0
20
79
0.606759
3.481283
false
false
false
false
kysonyangs/ysbilibili
ysbilibili/Classes/HomePage/View/ZHNhomePagePraviteCell.swift
1
3754
// // ZHNhomePagePraviteCell.swift // zhnbilibili // // Created by 张辉男 on 17/1/14. // Copyright © 2017年 zhn. All rights reserved. // import UIKit class ZHNhomePagePraviteCell: UITableViewCell { // MARK - 属性 var type: homePageSectionType = homePageSectionType.card { didSet { switch type { case homePageSectionType.coinVideoPravite: nameLabel.text = "最近投币" rightNoticeLabel.text = "没有公开投币" case homePageSectionType.favouritePravite: nameLabel.text = "TA的收藏夹" rightNoticeLabel.text = "没有公开的收藏夹" case homePageSectionType.seasonPravite: nameLabel.text = "TA的追番" rightNoticeLabel.text = "没有公开的追番" case homePageSectionType.gamePravite: nameLabel.text = "TA玩的游戏" rightNoticeLabel.text = "没有公开的游戏" case homePageSectionType.tagePravite: nameLabel.text = "TA关注的标签" rightNoticeLabel.text = "没有公开关注的标签" default: break } } } // MARK - 懒加载控件 lazy var nameLabel: UILabel = { let nameLabel = UILabel() nameLabel.font = UIFont.systemFont(ofSize: 14) return nameLabel }() lazy var countLabel: UILabel = { let countLabel = UILabel() countLabel.text = "0" countLabel.font = UIFont.systemFont(ofSize: 13) countLabel.textColor = UIColor.lightGray return countLabel }() lazy var iconImageView: UIImageView = { let iconImageView = UIImageView() iconImageView.image = UIImage(named: "space_hide_eye_icon") iconImageView.contentMode = .center return iconImageView }() lazy var rightNoticeLabel: UILabel = { let rightNoticeLabel = UILabel() rightNoticeLabel.textColor = UIColor.lightGray rightNoticeLabel.font = UIFont.systemFont(ofSize: 13) return rightNoticeLabel }() lazy var lineView: UIImageView = { let lineView = UIImageView() lineView.backgroundColor = kCellLineBlackColor return lineView }() // MARK - life cycle override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) self.selectionStyle = .none self.backgroundColor = kHomeBackColor self.addSubview(nameLabel) self.addSubview(countLabel) self.addSubview(iconImageView) self.addSubview(rightNoticeLabel) self.addSubview(lineView) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() nameLabel.snp.makeConstraints { (make) in make.left.equalTo(self).offset(10) make.centerY.equalTo(self) } countLabel.snp.makeConstraints { (make) in make.centerY.equalTo(self) make.left.equalTo(nameLabel.snp.right).offset(5) } iconImageView.snp.makeConstraints { (make) in make.left.equalTo(countLabel.snp.right).offset(5) make.centerY.equalTo(self) } rightNoticeLabel.snp.makeConstraints { (make) in make.right.equalTo(self).offset(-5) make.centerY.equalTo(self) } lineView.snp.makeConstraints { (make) in make.left.right.bottom.equalTo(self) make.height.equalTo(0.5) } } }
mit
093dbfe5a6394c596d41b5dbc81a86c3
31.294643
74
0.601051
4.487593
false
false
false
false
onebytecode/krugozor-iOSVisitors
Pods/SwiftyBeaver/Sources/SwiftyBeaver.swift
4
7317
// // SwiftyBeaver.swift // SwiftyBeaver // // Created by Sebastian Kreutzberger (Twitter @skreutzb) on 28.11.15. // Copyright © 2015 Sebastian Kreutzberger // Some rights reserved: http://opensource.org/licenses/MIT // import Foundation open class SwiftyBeaver { /// version string of framework public static let version = "1.4.2" // UPDATE ON RELEASE! /// build number of framework public static let build = 1420 // version 0.7.1 -> 710, UPDATE ON RELEASE! public enum Level: Int { case verbose = 0 case debug = 1 case info = 2 case warning = 3 case error = 4 } // a set of active destinations open private(set) static var destinations = Set<BaseDestination>() // MARK: Destination Handling /// returns boolean about success @discardableResult open class func addDestination(_ destination: BaseDestination) -> Bool { if destinations.contains(destination) { return false } destinations.insert(destination) return true } /// returns boolean about success @discardableResult open class func removeDestination(_ destination: BaseDestination) -> Bool { if destinations.contains(destination) == false { return false } destinations.remove(destination) return true } /// if you need to start fresh open class func removeAllDestinations() { destinations.removeAll() } /// returns the amount of destinations open class func countDestinations() -> Int { return destinations.count } /// returns the current thread name class func threadName() -> String { #if os(Linux) // on 9/30/2016 not yet implemented in server-side Swift: // > import Foundation // > Thread.isMainThread return "" #else if Thread.isMainThread { return "" } else { let threadName = Thread.current.name if let threadName = threadName, !threadName.isEmpty { return threadName } else { return String(format: "%p", Thread.current) } } #endif } // MARK: Levels /// log something generally unimportant (lowest priority) open class func verbose(_ message: @autoclosure () -> Any, _ file: String = #file, _ function: String = #function, line: Int = #line, context: Any? = nil) { custom(level: .verbose, message: message, file: file, function: function, line: line, context: context) } /// log something which help during debugging (low priority) open class func debug(_ message: @autoclosure () -> Any, _ file: String = #file, _ function: String = #function, line: Int = #line, context: Any? = nil) { custom(level: .debug, message: message, file: file, function: function, line: line, context: context) } /// log something which you are really interested but which is not an issue or error (normal priority) open class func info(_ message: @autoclosure () -> Any, _ file: String = #file, _ function: String = #function, line: Int = #line, context: Any? = nil) { custom(level: .info, message: message, file: file, function: function, line: line, context: context) } /// log something which may cause big trouble soon (high priority) open class func warning(_ message: @autoclosure () -> Any, _ file: String = #file, _ function: String = #function, line: Int = #line, context: Any? = nil) { custom(level: .warning, message: message, file: file, function: function, line: line, context: context) } /// log something which will keep you awake at night (highest priority) open class func error(_ message: @autoclosure () -> Any, _ file: String = #file, _ function: String = #function, line: Int = #line, context: Any? = nil) { custom(level: .error, message: message, file: file, function: function, line: line, context: context) } /// custom logging to manually adjust values, should just be used by other frameworks public class func custom(level: SwiftyBeaver.Level, message: @autoclosure () -> Any, file: String = #file, function: String = #function, line: Int = #line, context: Any? = nil) { dispatch_send(level: level, message: message, thread: threadName(), file: file, function: function, line: line, context: context) } /// internal helper which dispatches send to dedicated queue if minLevel is ok class func dispatch_send(level: SwiftyBeaver.Level, message: @autoclosure () -> Any, thread: String, file: String, function: String, line: Int, context: Any?) { var resolvedMessage: String? for dest in destinations { guard let queue = dest.queue else { continue } resolvedMessage = resolvedMessage == nil && dest.hasMessageFilters() ? "\(message())" : resolvedMessage if dest.shouldLevelBeLogged(level, path: file, function: function, message: resolvedMessage) { // try to convert msg object to String and put it on queue let msgStr = resolvedMessage == nil ? "\(message())" : resolvedMessage! let f = stripParams(function: function) if dest.asynchronously { queue.async { _ = dest.send(level, msg: msgStr, thread: thread, file: file, function: f, line: line, context: context) } } else { queue.sync { _ = dest.send(level, msg: msgStr, thread: thread, file: file, function: f, line: line, context: context) } } } } } /** DEPRECATED & NEEDS COMPLETE REWRITE DUE TO SWIFT 3 AND GENERAL INCORRECT LOGIC Flush all destinations to make sure all logging messages have been written out Returns after all messages flushed or timeout seconds - returns: true if all messages flushed, false if timeout or error occurred */ public class func flush(secondTimeout: Int64) -> Bool { /* guard let grp = dispatch_group_create() else { return false } for dest in destinations { if let queue = dest.queue { dispatch_group_enter(grp) queue.asynchronously(execute: { dest.flush() grp.leave() }) } } let waitUntil = DispatchTime.now(dispatch_time_t(DISPATCH_TIME_NOW), secondTimeout * 1000000000) return dispatch_group_wait(grp, waitUntil) == 0 */ return true } /// removes the parameters from a function because it looks weird with a single param class func stripParams(function: String) -> String { var f = function if let indexOfBrace = f.characters.index(of: "(") { #if swift(>=4.0) f = String(f[..<indexOfBrace]) #else f = f.substring(to: indexOfBrace) #endif } f += "()" return f } }
apache-2.0
4fb845aa7c2f98bd6c0fbddd077f42a7
37.303665
128
0.58953
4.621605
false
false
false
false
ytfhqqu/iCC98
CC98Kit/CC98Kit/Deprecated/Structures.swift
1
16433
// // Structures.swift // CC98Kit // // Created by Duo Xu on 3/30/17. // Copyright © 2017 Duo Xu. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import ObjectMapper /** 表示一个主题最后一次发言的信息。 - seealso: [Page](http://api.cc98.org/Help/ResourceModel?modelName=TopicLastPostInfo) */ public struct TopicLastPostInfo: Mappable { /// 最后发言的用户名。如果主题为匿名主题,则该属性为 nil。 public var userName: String? /// 最后发言的内容摘要。如果主题的最后发言并非所有用户可见,则该属性为 nil。 public var contentSummary: String? /// 最后发言的时间。 public var time: Date? public init?(map: Map) { } mutating public func mapping(map: Map) { userName <- map["userName"] contentSummary <- map["contentSummary"] time <- (map["time"], MultipleDateFormatterTransform(dateFormatterArray: [Constants.cc98APIDateFormatter, Constants.cc98APIDateFormatterWithMilliseconds, Constants.cc98APIDateFormatterWithMillisecondsAndTimeZone])) } } /** 表示要新创建或者修改的发言信息。 - seealso: [Page](http://api.cc98.org/Help/ResourceModel?modelName=NewPostInfo) */ public struct NewPostInfo: Mappable { /// 发言的标题。 public var title: String? /// 发言的内容。 public var content: String? /// 发言的内容格式。 /// 枚举值参考 `Constants.PostContentType`。 public var contentType: Int? public init?(map: Map) { } public init() { } mutating public func mapping(map: Map) { title <- map["title"] content <- map["content"] contentType <- map["contentType"] } public var isValid: Bool { if title != nil, let content = content, let contentType = contentType { let validContentType = Constants.PostContentType(rawValue: contentType) if content.isEmpty || validContentType == nil { return false } else { return true } } else { return false } } } /** 表示用户发言信息的对象。 - seealso: [Page](http://api.cc98.org/Help/ResourceModel?modelName=PostInfo) */ public struct PostInfo: Mappable { /// 发言的标识。 public var id: Int? /// 发言的标题。如果发言已经被删除,则该属性为 nil。 public var title: String? /// 发言的内容。如果发言已经被删除或正在审核,则该属性为 nil。 public var content: String? /// 发言的时间。 public var time: Date? /// 发言是否已经被删除。true 表示被删除,false 表示未被删除。 public var isDeleted: Bool? /// 发言所在的主题的标识。 public var topicId: Int? /// 发言是否需要审核。 public var needAudit: Bool? /// 发言的楼层数。第一楼为 1。 public var floor: Int? /// 发言的用户名。如果该发言是匿名发言或已经被删除,则该属性为 nil。 public var userName: String? /// 发言的用户的标识。如果该发言是匿名发言或已经被删除,则该属性为 nil。 public var userId: Int? /// 发言是否为匿名发言。true 表示是匿名发言,false 表示不是匿名发言。 public var isAnonymous: Bool? /// 发言的内容类型。 /// 枚举值参考 `Constants.PostContentType`。 public var contentType: Int? /// 发言最后一次更新的作者。如果发言没有进行过更新或最后更新的作者就是发言的创建者,则该属性为 nil。 public var lastUpdateAuthor: String? /// 发言最后一次更新的时间。如果发言没有进行过更新,则该属性为 nil。 public var lastUpdateTime: Date? public init?(map: Map) { } mutating public func mapping(map: Map) { id <- map["id"] title <- map["title"] content <- map["content"] time <- (map["time"], MultipleDateFormatterTransform(dateFormatterArray: [Constants.cc98APIDateFormatter, Constants.cc98APIDateFormatterWithMilliseconds, Constants.cc98APIDateFormatterWithMillisecondsAndTimeZone])) isDeleted <- map["isDeleted"] topicId <- map["topicId"] needAudit <- map["needAudit"] floor <- map["floor"] userName <- map["userName"] userId <- map["userId"] isAnonymous <- map["isAnonymous"] contentType <- map["contentType"] lastUpdateAuthor <- map["lastUpdateAuthor"] lastUpdateTime <- (map["lastUpdateTime"], MultipleDateFormatterTransform(dateFormatterArray: [Constants.cc98APIDateFormatter, Constants.cc98APIDateFormatterWithMilliseconds, Constants.cc98APIDateFormatterWithMillisecondsAndTimeZone])) } } /** 表示一个用户的信息。 - seealso: [Page](http://api.cc98.org/Help/ResourceModel?modelName=UserInfo) */ public struct UserInfo: Mappable { /// 获取或设置用户的标识。 public var id: Int? /// 获取或设置用户的名称。 public var name: String? /// 获取或设置用户头衔。 public var title: String? /// 获取或设置用户的文章数。 public var postCount: Int? /// 获取或设置用户的威望。 public var prestige: Int? /// 获取或设置用户门派。 public var faction: String? /// 用户组名称。 public var groupName: String? /// 获取或设置用户注册的时间。 public var registerTime: Date? /// 获取或设置用户最后登录的时间。 public var lastLogOnTime: Date? /// 获取或设置一个值,指示当前用户是否在线。 public var isOnline: Bool? /// 获取或设置头像的图片 URL 地址。 public var portraitUrl: String? /// 获取或设置头像图片的高度。 public var portraitHeight: Int? /// 获取或设置头像图片的宽度。 public var portraitWidth: Int? /// 获取或设置个人照片的 URL 地址。 public var photoUrl: String? /// 获取或设置用户签名档的代码。 public var signatureCode: String? /// 获取或设置用户的性别。 /// 枚举值参考 `Constants.UserGender`。 public var gender: Int? /// 获取或设置用户的发言等级。 public var level: String? /// 获取或设置用户的个人邮件地址。 public var emailAddress: String? /// 获取或设置用户的个人主页地址。 public var homePageUrl: String? /// 获取或设置用户的生日。 public var birthday: Date? /// 获取或设置用户的 QQ 账号。 public var qq: String? /// 获取或设置用户的 MSN 账号。 public var msn: String? public init?(map: Map) { } mutating public func mapping(map: Map) { id <- map["id"] name <- map["name"] title <- map["title"] postCount <- map["postCount"] prestige <- map["prestige"] faction <- map["faction"] groupName <- map["groupName"] registerTime <- (map["registerTime"], MultipleDateFormatterTransform(dateFormatterArray: [Constants.cc98APIDateFormatter, Constants.cc98APIDateFormatterWithMilliseconds, Constants.cc98APIDateFormatterWithMillisecondsAndTimeZone])) lastLogOnTime <- (map["lastLogOnTime"], MultipleDateFormatterTransform(dateFormatterArray: [Constants.cc98APIDateFormatter, Constants.cc98APIDateFormatterWithMilliseconds, Constants.cc98APIDateFormatterWithMillisecondsAndTimeZone])) isOnline <- map["isOnline"] portraitUrl <- map["portraitUrl"] portraitHeight <- map["portraitHeight"] portraitWidth <- map["portraitWidth"] photoUrl <- map["photoUrl"] signatureCode <- map["signatureCode"] gender <- map["gender"] level <- map["level"] emailAddress <- map["emailAddress"] homePageUrl <- map["homePageUrl"] birthday <- (map["birthday"], MultipleDateFormatterTransform(dateFormatterArray: [Constants.cc98APIDateFormatter, Constants.cc98APIDateFormatterWithMilliseconds, Constants.cc98APIDateFormatterWithMillisecondsAndTimeZone])) qq <- map["qq"] msn <- map["msn"] } } /** 表示一个版面最后一次发言的信息。 - seealso: [Page](http://api.cc98.org/Help/ResourceModel?modelName=BoardLastPostInfo) */ public struct BoardLastPostInfo: Mappable { /// 获取或设置发言的版面标识。 public var boardId: Int? /// 最后发言的主题标识。 public var topicId: Int? /// 最后发言的标识。 public var postId: Int? /// 最后发言的时间。 public var dateTime: Date? /// 最后发言的用户名称。 public var userName: String? /// 最后发言的用户标识。 public var userId: Int? /// 最后发言的主题的标题。 public var topicTitle: String? public init?(map: Map) { } mutating public func mapping(map: Map) { boardId <- map["boardId"] topicId <- map["topicId"] postId <- map["postId"] dateTime <- (map["dateTime"], MultipleDateFormatterTransform(dateFormatterArray: [Constants.cc98APIDateFormatter, Constants.cc98APIDateFormatterWithMilliseconds, Constants.cc98APIDateFormatterWithMillisecondsAndTimeZone])) userName <- map["userName"] userId <- map["userId"] topicTitle <- map["topicTitle"] } } /** 用户的基础信息。 - seealso: [Page](http://api.cc98.org/Help/ResourceModel?modelName=UserBasicInfo) */ public struct UserBasicInfo: Mappable { /// 用户的 V1 版本标识(CC98 论坛所使用的 ID 值)。 public var v1Id: Int? /// 用户的 V2 版本标识(CC98 其他组件所使用的 ID 值)。 public var v2Id: Int? /// 用户所属的所有角色组的集合。 public var roles: [String]? /// 用户名。 public var name: String? /// 头像的图片 URL 地址。 public var portraitUrl: String? public init?(map: Map) { } mutating public func mapping(map: Map) { v1Id <- map["v1Id"] v2Id <- map["v2Id"] roles <- map["roles"] name <- map["name"] portraitUrl <- map["portraitUrl"] } } /** 表示 CC98 API 系统的相关设置。 - seealso: [Page](http://api.cc98.org/Help/ResourceModel?modelName=SystemSetting) */ public struct SystemSetting: Mappable { /// 使用 GET Board/All 时一次允许查询的最多版面数。 public var boardQueryMaxCount: Int? /// 使用 GET Topic/New 时一次允许查询的最多主题数。 public var topicQueryMaxCount: Int? /// 使用 GET Post/Topic 时一次允许查询的最多发言数。 public var postQueryMaxCount: Int? /// 使用 GET Topic/New 时如果不指定数量则使用的默认数量。 public var topicQueryDefaultCount: Int? /// 发言的标题允许的字符数上限。 public var postTitleMaxLength: Int? /// 发言的内容允许的字符数上限。 public var postContentMaxLength: Int? /// 使用 GET Message 时一次允许查询的最多短消息数。 public var messageQueryMaxCount: Int? /// 短消息的标题允许的字符数上限。 public var messageTitleMaxLength: Int? /// 短消息的内容允许的字符数上限。 public var messageContentMaxLength: Int? /// 当用户试图获取的资源已经被删除时,是否返回 HTTP 408 Gone 响应。 public var useHttp408ForDeletedItems: Bool? public init?(map: Map) { } mutating public func mapping(map: Map) { boardQueryMaxCount <- map["boardQueryMaxCount"] topicQueryMaxCount <- map["topicQueryMaxCount"] postQueryMaxCount <- map["postQueryMaxCount"] topicQueryDefaultCount <- map["topicQueryDefaultCount"] postTitleMaxLength <- map["postTitleMaxLength"] postContentMaxLength <- map["postContentMaxLength"] messageQueryMaxCount <- map["messageQueryMaxCount"] messageTitleMaxLength <- map["messageTitleMaxLength"] messageContentMaxLength <- map["messageContentMaxLength"] useHttp408ForDeletedItems <- map["useHttp408ForDeletedItems"] } } /** 表示一条站内短消息。 - seealso: [Page](http://api.cc98.org/Help/ResourceModel?modelName=MessageInfo) */ public struct MessageInfo: Mappable { /// 消息的标识。 public var id: Int? /// 消息的发送者的用户名。如果是系统消息,则该属性为 nil。 public var senderName: String? /// 消息的接收者的用户名。 public var receiverName: String? /// 消息的标题。 public var title: String? /// 消息的正文。 public var content: String? /// 消息是否处于草稿状态。true 表示消息为草稿,false 表示消息不是草稿。 public var isDraft: Bool? /// 消息是否已经被阅读。true 表示消息已经阅读,false 表示消息尚未阅读。 public var isRead: Bool? /// 消息的发送时间。 public var sendTime: Date? public init?(map: Map) { } mutating public func mapping(map: Map) { id <- map["id"] senderName <- map["senderName"] receiverName <- map["receiverName"] title <- map["title"] content <- map["content"] isDraft <- map["isDraft"] isRead <- map["isRead"] sendTime <- (map["sendTime"], MultipleDateFormatterTransform(dateFormatterArray: [Constants.cc98APIDateFormatter, Constants.cc98APIDateFormatterWithMilliseconds, Constants.cc98APIDateFormatterWithMillisecondsAndTimeZone])) } } /** 表示要创建的新消息的内容。 - seealso: [Page](http://api.cc98.org/Help/ResourceModel?modelName=NewMessageInfo) */ public struct NewMessageInfo: Mappable { /// 消息接收者的用户名。 public var receiverName: String? /// 消息的标题。 public var title: String? /// 消息的内容。 public var content: String? public init?(map: Map) { } public init() { } mutating public func mapping(map: Map) { receiverName <- map["receiverName"] title <- map["title"] content <- map["content"] } public var isValid: Bool { if let receiverName = receiverName, let title = title, let content = content { if receiverName.isEmpty || title.isEmpty || content.isEmpty { return false } else { return true } } else { return false } } } /** 表示 CC98 API 返回的结果。 */ public enum ResponseResult<T> { /// 成功的响应。 case success(status: Int, data: T?) /// 失败的响应。 case failure(status: Int, message: String?) /// 没有响应。 case noResponse }
mit
ddc89e6593bd5b9b1b8652bd6a449982
26.848303
242
0.632669
3.842468
false
false
false
false
keygx/AlertHelperKit
AlertHelperKitSample/AlertHelperKitSample/ViewController.swift
1
3646
// // ViewController.swift // AlertHelperKitSample // // Created by keygx on 2015/07/21. // Copyright (c) 2015年 keygx. All rights reserved. // import UIKit import AlertHelperKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } @IBAction func btnAlertAction(_ sender: AnyObject) { AlertHelperKit().showAlert(self, title: "Alert", message: "Message", button: "OK") } @IBAction func btnAlertWithHandlerAction(_ sender: AnyObject) { let params = Parameters( title: "Alert", message: "Message", cancelButton: "Cancel", otherButtons: ["OK"] ) AlertHelperKit().showAlertWithHandler(self, parameters: params) { buttonIndex in switch buttonIndex { case 0: print("Cancel: \(buttonIndex)") default: print("OK: \(buttonIndex)") } } } @IBAction func btnAlertWithTextFieldsAction(_ sender: AnyObject) { let params = Parameters( title: "Alert", message: "Message", cancelButton: "Cancel", otherButtons: ["OK"], inputFields: [InputField(placeholder: "username", secure: false), InputField(placeholder: "password", secure: true)] ) let alert = AlertHelperKit() alert.showAlertWithHandler(self, parameters: params) { buttonIndex in switch buttonIndex { case 0: print("Cancel: \(buttonIndex)") default: print("OK: \(buttonIndex)") guard let textFields = alert.textFields else { return } // username let name: UITextField = textFields[0] as! UITextField if name.text!.count > 0 { print(name.text!) } // password let pass: UITextField = textFields[1] as! UITextField if pass.text!.count > 0 { print(pass.text!) } } } } @IBAction func btnActionSheetAction(_ sender: AnyObject) { let params = Parameters( cancelButton: "Cancel", destructiveButtons: ["Action1"], otherButtons: ["Action2", "Action3", "Action4"], sender: sender, arrowDirection: .up ) AlertHelperKit().showActionSheet(self, parameters: params) { buttonIndex in switch buttonIndex { case 0: print("Cancel: \(buttonIndex)") default: print("Action: \(buttonIndex)") } } } @IBAction func btnBarMenuAction(_ sender: AnyObject) { let params = Parameters( cancelButton: "Cancel", otherButtons: ["Menu1", "Menu2", "Menu3", "Menu4", "Menu5"], disabledButtons: ["Menu1", "Menu4"], sender: sender, arrowDirection: .down, popoverStyle: .barButton ) AlertHelperKit().showActionSheet(self, parameters: params) { buttonIndex in switch buttonIndex { case 0: print("Cancel: \(buttonIndex)") default: print("Menu: \(buttonIndex)") } } } }
mit
fde038d731b8b512e4a1bc0c59314a03
28.626016
90
0.502744
5.422619
false
false
false
false
mssun/passforios
passShortcuts/SyncRepositoryIntentHandler.swift
2
2053
// // SyncRepositoryIntentHandler.swift // passShortcuts // // Created by Danny Moesch on 03.03.20. // Copyright © 2020 Bob Sun. All rights reserved. // import Intents import passKit public class SyncRepositoryIntentHandler: NSObject, SyncRepositoryIntentHandling { private let passwordStore = PasswordStore.shared private let keychain = AppKeychain.shared private var gitCredential: GitCredential { GitCredential.from( authenticationMethod: Defaults.gitAuthenticationMethod, userName: Defaults.gitUsername, keyStore: keychain ) } public func handle(intent _: SyncRepositoryIntent, completion: @escaping (SyncRepositoryIntentResponse) -> Void) { guard passwordStore.repositoryExists() else { completion(SyncRepositoryIntentResponse(code: .noRepository, userActivity: nil)) return } guard isPasswordRemembered else { completion(SyncRepositoryIntentResponse(code: .noPassphrase, userActivity: nil)) return } do { try passwordStore.pullRepository(options: gitCredential.getCredentialOptions()) } catch { completion(SyncRepositoryIntentResponse(code: .pullFailed, userActivity: nil)) return } if passwordStore.numberOfLocalCommits > 0 { do { try passwordStore.pushRepository(options: gitCredential.getCredentialOptions()) } catch { completion(SyncRepositoryIntentResponse(code: .pushFailed, userActivity: nil)) return } } completion(SyncRepositoryIntentResponse(code: .success, userActivity: nil)) } private var isPasswordRemembered: Bool { let authenticationMethod = Defaults.gitAuthenticationMethod return authenticationMethod == .password && keychain.contains(key: Globals.gitPassword) || authenticationMethod == .key && keychain.contains(key: Globals.gitSSHPrivateKeyPassphrase) } }
mit
1260c3c6c1b0d2cce1599f06392c4474
36.309091
118
0.670565
5.261538
false
false
false
false
Git-spy/git-spy-ios
gitspy/GitHubOAuthController.swift
1
4041
// // GitHubOAuthController.swift // gitspy // // Created by Joan Romano on 08/11/15. // Copyright © 2015 Joan Romano. All rights reserved. // import Foundation private enum OAuthError: ErrorType { case TokenRequest } class GitHubOAuthController: OAuth { private let clientId : String private let clientSecret : String private let redirectUri : String private let scope : String var authUrl : NSURL? { return NSURL(string: "https://github.com/login/oauth/authorize?redirect_uri=" + redirectUri + "&client_id=" + clientId + "&scope=" + scope) } init (clientId : String, clientSecret: String, redirectUri: String, scope: String) { self.clientId = clientId self.clientSecret = clientSecret self.redirectUri = redirectUri self.scope = scope } func exchangeCodeForAccessToken(withURL url: NSURL, failure: (error: NSError?) -> Void, success: (token: String) -> Void) { do { let JSONDataParams = try dataParams(forURL: url) let accessTokenRequest: NSURLRequest = request(forJSONData: JSONDataParams) let session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration(), delegate: nil, delegateQueue: NSOperationQueue.mainQueue()) let task = session.dataTaskWithRequest(accessTokenRequest, completionHandler: { (data, response: NSURLResponse?, error) -> Void in do { try self.handleData(data, response: response, error: error, success: success) } catch let error as NSError { failure(error: error) } catch OAuthError.TokenRequest { failure(error: nil) } }) task.resume() } catch { failure(error: nil) } } // MARK: Private private func dataParams(forURL url: NSURL) throws -> NSData { let match: String = "?code=" let range: Range = url.absoluteString.rangeOfString(match)! let code = url.absoluteString.substringFromIndex(range.startIndex.advancedBy(match.characters.count)) let paramDict = ["code" : code, "client_id" : clientId, "client_secret" : clientSecret, "grant_type" : "authorization_code"] return try NSJSONSerialization.dataWithJSONObject(paramDict as AnyObject, options: .PrettyPrinted) } private func request(forJSONData data: NSData) -> NSURLRequest { let url = NSURL(string: "https://github.com/login/oauth/access_token")! let request: NSMutableURLRequest = NSMutableURLRequest(URL: url) request.HTTPMethod = "POST" request.setValue("application/json", forHTTPHeaderField: "Accept") request.setValue("application/json", forHTTPHeaderField: "Content-Type") request.setValue(String(data.length), forHTTPHeaderField: "Content-Length") request.HTTPBody = data return request.copy() as! NSURLRequest } private func handleData(data: NSData?, response: NSURLResponse?, error: NSError?, success: (token: String) -> Void) throws { let indexSet = NSIndexSet(indexesInRange: NSRange(location: 200, length: 99)); let httpResponse = response as! NSHTTPURLResponse let statusCode = httpResponse.statusCode guard let data = data where indexSet.containsIndex(statusCode) else { throw OAuthError.TokenRequest } do { let dictionary = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary if let accessToken = dictionary["access_token"] as? String { success(token: accessToken) } else { throw OAuthError.TokenRequest } } catch { throw OAuthError.TokenRequest } } }
mit
d29f8828c64c9f0924c074f04758add2
39
170
0.622277
5.088161
false
false
false
false
xBrux/xPop
xPop/BruxLayerAndViewPopObject.swift
1
7035
// // BruxLayerAndViewPopObject.swift // imeican // // Created by BRUX on 11/23/15. // Copyright © 2015 Meican Co., Ltd. All rights reserved. // import UIKit public class BruxLayerAndViewPopObject: BruxPopObject { // private let target:NSObject override init(target:NSObject) { super.init(target: target) } //MARK: - Basic Animations public func frameTo(frame:CGRect, duration:NSTimeInterval? = nil) -> Self { let anim = animWithPropertyName(kPOPViewFrame, toValue: NSValue(CGRect: frame), duration: duration) addAnims([anim]) return self } public func alphaTo(alpha:CGFloat, duration:NSTimeInterval? = nil) -> Self { if target is UIView { let anim = animWithPropertyName(kPOPViewAlpha, toValue: alpha, duration: duration) addAnims([anim], autoDelay: anim.duration) } return self } public func scaleXYTo(scale:CGPoint, duration:NSTimeInterval? = nil) -> Self { let propertyName = target is UIView ? kPOPViewScaleXY : kPOPLayerScaleXY let anim = animWithPropertyName(propertyName, toValue: NSValue(CGPoint: scale), duration: duration) addAnims([anim], autoDelay: anim.duration) return self } public func originTo(point:CGPoint, duration:NSTimeInterval? = nil) -> Self { let anim = animWithPropertyName(kPOPViewFrame, toValue: NSValue(CGRect: CGRect(origin: point, size: frameOfTarget().size)), duration: duration) addAnims([anim], autoDelay: anim.duration) return self } public func sizeTo(size:CGSize, duration:NSTimeInterval? = nil) -> Self { let anim = animWithPropertyName(kPOPViewFrame, toValue: NSValue(CGRect: CGRect(origin: frameOfTarget().origin, size: size)), duration: duration) addAnims([anim], autoDelay: anim.duration) return self } public func moveUp(offset:CGFloat, duration:NSTimeInterval? = nil) -> Self { let anim = animWithPropertyName(kPOPViewFrame, toValue: NSValue(CGRect: CGRect(origin: CGPoint(x: frameOfTarget().origin.x, y: frameOfTarget().origin.y - offset), size: frameOfTarget().size)), duration: duration) addAnims([anim], autoDelay: anim.duration) return self } public func moveDown(offset:CGFloat, duration:NSTimeInterval? = nil) -> Self { let anim = animWithPropertyName(kPOPViewFrame, toValue: NSValue(CGRect: CGRect(origin: CGPoint(x: frameOfTarget().origin.x, y: frameOfTarget().origin.y + offset), size: frameOfTarget().size)), duration: duration) addAnims([anim], autoDelay: anim.duration) return self } public func moveLeft(offset:CGFloat, duration:NSTimeInterval? = nil) -> Self { let anim = animWithPropertyName(kPOPViewFrame, toValue: NSValue(CGRect: CGRect(origin: CGPoint(x: frameOfTarget().origin.x - offset, y: frameOfTarget().origin.y), size: frameOfTarget().size)), duration: duration) addAnims([anim], autoDelay: anim.duration) return self } public func moveRight(offset:CGFloat, duration:NSTimeInterval? = nil) -> Self { let anim = animWithPropertyName(kPOPViewFrame, toValue: NSValue(CGRect: CGRect(origin: CGPoint(x: frameOfTarget().origin.x + offset, y: frameOfTarget().origin.y), size: frameOfTarget().size)), duration: duration) addAnims([anim], autoDelay: anim.duration) return self } public func rotate(radian:CGFloat, duration:NSTimeInterval? = nil) -> Self { guard target is CALayer else {return self } let anim = animWithPropertyName(kPOPLayerRotation, toValue: radian, duration: duration) addAnims([anim], autoDelay: anim.duration) return self } //MARK: - Spring Animations public func springOriginTo(point:CGPoint, speed:CGFloat = 20, bounciness:CGFloat = 15) -> Self { let anim = springAnimWithPropertyName(kPOPViewFrame, toValue: NSValue(CGRect: CGRect(origin: point, size: frameOfTarget().size)), speed: speed, bounciness: bounciness) addAnims([anim]) return self } public func springSizeTo(size:CGSize, speed:CGFloat = 20, bounciness:CGFloat = 15) -> Self { let anim = springAnimWithPropertyName(kPOPViewFrame, toValue: NSValue(CGRect: CGRect(origin: frameOfTarget().origin, size: size)), speed: speed, bounciness: bounciness) addAnims([anim]) return self } public func springFrameTo(frame:CGRect, speed:CGFloat = 20, bounciness:CGFloat = 15) -> Self { let anim = springAnimWithPropertyName(kPOPViewFrame, toValue: NSValue(CGRect: frame), speed: speed, bounciness: bounciness) addAnims([anim]) return self } public func springScaleXYTo(scale:CGPoint, speed:CGFloat = 20, bounciness:CGFloat = 15) -> Self { let propertyName = target is UIView ? kPOPViewScaleXY : kPOPLayerScaleXY let anim = springAnimWithPropertyName(propertyName, toValue: NSValue(CGPoint: scale), speed: speed, bounciness: bounciness) addAnims([anim]) return self } public func springMoveUp(offset:CGFloat, speed:CGFloat = 20, bounciness:CGFloat = 15) -> Self { let anim = springAnimWithPropertyName(kPOPViewFrame, toValue: NSValue(CGRect: CGRect(origin: CGPoint(x: frameOfTarget().origin.x, y: frameOfTarget().origin.y - offset), size: frameOfTarget().size)), speed: speed, bounciness: bounciness) addAnims([anim]) return self } public func springMoveDown(offset:CGFloat, speed:CGFloat = 20, bounciness:CGFloat = 15) -> Self { let anim = springAnimWithPropertyName(kPOPViewFrame, toValue: NSValue(CGRect: CGRect(origin: CGPoint(x: frameOfTarget().origin.x, y: frameOfTarget().origin.y + offset), size: frameOfTarget().size)), speed: speed, bounciness: bounciness) addAnims([anim]) return self } public func springMoveLeft(offset:CGFloat, speed:CGFloat = 20, bounciness:CGFloat = 15) -> Self { let anim = springAnimWithPropertyName(kPOPViewFrame, toValue: NSValue(CGRect: CGRect(origin: CGPoint(x: frameOfTarget().origin.x - offset, y: frameOfTarget().origin.y), size: frameOfTarget().size)), speed: speed, bounciness: bounciness) addAnims([anim]) return self } public func springMoveRight(offset:CGFloat, speed:CGFloat = 20, bounciness:CGFloat = 15) -> Self { let anim = springAnimWithPropertyName(kPOPViewFrame, toValue: NSValue(CGRect: CGRect(origin: CGPoint(x: frameOfTarget().origin.x + offset, y: frameOfTarget().origin.y), size: frameOfTarget().size)), speed: speed, bounciness: bounciness) addAnims([anim]) return self } public func opacityTo(opacity:Float, duration:NSTimeInterval? = nil) -> Self { if target is CALayer { let anim = animWithPropertyName(kPOPLayerOpacity, toValue: opacity, duration: duration) addAnims([anim], autoDelay: anim.duration) } return self } }
mit
1b6781a5c2bc04e95bea77b49d6af4e7
48.535211
244
0.679556
4.130358
false
false
false
false
wuwen1030/ViewControllerTransitionDemo
ViewControllerTransition/NavigationTransition.swift
1
2731
// // NavigationTransition.swift // ViewControllerTransition // // Created by Ben on 15/7/21. // Copyright (c) 2015年 X-Team. All rights reserved. // import UIKit class NavigationTransition: NSObject, UINavigationControllerDelegate { let pushAnimator = PushAnimator() let popAnimator = PopAnimator() private var popInteractiveAnimator: UIPercentDrivenInteractiveTransition? weak var navigationController: UINavigationController? func navigationController(navigationController: UINavigationController, animationControllerForOperation operation: UINavigationControllerOperation, fromViewController fromVC: UIViewController, toViewController toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? { if operation == UINavigationControllerOperation.Push { return pushAnimator } else { return popAnimator } } func navigationController(navigationController: UINavigationController, interactionControllerForAnimationController animationController: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? { return animationController is PopAnimator ? popInteractiveAnimator : nil } func wireToNavigationController(navigationController:UINavigationController) { self.navigationController = navigationController let gestureRecognizer = navigationController.interactivePopGestureRecognizer gestureRecognizer.enabled = false let pan = UIPanGestureRecognizer(target: self, action: "handlePan:") navigationController.view.addGestureRecognizer(pan) } func handlePan(gestureRecognizer:UIPanGestureRecognizer) -> Void { let translation = gestureRecognizer.translationInView(gestureRecognizer.view!) let width = gestureRecognizer.view!.bounds.size.width let progress = translation.x / width switch gestureRecognizer.state { case UIGestureRecognizerState.Began: popInteractiveAnimator = UIPercentDrivenInteractiveTransition() navigationController?.popViewControllerAnimated(true) case UIGestureRecognizerState.Changed: popInteractiveAnimator?.updateInteractiveTransition(progress) case UIGestureRecognizerState.Cancelled, UIGestureRecognizerState.Ended: if progress > 0.5 { popInteractiveAnimator?.finishInteractiveTransition() } else { popInteractiveAnimator?.cancelInteractiveTransition() } popInteractiveAnimator = nil default: println("Stupid language") } } }
mit
a59e20cf29322f32a9ba08d3f1f7af6d
39.731343
281
0.717112
7.106771
false
false
false
false
apple/swift-nio-extras
Sources/NIOSOCKS/Messages/SOCKSRequest.swift
1
7600
//===----------------------------------------------------------------------===// // // This source file is part of the SwiftNIO open source project // // Copyright (c) 2021 Apple Inc. and the SwiftNIO project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of SwiftNIO project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// #if os(macOS) || os(tvOS) || os(iOS) || os(watchOS) import Darwin #else import Glibc #endif import NIOCore // MARK: - ClientRequest /// Instructs the SOCKS proxy server of the target host, /// and how to connect. public struct SOCKSRequest: Hashable, Sendable { /// The SOCKS protocol version - we currently only support v5. public let version: UInt8 = 5 /// How to connect to the host. public var command: SOCKSCommand /// The target host address. public var addressType: SOCKSAddress /// Creates a new ``SOCKSRequest``. /// - parameter command: How to connect to the host. /// - parameter addressType: The target host address. public init(command: SOCKSCommand, addressType: SOCKSAddress) { self.command = command self.addressType = addressType } } extension ByteBuffer { @discardableResult mutating func writeClientRequest(_ request: SOCKSRequest) -> Int { var written = self.writeInteger(request.version) written += self.writeInteger(request.command.value) written += self.writeInteger(UInt8(0)) written += self.writeAddressType(request.addressType) return written } @discardableResult mutating func readClientRequest() throws -> SOCKSRequest? { return try self.parseUnwindingIfNeeded { buffer -> SOCKSRequest? in guard try buffer.readAndValidateProtocolVersion() != nil, let command = buffer.readInteger(as: UInt8.self), try buffer.readAndValidateReserved() != nil, let address = try buffer.readAddressType() else { return nil } return .init(command: .init(value: command), addressType: address) } } } // MARK: - SOCKSCommand /// What type of connection the SOCKS server should establish with /// the target host. public struct SOCKSCommand: Hashable, Sendable { /// Typically the primary connection type, suitable for HTTP. public static let connect = SOCKSCommand(value: 0x01) /// Used in protocols that require the client to accept connections /// from the server, e.g. FTP. public static let bind = SOCKSCommand(value: 0x02) /// Used to establish an association within the UDP relay process to /// handle UDP datagrams. public static let udpAssociate = SOCKSCommand(value: 0x03) /// Command value as defined in RFC public var value: UInt8 public init(value: UInt8) { self.value = value } } // MARK: - SOCKSAddress /// The address used to connect to the target host. public enum SOCKSAddress: Hashable, Sendable { /// Socket Adress case address(SocketAddress) /// Host and port case domain(String, port: Int) static let ipv4IdentifierByte: UInt8 = 0x01 static let domainIdentifierByte: UInt8 = 0x03 static let ipv6IdentifierByte: UInt8 = 0x04 /// How many bytes are needed to represent the address, excluding the port var size: Int { switch self { case .address(.v4): return 4 case .address(.v6): return 16 case .address(.unixDomainSocket): fatalError("Unsupported") case .domain(let domain, port: _): // the +1 is for the leading "count" byte // containing how many UTF8 bytes are in the // domain return domain.utf8.count + 1 } } } extension ByteBuffer { mutating func readAddressType() throws -> SOCKSAddress? { return try self.parseUnwindingIfNeeded { buffer in guard let type = buffer.readInteger(as: UInt8.self) else { return nil } switch type { case SOCKSAddress.ipv4IdentifierByte: return try buffer.readIPv4Address() case SOCKSAddress.domainIdentifierByte: return buffer.readDomain() case SOCKSAddress.ipv6IdentifierByte: return try buffer.readIPv6Address() default: throw SOCKSError.InvalidAddressType(actual: type) } } } mutating func readIPv4Address() throws -> SOCKSAddress? { return try self.parseUnwindingIfNeeded { buffer in guard let bytes = buffer.readSlice(length: 4), let port = buffer.readPort() else { return nil } return .address(try .init(packedIPAddress: bytes, port: port)) } } mutating func readIPv6Address() throws -> SOCKSAddress? { return try self.parseUnwindingIfNeeded { buffer in guard let bytes = buffer.readSlice(length: 16), let port = buffer.readPort() else { return nil } return .address(try .init(packedIPAddress: bytes, port: port)) } } mutating func readDomain() -> SOCKSAddress? { return self.parseUnwindingIfNeeded { buffer in guard let length = buffer.readInteger(as: UInt8.self), let host = buffer.readString(length: Int(length)), let port = buffer.readPort() else { return nil } return .domain(host, port: port) } } mutating func readPort() -> Int? { guard let port = self.readInteger(as: UInt16.self) else { return nil } return Int(port) } @discardableResult mutating func writeAddressType(_ type: SOCKSAddress) -> Int { switch type { case .address(.v4(let address)): return self.writeInteger(SOCKSAddress.ipv4IdentifierByte) + self.writeIPv4Address(address.address) + self.writeInteger(UInt16(bigEndian: address.address.sin_port)) case .address(.v6(let address)): return self.writeInteger(SOCKSAddress.ipv6IdentifierByte) + self.writeIPv6Address(address.address) + self.writeInteger(UInt16(bigEndian: address.address.sin6_port)) case .address(.unixDomainSocket): // enforced in the channel initalisers. fatalError("UNIX domain sockets are not supported") case .domain(let domain, port: let port): return self.writeInteger(SOCKSAddress.domainIdentifierByte) + self.writeInteger(UInt8(domain.utf8.count)) + self.writeString(domain) + self.writeInteger(UInt16(port)) } } @discardableResult mutating func writeIPv6Address(_ addr: sockaddr_in6) -> Int { return withUnsafeBytes(of: addr.sin6_addr) { pointer in return self.writeBytes(pointer) } } @discardableResult mutating func writeIPv4Address(_ addr: sockaddr_in) -> Int { return withUnsafeBytes(of: addr.sin_addr) { pointer in return self.writeBytes(pointer) } } }
apache-2.0
2e1cc0e6107e09d93fe5638168abd196
32.480176
89
0.594211
4.645477
false
false
false
false
luckymarmot/ThemeKit
Sources/NSColor+ThemeKit.swift
1
4785
// // NSColor+ThemeKit.swift // ThemeKit // // Created by Nuno Grilo on 24/09/2016. // Copyright © 2016 Paw & Nuno Grilo. All rights reserved. // import Foundation /** `NSColor` ThemeKit extension to help on when overriding colors in `ThemeColor` extensions. */ extension NSColor { // MARK: - // MARK: Color override /// Swizzle NSColor in case we are replacing system colors by themable colors. @objc static func swizzleNSColor() { swizzleNSColorOnce } /// Swizzle NSColor in case we are replacing system colors by themable colors. /// This code is executed *only once* (even if invoked multiple times). private static let swizzleNSColorOnce: Void = { // swizzle only if needed guard needsSwizzling else { return } // swizzle NSColor methods swizzleInstanceMethod(cls: NSClassFromString("NSDynamicSystemColor"), selector: #selector(set), withSelector: #selector(themeKitSet)) swizzleInstanceMethod(cls: NSClassFromString("NSDynamicSystemColor"), selector: #selector(setFill), withSelector: #selector(themeKitSetFill)) swizzleInstanceMethod(cls: NSClassFromString("NSDynamicSystemColor"), selector: #selector(setStroke), withSelector: #selector(themeKitSetStroke)) }() /// Check if color is being overriden in a ThemeColor extension. @objc public var isThemeOverriden: Bool { // check if `NSColor` provides this color let selector = Selector(colorNameComponent) let nsColorMethod = class_getClassMethod(NSColor.classForCoder(), selector) guard nsColorMethod != nil else { return false } // get current theme let theme = ThemeManager.shared.effectiveTheme // `UserTheme`: check `hasThemeAsset(_:)` method if let userTheme = theme as? UserTheme { return userTheme.hasThemeAsset(colorNameComponent) } // native themes: look up for an instance method else { let themeClass: AnyClass = object_getClass(theme)! let themeColorMethod = class_getInstanceMethod(themeClass, selector) return themeColorMethod != nil && nsColorMethod != themeColorMethod } } /// Get all `NSColor` color methods. /// Overridable class methods (can be overriden in `ThemeColor` extension). @objc public class func colorMethodNames() -> [String] { let nsColorMethods = NSObject.classMethodNames(for: NSColor.classForCoder()).filter { (methodName) -> Bool in return methodName.hasSuffix("Color") } return nsColorMethods } // MARK: - Private /// Check if we need to swizzle NSDynamicSystemColor class. private class var needsSwizzling: Bool { let themeColorMethods = classMethodNames(for: ThemeColor.classForCoder()).filter { (methodName) -> Bool in return methodName.hasSuffix("Color") } let nsColorMethods = classMethodNames(for: NSColor.classForCoder()).filter { (methodName) -> Bool in return methodName.hasSuffix("Color") } // checks if NSColor `*Color` class methods are being overriden for colorMethod in themeColorMethods { if nsColorMethods.contains(colorMethod) { // theme color with `colorMethod` selector is overriding a `NSColor` method -> swizzling needed. return true } } return false } // ThemeKit.set() replacement to use theme-aware color @objc public func themeKitSet() { // call original .set() function themeKitSet() // check if the user provides an alternative color if ThemeManager.shared.isEnabled && isThemeOverriden { // call ThemeColor.set() function ThemeColor.color(with: Selector(colorNameComponent)).set() } } // ThemeKit.setFill() replacement to use theme-aware color @objc public func themeKitSetFill() { // call original .setFill() function themeKitSetFill() // check if the user provides an alternative color if ThemeManager.shared.isEnabled && isThemeOverriden { // call ThemeColor.setFill() function ThemeColor.color(with: Selector(colorNameComponent)).setFill() } } // ThemeKit.setStroke() replacement to use theme-aware color @objc public func themeKitSetStroke() { // call original .setStroke() function themeKitSetStroke() // check if the user provides an alternative color if ThemeManager.shared.isEnabled && isThemeOverriden { // call ThemeColor.setStroke() function ThemeColor.color(with: Selector(colorNameComponent)).setStroke() } } }
mit
9868ae6270122c6c555b5e54d5d13af5
36.085271
153
0.655727
4.952381
false
false
false
false
CatchChat/Yep
Yep/Views/Buttons/SkillCategoryButton.swift
1
3954
// // SkillCategoryButton.swift // Yep // // Created by NIX on 15/4/15. // Copyright (c) 2015年 Catch Inc. All rights reserved. // import UIKit @IBDesignable final class SkillCategoryButton: UIButton { @IBInspectable var categoryImage: UIImage = UIImage() { willSet { categoryImageView.image = newValue } } @IBInspectable var categoryTitle: String = "" { willSet { categoryTitleLabel.text = newValue } } var inSelectionState: Bool = false { willSet { if inSelectionState != newValue { if newValue { let toAngle = CGFloat(M_PI * 0.5) rotateArrowFromAngle(0, toAngle: toAngle) } else { let fromAngle = CGFloat(M_PI * 0.5) rotateArrowFromAngle(fromAngle, toAngle: 0) } } } } var toggleSelectionStateAction: ((inSelectionState: Bool) -> Void)? lazy var categoryImageView: UIImageView = { let imageView = UIImageView() imageView.contentMode = .Center imageView.tintColor = UIColor.whiteColor() return imageView }() lazy var categoryTitleLabel: UILabel = { let label = UILabel() label.textColor = UIColor.whiteColor() label.font = UIFont.systemFontOfSize(24, weight: UIFontWeightThin) return label }() lazy var arrowImageView: UIImageView = { let imageView = UIImageView() imageView.contentMode = .Center imageView.image = UIImage.yep_iconSkillCategoryArrow imageView.tintColor = UIColor.whiteColor() imageView.tintAdjustmentMode = .Normal return imageView }() override func didMoveToSuperview() { super.didMoveToSuperview() makeUI() self.addTarget(self, action: #selector(SkillCategoryButton.toggleSelectionState), forControlEvents: .TouchUpInside) } func makeUI() { addSubview(categoryImageView) addSubview(categoryTitleLabel) addSubview(arrowImageView) categoryImageView.translatesAutoresizingMaskIntoConstraints = false categoryTitleLabel.translatesAutoresizingMaskIntoConstraints = false arrowImageView.translatesAutoresizingMaskIntoConstraints = false let viewsDictionary: [String: AnyObject] = [ "categoryImageView": categoryImageView, "categoryTitleLabel": categoryTitleLabel, "arrowImageView": arrowImageView, ] let constraintsV = NSLayoutConstraint.constraintsWithVisualFormat("V:|[categoryImageView]|", options: [], metrics: nil, views: viewsDictionary) let constraintsH = NSLayoutConstraint.constraintsWithVisualFormat("H:|-20-[categoryImageView(40)]-20-[categoryTitleLabel][arrowImageView(20)]-20-|", options: [.AlignAllCenterY, .AlignAllTop, .AlignAllBottom], metrics: nil, views: viewsDictionary) NSLayoutConstraint.activateConstraints(constraintsV) NSLayoutConstraint.activateConstraints(constraintsH) } func toggleSelectionState() { inSelectionState = !inSelectionState if let action = toggleSelectionStateAction { action(inSelectionState: inSelectionState) } } func rotateArrowFromAngle(fromAngle: CGFloat, toAngle: CGFloat) { let rotationAnimation = CABasicAnimation(keyPath: "transform.rotation.z") rotationAnimation.repeatCount = 0 rotationAnimation.fromValue = fromAngle rotationAnimation.toValue = toAngle rotationAnimation.duration = 0.25 rotationAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) rotationAnimation.removedOnCompletion = false rotationAnimation.fillMode = kCAFillModeBoth arrowImageView.layer.addAnimation(rotationAnimation, forKey: "rotationAnimation") } }
mit
c92599335204de68689b21bbfcc94643
31.661157
254
0.662702
5.719247
false
false
false
false
sovata8/RevealingTableViewCell
RevealingTableViewCell/DistanceHelper.swift
1
1465
// // DistanceHelper.swift // RevealingTableViewCell // // Created by sovata on 05/04/2017. // Copyright © 2017 Nikolay Suvandzhiev. All rights reserved. // import QuartzCore internal enum DistanceHelper { // This is 1D internal static func getClosestX_consideringVelocity(originX: CGFloat, velocityDx: CGFloat, arrayOfX_toCheck: [CGFloat] ) -> CGFloat { guard arrayOfX_toCheck.count > 0 else { fatalError("WARNING: Not allowed to pass an empty array for `arrayOfX_toCheck`") } // The higher this is, the harder the user has to 'throw' the view to a particular position for it to 'snap' to it let factorToDivideVelocityBy: CGFloat = 20.0 let pointOfOriginPlusScaledVelocity:CGFloat = originX + velocityDx/factorToDivideVelocityBy var smallestDistanceSoFar: CGFloat = CGFloat.infinity var answer_X_soFar: CGFloat = arrayOfX_toCheck[0] for X_toCheck in arrayOfX_toCheck { let distanceX = abs(pointOfOriginPlusScaledVelocity - X_toCheck) if distanceX < smallestDistanceSoFar { smallestDistanceSoFar = distanceX answer_X_soFar = X_toCheck } } return answer_X_soFar } }
mit
737647656762deba63916f7e34a8d19e
30.826087
122
0.569672
4.692308
false
false
false
false
BellAppLab/Permissionable
Source/Camera/Permissionable+Camera.swift
1
1268
import AVFoundation import Alertable extension Permissions.Camera { public static var isThere: Bool { if let result = Permissions.Camera().hasAccess() { return result.boolValue } return false } public static var hasAsked: Bool { return Permissions.Camera().hasAccess() != nil } @objc func hasAccess() -> NSNumber? { let status = AVCaptureDevice.authorizationStatusForMediaType(AVMediaTypeVideo) switch status { case .Authorized: return NSNumber(bool: true) case .Denied, .Restricted: return NSNumber(bool: false) case .NotDetermined: return nil } } @objc func makeAction(sender: UIViewController, _ block: Permissions.Result?) -> AnyObject { return Alert.Action(title: NSLocalizedString("Yes", comment: ""), style: .Default, handler: { (UIAlertAction) -> Void in Alert.on = true AVCaptureDevice.requestAccessForMediaType(AVMediaTypeVideo, completionHandler: { (success: Bool) -> Void in Alert.on = false dispatch_async(dispatch_get_main_queue()) { () -> Void in block?(success: success) } }) }) } }
mit
78bd89b83d9c86bd24df0fb3a00b0345
31.512821
128
0.597792
5.031746
false
false
false
false
fgulan/letter-ml
project/LetterML/Frameworks/framework/Source/Operations/ChromaKeyBlend.swift
9
619
public class ChromaKeyBlend: BasicOperation { public var thresholdSensitivity:Float = 0.4 { didSet { uniformSettings["thresholdSensitivity"] = thresholdSensitivity } } public var smoothing:Float = 0.1 { didSet { uniformSettings["smoothing"] = smoothing } } public var colorToReplace:Color = Color.green { didSet { uniformSettings["colorToReplace"] = colorToReplace } } public init() { super.init(fragmentShader:ChromaKeyBlendFragmentShader, numberOfInputs:2) ({thresholdSensitivity = 0.4})() ({smoothing = 0.1})() ({colorToReplace = Color.green})() } }
mit
f982ce8c3791774c37186a365c121d3f
46.615385
125
0.678514
4.551471
false
false
false
false
banxi1988/BXAppKit
BXForm/Controller/AlertPresentationController.swift
1
3000
// // AlertPresentationController.swift // Pods // // Created by Haizhen Lee on 16/1/27. // // import Foundation import UIKit open class AlertPresentationController:UIPresentationController{ lazy var dimmingView : UIView = { let view = UIView() view.backgroundColor = UIColor(white: 0.0, alpha: 0.4) view.alpha = 0.0 return view }() public var dimissOnTapDimmingView = true open override var frameOfPresentedViewInContainerView : CGRect { let bounds = containerView!.bounds let preferedSize = presentedViewController.preferredContentSize let width = min(bounds.width - 30, preferedSize.width) let height = min(bounds.height - 30, preferedSize.height) return CGRect(center: bounds.center, size:CGSize(width: width, height: height)) } public override init(presentedViewController: UIViewController, presenting presentingViewController: UIViewController?) { super.init(presentedViewController: presentedViewController, presenting: presentingViewController) let tap = UITapGestureRecognizer(target: self, action: #selector(dimmingViewTapped)) dimmingView.addGestureRecognizer(tap) } @objc func dimmingViewTapped(gesture:UITapGestureRecognizer) { if gesture.state == .ended && dimissOnTapDimmingView{ presentingViewController.dismiss(animated: true, completion: nil) } } open override func presentationTransitionWillBegin() { let containerView = self.containerView! let presentedVC = self.presentedViewController // let presentingVC = self.presentingViewController // Set the dimming view to the size of the container's bounds, and make it transparent initialy dimmingView.frame = containerView.bounds dimmingView.alpha = 0.0 // Insert the dimming view below everything containerView.insertSubview(dimmingView, at: 0) // Set up the animations for fading in the dimming view. if let coordinator = presentedVC.transitionCoordinator{ coordinator.animate(alongsideTransition: { (ctx) -> Void in // Fade ind self.dimmingView.alpha = 1.0 }, completion: { (ctx) -> Void in }) }else{ self.dimmingView.alpha = 0.0 } } open override func presentationTransitionDidEnd(_ completed: Bool) { // If the presentation was canceld, remove the dimming view. if !completed{ self.dimmingView.removeFromSuperview() } } open override func dismissalTransitionWillBegin() { // Fade the dimming view back out if let coordinator = presentedViewController.transitionCoordinator{ coordinator.animate(alongsideTransition: { (ctx) -> Void in self.dimmingView.alpha = 0.0 }, completion: nil) }else{ self.dimmingView.alpha = 1.0 } } open override func dismissalTransitionDidEnd(_ completed: Bool) { // If the dismissal was successful, remove the dimming view if completed{ self.dimmingView.removeFromSuperview() } } }
mit
e885cf3aba5016ae61d900c6fdb50b6b
31.608696
123
0.71
4.926108
false
false
false
false
Mazy-ma/DemoBySwift
TransparentBackgroundViews/TransparentBackgroundViews/FirstViewController.swift
1
1754
// // FirstViewController.swift // TransparentBackgroundViews // // Created by Mazy on 2017/12/28. // Copyright © 2017年 Mazy. All rights reserved. // import UIKit class FirstViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .clear let titleLabel = UILabel() titleLabel.translatesAutoresizingMaskIntoConstraints = false titleLabel.text = "FirstViewController" titleLabel.textColor = .white titleLabel.font = UIFont.systemFont(ofSize: 24) view.addSubview(titleLabel) let showSecondVCButton = UIButton(type: .system) showSecondVCButton.translatesAutoresizingMaskIntoConstraints = false showSecondVCButton.backgroundColor = .lightGray showSecondVCButton.setTitle("Show SecondViewController", for: .normal) showSecondVCButton.setTitleColor(.white, for: .normal) showSecondVCButton.addTarget(self, action: #selector(didTapShowSecondButton), for: .touchUpInside) view.addSubview(showSecondVCButton) titleLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true titleLabel.topAnchor.constraint(equalTo: view.topAnchor, constant: 20.0).isActive = true showSecondVCButton.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true showSecondVCButton.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true } @objc func didTapShowSecondButton() { self.navigationController?.pushViewController(SecondViewController(), animated: true) } override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } }
apache-2.0
fd8a719048009b4f04b6c5e42f972189
35.479167
106
0.712736
5.306061
false
false
false
false
DanielAsher/VIPER-SWIFT
Carthage/Checkouts/RxSwift/Rx.playground/Pages/Error_Handling_Operators.xcplaygroundpage/Contents.swift
2
2666
/*: > # IMPORTANT: To use `Rx.playground`, please: 1. Open `Rx.xcworkspace` 2. Build `RxSwift-OSX` scheme 3. And then open `Rx` playground in `Rx.xcworkspace` tree view. 4. Choose `View > Show Debug Area` */ //: [<< Previous](@previous) - [Index](Index) import RxSwift import Foundation /*: ## Error Handling Operators Operators that help to recover from error notifications from an Observable. */ /*: ### `catchError` Recover from an `Error` notification by continuing the sequence without error ![](https://raw.githubusercontent.com/kzaher/rxswiftcontent/master/MarbleDiagrams/png/catch.png) [More info in reactive.io website]( http://reactivex.io/documentation/operators/catch.html ) */ example("catchError 1") { let sequenceThatFails = PublishSubject<Int>() let recoverySequence = Observable.of(100, 200, 300, 400) _ = sequenceThatFails .catchError { error in return recoverySequence } .subscribe { print($0) } sequenceThatFails.on(.Next(1)) sequenceThatFails.on(.Next(2)) sequenceThatFails.on(.Next(3)) sequenceThatFails.on(.Next(4)) sequenceThatFails.on(.Error(NSError(domain: "Test", code: 0, userInfo: nil))) } example("catchError 2") { let sequenceThatFails = PublishSubject<Int>() _ = sequenceThatFails .catchErrorJustReturn(100) .subscribe { print($0) } sequenceThatFails.on(.Next(1)) sequenceThatFails.on(.Next(2)) sequenceThatFails.on(.Next(3)) sequenceThatFails.on(.Next(4)) sequenceThatFails.on(.Error(NSError(domain: "Test", code: 0, userInfo: nil))) } /*: ### `retry` If a source Observable emits an error, resubscribe to it in the hopes that it will complete without error ![](https://raw.githubusercontent.com/kzaher/rxswiftcontent/master/MarbleDiagrams/png/retry.png) [More info in reactive.io website]( http://reactivex.io/documentation/operators/retry.html ) */ example("retry") { var count = 1 // bad practice, only for example purposes let funnyLookingSequence = Observable<Int>.create { observer in let error = NSError(domain: "Test", code: 0, userInfo: nil) observer.on(.Next(0)) observer.on(.Next(1)) observer.on(.Next(2)) if count < 2 { observer.on(.Error(error)) count += 1 } observer.on(.Next(3)) observer.on(.Next(4)) observer.on(.Next(5)) observer.on(.Completed) return NopDisposable.instance } _ = funnyLookingSequence .retry() .subscribe { print($0) } } //: [Index](Index) - [Next >>](@next)
mit
4faf3f90714deda46ff58f964b3f1f90
24.883495
105
0.642911
4.003003
false
false
false
false
gregomni/swift
test/attr/attr_inlinable_available_maccatalyst.swift
1
21692
// This is the same test as attr_inlinable_available, but specifically using a // macCatalyst target which has its own version floor separate from iOS. The two // tests could be merged in the future if there were a CI bot running tests with // OS=maccatalyst and there were a lit.py substitution for the -target argument // that substituted to a macCatalyst SDK version compatible with the // configuration of this test. // REQUIRES: maccatalyst_support // Primary execution of this test. Uses the default minimum inlining version, // which is the version when Swift was introduced. // RUN: %target-typecheck-verify-swift -swift-version 5 -enable-library-evolution -target %target-cpu-apple-ios14.4-macabi -target-min-inlining-version min // FIXME: Re-enable with rdar://91387029 // Check that `-library-level api` implies `-target-min-inlining-version min` // RUN/: %target-typecheck-verify-swift -swift-version 5 -enable-library-evolution -target %target-cpu-apple-ios14.4-macabi -library-level api // Check that these rules are only applied when requested and that at least some // diagnostics are not present without it. // RUN: not %target-typecheck-verify-swift -swift-version 5 -target %target-cpu-apple-ios14.4-macabi 2>&1 | %FileCheck --check-prefix NON_MIN %s // Check that -target-min-inlining-version overrides -library-level, allowing // library owners to disable this behavior for API libraries if needed. // RUN: not %target-typecheck-verify-swift -swift-version 5 -target %target-cpu-apple-ios14.4-macabi -target-min-inlining-version target -library-level api 2>&1 | %FileCheck --check-prefix NON_MIN %s // Check that we respect -target-min-inlining-version by cranking it up high // enough to suppress any possible errors. // RUN: %target-swift-frontend -typecheck -disable-objc-attr-requires-foundation-module %s -swift-version 5 -enable-library-evolution -target %target-cpu-apple-ios14.4-macabi -target-min-inlining-version 42.0 // NON_MIN: error: expected error not produced // NON_MIN: {'BetweenTargets' is only available in} /// Declaration with no availability annotation. Should be inferred as minimum /// inlining target. public struct NoAvailable { @usableFromInline internal init() {} } @available(macCatalyst 12, *) public struct BeforeInliningTarget { @usableFromInline internal init() {} } @available(macCatalyst 13.1, *) public struct AtInliningTarget { @usableFromInline internal init() {} } @available(macCatalyst 14, *) public struct BetweenTargets { @usableFromInline internal init() {} } @available(macCatalyst 14.4, *) public struct AtDeploymentTarget { @usableFromInline internal init() {} } @available(macCatalyst 15, *) public struct AfterDeploymentTarget { @usableFromInline internal init() {} } // // Uses in resilient functions are based on the minimum deployment target // (i.e. the -target). // public func deployedUseNoAvailable( // expected-note 5 {{add @available attribute}} _: NoAvailable, _: BeforeInliningTarget, _: AtInliningTarget, _: BetweenTargets, // expected-error {{'BetweenTargets' is only available in}} _: AtDeploymentTarget, // expected-error {{'AtDeploymentTarget' is only available in}} _: AfterDeploymentTarget // expected-error {{'AfterDeploymentTarget' is only available in}} ) { defer { _ = AtDeploymentTarget() _ = AfterDeploymentTarget() // expected-error {{'AfterDeploymentTarget' is only available in}} expected-note {{add 'if #available'}} } _ = NoAvailable() _ = BeforeInliningTarget() _ = AtInliningTarget() _ = BetweenTargets() _ = AtDeploymentTarget() _ = AfterDeploymentTarget() // expected-error {{'AfterDeploymentTarget' is only available in}} expected-note {{add 'if #available'}} if #available(macCatalyst 15, *) { _ = AfterDeploymentTarget() } } @available(macCatalyst 12, *) public func deployedUseBeforeInliningTarget( _: NoAvailable, _: BeforeInliningTarget, _: AtInliningTarget, _: BetweenTargets, // expected-error {{'BetweenTargets' is only available in}} _: AtDeploymentTarget, // expected-error {{'AtDeploymentTarget' is only available in}} _: AfterDeploymentTarget // expected-error {{'AfterDeploymentTarget' is only available in}} ) { defer { _ = AtDeploymentTarget() _ = AfterDeploymentTarget() // expected-error {{'AfterDeploymentTarget' is only available in}} expected-note {{add 'if #available'}} } _ = NoAvailable() _ = BeforeInliningTarget() _ = AtInliningTarget() _ = BetweenTargets() _ = AtDeploymentTarget() _ = AfterDeploymentTarget() // expected-error {{'AfterDeploymentTarget' is only available in}} expected-note {{add 'if #available'}} if #available(macCatalyst 15, *) { _ = AfterDeploymentTarget() } } @available(macCatalyst 13.1, *) public func deployedUseAtInliningTarget( _: NoAvailable, _: BeforeInliningTarget, _: AtInliningTarget, _: BetweenTargets, // expected-error {{'BetweenTargets' is only available in}} _: AtDeploymentTarget, // expected-error {{'AtDeploymentTarget' is only available in}} _: AfterDeploymentTarget // expected-error {{'AfterDeploymentTarget' is only available in}} ) { defer { _ = AtDeploymentTarget() _ = AfterDeploymentTarget() // expected-error {{'AfterDeploymentTarget' is only available in}} expected-note {{add 'if #available'}} } _ = NoAvailable() _ = BeforeInliningTarget() _ = AtInliningTarget() _ = BetweenTargets() _ = AtDeploymentTarget() _ = AfterDeploymentTarget() // expected-error {{'AfterDeploymentTarget' is only available in}} expected-note {{add 'if #available'}} if #available(macCatalyst 15, *) { _ = AfterDeploymentTarget() } } @available(macCatalyst 14, *) public func deployedUseBetweenTargets( _: NoAvailable, _: BeforeInliningTarget, _: AtInliningTarget, _: BetweenTargets, _: AtDeploymentTarget, // expected-error {{'AtDeploymentTarget' is only available in}} _: AfterDeploymentTarget // expected-error {{'AfterDeploymentTarget' is only available in}} ) { defer { _ = AtDeploymentTarget() _ = AfterDeploymentTarget() // expected-error {{'AfterDeploymentTarget' is only available in}} expected-note {{add 'if #available'}} } _ = NoAvailable() _ = BeforeInliningTarget() _ = AtInliningTarget() _ = BetweenTargets() _ = AtDeploymentTarget() _ = AfterDeploymentTarget() // expected-error {{'AfterDeploymentTarget' is only available in}} expected-note {{add 'if #available'}} if #available(macCatalyst 15, *) { _ = AfterDeploymentTarget() } } @available(macCatalyst 14.4, *) public func deployedUseAtDeploymentTarget( _: NoAvailable, _: BeforeInliningTarget, _: AtInliningTarget, _: BetweenTargets, _: AtDeploymentTarget, _: AfterDeploymentTarget // expected-error {{'AfterDeploymentTarget' is only available in}} ) { defer { _ = AtDeploymentTarget() _ = AfterDeploymentTarget() // expected-error {{'AfterDeploymentTarget' is only available in}} expected-note {{add 'if #available'}} } _ = NoAvailable() _ = BeforeInliningTarget() _ = AtInliningTarget() _ = BetweenTargets() _ = AtDeploymentTarget() _ = AfterDeploymentTarget() // expected-error {{'AfterDeploymentTarget' is only available in}} expected-note {{add 'if #available'}} if #available(macCatalyst 15, *) { _ = AfterDeploymentTarget() } } @available(macCatalyst 15, *) public func deployedUseAfterDeploymentTarget( _: NoAvailable, _: BeforeInliningTarget, _: AtInliningTarget, _: BetweenTargets, _: AtDeploymentTarget, _: AfterDeploymentTarget ) { defer { _ = AtDeploymentTarget() _ = AfterDeploymentTarget() } _ = NoAvailable() _ = BeforeInliningTarget() _ = AtInliningTarget() _ = BetweenTargets() _ = AtDeploymentTarget() _ = AfterDeploymentTarget() } // // Uses in inlinable functions are based on the minimum inlining target // @inlinable public func inlinedUseNoAvailable( // expected-note 8 {{add @available attribute}} _: NoAvailable, _: BeforeInliningTarget, _: AtInliningTarget, _: BetweenTargets, // expected-error {{'BetweenTargets' is only available in}} _: AtDeploymentTarget, // expected-error {{'AtDeploymentTarget' is only available in}} _: AfterDeploymentTarget // expected-error {{'AfterDeploymentTarget' is only available in}} ) { defer { _ = AtDeploymentTarget() // expected-error {{'AtDeploymentTarget' is only available in}} expected-note {{add 'if #available'}} _ = AfterDeploymentTarget() // expected-error {{'AfterDeploymentTarget' is only available in}} expected-note {{add 'if #available'}} } _ = NoAvailable() _ = BeforeInliningTarget() _ = AtInliningTarget() _ = BetweenTargets() // expected-error {{'BetweenTargets' is only available in}} expected-note {{add 'if #available'}} _ = AtDeploymentTarget() // expected-error {{'AtDeploymentTarget' is only available in}} expected-note {{add 'if #available'}} _ = AfterDeploymentTarget() // expected-error {{'AfterDeploymentTarget' is only available in}} expected-note {{add 'if #available'}} if #available(macCatalyst 14, *) { _ = BetweenTargets() } if #available(macCatalyst 14.4, *) { _ = AtDeploymentTarget() } if #available(macCatalyst 15, *) { _ = AfterDeploymentTarget() } } @available(macCatalyst 12, *) @inlinable public func inlinedUseBeforeInliningTarget( _: NoAvailable, _: BeforeInliningTarget, _: AtInliningTarget, _: BetweenTargets, // expected-error {{'BetweenTargets' is only available in}} _: AtDeploymentTarget, // expected-error {{'AtDeploymentTarget' is only available in}} _: AfterDeploymentTarget // expected-error {{'AfterDeploymentTarget' is only available in}} ) { defer { _ = AtDeploymentTarget() // expected-error {{'AtDeploymentTarget' is only available in}} expected-note {{add 'if #available'}} _ = AfterDeploymentTarget() // expected-error {{'AfterDeploymentTarget' is only available in}} expected-note {{add 'if #available'}} } _ = NoAvailable() _ = BeforeInliningTarget() _ = AtInliningTarget() _ = BetweenTargets() // expected-error {{'BetweenTargets' is only available in}} expected-note {{add 'if #available'}} _ = AtDeploymentTarget() // expected-error {{'AtDeploymentTarget' is only available in}} expected-note {{add 'if #available'}} _ = AfterDeploymentTarget() // expected-error {{'AfterDeploymentTarget' is only available in}} expected-note {{add 'if #available'}} if #available(macCatalyst 14, *) { _ = BetweenTargets() } if #available(macCatalyst 14.4, *) { _ = AtDeploymentTarget() } if #available(macCatalyst 15, *) { _ = AfterDeploymentTarget() } } @available(macCatalyst 13.1, *) @inlinable public func inlinedUseAtInliningTarget( _: NoAvailable, _: BeforeInliningTarget, _: AtInliningTarget, _: BetweenTargets, // expected-error {{'BetweenTargets' is only available in}} _: AtDeploymentTarget, // expected-error {{'AtDeploymentTarget' is only available in}} _: AfterDeploymentTarget // expected-error {{'AfterDeploymentTarget' is only available in}} ) { defer { _ = AtDeploymentTarget() // expected-error {{'AtDeploymentTarget' is only available in}} expected-note {{add 'if #available'}} _ = AfterDeploymentTarget() // expected-error {{'AfterDeploymentTarget' is only available in}} expected-note {{add 'if #available'}} } _ = NoAvailable() _ = BeforeInliningTarget() _ = AtInliningTarget() _ = BetweenTargets() // expected-error {{'BetweenTargets' is only available in}} expected-note {{add 'if #available'}} _ = AtDeploymentTarget() // expected-error {{'AtDeploymentTarget' is only available in}} expected-note {{add 'if #available'}} _ = AfterDeploymentTarget() // expected-error {{'AfterDeploymentTarget' is only available in}} expected-note {{add 'if #available'}} if #available(macCatalyst 14, *) { _ = BetweenTargets() } if #available(macCatalyst 14.4, *) { _ = AtDeploymentTarget() } if #available(macCatalyst 15, *) { _ = AfterDeploymentTarget() } } @available(macCatalyst 14, *) @inlinable public func inlinedUseBetweenTargets( _: NoAvailable, _: BeforeInliningTarget, _: AtInliningTarget, _: BetweenTargets, _: AtDeploymentTarget, // expected-error {{'AtDeploymentTarget' is only available in}} _: AfterDeploymentTarget // expected-error {{'AfterDeploymentTarget' is only available in}} ) { defer { _ = AtDeploymentTarget() // expected-error {{'AtDeploymentTarget' is only available in}} _ = AfterDeploymentTarget() // expected-error {{'AfterDeploymentTarget' is only available in}} expected-note {{add 'if #available'}} } _ = NoAvailable() _ = BeforeInliningTarget() _ = AtInliningTarget() _ = BetweenTargets() _ = AtDeploymentTarget() // expected-error {{'AtDeploymentTarget' is only available in}} _ = AfterDeploymentTarget() // expected-error {{'AfterDeploymentTarget' is only available in}} expected-note {{add 'if #available'}} if #available(macCatalyst 14.4, *) { _ = AtDeploymentTarget() } if #available(macCatalyst 15, *) { _ = AfterDeploymentTarget() } } @available(macCatalyst 14.4, *) @inlinable public func inlinedUseAtDeploymentTarget( _: NoAvailable, _: BeforeInliningTarget, _: AtInliningTarget, _: BetweenTargets, _: AtDeploymentTarget, _: AfterDeploymentTarget // expected-error {{'AfterDeploymentTarget' is only available in}} ) { defer { _ = AtDeploymentTarget() _ = AfterDeploymentTarget() // expected-error {{'AfterDeploymentTarget' is only available in}} expected-note {{add 'if #available'}} } _ = NoAvailable() _ = BeforeInliningTarget() _ = AtInliningTarget() _ = BetweenTargets() _ = AtDeploymentTarget() _ = AfterDeploymentTarget() // expected-error {{'AfterDeploymentTarget' is only available in}} expected-note {{add 'if #available'}} if #available(macCatalyst 15, *) { _ = AfterDeploymentTarget() } } @available(macCatalyst 15, *) @inlinable public func inlinedUseAfterDeploymentTarget( _: NoAvailable, _: BeforeInliningTarget, _: AtInliningTarget, _: BetweenTargets, _: AtDeploymentTarget, _: AfterDeploymentTarget ) { defer { _ = AtDeploymentTarget() _ = AfterDeploymentTarget() } _ = NoAvailable() _ = BeforeInliningTarget() _ = AtInliningTarget() _ = BetweenTargets() _ = AtDeploymentTarget() _ = AfterDeploymentTarget() } // // Edge cases. // // Internal functions should use the minimum deployment target. internal func fn() { _ = AtDeploymentTarget() } // @_alwaysEmitIntoClient acts like @inlinable. @_alwaysEmitIntoClient public func aEICUseNoAvailable( // expected-note 8 {{add @available attribute}} _: NoAvailable, _: BeforeInliningTarget, _: AtInliningTarget, _: BetweenTargets, // expected-error {{'BetweenTargets' is only available in}} _: AtDeploymentTarget, // expected-error {{'AtDeploymentTarget' is only available in}} _: AfterDeploymentTarget // expected-error {{'AfterDeploymentTarget' is only available in}} ) { defer { _ = AtDeploymentTarget() // expected-error {{'AtDeploymentTarget' is only available in}} expected-note {{add 'if #available'}} _ = AfterDeploymentTarget() // expected-error {{'AfterDeploymentTarget' is only available in}} expected-note {{add 'if #available'}} } _ = NoAvailable() _ = BeforeInliningTarget() _ = AtInliningTarget() _ = BetweenTargets() // expected-error {{'BetweenTargets' is only available in}} expected-note {{add 'if #available'}} _ = AtDeploymentTarget() // expected-error {{'AtDeploymentTarget' is only available in}} expected-note {{add 'if #available'}} _ = AfterDeploymentTarget() // expected-error {{'AfterDeploymentTarget' is only available in}} expected-note {{add 'if #available'}} if #available(macCatalyst 14, *) { _ = BetweenTargets() } if #available(macCatalyst 14.4, *) { _ = AtDeploymentTarget() } if #available(macCatalyst 15, *) { _ = AfterDeploymentTarget() } } // @_backDeploy acts like @inlinable. @available(macCatalyst 13.1, *) @_backDeploy(before: macCatalyst 999.0) public func backDeployedToInliningTarget( _: NoAvailable, _: BeforeInliningTarget, _: AtInliningTarget, _: BetweenTargets, // expected-error {{'BetweenTargets' is only available in}} _: AtDeploymentTarget, // expected-error {{'AtDeploymentTarget' is only available in}} _: AfterDeploymentTarget // expected-error {{'AfterDeploymentTarget' is only available in}} ) { defer { _ = AtDeploymentTarget() // expected-error {{'AtDeploymentTarget' is only available in}} expected-note {{add 'if #available'}} _ = AfterDeploymentTarget() // expected-error {{'AfterDeploymentTarget' is only available in}} expected-note {{add 'if #available'}} } _ = NoAvailable() _ = BeforeInliningTarget() _ = AtInliningTarget() _ = BetweenTargets() // expected-error {{'BetweenTargets' is only available in}} expected-note {{add 'if #available'}} _ = AtDeploymentTarget() // expected-error {{'AtDeploymentTarget' is only available in}} expected-note {{add 'if #available'}} _ = AfterDeploymentTarget() // expected-error {{'AfterDeploymentTarget' is only available in}} expected-note {{add 'if #available'}} if #available(macCatalyst 14, *) { _ = BetweenTargets() } if #available(macCatalyst 14.4, *) { _ = AtDeploymentTarget() } if #available(macCatalyst 15, *) { _ = AfterDeploymentTarget() } } // Default arguments act like @inlinable. public func defaultArgsUseNoAvailable( // expected-note 3 {{add @available attribute}} _: Any = NoAvailable.self, _: Any = BeforeInliningTarget.self, _: Any = AtInliningTarget.self, _: Any = BetweenTargets.self, // expected-error {{'BetweenTargets' is only available in}} _: Any = AtDeploymentTarget.self, // expected-error {{'AtDeploymentTarget' is only available in}} _: Any = AfterDeploymentTarget.self // expected-error {{'AfterDeploymentTarget' is only available in}} ) {} public struct PublicStruct { // expected-note 6 {{add @available attribute}} // Public declarations act like @inlinable. public var aPublic: NoAvailable public var bPublic: BeforeInliningTarget public var cPublic: AtInliningTarget public var dPublic: BetweenTargets // expected-error {{'BetweenTargets' is only available in}} public var ePublic: AtDeploymentTarget // expected-error {{'AtDeploymentTarget' is only available in}} public var fPublic: AfterDeploymentTarget // expected-error {{'AfterDeploymentTarget' is only available in}} // Internal declarations act like non-inlinable. var aInternal: NoAvailable var bInternal: BeforeInliningTarget var cInternal: AtInliningTarget var dInternal: BetweenTargets var eInternal: AtDeploymentTarget var fInternal: AfterDeploymentTarget // expected-error {{'AfterDeploymentTarget' is only available in}} @available(macCatalyst 14, *) public internal(set) var internalSetter: Void { @inlinable get { // Public inlinable getter acts like @inlinable _ = NoAvailable() _ = BeforeInliningTarget() _ = AtInliningTarget() _ = BetweenTargets() _ = AtDeploymentTarget() // expected-error {{'AtDeploymentTarget' is only available in}} _ = AfterDeploymentTarget() // expected-error {{'AfterDeploymentTarget' is only available in}} expected-note {{add 'if #available'}} } set { // Private setter acts like non-inlinable _ = NoAvailable() _ = BeforeInliningTarget() _ = AtInliningTarget() _ = BetweenTargets() _ = AtDeploymentTarget() _ = AfterDeploymentTarget() // expected-error {{'AfterDeploymentTarget' is only available in}} expected-note {{add 'if #available'}} } } } @frozen public struct FrozenPublicStruct { // expected-note 6 {{add @available attribute}} // Public declarations act like @inlinable. public var aPublic: NoAvailable public var bPublic: BeforeInliningTarget public var cPublic: AtInliningTarget public var dPublic: BetweenTargets // expected-error {{'BetweenTargets' is only available in}} public var ePublic: AtDeploymentTarget // expected-error {{'AtDeploymentTarget' is only available in}} public var fPublic: AfterDeploymentTarget // expected-error {{'AfterDeploymentTarget' is only available in}} // Internal declarations act like @inlinable in a frozen struct. var aInternal: NoAvailable var bInternal: BeforeInliningTarget var cInternal: AtInliningTarget var dInternal: BetweenTargets // expected-error {{'BetweenTargets' is only available in}} var eInternal: AtDeploymentTarget // expected-error {{'AtDeploymentTarget' is only available in}} var fInternal: AfterDeploymentTarget // expected-error {{'AfterDeploymentTarget' is only available in}} } internal struct InternalStruct { // expected-note {{add @available attribute}} // Internal declarations act like non-inlinable. var aInternal: NoAvailable var bInternal: BeforeInliningTarget var cInternal: AtInliningTarget var dInternal: BetweenTargets var eInternal: AtDeploymentTarget var fInternal: AfterDeploymentTarget // expected-error {{'AfterDeploymentTarget' is only available in}} } // Top-level code, if somehow present in a resilient module, is treated like // a non-inlinable function. defer { _ = AtDeploymentTarget() _ = AfterDeploymentTarget() // expected-error {{'AfterDeploymentTarget' is only available in}} expected-note {{add 'if #available'}} } _ = NoAvailable() _ = BeforeInliningTarget() _ = AtInliningTarget() _ = BetweenTargets() _ = AtDeploymentTarget() _ = AfterDeploymentTarget() // expected-error {{'AfterDeploymentTarget' is only available in}} expected-note {{add 'if #available'}} if #available(macCatalyst 15, *) { _ = AfterDeploymentTarget() }
apache-2.0
92feeff4849078e320617795cc849929
37.257496
208
0.711184
4.281034
false
false
false
false
nnorris7/Prime-Related
SieveOfAtkin.swift
1
5328
// // SieveOfAtkin.swift // Consecutive Primes Distribution // // Created by Norm Norris on 3/18/16. // Copyright © 2016 Norm Norris. All rights reserved. // import Foundation class SieveOfAtkin: NSObject { func basic(limit: Int) -> [Bool] { let limitSqrt = Int(sqrt(Double(limit))) var sieveList = Array(count:limit + 1, repeatedValue:false) sieveList[0] = false sieveList[1] = false sieveList[2] = true sieveList[3] = true for x in 1...limitSqrt { for y in 1...limitSqrt { // first quadractic var n = (4 * x * x) + (y * y) if n <= limit && (n % 12 == 1 || n % 12 == 5) { sieveList[n] = !sieveList[n] } // second quadractic n = (3 * x * x) + (y * y) if n <= limit && (n % 12 == 7) { sieveList[n] = !sieveList[n] } // third quadractic n = (3 * x * x) - (y * y) if x > y && n <= limit && (n % 12 == 11) { sieveList[n] = !sieveList[n] } } } if limitSqrt > 5 { for n in 5...limitSqrt { if sieveList[n] { let x = n * n var i = x while i <= limit { sieveList[i] = false i += x } } } } return sieveList } func wiki(limit: Int) -> [Bool] { let s = [1, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 49, 53, 59] let limitSqrt = Int(sqrt(Double(limit))) + 1 var sieveList = Array(count:limit + 1, repeatedValue:false) sieveList[0] = false sieveList[1] = false sieveList[2] = true sieveList[3] = true sieveList[4] = false sieveList[5] = true // first quadratic for x in 1 ..< (limitSqrt/2 + 1) { var y = 1 y_loop: while y < limitSqrt { let n = (4 * x * x) + (y * y) if n < limit { switch n % 60 { case 1, 13, 17, 29, 37, 41, 49, 53: sieveList[n] = !sieveList[n] default: break } } else { break y_loop } y += 2 } } // second quadratic var x = 1 while x < limitSqrt { var y = 2 while y < limitSqrt { let n = (3 * x * x) + (y * y) if n < limit { switch n % 60 { case 7, 19, 31, 43: sieveList[n] = !sieveList[n] default: break } } y += 2 } x += 2 } // third quadratic for x in 2 ..< limitSqrt { var y = x - 1 while y > 0 { let n = (3 * x * x) - (y * y) if n < limit { switch n % 60 { case 11, 23, 47, 59: sieveList[n] = !sieveList[n] default: break } } y -= 2 } } for w in 0 ..< (limitSqrt/60 + 1) { for i in 0 ..< 16 { let n = 60 * w + s[i] if n >= 7 && n * n <= limit { if sieveList[n] { ww_loop: for ww in 0..<(limit/60) { for j in 0 ..< 16 { let c = n * n * (60 * ww + s[j]) if c <= limit { sieveList[c] = false } else { break ww_loop } } } } } } } return sieveList } func consolidatePrimes(arrayOfBools: [Bool]) -> [Int] { var primes = [Int]() for (index, value) in arrayOfBools.enumerate() { if value == true { primes.append(index) } } return primes } func printPrimes(arrayOfBools: [Bool]) { print("Primes: ") for (index, value) in arrayOfBools.enumerate() { if value == true { print("\(index)", terminator: ", ") } } } func exportPrimes(arrayOfBools: [Bool]) -> String { var primes = "Primes:\n" for (index, value) in arrayOfBools.enumerate() { if value == true { primes.appendContentsOf("\(index), ") } } primes = String(primes.characters.dropLast(2)) return primes } }
mit
d42d0c722f6be0a3ab73517ccef1ee6c
27.794595
78
0.334898
4.495359
false
false
false
false
sharath-cliqz/browser-ios
Client/Cliqz/Foundation/JSEngine/Crypto.swift
2
9270
// // Crypto.swift // Client // // Created by Mahmoud Adam on 7/17/17. // Copyright © 2017 Mozilla. All rights reserved. // import UIKit import React @objc(Crypto) open class Crypto : RCTEventEmitter { private let privateKeyTag = "com.connect.cliqz.private" private let publicKeyTag = "com.connect.cliqz.public" private let blockSizeInBytes = 256 private let secNoPadding = SecPadding.init(rawValue: 0) @objc(generateRandomSeed:reject:) func generateRandomSeed(_ resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) -> Void { let length = 128 if let randomSeed = generateRandomBytes(length) { resolve(randomSeed) } else { reject("RandomNumberGenerationFailure", "Could not generate random seed", nil) } } @objc(generateRSAKey:reject:) func generateRSAKey(_ resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) -> Void { let privateKeyAttr : [String: Any] = [ kSecAttrIsPermanent as String: kCFBooleanFalse, kSecAttrApplicationTag as String: privateKeyTag ] let publicKeyAttr : [String: Any] = [ kSecAttrIsPermanent as String: kCFBooleanFalse, kSecAttrApplicationTag as String: publicKeyTag ] let parameters: [String: Any] = [ kSecAttrKeyType as String: kSecAttrKeyTypeRSA, kSecAttrKeySizeInBits as String: blockSizeInBytes * 8, kSecPrivateKeyAttrs as String : privateKeyAttr, kSecPublicKeyAttrs as String: publicKeyAttr ] var publicKey, privateKey: SecKey? SecKeyGeneratePair(parameters as CFDictionary, &publicKey, &privateKey) var privateKeyData: Data? var error:Unmanaged<CFError>? if #available(iOS 10.0, *) { if let cfdata = SecKeyCopyExternalRepresentation(privateKey!, &error) { privateKeyData = cfdata as Data } } else { let query: [String:Any] = [ kSecClass as String: kSecClassKey, kSecAttrKeyType as String: kSecAttrKeyTypeRSA, kSecAttrApplicationTag as String: privateKeyTag, kSecReturnData as String: kCFBooleanTrue, ] var secureItemValue: AnyObject? let statusCode: OSStatus = SecItemCopyMatching(query as CFDictionary, &secureItemValue) if let data = secureItemValue as? Data, statusCode == noErr { privateKeyData = data } } if let data = privateKeyData { resolve(data.base64EncodedString()) } else { reject("generateRSAKeyError", "Export privateKey failed.", nil) } } @objc(encryptRSA:base64PublicKey:resolve:reject:) func encryptRSA(base64Data: String, base64PublicKey: String, resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) { if let decodedData = Data(base64Encoded: base64Data) , let publicKey = getKey(base64PublicKey, secAttrKeyClass: kSecAttrKeyClassPublic as String, keyTag: publicKeyTag) { let plainTextData = [UInt8](decodedData) let plainTextDataLength = plainTextData.count var encryptedData = [UInt8](repeating: 0, count: Int(blockSizeInBytes)) var encryptedDataLength = blockSizeInBytes let result = SecKeyEncrypt(publicKey, secNoPadding, plainTextData, plainTextDataLength, &encryptedData, &encryptedDataLength) if result == noErr { let encData = NSData(bytes: encryptedData, length: encryptedDataLength) resolve(encData.base64EncodedString()) return } } reject("EncryptionError", "Could not encrypt data", nil) } @objc(decryptRSA:base64PrivateKey:resolve:reject:) func decryptRSA(base64Data: String, base64PrivateKey: String, resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) { if let decodedData = Data(base64Encoded: base64Data) , let privateKey = getKey(base64PrivateKey, secAttrKeyClass: kSecAttrKeyClassPrivate as String, keyTag: privateKeyTag) { let encryptedData = [UInt8](decodedData) let encryptedDataLength = encryptedData.count var decryptedData = [UInt8](repeating: 0, count: Int(blockSizeInBytes)) var decryptedDataLength = blockSizeInBytes let result = SecKeyDecrypt(privateKey, secNoPadding, encryptedData, encryptedDataLength, &decryptedData, &decryptedDataLength) if result == noErr { let decData = NSData(bytes: decryptedData, length: decryptedDataLength) resolve(decData.base64EncodedString()) return } } reject("DecryptionError", "Could not decrypt data", nil) } @objc(signRSA:base64PrivateKey:resolve:reject:) func signRSA(base64Data: String, base64PrivateKey: String, resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) { if let decodedData = Data(base64Encoded: base64Data) , let privateKey = getKey(base64PrivateKey, secAttrKeyClass: kSecAttrKeyClassPrivate as String, keyTag: privateKeyTag) { let data = [UInt8](decodedData) let dataLength = data.count var sigData = [UInt8](repeating: 0, count: Int(blockSizeInBytes)) var sigDataLength = blockSizeInBytes let result = SecKeyRawSign(privateKey, .PKCS1SHA256, data, dataLength, &sigData, &sigDataLength) if result == noErr { let singedData = NSData(bytes: sigData, length: sigDataLength) resolve(singedData.base64EncodedString()) return } } reject("SigningError", "Could not sign data", nil) } // MARK: - Private helpers private func generateRandomBytes(_ length: Int) -> String? { var keyData = Data(count: length) let result = keyData.withUnsafeMutableBytes { SecRandomCopyBytes(kSecRandomDefault, keyData.count, $0) } if result == errSecSuccess { return keyData.base64EncodedString() } else { // in case of failure var randomString = "" for _ in 0..<length { let randomNumber = Int(arc4random_uniform(10)) randomString += String(randomNumber) } return randomString.data(using: String.Encoding.utf8)?.base64EncodedString() } } private func getKey(_ base64Key: String, secAttrKeyClass: String, keyTag: String) -> SecKey? { var secKey: SecKey? guard let secKeyData = Data(base64Encoded: base64Key) else { return nil } if #available(iOS 10.0, *) { let attributes: [String:Any] = [ kSecAttrKeyClass as String: secAttrKeyClass, kSecAttrKeyType as String: kSecAttrKeyTypeRSA, kSecAttrKeySizeInBits as String: blockSizeInBytes * 8, ] secKey = SecKeyCreateWithData(secKeyData as CFData, attributes as CFDictionary, nil) } else { /* let query: [String:Any] = [ kSecClass as String: kSecClassKey, kSecAttrKeyType as String: kSecAttrKeyTypeRSA, kSecAttrApplicationTag as String: keyTag, kSecReturnPersistentRef as String: kCFBooleanTrue, kSecValueData as String : secKeyData ] var persistentRef: AnyObject? let status = SecItemAdd(query as CFDictionary, &persistentRef) if status == noErr || status == errSecDuplicateItem { secKey = obtainKey(keyTag) } */ } return secKey } /* private func obtainKey(_ tag: String) -> SecKey? { var keyRef: AnyObject? let query: [String:Any] = [ kSecClass as String: kSecClassKey, kSecAttrKeyType as String: kSecAttrKeyTypeRSA, kSecAttrApplicationTag as String: tag, kSecReturnRef as String: kCFBooleanTrue, ] let status = SecItemCopyMatching(query as CFDictionary, &keyRef) if status == noErr, let ref = keyRef { let deleteQuery: [String:Any] = [ kSecClass as String: kSecClassKey, kSecAttrApplicationTag as String: tag ] SecItemDelete(deleteQuery as CFDictionary) return (ref as! SecKey) } return nil } */ }
mpl-2.0
d9eb2ca2e1faa9654a87eb8a6acada5f
37.144033
131
0.57989
5.537037
false
false
false
false
benlangmuir/swift
validation-test/Reflection/reflect_Bool.swift
19
1777
// RUN: %empty-directory(%t) // RUN: %target-build-swift -lswiftSwiftReflectionTest %s -o %t/reflect_Bool // RUN: %target-codesign %t/reflect_Bool // RUN: %target-run %target-swift-reflection-test %t/reflect_Bool | %FileCheck %s --check-prefix=CHECK-%target-ptrsize // REQUIRES: reflection_test_support // REQUIRES: executable_test // UNSUPPORTED: use_os_stdlib import SwiftReflectionTest class TestClass { var t: Bool init(t: Bool) { self.t = t } } var obj = TestClass(t: true) reflect(object: obj) // CHECK-64: Reflecting an object. // CHECK-64: Instance pointer in child address space: 0x{{[0-9a-fA-F]+}} // CHECK-64: Type reference: // CHECK-64: (class reflect_Bool.TestClass) // CHECK-64: Type info: // CHECK-64: (class_instance size=17 alignment=1 stride=17 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64: (field name=t offset=16 // CHECK-64: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=254 bitwise_takable=1 // CHECK-64: (field name=_value offset=0 // CHECK-64: (builtin size=1 alignment=1 stride=1 num_extra_inhabitants=254 bitwise_takable=1))))) // CHECK-32: Reflecting an object. // CHECK-32: Instance pointer in child address space: 0x{{[0-9a-fA-F]+}} // CHECK-32: Type reference: // CHECK-32: (class reflect_Bool.TestClass) // CHECK-32: Type info: // CHECK-32: (class_instance size=9 alignment=1 stride=9 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32: (field name=t offset=8 // CHECK-32: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=254 bitwise_takable=1 // CHECK-32: (field name=_value offset=0 // CHECK-32: (builtin size=1 alignment=1 stride=1 num_extra_inhabitants=254 bitwise_takable=1))))) doneReflecting() // CHECK-64: Done. // CHECK-32: Done.
apache-2.0
57bf035209f120000a9959775cb9f3ef
33.173077
118
0.693866
3.139576
false
true
false
false
davidisaaclee/VectorKit
Example/Tests/CustomVectorSpec.swift
1
3384
import Quick import Nimble import VectorKit class CustomVector2TypeSpec: QuickSpec { typealias VectorType = CustomVector2 override func spec() { describe("Custom vectors") { let pt = VectorType(collection: [3, 4]) it("can initialize from collections") { expect(CustomVector2(x: 0, y: 1)).to(equal(CustomVector2(x: 0, y: 1))) expect(VectorType(collection: [1, 2])).to(equal(CustomVector2(x: 1, y: 2))) expect(VectorType(collection: [-1, -2, 3])).to(equal(CustomVector2(x: -1, y: -2))) } it("adopts CollectionType") { expect(pt[0]).to(equal(pt.x)) expect(pt[1]).to(equal(pt.y)) } it("calculates magnitude") { expect(pt.magnitude).to(equal(5)) } it("can add") { let pt2 = VectorType(collection: [1, -2]) expect(pt + pt2).to(equal(VectorType(collection: [4, 2]))) } it("can scale") { expect(pt * Float(3)).to(equal(VectorType(collection: [9, 12]))) expect(pt * Float(-1)).to(equal(VectorType(collection: [-3, -4]))) } it("can get unit vector") { expect(VectorType(collection: [10, 0]).unit).to(equal(VectorType(collection: [1, 0]))) expect(VectorType(collection: [0, 10]).unit).to(equal(VectorType(collection: [0, 1]))) let u = VectorType(collection: [3, 4]).unit expect(u.x).to(beCloseTo(0.6)) expect(u.y).to(beCloseTo(0.8)) } it("can negate") { expect(pt.negative).to(equal(VectorType(collection: [-pt.x, -pt.y]))) } it("can subtract") { expect(pt - VectorType(collection: [-2, 4])).to(equal(VectorType(collection: [pt.x + 2, pt.y - 4]))) } } } } class CustomVector3TypeSpec: QuickSpec { typealias VectorType = CustomVector3 override func spec() { describe("Custom vectors") { let pt = VectorType(collection: [3, 4, 5]) it("can initialize from collections") { expect(VectorType(collection: [1, 2, 3])).to(equal(VectorType(x: 1, y: 2, z: 3))) expect(VectorType(collection: [-1, -2, 3, 4])).to(equal(VectorType(x: -1, y: -2, z: 3))) } it("adopts CollectionType") { expect(pt[0]).to(equal(pt.x)) expect(pt[1]).to(equal(pt.y)) expect(pt[2]).to(equal(pt.z)) } it("calculates magnitude") { expect(pt.magnitude).to(beCloseTo(5 * Float(2.0).toThePowerOf(0.5))) } it("can add") { let pt2 = VectorType(collection: [1, -2, 3]) expect(pt + pt2).to(equal(VectorType(collection: [3 + 1, 4 + -2, 5 + 3]))) } it("can scale") { expect(pt * Float(3)).to(equal(VectorType(collection: [9, 12, 15]))) expect(pt * Float(-1)).to(equal(VectorType(collection: [-3, -4, -5]))) } it("can get unit vector") { expect(VectorType(collection: [10, 0, 0]).unit).to(equal(VectorType(collection: [1, 0, 0]))) expect(VectorType(collection: [0, 10, 0]).unit).to(equal(VectorType(collection: [0, 1, 0]))) expect(VectorType(collection: [0, 0, 10]).unit).to(equal(VectorType(collection: [0, 0, 1]))) let u = VectorType(collection: [3, 4, 5]).unit expect(u.x).to(beCloseTo(3.0 / (5.0 * pow(2.0, 0.5)))) expect(u.y).to(beCloseTo(2.0 * pow(2.0, 0.5) / 5.0)) expect(u.z).to(beCloseTo(1.0 / pow(2.0, 0.5))) } it("can negate") { expect(pt.negative).to(equal(VectorType(collection: [-pt.x, -pt.y, -pt.z]))) } it("can subtract") { expect(pt - VectorType(collection: [-2, 4, 1])).to(equal(VectorType(collection: [pt.x + 2, pt.y - 4, pt.z - 1]))) } } } }
mit
39439ab7c90668ea775e1dfbd300d893
30.055046
117
0.60727
2.769231
false
false
false
false
waterskier2007/NVActivityIndicatorView
NVActivityIndicatorView/Animations/NVActivityIndicatorAnimationBallSpinFadeLoader.swift
1
3669
// // NVActivityIndicatorAnimationBallSpinFadeLoader.swift // NVActivityIndicatorViewDemo // // The MIT License (MIT) // Copyright (c) 2016 Vinh Nguyen // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import UIKit class NVActivityIndicatorAnimationBallSpinFadeLoader: NVActivityIndicatorAnimationDelegate { func setUpAnimation(in layer: CALayer, size: CGSize, color: UIColor) { let circleSpacing: CGFloat = -2 let circleSize = (size.width - 4 * circleSpacing) / 5 let x = (layer.bounds.width - size.width) / 2 let y = (layer.bounds.height - size.height) / 2 let duration: CFTimeInterval = 1 let beginTime = CACurrentMediaTime() let beginTimes: [CFTimeInterval] = [0, 0.12, 0.24, 0.36, 0.48, 0.6, 0.72, 0.84] // Scale animation let scaleAnimation = CAKeyframeAnimation(keyPath: "transform.scale") scaleAnimation.keyTimes = [0, 0.5, 1] scaleAnimation.values = [1, 0.4, 1] scaleAnimation.duration = duration // Opacity animation let opacityAnimaton = CAKeyframeAnimation(keyPath: "opacity") opacityAnimaton.keyTimes = [0, 0.5, 1] opacityAnimaton.values = [1, 0.3, 1] opacityAnimaton.duration = duration // Animation let animation = CAAnimationGroup() animation.animations = [scaleAnimation, opacityAnimaton] animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear) animation.duration = duration animation.repeatCount = HUGE animation.isRemovedOnCompletion = false // Draw circles for i in 0 ..< 8 { let circle = circleAt(angle: CGFloat.pi / 4 * CGFloat(i), size: circleSize, origin: CGPoint(x: x, y: y), containerSize: size, color: color) animation.beginTime = beginTime + beginTimes[i] circle.add(animation, forKey: "animation") layer.addSublayer(circle) } } func circleAt(angle: CGFloat, size: CGFloat, origin: CGPoint, containerSize: CGSize, color: UIColor) -> CALayer { let radius = containerSize.width / 2 - size / 2 let circle = NVActivityIndicatorShape.circle.layerWith(size: CGSize(width: size, height: size), color: color) let frame = CGRect( x: origin.x + radius * (cos(angle) + 1), y: origin.y + radius * (sin(angle) + 1), width: size, height: size) circle.frame = frame return circle } }
mit
3ab19ca447519e9a408cc1aae32961a9
39.318681
117
0.651949
4.74031
false
false
false
false
SuperJerry/Swift
CookieCrunch-Swift-Part1/CookieCrunch/Swap.swift
2
657
// // Swap.swift // CookieCrunch // // Created by Matthijs on 19-06-14. // Copyright (c) 2014 Razeware LLC. All rights reserved. // struct Swap: Printable, Hashable { let cookieA: Cookie let cookieB: Cookie init(cookieA: Cookie, cookieB: Cookie) { self.cookieA = cookieA self.cookieB = cookieB } var description: String { return "swap \(cookieA) with \(cookieB)" } var hashValue: Int { return cookieA.hashValue ^ cookieB.hashValue } } func ==(lhs: Swap, rhs: Swap) -> Bool { return (lhs.cookieA == rhs.cookieA && lhs.cookieB == rhs.cookieB) || (lhs.cookieB == rhs.cookieA && lhs.cookieA == rhs.cookieB) }
mit
0b63d42fbbf89730ceb51667dde5987b
20.9
70
0.642314
3.494681
false
false
false
false
nifty-swift/Nifty
Sources/lu.swift
2
4834
/*************************************************************************************************** * lu.swift * * This file provides functionality for computing the LU decomposition of a matrix. * * Author: Philip Erickson * Creation Date: 25 Dec 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. * * Copyright 2016 Philip Erickson **************************************************************************************************/ // TODO: MATLAB provides more info, e.g. (L,U,P,Q,R) = lu(A). Should we provide Q and R? #if NIFTY_XCODE_BUILD import Accelerate #else import CLapacke #endif /// Compute the LU decomposition of a given square matrix. /// /// A warning is printed if the U factor is singular. /// /// - Parameters: /// - A: matrix to decompose /// - Returns: lower triangular matrix L and the upper triangular matrix U public func lu(_ A: Matrix<Double>) -> (L: Matrix<Double>, U: Matrix<Double>) { let (L, U, _) = _lu(A) return (L, U) } /// Compute the LU decomposition of a given square matrix. /// /// A warning is printed if the U factor is singular. /// /// - Parameters: /// - A: matrix to decompose /// - Returns: the lower triangular matrix L, the upper triangular matrix U, and the permutation /// matrix P (indicating how the rows of L were permuted), such that P*A=L*U public func lu(_ A: Matrix<Double>) -> (L: Matrix<Double>, U: Matrix<Double>, P: Matrix<Double>) { let (L, U, ipiv) = _lu(A) // FIXME: verify that this ipiv to permutation conversion is correct // The dimensions on the ipiv array concern me, still unclear on the // dimensionality, "(min(M,N))" from LAPACK doc... let m = Int32(A.size[0]) let n = Int32(A.size[1]) var P = _ipiv2p(ipiv: ipiv, m: m, n: n) if let nameA = A.name { P.name = "lu(\(nameA)).P" } if A.showName { P.showName = true } return (L, U, P) } /// Compute the LU decomposition, returning L, U, and the pivot indices. /// /// A warning is printed if the U factor is singular. /// /// This function is just useful as an intermediate, so that the user can avoid computing the /// permutation matrix from the pivot indices if the permutation matrix isn't needed. /// /// - Parameters: /// - A: matrix to decompose /// - Returns: the lower triangular matrix L, the upper triangular matrix U, and the pivot indices fileprivate func _lu(_ A: Matrix<Double>) -> (L: Matrix<Double>, U: Matrix<Double>, ipiv: [Int32]) { var m = Int32(A.size[0]) var n = Int32(A.size[1]) var a = A.data // The leading dimension equals the number of elements in the major dimension. In this case, // we are doing row-major so lda is the number of columns in A. var lda = n var ipiv = Array<Int32>(repeating: 0, count: Int(n)) var info = Int32(0) // compute LU factorization // TODO: find better way to resolve the difference between clapack used by Accelerate and LAPACKE #if NIFTY_XCODE_BUILD let At = transpose(A) var at = At.data dgetrf_(&m, &n, &at, &lda, &ipiv, &info) a = transpose(Matrix(Int(n), Int(n), at)).data #else info = LAPACKE_dgetrf(LAPACK_ROW_MAJOR, m, n, &a, lda, &ipiv) #endif precondition(info >= 0, "Illegal value in LAPACK argument \(-1*info)") if info > 0 { print("Warning: U(\(info),\(info)) is exactly zero. The factorization has been completed, " + "but the factor U is exactly singular, and division by zero will occur if it is used " + "to solve a system of equations.") } // separate out lower and upper components var u = [Double](repeating: 0, count: Int(m)*Int(n)) var l = [Double](repeating: 0, count: Int(m)*Int(m)) for r in 0..<Int(m) { for c in 0..<Int(n) { let i = r*Int(n) + c if r < c { u[i] = a[i] l[i] = 0 } else if r == c { u[i] = a[i] l[i] = 1 } else { u[i] = 0 l[i] = a[i] } } } var L = Matrix(Int(m), Int(m), l) var U = Matrix(Int(m), Int(n), u) if let nameA = A.name { L.name = "lu(\(nameA)).L" U.name = "lu(\(nameA)).U" } if A.showName { L.showName = true U.showName = true } return (L, U, ipiv) }
apache-2.0
ecffed0b62c635c14e5921a6fe58998a
29.402516
101
0.58916
3.336094
false
false
false
false
kstaring/swift
test/Parse/ConditionalCompilation/basicIdentity.swift
24
927
// RUN: %swift -parse %s -verify -D FOO -D BAZ -target x86_64-apple-macosx10.9 -parse-stdlib struct Foo {} #if FOO var a = Foo() #endif var b = a #if !BAR var c = Foo() #endif var d = c #if FOO || BAR var e = Foo() #endif var f = e #if BAR || FOO var g = Foo() #endif var h = g #if FOO && BAZ var i = Foo() #endif var j = i #if os(OSX) var k = Foo() #endif var l = k #if arch(x86_64) var m = Foo() #endif var n = m #if FOO && !BAR && BAZ && os(OSX) && arch(x86_64) && _runtime(_ObjC) var o = Foo() #endif var p = o #if FOO && (!BAR && BAZ && os(OSX) && arch(x86_64)) && _runtime(_ObjC) var q = Foo() #endif var r = q #if FOO && !(!BAZ && BAZ && os(OSX) && arch(x86_64)) && _runtime(_ObjC) var s = Foo() #endif var t = s // Test symmetric version of FOO || BAR from above #if BAR || FOO var u = Foo() #endif var v = u // Test symmetric version of FOO && BAR from above #if BAZ && FOO var w = Foo() #endif var x = w
apache-2.0
42e6d064eca15a1e6ee2deaecfcff1c3
13.261538
92
0.568501
2.420366
false
false
false
false
ello/ello-ios
Sources/Controllers/ArtistInvites/ArtistInvitesViewController.swift
1
4745
//// /// ArtistInvitesViewController.swift // class ArtistInvitesViewController: StreamableViewController { override func trackerName() -> String? { return "ArtistInvites" } override func trackerProps() -> [String: Any]? { return nil } override func trackerStreamInfo() -> (String, String?)? { return nil } private var _mockScreen: StreamableScreenProtocol? var screen: StreamableScreenProtocol { set(screen) { _mockScreen = screen } get { return fetchScreen(_mockScreen) } } var generator: ArtistInvitesGenerator! typealias Usage = HomeViewController.Usage private let usage: Usage init(usage: Usage) { self.usage = usage super.init(nibName: nil, bundle: nil) title = InterfaceString.ArtistInvites.Title generator = ArtistInvitesGenerator( currentUser: currentUser, destination: self ) streamViewController.streamKind = generator.streamKind streamViewController.reloadClosure = { [weak self] in self?.generator?.load(reload: true) } streamViewController.initialLoadClosure = { [weak self] in self?.loadArtistInvites() } } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func didSetCurrentUser() { super.didSetCurrentUser() generator.currentUser = currentUser if currentUser != nil, isViewLoaded { screen.navigationBar.leftItems = [.burger] } } override func loadView() { let screen = ArtistInvitesScreen(usage: usage) screen.delegate = self screen.navigationBar.title = "" if currentUser != nil { screen.navigationBar.leftItems = [.burger] } view = screen viewContainer = screen.streamContainer } override func viewDidLoad() { super.viewDidLoad() streamViewController.showLoadingSpinner() streamViewController.loadInitialPage() } private func updateInsets() { updateInsets(navBar: screen.navigationBar) } override func showNavBars(animated: Bool) { super.showNavBars(animated: animated) positionNavBar( screen.navigationBar, visible: true, withConstraint: screen.navigationBarTopConstraint, animated: animated ) updateInsets() } override func hideNavBars(animated: Bool) { super.hideNavBars(animated: animated) positionNavBar( screen.navigationBar, visible: false, withConstraint: screen.navigationBarTopConstraint, animated: animated ) updateInsets() } } extension ArtistInvitesViewController: StreamDestination { var isPagingEnabled: Bool { get { return streamViewController.isPagingEnabled } set { streamViewController.isPagingEnabled = newValue } } func loadArtistInvites() { streamViewController.isPagingEnabled = false generator.load() } func replacePlaceholder( type: StreamCellType.PlaceholderType, items: [StreamCellItem], completion: @escaping Block ) { if type == .pageHeader, let pageHeader = items.compactMap({ $0.jsonable as? PageHeader }).first, let trackingPostToken = pageHeader.postToken { let trackViews: ElloAPI = .promotionalViews(tokens: [trackingPostToken]) ElloProvider.shared.request(trackViews).ignoreErrors() } streamViewController.replacePlaceholder(type: type, items: items) { if self.streamViewController.hasCellItems(for: .pageHeader) && !self.streamViewController.hasCellItems(for: .artistInvites) { self.streamViewController.replacePlaceholder( type: .artistInvites, items: [StreamCellItem(type: .streamLoading)] ) } completion() } if type == .artistInvites { streamViewController.doneLoading() } } func setPlaceholders(items: [StreamCellItem]) { streamViewController.clearForInitialLoad(newItems: items) } func setPrimary(jsonable: Model) { } func setPagingConfig(responseConfig: ResponseConfig) { streamViewController.responseConfig = responseConfig } func primaryModelNotFound() { self.showGenericLoadFailure() self.streamViewController.doneLoading() } } extension ArtistInvitesViewController: ArtistInvitesScreenDelegate { func scrollToTop() { streamViewController.scrollToTop(animated: true) } }
mit
deec7abcf18078be1f5cc314d064169e
28.842767
99
0.638356
5.260532
false
false
false
false
perrystreetsoftware/PSSRedisClient
Sources/PSSRedisClient/RedisClient.swift
1
9187
// // RedisClient.swift // Husband Material // // import Foundation import CocoaAsyncSocket @objc public protocol RedisManagerDelegate: NSObjectProtocol { func subscriptionMessageReceived(channel: String, message: String) func socketDidDisconnect(client: RedisClient, error: Error?) func socketDidConnect(client: RedisClient) func socketDidSubscribe(socket: RedisClient, channel: String) func socketDidReceivePong(socket: RedisClient) } @objc public class RedisClient: NSObject, GCDAsyncSocketDelegate, RedisMessageReceivedDelegate { public typealias CompletionBlock = (NSArray) -> Void public weak var delegate: RedisManagerDelegate? var socket: GCDAsyncSocket var separator: Data var parseManager: RedisResponseParser var completionBlocks: Array<CompletionBlock?> @objc private(set) public var lastPongDate: Date? @objc public var autoPingInterval: TimeInterval = 20 @objc public var enableAutoPing: Bool = false { didSet { if enableAutoPing == true { startAutoPinging() } } } private var isDebugLogEnabled: Bool @objc public init(delegate: RedisManagerDelegate?, isDebugLogEnabled: Bool = true) { self.socket = GCDAsyncSocket(delegate: nil, delegateQueue: DispatchQueue.main) self.separator = RedisClient.convertStringIntoData(str: "\r\n")! self.parseManager = RedisResponseParser(delegate: nil, isDebugLogEnabled: isDebugLogEnabled) self.delegate = delegate self.completionBlocks = Array<CompletionBlock>() self.isDebugLogEnabled = isDebugLogEnabled super.init() self.socket.delegate = self self.parseManager.delegate = self } static func convertStringIntoData(str: String) -> Data? { if let data = str.data(using: String.Encoding.utf8) { return data } return nil } deinit { NSObject.cancelPreviousPerformRequests(withTarget: self) } private func doDisconnect() { self.socket.disconnect() self.parseManager.reset() self.completionBlocks.removeAll() self.lastPongDate = nil } private var isAutoPingScheduled = false private func startAutoPinging() { guard isAutoPingScheduled == false else { return } if enableAutoPing && isConnected() { isAutoPingScheduled = true ping() DispatchQueue.main.asyncAfter(deadline: .now() + autoPingInterval) { [weak self] in guard let self = self else { return } self.isAutoPingScheduled = false self.startAutoPinging() } } else { isAutoPingScheduled = false } } @objc public func close() { self.doDisconnect() } @objc public func isConnected() -> Bool { return self.socket.isConnected } @objc public func connect(host: String, port: Int, pwd: String?) { // We might be using a new auth or channel, so let's disconnect if we are connected if self.socket.isConnected { self.doDisconnect() } logDebugMessage("SOCKET: Attempting doConnect to \(host) \(port) \(String(describing: pwd))") do { try self.socket.connect(toHost: host, onPort: UInt16(port)) if let actualPwd: String = pwd { if !actualPwd.isEmpty { // At this point the socket is NOT connected. // But I can start writing to it anyway! // The library will queue all my write operations, // and after the socket connects, it will automatically start executing my writes! self.exec(args: ["auth", actualPwd], completion: nil) } } } catch { logDebugMessage("SOCKET: Unable to connect") } } static func addStringToCommandArray(commandArray: inout Array<String>, str1: String) { commandArray.append("$\(str1.count)\r\n") commandArray.append("\(str1)\r\n") } static func buildStringCommand(_ args: String...) -> Data { var commandArray = Array<String>() commandArray.append("*\(args.count)\r\n") for arg in args { addStringToCommandArray(commandArray: &commandArray, str1: arg) } debugPrint("SOCKET: Command with \(commandArray.joined())") return RedisClient.convertStringIntoData(str: commandArray.joined())! as Data } // MARK: Redis functions @objc public func exec(command: String, completion: CompletionBlock?) { let components = command.components(separatedBy: [" "]) self.exec(args: components, completion: completion) } @objc public func exec(args: Array<String>, completion: CompletionBlock?) { var commandArray = Array<String>() commandArray.append("*\(args.count)\r\n") for arg in args { RedisClient.addStringToCommandArray(commandArray: &commandArray, str1: arg) } logDebugMessage("SOCKET: Command with \(commandArray.joined())") let data = RedisClient.convertStringIntoData(str: commandArray.joined())! as Data sendCommand(data, completion) } func sendCommand(_ data: Data, _ completion: CompletionBlock?) { // We create an array of completion blocks to call serially // as we get responses back from our redis operations self.completionBlocks.append(completion) self.socket.write(data, withTimeout: -1, tag: 0) self.socket.readData(to: self.separator, withTimeout: -1, tag: 0) } @objc public func ping() { logDebugMessage("SOCKET: Sending ping") exec(args: ["ping"], completion: nil) } @objc public func subscribe(to channel: String) { exec(args: ["subscribe", channel], completion: nil) } // MARK: CocaAsyncSocket Callbacks @objc public func socket(_ sock: GCDAsyncSocket, didRead data: Data, withTag tag: Int) { guard let line: String = String(data: data, encoding: .utf8) else { return } let trimmedString: String = line.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) logDebugMessage("SOCKET: Line from didReadData is \(trimmedString)") self.parseManager.parseLine(data: data) self.socket.readData(to: self.separator, withTimeout: -1, tag: 0) } @objc public func socket(_ sock: GCDAsyncSocket, didReadPartialDataOfLength partialLength: UInt, tag: Int) { logDebugMessage("SOCKET: Got something") } @objc public func socket(_ sock: GCDAsyncSocket, didConnectToHost host: String, port: UInt16) { logDebugMessage("SOCKET: Cool, I'm connected! That was easy."); self.delegate?.socketDidConnect(client: self) startAutoPinging() } @objc public func socket(_ sock: GCDAsyncSocket, didConnectTo url: URL) { logDebugMessage("SOCKET: Cool, I'm connected! That was easy."); } @objc public func socketDidDisconnect(_ sock: GCDAsyncSocket, withError err: Error?) { logDebugMessage("SOCKET: Disconnected me: \(String(describing: err?.localizedDescription))"); self.parseManager.reset() self.completionBlocks.removeAll() self.delegate?.socketDidDisconnect(client: self, error: err) } @objc public func socketDidCloseReadStream(_ sock: GCDAsyncSocket) { logDebugMessage("SOCKET: socketDidCloseReadStream: Disconnecting so we can rerun our connection") self.doDisconnect() } // MARK: Parser func redisMessageReceived(results: NSArray) { if let type = results.firstObject as? String { switch type.lowercased() { case "message": if results.count == 3 { logDebugMessage("SOCKET: Sending message of \(results[2])"); self.delegate?.subscriptionMessageReceived(channel: results[1] as! String, message: results[2] as! String) } case "pong": logDebugMessage("SOCKET: Received pong") lastPongDate = Date() delegate?.socketDidReceivePong(socket: self) case "subscribe": if results.count >= 2, let channel = results[1] as? String { logDebugMessage("SOCKET: Subscribed to \(channel)") delegate?.socketDidSubscribe(socket: self, channel: channel) } default: break } } if (self.completionBlocks.count > 0) { if let completionBlock: CompletionBlock = self.completionBlocks.removeFirst() { completionBlock(results) } } else { logDebugMessage("No completion blocks to send message \(results)") } } private func logDebugMessage(_ message: String) { if (isDebugLogEnabled) { debugPrint(message) } } }
mit
17c0c5d04f9e95e24b2ed5832dea451a
33.152416
112
0.61968
4.865996
false
false
false
false
KellenYangs/KLSwiftTest_05_05
VC跳转/VC跳转/CustomInteractionController.swift
1
1802
// // CustomInteractionController.swift // VC跳转 // // Created by bcmac3 on 16/5/30. // Copyright © 2016年 KellenYangs. All rights reserved. // import UIKit class CustomInteractionController: UIPercentDrivenInteractiveTransition { var navigationController: UINavigationController! var shouldCompleteTransition = false var transitionInProgress = false var completionSeed: CGFloat { return 1 - percentComplete } func attachToViewController(viewController: UIViewController) { navigationController = viewController.navigationController setupGestureRecognizer(viewController.view) } private func setupGestureRecognizer(view: UIView) { view.addGestureRecognizer(UIPanGestureRecognizer(target: self, action: #selector(CustomInteractionController.handlePanGesture(_:)))) } func handlePanGesture(gestureRecognizer: UIPanGestureRecognizer) { let viewTranslation = gestureRecognizer.translationInView(gestureRecognizer.view!.superview!) switch gestureRecognizer.state { case .Began: transitionInProgress = true navigationController.popViewControllerAnimated(true) case .Changed: let const = CGFloat(fminf(fmaxf(Float(viewTranslation.x / 200.0), 0.0), 1.0)) shouldCompleteTransition = const > 0.5 updateInteractiveTransition(const) case .Cancelled, .Ended: transitionInProgress = false if !shouldCompleteTransition || gestureRecognizer.state == .Cancelled { cancelInteractiveTransition() } else { finishInteractiveTransition() } default: print("Swift switch must be exhaustive, thus the default") } } }
mit
4194397218915d8d49b00afd2a209345
35.632653
140
0.683008
5.846906
false
false
false
false
PekanMmd/Pokemon-XD-Code
Objects/data types/XGBattleBingoPokemon.swift
1
3245
// // XGBattleBingoPokemon.swift // XG Tool // // Created by StarsMmd on 11/06/2015. // Copyright (c) 2015 StarsMmd. All rights reserved. // import Foundation let kSizeOfBattleBingoPokemonData = 0x0A let kBattleBingoPokemonPanelTypeOffset = 0x00 let kBattleBingoPokemonAbilityOffset = 0x01 let kBattleBingoPokemonNatureOffset = 0x02 let kBattleBingoPokemonGenderOffset = 0x03 let kBattleBingoPokemonSpeciesOffset = 0x04 let kBattleBingoPokemonMoveOffset = 0x06 class XGBattleBingoPokemon: NSObject, Codable { var typeOnCard = 0x0 var species = XGPokemon.index(0) var ability = 0x0 var nature = XGNatures.hardy var gender = XGGenders.male var move = XGMoves.index(0) var startOffset : Int = 0 override var description : String { get { return self.species.name.string + " (" + self.move.name.string + ")" } } override init() { super.init() } init(startOffset: Int) { super.init() self.startOffset = startOffset let rel = XGFiles.common_rel.data! self.typeOnCard = rel.getByteAtOffset(startOffset + kBattleBingoPokemonPanelTypeOffset) let species = rel.get2BytesAtOffset(startOffset + kBattleBingoPokemonSpeciesOffset) self.species = XGPokemon.index(species) self.ability = rel.getByteAtOffset(startOffset + kBattleBingoPokemonAbilityOffset) let gender = rel.getByteAtOffset(startOffset + kBattleBingoPokemonGenderOffset) self.gender = XGGenders(rawValue: gender) ?? .male let nature = rel.getByteAtOffset(startOffset + kBattleBingoPokemonNatureOffset) self.nature = XGNatures(rawValue: nature) ?? .hardy let move = rel.get2BytesAtOffset(startOffset + kBattleBingoPokemonMoveOffset) self.move = .index(move) } func save() { guard self.startOffset > 0 else { return } let rel = XGFiles.common_rel.data! rel.replaceByteAtOffset(startOffset + kBattleBingoPokemonPanelTypeOffset, withByte: self.typeOnCard > 0 ? 1 : 0) rel.replace2BytesAtOffset(startOffset + kBattleBingoPokemonSpeciesOffset, withBytes: self.species.index) rel.replaceByteAtOffset(startOffset + kBattleBingoPokemonAbilityOffset, withByte: self.ability > 0 ? 1 : 0) rel.replaceByteAtOffset(startOffset + kBattleBingoPokemonGenderOffset, withByte: self.gender.rawValue) rel.replaceByteAtOffset(startOffset + kBattleBingoPokemonNatureOffset, withByte: self.nature.rawValue) rel.replace2BytesAtOffset(startOffset + kBattleBingoPokemonMoveOffset, withBytes: self.move.index) rel.save() } } extension XGBattleBingoPokemon: XGDocumentable { static var className: String { return "Battle Bingo Pokemon" } var documentableName: String { return species.name.string } static var DocumentableKeys: [String] { return ["name", "type", "ability", "nature", "gender", "move"] } func documentableValue(for key: String) -> String { switch key { case "name": return species.name.string case "type": return typeOnCard == 0 ? species.type1.name : species.type2.name case "ability": return ability == 0 ? species.ability1 : species.ability2 case "nature": return nature.string case "gender": return gender.string case "move": return move.name.string default: return "" } } }
gpl-2.0
e6650c5c9321404f570bc0cb275dd543
22.345324
114
0.735901
3.328205
false
false
false
false
grpc/grpc-swift
Sources/GRPC/AsyncAwaitSupport/AsyncServerHandler/ServerHandlerStateMachine/ServerHandlerStateMachine.swift
1
11763
/* * Copyright 2022, gRPC Authors All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #if compiler(>=5.6) import NIOHPACK @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) @usableFromInline internal struct ServerHandlerStateMachine { @usableFromInline internal private(set) var state: Self.State @inlinable init() { self.state = .idle(.init()) } @inlinable mutating func setResponseHeaders(_ headers: HPACKHeaders) { switch self.state { case var .handling(handling): let nextStateAndOutput = handling.setResponseHeaders(headers) self.state = nextStateAndOutput.nextState.state return nextStateAndOutput.output case var .draining(draining): let nextStateAndOutput = draining.setResponseHeaders(headers) self.state = nextStateAndOutput.nextState.state return nextStateAndOutput.output case var .finished(finished): let nextStateAndOutput = finished.setResponseHeaders(headers) self.state = nextStateAndOutput.nextState.state return nextStateAndOutput.output case .idle: preconditionFailure() } } @inlinable mutating func setResponseTrailers(_ trailers: HPACKHeaders) { switch self.state { case var .handling(handling): let nextStateAndOutput = handling.setResponseTrailers(trailers) self.state = nextStateAndOutput.nextState.state return nextStateAndOutput.output case var .draining(draining): let nextStateAndOutput = draining.setResponseTrailers(trailers) self.state = nextStateAndOutput.nextState.state return nextStateAndOutput.output case var .finished(finished): let nextStateAndOutput = finished.setResponseTrailers(trailers) self.state = nextStateAndOutput.nextState.state return nextStateAndOutput.output case .idle: preconditionFailure() } } @inlinable mutating func handleMetadata() -> HandleMetadataAction { switch self.state { case var .idle(idle): let nextStateAndOutput = idle.handleMetadata() self.state = nextStateAndOutput.nextState.state return nextStateAndOutput.output case var .handling(handling): let nextStateAndOutput = handling.handleMetadata() self.state = nextStateAndOutput.nextState.state return nextStateAndOutput.output case var .draining(draining): let nextStateAndOutput = draining.handleMetadata() self.state = nextStateAndOutput.nextState.state return nextStateAndOutput.output case var .finished(finished): let nextStateAndOutput = finished.handleMetadata() self.state = nextStateAndOutput.nextState.state return nextStateAndOutput.output } } @inlinable mutating func handleMessage() -> HandleMessageAction { switch self.state { case var .idle(idle): let nextStateAndOutput = idle.handleMessage() self.state = nextStateAndOutput.nextState.state return nextStateAndOutput.output case var .handling(handling): let nextStateAndOutput = handling.handleMessage() self.state = nextStateAndOutput.nextState.state return nextStateAndOutput.output case var .draining(draining): let nextStateAndOutput = draining.handleMessage() self.state = nextStateAndOutput.nextState.state return nextStateAndOutput.output case var .finished(finished): let nextStateAndOutput = finished.handleMessage() self.state = nextStateAndOutput.nextState.state return nextStateAndOutput.output } } @inlinable mutating func handleEnd() -> HandleEndAction { switch self.state { case var .idle(idle): let nextStateAndOutput = idle.handleEnd() self.state = nextStateAndOutput.nextState.state return nextStateAndOutput.output case var .handling(handling): let nextStateAndOutput = handling.handleEnd() self.state = nextStateAndOutput.nextState.state return nextStateAndOutput.output case var .draining(draining): let nextStateAndOutput = draining.handleEnd() self.state = nextStateAndOutput.nextState.state return nextStateAndOutput.output case var .finished(finished): let nextStateAndOutput = finished.handleEnd() self.state = nextStateAndOutput.nextState.state return nextStateAndOutput.output } } @inlinable mutating func sendMessage() -> SendMessageAction { switch self.state { case var .handling(handling): let nextStateAndOutput = handling.sendMessage() self.state = nextStateAndOutput.nextState.state return nextStateAndOutput.output case var .draining(draining): let nextStateAndOutput = draining.sendMessage() self.state = nextStateAndOutput.nextState.state return nextStateAndOutput.output case var .finished(finished): let nextStateAndOutput = finished.sendMessage() self.state = nextStateAndOutput.nextState.state return nextStateAndOutput.output case .idle: preconditionFailure() } } @inlinable mutating func sendStatus() -> SendStatusAction { switch self.state { case var .handling(handling): let nextStateAndOutput = handling.sendStatus() self.state = nextStateAndOutput.nextState.state return nextStateAndOutput.output case var .draining(draining): let nextStateAndOutput = draining.sendStatus() self.state = nextStateAndOutput.nextState.state return nextStateAndOutput.output case var .finished(finished): let nextStateAndOutput = finished.sendStatus() self.state = nextStateAndOutput.nextState.state return nextStateAndOutput.output case .idle: preconditionFailure() } } @inlinable mutating func cancel() -> CancelAction { switch self.state { case var .idle(idle): let nextStateAndOutput = idle.cancel() self.state = nextStateAndOutput.nextState.state return nextStateAndOutput.output case var .handling(handling): let nextStateAndOutput = handling.cancel() self.state = nextStateAndOutput.nextState.state return nextStateAndOutput.output case var .draining(draining): let nextStateAndOutput = draining.cancel() self.state = nextStateAndOutput.nextState.state return nextStateAndOutput.output case var .finished(finished): let nextStateAndOutput = finished.cancel() self.state = nextStateAndOutput.nextState.state return nextStateAndOutput.output } } @inlinable mutating func handlerInvoked(requestHeaders: HPACKHeaders) { switch self.state { case var .idle(idle): let nextStateAndOutput = idle.handlerInvoked(requestHeaders: requestHeaders) self.state = nextStateAndOutput.nextState.state return nextStateAndOutput.output case .handling: preconditionFailure() case .draining: preconditionFailure() case .finished: preconditionFailure() } } } @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) extension ServerHandlerStateMachine { /// The possible states the state machine may be in. @usableFromInline internal enum State { case idle(ServerHandlerStateMachine.Idle) case handling(ServerHandlerStateMachine.Handling) case draining(ServerHandlerStateMachine.Draining) case finished(ServerHandlerStateMachine.Finished) } } @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) extension ServerHandlerStateMachine { /// The next state to transition to and any output which may be produced as a /// result of a substate handling an action. @usableFromInline internal struct NextStateAndOutput<NextState, Output> { @usableFromInline internal var nextState: NextState @usableFromInline internal var output: Output @inlinable internal init(nextState: NextState, output: Output) { self.nextState = nextState self.output = output } } } @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) extension ServerHandlerStateMachine.NextStateAndOutput where Output == Void { @inlinable internal init(nextState: NextState) { self.nextState = nextState self.output = () } } @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) extension ServerHandlerStateMachine.Idle { /// States which can be reached directly from 'Idle'. @usableFromInline internal struct NextState { @usableFromInline let state: ServerHandlerStateMachine.State @inlinable internal init(_state: ServerHandlerStateMachine.State) { self.state = _state } @inlinable internal static func idle(_ state: ServerHandlerStateMachine.Idle) -> Self { return Self(_state: .idle(state)) } @inlinable internal static func handling( from: ServerHandlerStateMachine.Idle, requestHeaders: HPACKHeaders ) -> Self { return Self(_state: .handling(.init(from: from, requestHeaders: requestHeaders))) } @inlinable internal static func finished(from: ServerHandlerStateMachine.Idle) -> Self { return Self(_state: .finished(.init(from: from))) } } } @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) extension ServerHandlerStateMachine.Handling { /// States which can be reached directly from 'Handling'. @usableFromInline internal struct NextState { @usableFromInline let state: ServerHandlerStateMachine.State @inlinable internal init(_state: ServerHandlerStateMachine.State) { self.state = _state } @inlinable internal static func handling(_ state: ServerHandlerStateMachine.Handling) -> Self { return Self(_state: .handling(state)) } @inlinable internal static func draining(from: ServerHandlerStateMachine.Handling) -> Self { return Self(_state: .draining(.init(from: from))) } @inlinable internal static func finished(from: ServerHandlerStateMachine.Handling) -> Self { return Self(_state: .finished(.init(from: from))) } } } @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) extension ServerHandlerStateMachine.Draining { /// States which can be reached directly from 'Draining'. @usableFromInline internal struct NextState { @usableFromInline let state: ServerHandlerStateMachine.State @inlinable internal init(_state: ServerHandlerStateMachine.State) { self.state = _state } @inlinable internal static func draining(_ state: ServerHandlerStateMachine.Draining) -> Self { return Self(_state: .draining(state)) } @inlinable internal static func finished(from: ServerHandlerStateMachine.Draining) -> Self { return Self(_state: .finished(.init(from: from))) } } } @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) extension ServerHandlerStateMachine.Finished { /// States which can be reached directly from 'Finished'. @usableFromInline internal struct NextState { @usableFromInline let state: ServerHandlerStateMachine.State @inlinable init(_state: ServerHandlerStateMachine.State) { self.state = _state } @inlinable internal static func finished(_ state: ServerHandlerStateMachine.Finished) -> Self { return Self(_state: .finished(state)) } } } #endif // compiler(>=5.6)
apache-2.0
13a74f7673cf5f61ae9ac35a9d8c0c72
31.494475
88
0.716824
4.50517
false
false
false
false
Qminder/swift-api
QminderAPITests/TestHelperExtensions.swift
1
1650
// // TestHelperExtensions.swift // QminderAPITests // // Created by Kristaps Grinbergs on 17/05/2018. // Copyright © 2018 Kristaps Grinbergs. All rights reserved. // import Foundation extension Int { /// Random Int value static var random: Int { return random() } /** Random Int - Parameters: - max: Max value - Returns: Random Int */ static func random(max: Int = 20) -> Int { return Int.random(in: 0...max) } } extension Double { /// Random Double value static var random: Double { return random(min: 10, max: 20) } /** Random Double value from min and max - Parameters: - min: Minimal value - max: Maximal value - Returns: Random Double */ static func random(min: Double, max: Double) -> Double { return Double.random(in: min...max) } } extension String { /// Random String value static var random: String { return UUID().uuidString } } enum DateFormat: String { case withoutMilliseconds = "yyyy-MM-dd'T'HH:mm:ss'Z" case withMilliseconds = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z" } extension Date { /// Random Date (distant future) static var random: Date { return Date.distantFuture } /** Format date with - Parameters: - dateFormat: With or without milliseconds - Returns Formatted date string */ func format(_ dateFormat: DateFormat = .withoutMilliseconds) -> String { let dateFormatter = DateFormatter() dateFormatter.dateFormat = dateFormat.rawValue dateFormatter.timeZone = TimeZone.init(secondsFromGMT: 0) return dateFormatter.string(from: self) } }
mit
94974d433f1adaa38000b64aa4fa38c1
18.174419
74
0.642207
3.916865
false
false
false
false
VoIPGRID/vialer-ios
Vialer/AvailabilityModel.swift
1
11086
// // AvailabilityModel.swift // Vialer // // Created by Chris Kontos on 24/04/2019. // Copyright © 2019 VoIPGRID. All rights reserved. // let AvailabilityModelSelected = "availabilitySelected" let AvailabilityModelDestinationType = "availabilityType" let AvailabilityModelId = "availabilityId" private let AvailabilityModelFixedDestinationsKey = "fixeddestinations" private let AvailabilityModelPhoneaccountsKey = "phoneaccounts" private let AvailabilityModelDescriptionKey = "description" private let AvailabilityModelInternalNumbersKey = "internal_number" private let AvailabilityModelResourceUriKey = "resource_uri" private let AvailabilityModelSelectedUserDestinationKey = "selecteduserdestination" private let AvailabilityModelSelectedUserDestinationPhoneaccountKey = "phoneaccount" private let AvailabilityModelSelectedUserDestinationFixedKey = "fixeddestination" private let AvailabilityModelSelectedUserDestinationIdKey = "id" private let AvailabilityModelFetchInterval: TimeInterval = 5 // number of seconds between fetching of availability @objc class AvailabilityModel: NSObject { @objc var availabilityOptions: NSArray = [] private var availabilityResourceUri = "" lazy private var voipgridRequestOperationManager: VoIPGRIDRequestOperationManager = { let url = URL(string: UrlsConfiguration.shared.apiUrl()) return VoIPGRIDRequestOperationManager(baseURL: url) }() @objc func getUserDestinations(_ completion: @escaping (_ localizedErrorString: String?) -> Void) { voipgridRequestOperationManager.userDestinations(completion: { operation, responseData, error in let localizedStringError = NSLocalizedString("Error getting the availability options", comment: "") if error != nil { completion(localizedStringError) } else { if let unwrappedResponseData = responseData as? [String: Any]{ if let unwrappedResponseDataObjects = unwrappedResponseData["objects"] as? NSArray { if let unwrappedUserDestinations = unwrappedResponseDataObjects[0] as? NSDictionary { self.userDestinations(toArray: unwrappedUserDestinations) completion(nil) } } } } }) } @objc func userDestinations(toArray userDestinations: NSDictionary) { let destinations: NSMutableArray = [] let phoneAccounts = userDestinations[AvailabilityModelPhoneaccountsKey] as? NSArray let fixedDestinations = userDestinations[AvailabilityModelFixedDestinationsKey] as? NSArray let selectedDestination = userDestinations[AvailabilityModelSelectedUserDestinationKey] as? NSDictionary var availabilitySelected = 0 if let phoneAccountDestination = selectedDestination?[AvailabilityModelSelectedUserDestinationPhoneaccountKey], let fixedDestination = selectedDestination?[AvailabilityModelSelectedUserDestinationFixedKey]{ let strPhoneAccountDestination = String(describing:phoneAccountDestination) let strFixedDestination = String(describing:fixedDestination) if (strPhoneAccountDestination.isEmpty || strPhoneAccountDestination == "<null>") && (strFixedDestination.isEmpty || strFixedDestination == "<null>") { availabilitySelected = 1 } } let defaultDict = [SystemUserAvailabilityDescriptionKey: NSLocalizedString("Not available", comment: ""), SystemUserAvailabilityPhoneNumberKey: 0, AvailabilityModelSelected: availabilitySelected] as NSDictionary destinations.add(defaultDict) let unwrappedDestinations = createDestinations(phoneAccounts, withDestinationType: AvailabilityModelSelectedUserDestinationPhoneaccountKey, withSelectedDestination: selectedDestination) if unwrappedDestinations.count > 0 { destinations.addObjects(from: unwrappedDestinations as! [NSDictionary]) } let unwrappedFixedDestinations = createDestinations(fixedDestinations, withDestinationType: AvailabilityModelSelectedUserDestinationFixedKey, withSelectedDestination: selectedDestination) if unwrappedFixedDestinations.count > 0 { destinations.addObjects(from: unwrappedFixedDestinations as! [NSDictionary]) } availabilityOptions = destinations if let unwrappedSelectedDestination = selectedDestination?[AvailabilityModelResourceUriKey] as? String { availabilityResourceUri = unwrappedSelectedDestination } } @objc func createDestinations(_ userDestinations: NSArray?, withDestinationType destinationType: String, withSelectedDestination selectedDestination: NSDictionary?) -> NSArray { var phoneNumber: NSNumber? let destinations: NSMutableArray = [] if let unwrappedUserDestinations = userDestinations { if unwrappedUserDestinations.count != 0 { for userDestination in unwrappedUserDestinations { if let unwrappedUserDestination = userDestination as? NSDictionary { var availabilitySelected = 0 if (destinationType == AvailabilityModelSelectedUserDestinationFixedKey) { let numberFormatter = NumberFormatter() phoneNumber = numberFormatter.number(from: unwrappedUserDestination[SystemUserAvailabilityPhoneNumberKey] as? String ?? "") } else { phoneNumber = unwrappedUserDestination[AvailabilityModelInternalNumbersKey] as? NSNumber } if let unwrappedSelectedDestination = selectedDestination { // Cast both values to strings. Because of old api code that sent an id as a number and the other as a string. let availabilityDestinationId = String("\(unwrappedUserDestination[AvailabilityModelSelectedUserDestinationIdKey] ?? "")") let selectedDestinationTypeInt = unwrappedSelectedDestination[destinationType] let selectedDestinationType = String("\(selectedDestinationTypeInt ?? "")") if (availabilityDestinationId == selectedDestinationType) { availabilitySelected = 1 if let unwrappedAvailabilityModelDescription = unwrappedUserDestination[AvailabilityModelDescriptionKey]{ SystemUser.current().storeNewAvailability(inSUD: [ SystemUserAvailabilityPhoneNumberKey: phoneNumber as Any, SystemUserAvailabilityDescriptionKey: unwrappedAvailabilityModelDescription ]) } } } let destination = [ AvailabilityModelId: unwrappedUserDestination[AvailabilityModelSelectedUserDestinationIdKey], SystemUserAvailabilityDescriptionKey: unwrappedUserDestination[AvailabilityModelDescriptionKey], SystemUserAvailabilityPhoneNumberKey: phoneNumber, AvailabilityModelSelected: availabilitySelected, AvailabilityModelDestinationType: destinationType ] destinations.add(destination) } } } } return destinations } @objc func saveUserDestination(_ index: Int, withCompletion completion: @escaping (_ localizedErrorString: String?) -> Void) { let selectedDict = availabilityOptions[index] as? NSDictionary var phoneaccount = "" var fixedDestination = "" if (selectedDict?[AvailabilityModelDestinationType] as? String == AvailabilityModelSelectedUserDestinationPhoneaccountKey) { phoneaccount = selectedDict?[AvailabilityModelId] as? String ?? "" } else if (selectedDict?[AvailabilityModelDestinationType] as? String == AvailabilityModelSelectedUserDestinationFixedKey) { fixedDestination = selectedDict?[AvailabilityModelId] as? String ?? "" } let saveDict = [ AvailabilityModelSelectedUserDestinationPhoneaccountKey: phoneaccount, AvailabilityModelSelectedUserDestinationFixedKey: fixedDestination ] voipgridRequestOperationManager.pushSelectedUserDestination(availabilityResourceUri, destinationDict: saveDict, withCompletion: { operation, responseData, error in if error != nil { let error = NSLocalizedString("Saving availability has failed", comment: "") completion(error) } SystemUser.current().storeNewAvailability(inSUD: selectedDict as? [AnyHashable : Any]) completion(nil) }) } @objc func getCurrentAvailability(withBlock completionBlock: @escaping (_ currentAvailability: String?, _ localizedError: String?) -> Void) { let currentAvailability = SystemUser.current().currentAvailability // Check no availability or outdated. if ((currentAvailability?[SystemUserAvailabilityLastFetchKey]) == nil) || abs(Float((currentAvailability?[SystemUserAvailabilityLastFetchKey] as? Date)?.timeIntervalSinceNow ?? 0.0)) > Float(AvailabilityModelFetchInterval) { // Fetch new info. getUserDestinations({ localizedErrorString in if localizedErrorString != nil { completionBlock(nil, localizedErrorString) } if let unwrappedAvailabilityOptions = self.availabilityOptions as? [NSDictionary] { for option: NSDictionary? in unwrappedAvailabilityOptions { // Find current selected. if (option?[AvailabilityModelSelected] as? Int == 1) { //Create string and update SUD. let newAvailabilityString = SystemUser.current().storeNewAvailability(inSUD: option as? [AnyHashable : Any]) // Return new string. completionBlock(newAvailabilityString, nil) break } } } }) } else { // Return existing key. if let currentAvailabilityKeyString = currentAvailability?[SystemUserAvailabilityAvailabilityKey] as? String { completionBlock(currentAvailabilityKeyString, nil) } } } }
gpl-3.0
baf2a0fb59db1c1a66468305115a023c
56.734375
232
0.64673
6.356078
false
false
false
false
vimeo/VimeoNetworking
Sources/Shared/Models/GCS.swift
1
2114
// // GCS.swift // Vimeo // // Created by Nguyen, Van on 11/8/18. // Copyright © 2018 Vimeo. 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. // public class GCS: VIMModelObject { public enum Connection: String { case uploadAttempt = "upload_attempt" } @objc public private(set) var startByte: NSNumber? @objc public private(set) var endByte: NSNumber? @objc public private(set) var uploadLink: String? @objc internal private(set) var metadata: [String: Any]? public private(set) var connections = [Connection: VIMConnection]() override public func didFinishMapping() { guard let metadata = self.metadata, let connections = metadata["connections"] as? [String: Any] else { return } let uploadAttemptDict = connections[Connection.uploadAttempt.rawValue] as? [String: Any] let uploadAttemptConnection = VIMConnection(keyValueDictionary: uploadAttemptDict) self.connections[.uploadAttempt] = uploadAttemptConnection } }
mit
1f9430cdb755c1365be7607fc0a7ff3b
42.122449
110
0.71415
4.411273
false
false
false
false
cbguder/CBGPromise
Examples/Mapping.swift
1
966
// You can map and chain promises using the map() and futureMap() functions: import CBGPromise class Client { func getIntegerValue() -> Future<Int> { let promise = Promise<Int>() otherAsyncCall { promise.resolve(42) } return promise.future } func getArrayValue(_ int: Int) -> Future<[String]> { let promise = Promise<[String]>() someAsyncCall(int) { promise.resolve(["Test 1", "Test 2"]) } return promise.future } } class MappingExample { func main() { let client = Client() let integerFuture = client.getIntegerValue() let arrayFuture = integerFuture.map { int -> Future<[String]> in return client.getArrayValue(int) } let stringFuture = arrayFuture.map { arr -> String? in return arr.first } stringFuture.then { value in print(value) } } }
mit
b11147c58d2eff0d5d9d0b4df984d387
20.466667
76
0.557971
4.451613
false
false
false
false
miDrive/MDAlert
MDAlert/Classes/MDAlertView.swift
1
4006
// // MDAlertView.swift // Pods // // Created by Chris Byatt on 27/07/2016. // // import UIKit class MDAlertView: UIViewController { var controller: MDAlertController! var image: UIImage? var titleMessage: String! var bodyMessage: String! var customView: UIView? var showsCancel: Bool! var actions = [MDAlertAction]() @IBOutlet var viewInsets: [NSLayoutConstraint]! { didSet { if UIScreen.main.bounds.size.width <= 320 { viewInsets.forEach { constraint in constraint.constant = 10 } } } } @IBOutlet var viewMidConstraint: NSLayoutConstraint? @IBOutlet var imageView: UIImageView! @IBOutlet var imageViewHeightConstraint: NSLayoutConstraint! @IBOutlet private var titleLabel: UILabel! @IBOutlet private var bodyLabel: UILabel! @IBOutlet var customViewHolder: UIView! @IBOutlet var alertView: UIView! @IBOutlet var spacerView: UIView! @IBOutlet private var bodyView: UIView! @IBOutlet var bodyStackView: UIStackView! @IBOutlet var buttonView: UIStackView! @IBOutlet var buttonSpacerView: UIView! @IBOutlet var cancelButton: UIButton! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. setup() setStyles() } func setup() { self.alertView.alpha = 0.0 titleLabel.text = titleMessage bodyLabel.text = bodyMessage cancelButton.isHidden = !showsCancel if let image = image { imageView.isHidden = false imageView.image = image imageViewHeightConstraint.constant = image.size.height + 60 spacerView.isHidden = true } if let customView = customView { customViewHolder.isHidden = false customView.translatesAutoresizingMaskIntoConstraints = false customViewHolder.addSubview(customView) customViewHolder.addConstraint(customView.topAnchor.constraint(equalTo: customViewHolder.topAnchor)) customViewHolder.addConstraint(customView.leftAnchor.constraint(equalTo: customViewHolder.leftAnchor)) customViewHolder.addConstraint(customView.bottomAnchor.constraint(equalTo: customViewHolder.bottomAnchor)) customViewHolder.addConstraint(customView.rightAnchor.constraint(equalTo: customViewHolder.rightAnchor)) } if bodyMessage == nil { bodyLabel.isHidden = true } for action in actions { if customView == nil { buttonSpacerView.isHidden = true } buttonView.isHidden = false buttonSpacerView.isHidden = false buttonView.addArrangedSubview(action.button) } if actions.count > 1 { bodyStackView.spacing = 0.0 } } func setStyles() { bodyView.layer.cornerRadius = controller.alertCornerRadius bodyView.backgroundColor = controller.alertBackgroundColour titleLabel.font = controller.titleFont titleLabel.textColor = controller.titleColour bodyLabel.font = controller.bodyFont bodyLabel.textColor = controller.bodyColour cancelButton.titleLabel!.font = controller.bodyFont buttonView.addConstraint(NSLayoutConstraint(item: self.buttonView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: (CGFloat(actions.count) * controller.actionHeight) + CGFloat((actions.count - 1) * 1))) } @IBAction func pressedCancel(_ sender: UIButton) { controller.dismiss(nil) } } extension Collection { /// Returns the element at the specified index iff it is within bounds, otherwise nil. public subscript(safe index: Index) -> Element? { return index >= startIndex && index < endIndex ? self[index] : nil } }
mit
ce042613c8fb58c667fb5fb790469b51
29.580153
269
0.654518
5.175711
false
false
false
false
KimpossibleG/billfold
BillFoldApp/BillFold/BillFold/AppDelegate.swift
1
2515
// // AppDelegate.swift // BillFold // // Created by Michael Pourhadi on 7/3/14. // Copyright (c) 2014 Michael Pourhadi. All rights reserved. // import UIKit let black = UIColor.blackColor() let lightColor: UIColor = UIColor(red: 1, green: 0.212, blue: 0, alpha: 1) let translucentOrange: UIColor = UIColor(red: 1, green: 0.212, blue: 0, alpha: 0.1) let lightBlue = UIColor(red: 0.698, green: 0.831, blue: 0.863, alpha: 1) let darkBlue = UIColor(red: 0.165, green: 0.227, blue: 0.282, alpha: 1) @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow! func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool { application.statusBarStyle = UIStatusBarStyle.LightContent return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
mit
f5a47857c289e7cb35d1d1516de17448
47.365385
285
0.736779
4.921722
false
false
false
false
bustoutsolutions/siesta
Source/Siesta/Pipeline/ResponseTransformer.swift
1
11667
// // ResponseTransformer.swift // Siesta // // Created by Paul on 2015/7/8. // Copyright © 2016 Bust Out Solutions. All rights reserved. // import Foundation #if os(macOS) import AppKit /// A cross-platform alias for the output type of Siesta’s image content transformer. /// `UIImage` on iOS; `NSImage` on macOS. public typealias Image = NSImage #elseif os(iOS) || os(tvOS) || os(watchOS) import UIKit /// A cross-platform alias for the output type of Siesta’s image content transformer. /// `UIImage` on iOS; `NSImage` on macOS. public typealias Image = UIImage #endif /** Transforms a response from a less parsed form (e.g. `Data`) to a more parsed data structure. Responses pass through a chain of transformers before being sent to response hooks or observers. - Warning: Transformers run in a GCD background queue, and **must be thread-safe**. You’re in the clear if your transformer touches only its input parameters, and those parameters are value types or otherwise exclusively owned. */ public protocol ResponseTransformer: CustomDebugStringConvertible { /** Returns the parsed form of this response, or returns it unchanged if this transformer does not apply. Note that a `Response` can contain either data or an error, so this method can turn success into failure if the response fails to parse. */ func process(_ response: Response) -> Response } extension ResponseTransformer { /// Prints the name of the transformer’s Swift type. public var debugDescription: String { String(describing: type(of: self)) } /// Helper to log a transformation. Call this in your custom transformer. public func logTransformation(_ result: Response) -> Response { SiestaLog.log(.pipeline, [" ├╴Applied transformer:", self, "\n │ ↳", result.summary()]) return result } } // MARK: Wrapper types internal struct ContentTypeMatchTransformer: ResponseTransformer { let contentTypes: [String] // for logging let contentTypeMatcher: NSRegularExpression let delegate: ResponseTransformer init(_ delegate: ResponseTransformer, contentTypes: [String]) { self.delegate = delegate self.contentTypes = contentTypes let contentTypeRegexps = contentTypes.map { NSRegularExpression.escapedPattern(for: $0) .replacingOccurrences(of: "\\*", with:"[^/+]+") } let pattern = "^" + contentTypeRegexps.joined(separator: "|") + "($|;)" self.contentTypeMatcher = try! NSRegularExpression(pattern: pattern) } func process(_ response: Response) -> Response { let contentType: String? switch response { case .success(let entity): contentType = entity.contentType case .failure(let error): contentType = error.entity?.contentType } if let contentType = contentType, contentTypeMatcher.matches(contentType) { SiestaLog.log(.pipeline, [" ├╴Transformer", self, "matches content type", debugStr(contentType)]) return delegate.process(response) } else { return response } } var debugDescription: String { "⟨\(contentTypes.joined(separator: " "))⟩ \(delegate)" } } /** A simplified `ResponseTransformer` that deals only with the content of the response entity, and does not touch the surrounding metadata. If `processEntity(_:)` throws or returns nil, the output is an error. If the input entity’s content does not match the `InputContentType`, the response is an error. */ public struct ResponseContentTransformer<InputContentType, OutputContentType>: ResponseTransformer { /** Action to take when actual input type at runtime does not match expected input type declared in code. - See: `ResponseContentTransformer.init(...)` - See: `Service.configureTransformer(...)` */ public enum InputTypeMismatchAction { /// Output `RequestError.Cause.WrongInputTypeInTranformerPipeline`. case error /// Pass the input response through unmodified. case skip /// Pass the input response through unmodified if it matches the output type; otherwise output an error. case skipIfOutputTypeMatches } /** A closure that both processes the content and describes the required input and output types. The input will be an `Entity` whose `content` is safely cast to the type expected by the closure. If the response content is not castable to `InputContentType`, then the pipeline skips the closure and replaces the resopnse with a `RequestError` describing the type mismatch. The closure can throw an error to indicate that parsing failed. If it throws a `RequestError`, that error is passed on to the resource as is. Other failures are wrapped in a `RequestError`. */ public typealias Processor = (Entity<InputContentType>) throws -> OutputContentType? private let processor: Processor private let mismatchAction: InputTypeMismatchAction private let transformErrors: Bool /** - Parameter mismatchAction: Determines what happens when the actual content coming down the pipeline doesn’t match `InputContentType`. See `InputTypeMismatchAction` for options. The default is `.error`. - Parameter transformErrors: When true, apply the transformation to `RequestError.content` (if present). When false, only parse success responses. Default is false. - Parameter processor: The transformation logic. */ public init( onInputTypeMismatch mismatchAction: InputTypeMismatchAction = .error, transformErrors: Bool = false, processor: @escaping Processor) { self.mismatchAction = mismatchAction self.transformErrors = transformErrors self.processor = processor } /// :nodoc: public func process(_ response: Response) -> Response { switch response { case .success(let entity): return processEntity(entity) case .failure(let error): return processError(error) } } private func processEntity(_ entity: Entity<Any>) -> Response { guard let typedEntity = entity.withContentRetyped() as Entity<InputContentType>? else { switch mismatchAction { case .skip, .skipIfOutputTypeMatches where entity.content is OutputContentType: SiestaLog.log(.pipeline, [self, "skipping transformer because its mismatch rule is", mismatchAction, ", and it expected content of type", InputContentType.self, "but got a", type(of: entity.content)]) return .success(entity) case .error, .skipIfOutputTypeMatches: return logTransformation(contentTypeMismatchError(entity)) } } do { guard let result = try processor(typedEntity) else { throw RequestError.Cause.TransformerReturnedNil(transformer: self) } var entity = entity entity.content = result return logTransformation(.success(entity)) } catch { let siestaError = error as? RequestError ?? RequestError( userMessage: NSLocalizedString("Cannot parse server response", comment: "userMessage"), cause: error) return logTransformation(.failure(siestaError)) } } private func contentTypeMismatchError(_ entityFromUpstream: Entity<Any>) -> Response { .failure(RequestError( userMessage: NSLocalizedString("Cannot parse server response", comment: "userMessage"), cause: RequestError.Cause.WrongInputTypeInTranformerPipeline( expectedType: InputContentType.self, actualType: type(of: entityFromUpstream.content), transformer: self))) } private func processError(_ error: RequestError) -> Response { if transformErrors, let errorData = error.entity { switch processEntity(errorData) { case .success(let errorDataTransformed): var error = error error.entity = errorDataTransformed return logTransformation(.failure(error)) case .failure(let error): SiestaLog.log(.pipeline, ["Unable to parse error response body; will leave error body unprocessed:", error]) } } return .failure(error) } public var debugDescription: String { var result = "\(InputContentType.self) → \(OutputContentType.self)" var options: [String] = [] if mismatchAction != .error { options.append("mismatchAction: \(mismatchAction)") } if transformErrors { options.append("transformErrors: \(transformErrors)") } if !options.isEmpty { result += " [\(options.joined(separator: ", "))]" } return result } } // MARK: Transformers for standard types // swiftlint:disable identifier_name /// Parses `Data` content as text, using the encoding specified in the content type, or ISO-8859-1 by default. public func TextResponseTransformer(_ transformErrors: Bool = true) -> ResponseTransformer { ResponseContentTransformer<Data, String>(transformErrors: transformErrors) { let charsetName = $0.charset ?? "ISO-8859-1" let encodingID = CFStringConvertEncodingToNSStringEncoding( CFStringConvertIANACharSetNameToEncoding(charsetName as CFString)) guard encodingID != UInt(kCFStringEncodingInvalidId) else { throw RequestError.Cause.InvalidTextEncoding(encodingName: charsetName) } let encoding = String.Encoding(rawValue: encodingID) guard let string = String(data: $0.content, encoding: encoding) else { throw RequestError.Cause.UndecodableText(encoding: encoding) } return string } } /// Parses `Data` content as JSON using JSONSerialization, outputting either a dictionary or an array. public func JSONResponseTransformer(_ transformErrors: Bool = true) -> ResponseTransformer { ResponseContentTransformer<Data, JSONConvertible>(transformErrors: transformErrors) { let rawObj = try JSONSerialization.jsonObject(with: $0.content, options: [.allowFragments]) guard let jsonObj = rawObj as? JSONConvertible else { throw RequestError.Cause.JSONResponseIsNotDictionaryOrArray(actualType: type(of: rawObj)) } return jsonObj } } /// Parses `Data` content as an image, yielding a `UIImage`. public func ImageResponseTransformer(_ transformErrors: Bool = false) -> ResponseTransformer { ResponseContentTransformer<Data, Image>(transformErrors: transformErrors) { guard let image = Image(data: $0.content) else { throw RequestError.Cause.UnparsableImage() } return image } } // swiftlint:enable identifier_name
mit
f053b5fcb44d70093b0e7eab74080dc8
35.476489
220
0.638536
5.208594
false
false
false
false
calkinssean/TIY-Assignments
Day 39/matchbox20FanClub/matchbox20FanClub/TimeSlotsTableViewController.swift
1
4604
// // TimeSlotsTableViewController.swift // matchbox20FanClub // // Created by Sean Calkins on 3/25/16. // Copyright © 2016 Sean Calkins. All rights reserved. // import UIKit import Firebase class TimeSlotsTableViewController: UITableViewController { var formatter = NSDateFormatter() var timeInterval: NSTimeInterval = 0 var currentEvent = Event() var arrayOfTimeSlots = [TimeSlot]() var currentEventRef = Firebase(url: "https://matchbox20fanclub.firebaseio.com/events/") var timeSlotRef = Firebase(url: "https://matchbox20fanclub.firebaseio.com/timeslot/") override func viewDidLoad() { super.viewDidLoad() observeTimeSlots() print(currentEvent.hasSeededTimeSlots) self.title = "\(currentEvent.name)" timeInterval = currentEvent.startDate.timeIntervalSince1970 currentEventRef = Firebase(url: "https://matchbox20fanclub.firebaseio.com/events/\(currentEvent.key)") formatter.dateFormat = "MMM/dd/yyyy hh:mm" self.seedTimeSlots() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view delegate override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let timeSlot = arrayOfTimeSlots[indexPath.row] timeSlot.ref?.updateChildValues([ "taken": !timeSlot.taken ]) } // MARK: - Table view data source override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return arrayOfTimeSlots.count } // MARK: - Setting up cell override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("SlotCell", forIndexPath: indexPath) as! SlotTableViewCell let t = arrayOfTimeSlots[indexPath.row] cell.slotNameLabel.text = t.name if !t.taken { cell.accessoryType = UITableViewCellAccessoryType.None cell.backgroundColor = UIColor.greenColor() } else { cell.accessoryType = UITableViewCellAccessoryType.Checkmark cell.backgroundColor = UIColor.redColor() cell.textLabel?.backgroundColor = UIColor.redColor() } return cell } func seedTimeSlots() { if self.currentEvent.hasSeededTimeSlots == false { if timeInterval < currentEvent.endDate.timeIntervalSince1970 { let time = NSDate(timeIntervalSince1970: timeInterval) let date = formatter.stringFromDate(time) print("This is the date: \(date)") timeInterval = timeInterval + 900 let slot = TimeSlot() slot.name = date slot.eventKey = self.currentEvent.key slot.saveTimeslot() seedTimeSlots() } else { currentEventRef.updateChildValues(["hasSeededTimeSlots": true]) } } } func observeTimeSlots() { // Add observer for Events self.timeSlotRef.observeEventType(.Value, withBlock: { snapshot in print(snapshot.value) self.arrayOfTimeSlots.removeAll() if let snapshots = snapshot.children.allObjects as? [FDataSnapshot] { for snap in snapshots { if let dict = snap.value as? [String: AnyObject] { let key = snap.key let slot = TimeSlot(key: key, dict: dict) if slot.eventKey == self.currentEvent.key { slot.ref = Firebase(url: "https://matchbox20fanclub.firebaseio.com/timeslot/\(key)") self.arrayOfTimeSlots.append(slot) self.tableView.reloadData() } } } } }) } }
cc0-1.0
ee4c2c708f4a35acc613c85fd946f997
31.878571
121
0.552466
5.725124
false
false
false
false
ankyhe/SwiftLogger
SwiftLogger/SwiftLogger.swift
1
2410
// // SwiftLogger.swift // SwiftLogger // // Created by AnkyHe on 3/3/15. // import Foundation enum LoggerLevel : Int { case TINY = 10 case DETAIL = 20 case ENTER = 30 case RETURN = 31 case DEBUG = 40 case INFO = 50 case WARN = 60 case ERROR = 70 case TRACE0 = 75 case FATAL = 80 } enum LoggerLevelSetting : Int { case ALL = 0 case MINOR = 45 case MAJOR = 65 case NONE = 1000 } class SwiftLogger { var loggerLevelSetting = LoggerLevelSetting.MAJOR //MARK: - Singleton class var sharedInstance: SwiftLogger { struct Static { static let instance: SwiftLogger = SwiftLogger() } return Static.instance } /* END Singletone */ //MARK: - Log methods func enter(message: String) { log(.ENTER, message: message) } func rtn(message: String) { log(.RETURN, message: message) } func dbg(message: String) { log(.DEBUG, message: message) } func info(message: String) { log(.INFO, message: message) } func warn(message: String) { log(.WARN, message: message) } func error(message: String) { log(.ERROR, message: message) } func trace0(message: String) { log(.TRACE0, message: message) } func log(loggerLevel: LoggerLevel, message: String) { if (loggerLevel.rawValue > loggerLevelSetting.rawValue) { println("TID:\(self.dynamicType.threadString()) FILE:\(__FILE__.lastPathComponent) LINE:\(__LINE__) [\(self.dynamicType.loggerLevelString(loggerLevel))] \(message)") } } //MARK: - Help Methods private class func loggerLevelString(loggerLevel:LoggerLevel) -> String { switch loggerLevel { case .TINY: return "TINY" case .DETAIL : return "DETAIL" case .ENTER: return "ENTER" case .RETURN: return "RETURN" case .DEBUG: return "DEBUG" case .INFO: return "INFO" case .WARN: return "WARN" case .ERROR: return "ERROR" case .TRACE0: return "TRACE0" case .FATAL: return "FATAL" } } private class func threadString() -> String { if NSThread.currentThread().isMainThread { return "main" } return "\(NSThread.currentThread())" } }
mit
0a859cf0092053ce1c278c29fb086f59
21.952381
177
0.570124
4.091681
false
false
false
false
jverdi/Gramophone
Example/GramophoneExample/GramophoneExample/ViewController.swift
1
6359
// // Gramophone.swift // Gramophone // // Copyright (c) 2017 Jared Verdi. All Rights Reserved // // Icon created by Gan Khoon Lay from the Noun Project // // 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 Gramophone let CLIENT_ID = "{YOUR_INSTAGRAM_CLIENT_ID}" let REDIRECT_URI = "{YOUR_INSTAGRAM_REDIRECT_URI}" class ViewController: UITableViewController { private var gramophone: Gramophone! private var tableItems: [Media] private var isLoggedIn = false { didSet { updateLoginButton() loadData() } } override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { self.tableItems = [] super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) assert(CLIENT_ID != "{YOUR_INSTAGRAM_CLIENT_ID}" && REDIRECT_URI != "{YOUR_INSTAGRAM_REDIRECT_URI}", "Replace CLIENT_ID and REDIRECT_URI placeholders with your credentials from https://www.instagram.com/developer/clients/manage/ to run the demo.") setupGramophone() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() title = "Gramophone" view.backgroundColor = UIColor.white navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Login", style: .plain, target: self, action: #selector(didTapToggleLogin)) tableView.register(UITableViewCell.self, forCellReuseIdentifier: "MediaCell") tableView.delegate = self tableView.dataSource = self } // MARK: - Setup func setupGramophone() { let configuration = ClientConfiguration( clientID: CLIENT_ID, redirectURI: REDIRECT_URI, scopes: [.basic, .publicContent, .comments, .followerList, .likes, .relationships] ) gramophone = Gramophone(configuration: configuration) } // MARK: - Actions func login() { gramophone.client.authenticate(from: self) { [weak self] result in guard let strongSelf = self else { return } switch result { case .success(let response): let accessToken = response.data print("Authenticated - access token: \(accessToken)") strongSelf.isLoggedIn = true case .failure(let error): print("Failed to authenticate: \(error.localizedDescription)") } } } func logout() { gramophone.client.logout() } func loadData() { gramophone.client.myRecentMedia(options: nil) { [weak self] mediaResult in guard let strongSelf = self else { return } switch mediaResult { case .success(let response): let mediaItems = response.data.items for media in mediaItems { if let images = media.images, let rendition = images[.thumbnail] { print("Media [ID: \(media.ID), \(rendition.url)]") } } strongSelf.tableItems = mediaItems strongSelf.tableView.reloadData() case .failure(let error): print("Failed to load media: \(error.localizedDescription)") } } } // MARK: - Login button func didTapToggleLogin() { if isLoggedIn { logout() } else { login() } } func updateLoginButton() { guard let leftBarButtonItem = navigationItem.leftBarButtonItem else { return } leftBarButtonItem.title = isLoggedIn ? "Logout" : "Login" } // MARK: - UITableViewDataSource override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return tableItems.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "MediaCell", for: indexPath) let mediaItem = tableItems[indexPath.row] cell.textLabel!.text = mediaItem.caption?.text cell.imageView!.image = nil if let images = mediaItem.images, let rendition = images[.thumbnail] { DispatchQueue.global().async { do { let data = try Data(contentsOf: rendition.url) DispatchQueue.main.async { cell.imageView!.image = UIImage(data: data) cell.setNeedsLayout() } } catch {} } } return cell } // MARK: - UITableViewDelegate override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let mediaItem = tableItems[indexPath.row] let mediaViewController = DetailViewController(mediaItem: mediaItem, gramophone: gramophone) navigationController?.pushViewController(mediaViewController, animated: true) } }
mit
9b005f5122cc2ecd9611b21654c28216
34.52514
161
0.6078
5.178339
false
false
false
false
urbanthings/urbanthings-sdk-apple
UrbanThingsAPI/Public/Request/TransitRoutesByImportSourceRequest.swift
1
2305
// // TransitRoutesByImportSourceRequest.swift // UrbanThingsAPI // // Created by Mark Woollard on 28/04/2016. // Copyright © 2016 UrbanThings. All rights reserved. // import Foundation /// Defines the source for transit route request public enum TransitRoutesImportSource { /// Specified using an agency ID case AgencyID(String) /// Specified by import source case ImportSource(String) } /// Defines a request for a transit route information. public protocol TransitRoutesByImportSourceRequest: GetRequest { associatedtype Result = [TransitDetailedRouteInfo] /// Source for transit routes var source: TransitRoutesImportSource { get } } /// Default implementation of `TransitRoutesByImportSourceRequest` protocol provided by the API as standard means /// of passing parameters to API request methods. You may provide your own implementation if needed to pass to the API /// request methods. public struct UTTransitRoutesByImportSourceRequest: TransitRoutesByImportSourceRequest { public typealias Result = [TransitDetailedRouteInfo] public typealias Parser = (_ json: Any?, _ logger: Logger) throws -> Result public let endpoint = "static/routes/info/Source" /// Source for transit routes public let source: TransitRoutesImportSource /// Parser to use when processing response to the request public let parser: Parser /// Initialize an instance of `UTTransitRoutesByImportSourceRequest` /// - parameters: /// - agencyID: The agency ID for the transit agency to fetch data for. /// - parser: Optional custom parser to process the response from the server. If omitted standard parser will be used. public init(agencyID: String, parser: @escaping Parser = urbanThingsParser) { self.parser = parser self.source = .AgencyID(agencyID) } /// Initialize an instance of `UTTransitRoutesByImportSourceRequest` /// - parameters: /// - importSource: The import source to fetch data for. /// - parser: Optional custom parser to process the response from the server. If omitted standard parser will be used. public init(importSource: String, parser: @escaping Parser = urbanThingsParser) { self.parser = parser self.source = .ImportSource(importSource) } }
apache-2.0
92ad2f5af48d0a2360f34ddd7b37d9cc
36.770492
124
0.731337
4.654545
false
false
false
false
corichmond/turbo-adventure
project18/Project18/ViewController.swift
20
1200
// // ViewController.swift // Project18 // // Created by Hudzilla on 23/11/2014. // Copyright (c) 2014 Hudzilla. All rights reserved. // import iAd import UIKit class ViewController: UIViewController, ADBannerViewDelegate { var bannerView: ADBannerView! override func viewDidLoad() { super.viewDidLoad() bannerView = ADBannerView(adType: .Banner) bannerView.setTranslatesAutoresizingMaskIntoConstraints(false) bannerView.delegate = self bannerView.hidden = true view.addSubview(bannerView) let viewsDictionary = ["bannerView": bannerView] view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[bannerView]|", options: .allZeros, metrics: nil, views: viewsDictionary)) view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[bannerView]|", options: .allZeros, metrics: nil, views: viewsDictionary)) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func bannerViewDidLoadAd(banner: ADBannerView!) { bannerView.hidden = false } func bannerView(banner: ADBannerView!, didFailToReceiveAdWithError error: NSError!) { bannerView.hidden = true } }
unlicense
a09060918da9d3097abf0be24f386284
27.571429
147
0.769167
4.411765
false
false
false
false
Coderian/SwiftedKML
SwiftedKML/Elements/IconStyle.swift
1
3380
// // IconStyle.swift // SwiftedKML // // Created by 佐々木 均 on 2016/02/02. // Copyright © 2016年 S-Parts. All rights reserved. // import Foundation /// KML IconStyle /// /// [KML 2.2 shcema](http://schemas.opengis.net/kml/2.2.0/ogckml22.xsd) /// /// <element name="IconStyle" type="kml:IconStyleType" substitutionGroup="kml:AbstractColorStyleGroup"/> public class IconStyle :SPXMLElement, AbstractColorStyleGroup, HasXMLElementValue { public static var elementName: String = "IconStyle" public override var parent:SPXMLElement! { didSet { // 複数回呼ばれたて同じものがある場合は追加しない if self.parent.childs.contains(self) == false { self.parent.childs.insert(self) switch parent { case let v as Style: v.value.iconStyle = self default: break } } } } public var value : IconStyleType public required init(attributes:[String:String]){ self.value = IconStyleType(attributes: attributes) super.init(attributes: attributes) } public var abstractObject : AbstractObjectType { return self.value } public var abstractSubStyle : AbstractSubStyleType { return self.value } public var abstractColorStyle : AbstractColorStyleType { return self.value } } /// KML IconStyleType /// /// [KML 2.2 shcema](http://schemas.opengis.net/kml/2.2.0/ogckml22.xsd) /// /// <complexType name="IconStyleType" final="#all"> /// <complexContent> /// <extension base="kml:AbstractColorStyleType"> /// <sequence> /// <element ref="kml:scale" minOccurs="0"/> /// <element ref="kml:heading" minOccurs="0"/> /// <element name="Icon" type="kml:BasicLinkType" minOccurs="0"/> /// <element ref="kml:hotSpot" minOccurs="0"/> /// <element ref="kml:IconStyleSimpleExtensionGroup" minOccurs="0" maxOccurs="unbounded"/> /// <element ref="kml:IconStyleObjectExtensionGroup" minOccurs="0" maxOccurs="unbounded"/> /// </sequence> /// </extension> /// </complexContent> /// </complexType> /// <element name="IconStyleSimpleExtensionGroup" abstract="true" type="anySimpleType"/> /// <element name="IconStyleObjectExtensionGroup" abstract="true" substitutionGroup="kml:AbstractObjectGroup"/> public class IconStyleType: AbstractColorStyleType { public var scale : Scale! // = 0.0 public var heading: Heading! // = 0.0 /// Iconが複数あるのでStyleIconとしている public class Icon :SPXMLElement, HasXMLElementValue { public static var elementName:String = "Icon" public override var parent:SPXMLElement! { didSet { // 複数回呼ばれたて同じものがある場合は追加しない if self.parent.childs.contains(self) == false { self.parent.childs.insert(self) switch parent { case let v as IconStyle: v.value.icon = self default:break } } } } public var value: BasicLinkType = BasicLinkType() } public var icon: Icon! public var hotSpot: HotSpot! public var iconStyleSimpleExtensionGroup: [AnyObject] = [] public var iconStyleObjectExtensionGroup: [AbstractObjectGroup] = [] }
mit
82bb62bffa5d9141d452be7b3c3dd13a
38.192771
115
0.632954
4.107323
false
false
false
false
fs/Social-iOS
SocialNetworks/Source/Facebook/SocialFacebook.swift
1
1682
import UIKit //MARK: - public final class FacebookNetwork: NSObject { public static var permissions: [String] = ["publish_actions"] public class var shared: FacebookNetwork { struct Static { static var instance: FacebookNetwork? static var token: dispatch_once_t = 0 } dispatch_once(&Static.token) { Static.instance = FacebookNetwork() } return Static.instance! } private override init() { super.init() } } //MARK: - extension FacebookNetwork: SocialNetwork { public class var name: String { return "Facebook" } public class var isAuthorized: Bool { return FBSDKAccessToken.currentAccessToken() != nil } public class func authorization(completion: SocialNetworkSignInCompletionHandler?) { if self.isAuthorized == true { completion?(success: true, error: nil) } else { self.openNewSession(completion) } } public class func logout(completion: SocialNetworkSignOutCompletionHandler?) { if self.isAuthorized == true { FBSDKLoginManager().logOut() } completion?() } private class func openNewSession(completion: SocialNetworkSignInCompletionHandler?) { let manager = FBSDKLoginManager.init() manager.logInWithPublishPermissions(FacebookNetwork.permissions, fromViewController: nil) { (result: FBSDKLoginManagerLoginResult!, error: NSError!) -> Void in completion?(success: result.isCancelled == false && error == nil, error: error) } } }
mit
090742afb9a70fac1d33ab6841be5bce
27.508475
167
0.615933
5.322785
false
false
false
false
jshultz/ios9-swift2-multiplication-table
times table app/ViewController.swift
1
1789
// // ViewController.swift // times table app // // Created by Jason Shultz on 9/24/15. // Copyright © 2015 HashRocket. All rights reserved. // import UIKit class ViewController: UIViewController, UITableViewDelegate { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } @IBOutlet weak var table: UITableView! var cellContent = [0] @IBOutlet weak var sliderValue: UISlider! @IBOutlet weak var multiplyLabel: UILabel! @IBAction func sliderMoved(sender: AnyObject) { print(sliderValue) cellContent = [0] let factor = Int(sliderValue.value) // convert Float to Int to shave off decimal multiplyLabel.text = "Multiplying by \(factor)" var x = 1 while (x <= 20) { cellContent.append(factor * x) x++ } table.reloadData() } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return cellContent.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let factor = Int(sliderValue.value) // convert Float to Int to shave off decimal let cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "Cell") let rowText = "\(indexPath.row) times \(factor) equals \(String(cellContent[indexPath.row]))" cell.textLabel?.text = rowText return cell } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
faa87a2c2647aa5426b36e7b0fe8045a
25.686567
109
0.619687
5.022472
false
false
false
false
zapdroid/RXWeather
Pods/RxSwift/RxSwift/Observables/Implementations/Buffer.swift
1
3163
// // Buffer.swift // RxSwift // // Created by Krunoslav Zaher on 9/13/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // final class BufferTimeCount<Element>: Producer<[Element]> { fileprivate let _timeSpan: RxTimeInterval fileprivate let _count: Int fileprivate let _scheduler: SchedulerType fileprivate let _source: Observable<Element> init(source: Observable<Element>, timeSpan: RxTimeInterval, count: Int, scheduler: SchedulerType) { _source = source _timeSpan = timeSpan _count = count _scheduler = scheduler } override func run<O: ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == [Element] { let sink = BufferTimeCountSink(parent: self, observer: observer, cancel: cancel) let subscription = sink.run() return (sink: sink, subscription: subscription) } } final class BufferTimeCountSink<Element, O: ObserverType> : Sink<O> , LockOwnerType , ObserverType , SynchronizedOnType where O.E == [Element] { typealias Parent = BufferTimeCount<Element> typealias E = Element private let _parent: Parent let _lock = RecursiveLock() // state private let _timerD = SerialDisposable() private var _buffer = [Element]() private var _windowID = 0 init(parent: Parent, observer: O, cancel: Cancelable) { _parent = parent super.init(observer: observer, cancel: cancel) } func run() -> Disposable { createTimer(_windowID) return Disposables.create(_timerD, _parent._source.subscribe(self)) } func startNewWindowAndSendCurrentOne() { _windowID = _windowID &+ 1 let windowID = _windowID let buffer = _buffer _buffer = [] forwardOn(.next(buffer)) createTimer(windowID) } func on(_ event: Event<E>) { synchronizedOn(event) } func _synchronized_on(_ event: Event<E>) { switch event { case let .next(element): _buffer.append(element) if _buffer.count == _parent._count { startNewWindowAndSendCurrentOne() } case let .error(error): _buffer = [] forwardOn(.error(error)) dispose() case .completed: forwardOn(.next(_buffer)) forwardOn(.completed) dispose() } } func createTimer(_ windowID: Int) { if _timerD.isDisposed { return } if _windowID != windowID { return } let nextTimer = SingleAssignmentDisposable() _timerD.disposable = nextTimer let disposable = _parent._scheduler.scheduleRelative(windowID, dueTime: _parent._timeSpan) { previousWindowID in self._lock.performLocked { if previousWindowID != self._windowID { return } self.startNewWindowAndSendCurrentOne() } return Disposables.create() } nextTimer.setDisposable(disposable) } }
mit
d6179fff72f639ac32c2402a2a36aaef
25.571429
146
0.593612
4.71237
false
false
false
false
BlurredSoftware/BSWInterfaceKit
Sources/BSWInterfaceKit/Behaviour/NavBarTransparentBehavior.swift
1
3259
// // Created by Pierluigi Cifani on 05/01/16. // Copyright © 2018 TheLeftBit SL. All rights reserved. // #if canImport(UIKit) import UIKit public enum NavBarState { case regular, transparent } final public class NavBarTransparentBehavior: NSObject { private static let LimitOffsetTransparentNavBar: CGFloat = 100 private weak var navBar: UINavigationBar! private var observation: NSKeyValueObservation! private var state: NavBarState! private let defaultBackgroundImage: UIImage? private let defaultShadowImage: UIImage? let shouldShowShadow: Bool public init(navBar: UINavigationBar, scrollView: UIScrollView, shouldShowShadow: Bool) { self.defaultBackgroundImage = navBar.backgroundImage(for: .default) self.defaultShadowImage = navBar.shadowImage self.navBar = navBar self.shouldShowShadow = shouldShowShadow super.init() observation = scrollView.observe(\.contentOffset) { [weak self] (scrollView, _) in self?.updateNavBar(forScrollView: scrollView) } updateNavBar(forScrollView: scrollView) } deinit { observation.invalidate() } public func setNavBar(toState state: NavBarState) { guard state != self.state else { return } UIView.setAnimationsEnabled(false) NavBarTransparentBehavior.animate(navBar) let backgroundImage: UIImage? = { switch state { case .regular: return self.defaultBackgroundImage case .transparent: if shouldShowShadow { let size = CGSize(width: 1, height: navBar.frame.maxY) return GradientFactory.transparentGradient(size: size, isHorizontal: false) } else { return UIImage() } } }() let shadowImage: UIImage? = { switch state { case .regular: return self.defaultShadowImage case .transparent: return UIImage() } }() navBar.shadowImage = shadowImage navBar.setBackgroundImage(backgroundImage, for: .default) navBar.isTranslucent = true UIView.setAnimationsEnabled(true) self.state = state } private func updateNavBar(forScrollView scrollView: UIScrollView) { if scrollView.contentOffset.y < NavBarTransparentBehavior.LimitOffsetTransparentNavBar { setNavBar(toState: .transparent) } else { setNavBar(toState: .regular) } } private static func animate(_ navBar: UINavigationBar) { let transition = CATransition() transition.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeOut) transition.type = CATransitionType.fade transition.duration = 0.3 transition.isRemovedOnCompletion = true navBar.layer.add(transition, forKey: nil) } } extension NavBarTransparentBehavior: UIScrollViewDelegate { public func scrollViewDidScroll(_ scrollView: UIScrollView) { updateNavBar(forScrollView: scrollView) } } #endif
mit
fdeb375e37202b72d7cf8d63a8c87f8f
30.941176
98
0.633824
5.41196
false
false
false
false
suifengqjn/douyu
douyu/douyu/Classes/Home/ViewModel/RecommendViewModel.swift
1
4312
// // RecommendViewModel.swift // douyu // // Created by qianjn on 2016/12/25. // Copyright © 2016年 SF. All rights reserved. // import UIKit class RecommendViewModel { lazy var cycleGroup: [CycleModel] = [CycleModel]() lazy var group: [AnchorGroup] = [AnchorGroup]() lazy var BigDataGroup :AnchorGroup = AnchorGroup() lazy var PrettyGroup:AnchorGroup = AnchorGroup() } // MARK: - 网络请求 extension RecommendViewModel { //瀑布流数据 public func requestData (finishCallback: @escaping () -> ()) { var params = [String: String]() params["limit"] = "4" params["offset"] = "0" params["time"] = NSDate.getCurrentTime() let GCDGroup = DispatchGroup() //0 GCDGroup.enter() NetWork.requestData(type: .GET, URLString: "http://capi.douyucdn.cn/api/v1/getbigDataRoom", params: params) { (result) in // 1.将result转成字典类型 guard let resultDict = result as? [String : NSObject] else { return } // 2.根据data该key, 获取数据 guard let dataArray = resultDict["data"] as? [[String : NSObject]]else {return} // 3.遍历字典,并且转成模型数组 // 3.1设置组的属性 self.BigDataGroup.tag_name = "热门" self.BigDataGroup.icon_name = "home_header_hot" // 3.2获取主播数据 for dict in dataArray { let anchor = Anchor(dict: dict) self.BigDataGroup.anchors.append(anchor) } GCDGroup.leave() } //1 GCDGroup.enter() NetWork.requestData(type: .GET, URLString: "http://capi.douyucdn.cn/api/v1/getVerticalRoom", params: params) { (result) in // 1.将result转成字典类型 guard let resultDict = result as? [String : NSObject] else { return } // 2.根据data该key, 获取数据 guard let dataArray = resultDict["data"] as? [[String : NSObject]]else {return} // 3.遍历字典,并且转成模型数组 // 3.1设置组的属性 self.PrettyGroup.tag_name = "颜值" self.PrettyGroup.icon_name = "home_header_phone" // 3.2获取主播数据 for dict in dataArray { let anchor = Anchor(dict: dict) self.PrettyGroup.anchors.append(anchor) } // 3.3离开组 GCDGroup.leave() } // 2- 12 GCDGroup.enter() NetWork.requestData(type: .GET, URLString: "http://capi.douyucdn.cn/api/v1/getHotCate", params: params) { (result) in //1. 将result 转成字典类型 guard let dict = result as? [String : NSObject] else { return } //2. 取出需要的数据 guard let array = dict["data"] as? [[String : NSObject]] else { return } //3. 转换成模型 for dic in array { let gr = AnchorGroup(dict: dic) self.group.append(gr) } GCDGroup.leave() } GCDGroup.notify(queue: DispatchQueue.main) { self.group.insert(self.PrettyGroup, at: 0) self.group.insert(self.BigDataGroup, at: 0) finishCallback() } } //轮播图数据 public func requestCycleData(finishCallBack: @escaping() -> ()) { let param = ["version" : "2.300"] NetWork.requestData(type: .GET, URLString: "http://www.douyutv.com/api/v1/slide/6", params: param) { (result) in guard let resultDic = result as? [String : NSObject] else { return } guard let resultArr = resultDic["data"] as? [[String : NSObject]] else { return } for param in resultArr { self.cycleGroup.append(CycleModel(dict: param)) } finishCallBack() } } }
apache-2.0
9e6e48bd9b557ec44774233e54706c34
28.543478
130
0.499632
4.617214
false
false
false
false
telip007/ChatFire
Pods/ALCameraViewController/ALCameraViewController/ViewController/CameraViewControllerConstraint.swift
2
18249
// // CameraViewControllerConstraint.swift // CameraViewControllerConstraint // // Created by Pedro Paulo de Amorim. // Copyright (c) 2016 zero. All rights reserved. // import UIKit import AVFoundation /** * This extension provides the configuration of * constraints for CameraViewController. */ extension CameraViewController { /** * To attach the view to the edges of the superview, it needs to be pinned on the sides of the self.view, based on the edges of this superview. * This configure the cameraView to show, in real time, the * camera. */ func configCameraViewConstraints() { [.Left, .Right, .Top, .Bottom].forEach({ view.addConstraint(NSLayoutConstraint( item: cameraView, attribute: $0, relatedBy: .Equal, toItem: view, attribute: $0, multiplier: 1.0, constant: 0)) }) } /** * Add the constraints based on the device orientation, * this pin the button on the bottom part of the screen * when the device is portrait, when landscape, pin * the button on the right part of the screen. */ func configCameraButtonEdgeConstraint(statusBarOrientation: UIInterfaceOrientation) { view.autoRemoveConstraint(cameraButtonEdgeConstraint) let attribute : NSLayoutAttribute = { switch statusBarOrientation { case .Portrait: return .Bottom case .LandscapeRight: return .Right case .LandscapeLeft: return .Left default: return .Top } }() cameraButtonEdgeConstraint = NSLayoutConstraint( item: cameraButton, attribute: attribute, relatedBy: .Equal, toItem: view, attribute: attribute, multiplier: 1.0, constant: attribute == .Right || attribute == .Bottom ? -8 : 8) view.addConstraint(cameraButtonEdgeConstraint!) } /** * Add the constraints based on the device orientation, * centerX the button based on the width of screen. * When the device is landscape orientation, centerY * the button based on the height of screen. */ func configCameraButtonGravityConstraint(portrait: Bool) { view.autoRemoveConstraint(cameraButtonGravityConstraint) let attribute : NSLayoutAttribute = portrait ? .CenterX : .CenterY cameraButtonGravityConstraint = NSLayoutConstraint( item: cameraButton, attribute: attribute, relatedBy: .Equal, toItem: view, attribute: attribute, multiplier: 1.0, constant: 0) view.addConstraint(cameraButtonGravityConstraint!) } /** * Remove the constraints of container. */ func removeContainerConstraints() { view.autoRemoveConstraint(containerButtonsEdgeOneConstraint) view.autoRemoveConstraint(containerButtonsEdgeTwoConstraint) view.autoRemoveConstraint(containerButtonsGravityConstraint) } /** * Configure the edges constraints of container that * handle the center position of SwapButton and * LibraryButton. */ func configContainerEdgeConstraint(statusBarOrientation : UIInterfaceOrientation) { let attributeOne : NSLayoutAttribute let attributeTwo : NSLayoutAttribute switch statusBarOrientation { case .Portrait: attributeOne = .Left attributeTwo = .Right break case .LandscapeRight: attributeOne = .Bottom attributeTwo = .Top break case .LandscapeLeft: attributeOne = .Top attributeTwo = .Bottom break default: attributeOne = .Right attributeTwo = .Left break } containerButtonsEdgeOneConstraint = NSLayoutConstraint( item: containerSwapLibraryButton, attribute: attributeOne, relatedBy: .Equal, toItem: cameraButton, attribute: attributeTwo, multiplier: 1.0, constant: 0) view.addConstraint(containerButtonsEdgeOneConstraint!) containerButtonsEdgeTwoConstraint = NSLayoutConstraint( item: containerSwapLibraryButton, attribute: attributeTwo, relatedBy: .Equal, toItem: view, attribute: attributeTwo, multiplier: 1.0, constant: 0) view.addConstraint(containerButtonsEdgeTwoConstraint!) } /** * Configure the gravity of container, based on the * orientation of the device. */ func configContainerGravityConstraint(statusBarOrientation : UIInterfaceOrientation) { let attributeCenter : NSLayoutAttribute = statusBarOrientation.isPortrait ? .CenterY : .CenterX containerButtonsGravityConstraint = NSLayoutConstraint( item: containerSwapLibraryButton, attribute: attributeCenter, relatedBy: .Equal, toItem: cameraButton, attribute: attributeCenter, multiplier: 1.0, constant: 0) view.addConstraint(containerButtonsGravityConstraint!) } /** * Remove the SwapButton constraints to be updated when * the device was rotated. */ func removeSwapButtonConstraints() { view.autoRemoveConstraint(swapButtonEdgeOneConstraint) view.autoRemoveConstraint(swapButtonEdgeTwoConstraint) view.autoRemoveConstraint(swapButtonGravityConstraint) } /** * If the device is portrait, pin the SwapButton on the * right side of the CameraButton. * If landscape, pin the SwapButton on the top of the * CameraButton. */ func configSwapButtonEdgeConstraint(statusBarOrientation : UIInterfaceOrientation) { let attributeOne : NSLayoutAttribute let attributeTwo : NSLayoutAttribute switch statusBarOrientation { case .Portrait: attributeOne = .Top attributeTwo = .Bottom break case .LandscapeRight: attributeOne = .Left attributeTwo = .Right break case .LandscapeLeft: attributeOne = .Right attributeTwo = .Left break default: attributeOne = .Bottom attributeTwo = .Top break } swapButtonEdgeOneConstraint = NSLayoutConstraint( item: swapButton, attribute: attributeOne, relatedBy: .Equal, toItem: containerSwapLibraryButton, attribute: attributeOne, multiplier: 1.0, constant: 0) view.addConstraint(swapButtonEdgeOneConstraint!) swapButtonEdgeTwoConstraint = NSLayoutConstraint( item: swapButton, attribute: attributeTwo, relatedBy: .Equal, toItem: containerSwapLibraryButton, attribute: attributeTwo, multiplier: 1.0, constant: 0) view.addConstraint(swapButtonEdgeTwoConstraint!) } /** * Configure the center of SwapButton, based on the * axis center of CameraButton. */ func configSwapButtonGravityConstraint(portrait: Bool) { swapButtonGravityConstraint = NSLayoutConstraint( item: swapButton, attribute: portrait ? .Right : .Bottom, relatedBy: .LessThanOrEqual, toItem: containerSwapLibraryButton, attribute: portrait ? .CenterX : .CenterY, multiplier: 1.0, constant: -4.0 * DeviceConfig.SCREEN_MULTIPLIER) view.addConstraint(swapButtonGravityConstraint!) } func removeCloseButtonConstraints() { view.autoRemoveConstraint(closeButtonEdgeConstraint) view.autoRemoveConstraint(closeButtonGravityConstraint) } /** * Pin the close button to the left of the superview. */ func configCloseButtonEdgeConstraint(statusBarOrientation : UIInterfaceOrientation) { let attribute : NSLayoutAttribute = { switch statusBarOrientation { case .Portrait: return .Left case .LandscapeRight, .LandscapeLeft: return .CenterX default: return .Right } }() closeButtonEdgeConstraint = NSLayoutConstraint( item: closeButton, attribute: attribute, relatedBy: .Equal, toItem: attribute != .CenterX ? view : cameraButton, attribute: attribute, multiplier: 1.0, constant: attribute != .CenterX ? 16 : 0) view.addConstraint(closeButtonEdgeConstraint!) } /** * Add the constraint for the CloseButton, based on * the device orientation. * If portrait, it pin the CloseButton on the CenterY * of the CameraButton. * Else if landscape, pin this button on the Bottom * of superview. */ func configCloseButtonGravityConstraint(statusBarOrientation : UIInterfaceOrientation) { let attribute : NSLayoutAttribute let constant : CGFloat switch statusBarOrientation { case .Portrait: attribute = .CenterY constant = 0.0 break case .LandscapeRight: attribute = .Bottom constant = -16.0 break case .LandscapeLeft: attribute = .Top constant = 16.0 break default: attribute = .CenterX constant = 0.0 break } closeButtonGravityConstraint = NSLayoutConstraint( item: closeButton, attribute: attribute, relatedBy: .Equal, toItem: attribute == .Bottom || attribute == .Top ? view : cameraButton, attribute: attribute, multiplier: 1.0, constant: constant) view.addConstraint(closeButtonGravityConstraint!) } /** * Remove the LibraryButton constraints to be updated when * the device was rotated. */ func removeLibraryButtonConstraints() { view.autoRemoveConstraint(libraryButtonEdgeOneConstraint) view.autoRemoveConstraint(libraryButtonEdgeTwoConstraint) view.autoRemoveConstraint(libraryButtonGravityConstraint) } /** * Add the constraint of the LibraryButton, if the device * orientation is portrait, pin the right side of SwapButton * to the left side of LibraryButton. * If landscape, pin the bottom side of CameraButton on the * top side of LibraryButton. */ func configLibraryEdgeButtonConstraint(statusBarOrientation : UIInterfaceOrientation) { let attributeOne : NSLayoutAttribute let attributeTwo : NSLayoutAttribute switch statusBarOrientation { case .Portrait: attributeOne = .Top attributeTwo = .Bottom break case .LandscapeRight: attributeOne = .Left attributeTwo = .Right break case .LandscapeLeft: attributeOne = .Right attributeTwo = .Left break default: attributeOne = .Bottom attributeTwo = .Top break } libraryButtonEdgeOneConstraint = NSLayoutConstraint( item: libraryButton, attribute: attributeOne, relatedBy: .Equal, toItem: containerSwapLibraryButton, attribute: attributeOne, multiplier: 1.0, constant: 0) view.addConstraint(libraryButtonEdgeOneConstraint!) libraryButtonEdgeTwoConstraint = NSLayoutConstraint( item: libraryButton, attribute: attributeTwo, relatedBy: .Equal, toItem: containerSwapLibraryButton, attribute: attributeTwo, multiplier: 1.0, constant: 0) view.addConstraint(libraryButtonEdgeTwoConstraint!) } /** * Set the center gravity of the LibraryButton based * on the position of CameraButton. */ func configLibraryGravityButtonConstraint(portrait: Bool) { libraryButtonGravityConstraint = NSLayoutConstraint( item: libraryButton, attribute: portrait ? .Left : .Top, relatedBy: .LessThanOrEqual, toItem: containerSwapLibraryButton, attribute: portrait ? .CenterX : .CenterY, multiplier: 1.0, constant: 4.0 * DeviceConfig.SCREEN_MULTIPLIER) view.addConstraint(libraryButtonGravityConstraint!) } /** * If the device orientation is portrait, pin the top of * FlashButton to the top side of superview. * Else if, pin the FlashButton bottom side on the top side * of SwapButton. */ func configFlashEdgeButtonConstraint(statusBarOrientation: UIInterfaceOrientation) { view.autoRemoveConstraint(flashButtonEdgeConstraint) let constraintRight = statusBarOrientation == .Portrait || statusBarOrientation == .LandscapeRight let attribute : NSLayoutAttribute = constraintRight ? .Top : .Bottom flashButtonEdgeConstraint = NSLayoutConstraint( item: flashButton, attribute: attribute, relatedBy: .Equal, toItem: view, attribute: attribute, multiplier: 1.0, constant: constraintRight ? 8 : -8) view.addConstraint(flashButtonEdgeConstraint!) } /** * If the device orientation is portrait, pin the right side of FlashButton to the right side of * superview. * Else if, centerX the FlashButton on the CenterX * of CameraButton. */ func configFlashGravityButtonConstraint(statusBarOrientation: UIInterfaceOrientation) { view.autoRemoveConstraint(flashButtonGravityConstraint) let constraintRight = statusBarOrientation == .Portrait || statusBarOrientation == .LandscapeLeft let attribute : NSLayoutAttribute = constraintRight ? .Right : .Left flashButtonGravityConstraint = NSLayoutConstraint( item: flashButton, attribute: attribute, relatedBy: .Equal, toItem: view, attribute: attribute, multiplier: 1.0, constant: constraintRight ? -8 : 8) view.addConstraint(flashButtonGravityConstraint!) } /** * Used to create a perfect square for CameraOverlay. * This method will determinate the size of CameraOverlay, * if portrait, it will use the width of superview to * determinate the height of the view. Else if landscape, * it uses the height of the superview to create the width * of the CameraOverlay. */ func configCameraOverlayWidthConstraint(portrait: Bool) { view.autoRemoveConstraint(cameraOverlayWidthConstraint) cameraOverlayWidthConstraint = NSLayoutConstraint( item: cameraOverlay, attribute: portrait ? .Height : .Width, relatedBy: .Equal, toItem: cameraOverlay, attribute: portrait ? .Width : .Height, multiplier: 1.0, constant: 0) view.addConstraint(cameraOverlayWidthConstraint!) } /** * This method will center the relative position of * CameraOverlay, based on the biggest size of the * superview. */ func configCameraOverlayCenterConstraint(portrait: Bool) { view.autoRemoveConstraint(cameraOverlayCenterConstraint) let attribute : NSLayoutAttribute = portrait ? .CenterY : .CenterX cameraOverlayCenterConstraint = NSLayoutConstraint( item: cameraOverlay, attribute: attribute, relatedBy: .Equal, toItem: view, attribute: attribute, multiplier: 1.0, constant: 0) view.addConstraint(cameraOverlayCenterConstraint!) } /** * Remove the CameraOverlay constraints to be updated when * the device was rotated. */ func removeCameraOverlayEdgesConstraints() { view.autoRemoveConstraint(cameraOverlayEdgeOneConstraint) view.autoRemoveConstraint(cameraOverlayEdgeTwoConstraint) } /** * It needs to get a determined smallest size of the screen to create the smallest size to be used on CameraOverlay. It uses the orientation of the screen to determinate where the view will be pinned. */ func configCameraOverlayEdgeOneContraint(portrait: Bool, padding: CGFloat) { let attribute : NSLayoutAttribute = portrait ? .Left : .Bottom cameraOverlayEdgeOneConstraint = NSLayoutConstraint( item: cameraOverlay, attribute: attribute, relatedBy: .Equal, toItem: view, attribute: attribute, multiplier: 1.0, constant: padding) view.addConstraint(cameraOverlayEdgeOneConstraint!) } /** * It needs to get a determined smallest size of the screen to create the smallest size to be used on CameraOverlay. It uses the orientation of the screen to determinate where the view will be pinned. */ func configCameraOverlayEdgeTwoConstraint(portrait: Bool, padding: CGFloat) { let attributeTwo : NSLayoutAttribute = portrait ? .Right : .Top cameraOverlayEdgeTwoConstraint = NSLayoutConstraint( item: cameraOverlay, attribute: attributeTwo, relatedBy: .Equal, toItem: view, attribute: attributeTwo, multiplier: 1.0, constant: -padding) view.addConstraint(cameraOverlayEdgeTwoConstraint!) } }
apache-2.0
55a09ff38de8b220c5931e2bcfb902be
33.564394
106
0.615815
5.556943
false
false
false
false