repo_name
stringlengths
6
91
path
stringlengths
6
999
copies
stringclasses
283 values
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
cnoon/swift-compiler-crashes
crashes-duplicates/08370-swift-sourcemanager-getmessage.swift
11
272
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing enum b { var _ = { class B { func b: Int -> { for { extension g { protocol e { struct g { class case ,
mit
huonw/swift
test/ClangImporter/clang_builtins.swift
1
2844
// RUN: not %target-swift-frontend -swift-version 3 -typecheck %s 2> %t.3.txt // RUN: %FileCheck -check-prefix=CHECK-3 -check-prefix=CHECK-%target-runtime-3 %s < %t.3.txt // RUN: not %target-swift-frontend -swift-version 4 -typecheck %s 2> %t.4.txt // RUN: %FileCheck -check-prefix=CHECK-4 -check-prefix=CHECK-%target-runtime-4 %s < %t.4.txt #if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) import Darwin #elseif os(Android) || os(Cygwin) || os(FreeBSD) || os(Linux) import Glibc #elseif os(Windows) import MSVCRT #endif func test() { let _: Int = strxfrm // CHECK-3: [[@LINE-1]]:16: error: cannot convert value of type '({{.+}}) -> UInt'{{( [(]aka .+[)])?}} to specified type 'Int' // CHECK-4: [[@LINE-2]]:16: error: cannot convert value of type '({{.+}}) -> Int'{{( [(]aka .+[)])?}} to specified type 'Int' let _: Int = strcspn // CHECK-3: [[@LINE-1]]:16: error: cannot convert value of type '({{.+}}) -> UInt'{{( [(]aka .+[)])?}} to specified type 'Int' // CHECK-4: [[@LINE-2]]:16: error: cannot convert value of type '({{.+}}) -> Int'{{( [(]aka .+[)])?}} to specified type 'Int' let _: Int = strspn // CHECK-3: [[@LINE-1]]:16: error: cannot convert value of type '({{.+}}) -> UInt'{{( [(]aka .+[)])?}} to specified type 'Int' // CHECK-4: [[@LINE-2]]:16: error: cannot convert value of type '({{.+}}) -> Int'{{( [(]aka .+[)])?}} to specified type 'Int' let _: Int = strlen // CHECK-3: [[@LINE-1]]:16: error: cannot convert value of type '({{.+}}) -> UInt'{{( [(]aka .+[)])?}} to specified type 'Int' // CHECK-4: [[@LINE-2]]:16: error: cannot convert value of type '({{.+}}) -> Int'{{( [(]aka .+[)])?}} to specified type 'Int' } #if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) // These functions aren't consistently available across platforms, so only // test for them on Apple platforms. func testApple() { let _: Int = strlcpy // CHECK-objc-3: [[@LINE-1]]:16: error: cannot convert value of type '({{.+}}) -> UInt'{{( [(]aka .+[)])?}} to specified type 'Int' // CHECK-objc-4: [[@LINE-2]]:16: error: cannot convert value of type '({{.+}}) -> Int'{{( [(]aka .+[)])?}} to specified type 'Int' let _: Int = strlcat // CHECK-objc-3: [[@LINE-1]]:16: error: cannot convert value of type '({{.+}}) -> UInt'{{( [(]aka .+[)])?}} to specified type 'Int' // CHECK-objc-4: [[@LINE-2]]:16: error: cannot convert value of type '({{.+}}) -> Int'{{( [(]aka .+[)])?}} to specified type 'Int' // wcslen is different: it wasn't a builtin until Swift 4, and so its return // type has always been 'Int'. let _: Int = wcslen // CHECK-objc-3: [[@LINE-1]]:16: error: cannot convert value of type '({{.+}}) -> Int'{{( [(]aka .+[)])?}} to specified type 'Int' // CHECK-objc-4: [[@LINE-2]]:16: error: cannot convert value of type '({{.+}}) -> Int'{{( [(]aka .+[)])?}} to specified type 'Int' } #endif
apache-2.0
plushcube/Learning
Swift/Functional Swift Book/CoreImageFilter.playground/Contents.swift
1
1931
import UIKit typealias Filter = (CIImage) -> CIImage func blur(radius: Double) -> Filter { return { image in let parameters: [String: Any] = [ kCIInputRadiusKey: radius, kCIInputImageKey: image ] guard let filter = CIFilter(name: "CIGaussianBlur", withInputParameters: parameters) else { fatalError() } guard let outputImage = filter.outputImage else { fatalError() } return outputImage } } func generate(color: UIColor) -> Filter { return { image in let parameters = [ kCIInputColorKey: CIColor(cgColor: color.cgColor) ] guard let filter = CIFilter(name: "CIConstantColorGenerator", withInputParameters: parameters) else { fatalError() } guard let outputImage = filter.outputImage else { fatalError() } return outputImage.cropping(to: image.extent) } } func compositeSourceOver(overlay: CIImage) -> Filter { return { image in let parameters: [String: Any] = [ kCIInputBackgroundImageKey: image, kCIInputImageKey: overlay ] guard let filter = CIFilter(name: "CISourceOverCompositing", withInputParameters: parameters) else { fatalError() } guard let outputImage = filter.outputImage else { fatalError() } return outputImage.cropping(to: image.extent) } } func overlay(color: UIColor) -> Filter { return { image in let overlay = generate(color: color)(image) return compositeSourceOver(overlay: overlay)(image) } } infix operator >>> func >>>(filter1: @escaping Filter, filter2: @escaping Filter) -> Filter { return { image in filter2(filter1(image)) } } let url = URL(string: "http://www.objc.io/images/covers/16.jpg")! let image = CIImage(contentsOf: url)! let radius = 5.0 let color = UIColor.red.withAlphaComponent(0.2) let filter = blur(radius: radius) >>> overlay(color: color) let result = filter(image)
mit
ukitaka/FPRealm
Tests/AnyRealmIOSpec.swift
2
2430
// // AnyRealmIOSpec.swift // RealmIO // // Created by ukitaka on 2017/05/31. // Copyright © 2017年 waft. All rights reserved. // import RealmSwift import RealmIO import XCTest import Quick import Nimble class AnyRealmIOSpec: QuickSpec { let realm = try! Realm(configuration: Realm.Configuration(fileURL: nil, inMemoryIdentifier: "for test")) override func spec() { super.spec() it("works well with `init(io:)`") { let read = AnyRealmIO(io: RealmRO<Void> { _ in }) expect(read.isReadOnly).to(beTrue()) expect(try! self.realm.run(io: read)).notTo(throwError()) let write = AnyRealmIO(io: RealmRW<Void> { _ in }) expect(write.isReadWrite).to(beTrue()) expect(try! self.realm.run(io: write)).notTo(throwError()) } it("works well with `init(error:isReadOnly)`") { struct MyError: Error { } let error = MyError() let read = AnyRealmIO<Void>(error: error) expect(read.isReadOnly).to(beTrue()) expect { try self.realm.run(io: read) }.to(throwError()) let write = AnyRealmIO<Void>(error: error, isReadOnly: false) expect(write.isReadWrite).to(beTrue()) expect { try self.realm.run(io: write) }.to(throwError()) } it("works well with `map` operator") { let read = AnyRealmIO<Void>(io: RealmRO<Void> { _ in }).map { _ in "hello" } expect(try! self.realm.run(io: read)).to(equal("hello")) } it("works well with `flatMap` operator") { let read = RealmRO<String> { _ in "read" } let write = RealmRW<String> { _ in "write" } let io1 = AnyRealmIO(io: read).flatMap { _ in write } expect(io1).to(beAnInstanceOf(RealmRW<String>.self)) expect(try! self.realm.run(io: io1)).to(equal("write")) let io2 = AnyRealmIO(io: read).flatMap { _ in read } expect(io2).to(beAnInstanceOf(AnyRealmIO<String>.self)) expect(try! self.realm.run(io: io2)).to(equal("read")) } it("works well with `ask` operator") { let read = RealmRO<String> { _ in "read" } let io = AnyRealmIO(io: read).ask() expect(io).to(beAnInstanceOf(AnyRealmIO<Realm>.self)) expect(try! self.realm.run(io: io)).to(equal(self.realm)) } } }
mit
pawan007/SmartZip
SmartZip/Controllers/History/HistoryVC.swift
1
5387
// // HistoryVC.swift // SmartZip // // Created by Pawan Dhawan on 21/07/16. // Copyright © 2016 Pawan Kumar. All rights reserved. // import UIKit class HistoryVC: UIViewController { // don't forget to hook this up from the storyboard @IBOutlet var tableView: UITableView! // Data model: These strings will be the data for the table view cells var fileNames: [String] = [] var filePaths: [String] = [] // cell reuse id (cells that scroll out of view can be reused) let cellReuseIdentifier = "cell" override func viewDidLoad() { // Register the table view cell class and its reuse id self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: cellReuseIdentifier) // self.navigationController?.navigationBarHidden = true self.automaticallyAdjustsScrollViewInsets = false getZipFileList() } // number of rows in table view func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.fileNames.count } // create a cell for each table view row func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { // create a new cell if needed or reuse an old one let cell:UITableViewCell = self.tableView.dequeueReusableCellWithIdentifier(cellReuseIdentifier) as UITableViewCell! cell.textLabel?.text = fileNames[indexPath.row] return cell } // method to run when table view cell is tapped func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { print("You tapped cell number \(indexPath.row).") showActionSheet(indexPath.row) } func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool{ return false } func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath){ if editingStyle == .Delete { let path = filePaths[indexPath.row] print(path) try! kFileManager.removeItemAtPath(filePaths[indexPath.row]) filePaths.removeAtIndex(indexPath.row) fileNames.removeAtIndex(indexPath.row) tableView.reloadData() } } @IBAction func menuButtonAction(sender: AnyObject) { if let container = SideMenuManager.sharedManager().container { container.toggleDrawerSide(.Left, animated: true) { (val) -> Void in } } } func getZipFileList() -> Void { let directoryPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first if let enumerator = kFileManager.enumeratorAtPath(directoryPath!) { while let fileName = enumerator.nextObject() as? String { if fileName.containsString(".zip") { fileNames.append(fileName) filePaths.append("\(directoryPath!)/\(fileName)") } } } tableView.reloadData() } func showActionSheet(index:Int) { //Create the AlertController let actionSheetController: UIAlertController = UIAlertController(title: kAlertTitle, message: "", preferredStyle: .ActionSheet) //Create and add the Cancel action let cancelAction: UIAlertAction = UIAlertAction(title: "Cancel", style: .Cancel) { action -> Void in //Just dismiss the action sheet CommonFunctions.sharedInstance.getFreeDiscSpase() } actionSheetController.addAction(cancelAction) //Create and add first option action let takePictureAction: UIAlertAction = UIAlertAction(title: "Share", style: .Default) { action -> Void in //Code for launching the camera goes here let path = self.filePaths[index] print(path) CommonFunctions.sharedInstance.shareMyFile(path, vc: self) } actionSheetController.addAction(takePictureAction) //Create and add a second option action let choosePictureAction: UIAlertAction = UIAlertAction(title: "Delete", style: .Default) { action -> Void in //Code for picking from camera roll goes here let path = self.filePaths[index] print(path) try! kFileManager.removeItemAtPath(self.filePaths[index]) self.filePaths.removeAtIndex(index) self.fileNames.removeAtIndex(index) self.tableView.reloadData() } actionSheetController.addAction(choosePictureAction) if let popoverPresentationController = actionSheetController.popoverPresentationController { popoverPresentationController.sourceView = self.view var rect=self.view.frame rect.origin.y = rect.height popoverPresentationController.sourceRect = rect } //Present the AlertController self.presentViewController(actionSheetController, animated: true, completion: nil) } }
mit
mauryat/firefox-ios
StorageTests/TestSQLiteHistory.swift
1
69873
/* 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 import Deferred import XCTest let threeMonthsInMillis: UInt64 = 3 * 30 * 24 * 60 * 60 * 1000 let threeMonthsInMicros: UInt64 = UInt64(threeMonthsInMillis) * UInt64(1000) // Start everything three months ago. let baseInstantInMillis = Date.now() - threeMonthsInMillis let baseInstantInMicros = Date.nowMicroseconds() - threeMonthsInMicros func advanceTimestamp(_ timestamp: Timestamp, by: Int) -> Timestamp { return timestamp + UInt64(by) } func advanceMicrosecondTimestamp(_ timestamp: MicrosecondTimestamp, by: Int) -> MicrosecondTimestamp { return timestamp + UInt64(by) } extension Site { func asPlace() -> Place { return Place(guid: self.guid!, url: self.url, title: self.title) } } 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 { let err = db.executeChange(sql, withArgs: args) return err == nil } 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 = BookmarkNodeType.folder.rawValue let root = BookmarkRoots.RootID let titleMobile = NSLocalizedString("Mobile Bookmarks", tableName: "Storage", comment: "The title of the folder that contains mobile bookmarks. This should match bookmarks.folder.mobile.label on Android.") let titleMenu = NSLocalizedString("Bookmarks Menu", tableName: "Storage", comment: "The name of the folder that contains desktop bookmarks in the menu. This should match bookmarks.folder.menu.label on Android.") let titleToolbar = NSLocalizedString("Bookmarks Toolbar", tableName: "Storage", comment: "The name of the folder that contains desktop bookmarks in the toolbar. This should match bookmarks.folder.toolbar.label on Android.") let titleUnsorted = NSLocalizedString("Unsorted Bookmarks", tableName: "Storage", comment: "The name of the folder that contains unsorted desktop bookmarks. This should match bookmarks.folder.unfiled.label on Android.") let args: Args = [ root, BookmarkRoots.RootGUID, type, "Root", root, BookmarkRoots.MobileID, BookmarkRoots.MobileFolderGUID, type, titleMobile, root, BookmarkRoots.MenuID, BookmarkRoots.MenuFolderGUID, type, titleMenu, root, BookmarkRoots.ToolbarID, BookmarkRoots.ToolbarFolderGUID, type, titleToolbar, root, BookmarkRoots.UnfiledID, BookmarkRoots.UnfiledFolderGUID, type, titleUnsorted, root, ] let sql = "INSERT INTO bookmarks (id, guid, type, url, title, parent) VALUES " + "(?, ?, ?, NULL, ?, ?), " + // Root "(?, ?, ?, NULL, ?, ?), " + // Mobile "(?, ?, ?, NULL, ?, ?), " + // Menu "(?, ?, ?, NULL, ?, ?), " + // Toolbar "(?, ?, ?, NULL, ?, ?) " // Unsorted return self.run(db, sql: sql, args: args) } func CreateHistoryTable() -> String { return "CREATE TABLE IF NOT EXISTS \(TableHistory) (" + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "guid TEXT NOT NULL UNIQUE, " + // Not null, but the value might be replaced by the server's. "url TEXT UNIQUE, " + // May only be null for deleted records. "title TEXT NOT NULL, " + "server_modified INTEGER, " + // Can be null. Integer milliseconds. "local_modified INTEGER, " + // Can be null. Client clock. In extremis only. "is_deleted TINYINT NOT NULL, " + // Boolean. Locally deleted. "should_upload TINYINT NOT NULL, " + // Boolean. Set when changed or visits added. "domain_id INTEGER REFERENCES \(TableDomains)(id) ON DELETE CASCADE, " + "CONSTRAINT urlOrDeleted CHECK (url IS NOT NULL OR is_deleted = 1)" + ")" } func CreateDomainsTable() -> String { return "CREATE TABLE IF NOT EXISTS \(TableDomains) (" + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "domain TEXT NOT NULL UNIQUE, " + "showOnTopSites TINYINT NOT NULL DEFAULT 1" + ")" } func CreateQueueTable() -> String { return "CREATE TABLE IF NOT EXISTS \(TableQueuedTabs) (" + "url TEXT NOT NULL UNIQUE, " + "title TEXT" + ") " } override func create(_ db: SQLiteDBConnection) -> Bool { let visits = "CREATE TABLE IF NOT EXISTS \(TableVisits) (" + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "siteID INTEGER NOT NULL REFERENCES \(TableHistory)(id) ON DELETE CASCADE, " + "date REAL NOT NULL, " + // Microseconds since epoch. "type INTEGER NOT NULL, " + "is_local TINYINT NOT NULL, " + // Some visits are local. Some are remote ('mirrored'). This boolean flag is the split. "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 \(IndexHistoryShouldUpload) " + "ON \(TableHistory) (should_upload) WHERE should_upload = 1" } else { indexShouldUpload = "CREATE INDEX IF NOT EXISTS \(IndexHistoryShouldUpload) " + "ON \(TableHistory) (should_upload)" } let indexSiteIDDate = "CREATE INDEX IF NOT EXISTS \(IndexVisitsSiteIDIsLocalDate) " + "ON \(TableVisits) (siteID, is_local, date)" let faviconSites = "CREATE TABLE IF NOT EXISTS \(TableFaviconSites) (" + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "siteID INTEGER NOT NULL REFERENCES \(TableHistory)(id) ON DELETE CASCADE, " + "faviconID INTEGER NOT NULL REFERENCES \(TableFavicons)(id) ON DELETE CASCADE, " + "UNIQUE (siteID, faviconID) " + ") " let widestFavicons = "CREATE VIEW IF NOT EXISTS \(ViewWidestFaviconsForSites) AS " + "SELECT " + "\(TableFaviconSites).siteID AS siteID, " + "\(TableFavicons).id AS iconID, " + "\(TableFavicons).url AS iconURL, " + "\(TableFavicons).date AS iconDate, " + "\(TableFavicons).type AS iconType, " + "MAX(\(TableFavicons).width) AS iconWidth " + "FROM \(TableFaviconSites), \(TableFavicons) WHERE " + "\(TableFaviconSites).faviconID = \(TableFavicons).id " + "GROUP BY siteID " let historyIDsWithIcon = "CREATE VIEW IF NOT EXISTS \(ViewHistoryIDsWithWidestFavicons) AS " + "SELECT \(TableHistory).id AS id, " + "iconID, iconURL, iconDate, iconType, iconWidth " + "FROM \(TableHistory) " + "LEFT OUTER JOIN " + "\(ViewWidestFaviconsForSites) ON history.id = \(ViewWidestFaviconsForSites).siteID " let iconForURL = "CREATE VIEW IF NOT EXISTS \(ViewIconForURL) AS " + "SELECT history.url AS url, icons.iconID AS iconID FROM " + "\(TableHistory), \(ViewWidestFaviconsForSites) AS icons WHERE " + "\(TableHistory).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 = BookmarkNodeType.folder.rawValue let root = BookmarkRoots.RootID let titleMobile = NSLocalizedString("Mobile Bookmarks", tableName: "Storage", comment: "The title of the folder that contains mobile bookmarks. This should match bookmarks.folder.mobile.label on Android.") let titleMenu = NSLocalizedString("Bookmarks Menu", tableName: "Storage", comment: "The name of the folder that contains desktop bookmarks in the menu. This should match bookmarks.folder.menu.label on Android.") let titleToolbar = NSLocalizedString("Bookmarks Toolbar", tableName: "Storage", comment: "The name of the folder that contains desktop bookmarks in the toolbar. This should match bookmarks.folder.toolbar.label on Android.") let titleUnsorted = NSLocalizedString("Unsorted Bookmarks", tableName: "Storage", comment: "The name of the folder that contains unsorted desktop bookmarks. This should match bookmarks.folder.unfiled.label on Android.") let args: Args = [ root, BookmarkRoots.RootGUID, type, "Root", root, BookmarkRoots.MobileID, BookmarkRoots.MobileFolderGUID, type, titleMobile, root, BookmarkRoots.MenuID, BookmarkRoots.MenuFolderGUID, type, titleMenu, root, BookmarkRoots.ToolbarID, BookmarkRoots.ToolbarFolderGUID, type, titleToolbar, root, BookmarkRoots.UnfiledID, BookmarkRoots.UnfiledFolderGUID, type, titleUnsorted, root, ] let sql = "INSERT INTO bookmarks (id, guid, type, url, title, parent) VALUES " + "(?, ?, ?, NULL, ?, ?), " + // Root "(?, ?, ?, NULL, ?, ?), " + // Mobile "(?, ?, ?, NULL, ?, ?), " + // Menu "(?, ?, ?, NULL, ?, ?), " + // Toolbar "(?, ?, ?, NULL, ?, ?) " // Unsorted return self.run(db, sql: sql, args: args) } func getHistoryTableCreationString() -> String { return "CREATE TABLE IF NOT EXISTS history (" + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "guid TEXT NOT NULL UNIQUE, " + // Not null, but the value might be replaced by the server's. "url TEXT UNIQUE, " + // May only be null for deleted records. "title TEXT NOT NULL, " + "server_modified INTEGER, " + // Can be null. Integer milliseconds. "local_modified INTEGER, " + // Can be null. Client clock. In extremis only. "is_deleted TINYINT NOT NULL, " + // Boolean. Locally deleted. "should_upload TINYINT NOT NULL, " + // Boolean. Set when changed or visits added. "domain_id INTEGER REFERENCES \(TableDomains)(id) ON DELETE CASCADE, " + "CONSTRAINT urlOrDeleted CHECK (url IS NOT NULL OR is_deleted = 1)" + ")" } func getDomainsTableCreationString() -> String { return "CREATE TABLE IF NOT EXISTS \(TableDomains) (" + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "domain TEXT NOT NULL UNIQUE, " + "showOnTopSites TINYINT NOT NULL DEFAULT 1" + ")" } func getQueueTableCreationString() -> String { return "CREATE TABLE IF NOT EXISTS \(TableQueuedTabs) (" + "url TEXT NOT NULL UNIQUE, " + "title TEXT" + ") " } 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 \(TableVisits) (" + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "siteID INTEGER NOT NULL REFERENCES history(id) ON DELETE CASCADE, " + "date REAL NOT NULL, " + // Microseconds since epoch. "type INTEGER NOT NULL, " + "is_local TINYINT NOT NULL, " + // Some visits are local. Some are remote ('mirrored'). This boolean flag is the split. "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 \(IndexHistoryShouldUpload) " + "ON history (should_upload) WHERE should_upload = 1" } else { indexShouldUpload = "CREATE INDEX IF NOT EXISTS \(IndexHistoryShouldUpload) " + "ON history (should_upload)" } let indexSiteIDDate = "CREATE INDEX IF NOT EXISTS \(IndexVisitsSiteIDIsLocalDate) " + "ON \(TableVisits) (siteID, is_local, date)" let faviconSites = "CREATE TABLE IF NOT EXISTS \(TableFaviconSites) (" + "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 \(ViewWidestFaviconsForSites) AS " + "SELECT " + "\(TableFaviconSites).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 \(TableFaviconSites), favicons WHERE " + "\(TableFaviconSites).faviconID = favicons.id " + "GROUP BY siteID " let historyIDsWithIcon = "CREATE VIEW IF NOT EXISTS \(ViewHistoryIDsWithWidestFavicons) AS " + "SELECT history.id AS id, " + "iconID, iconURL, iconDate, iconType, iconWidth " + "FROM history " + "LEFT OUTER JOIN " + "\(ViewWidestFaviconsForSites) ON history.id = \(ViewWidestFaviconsForSites).siteID " let iconForURL = "CREATE VIEW IF NOT EXISTS \(ViewIconForURL) AS " + "SELECT history.url AS url, icons.iconID AS iconID FROM " + "\(TableHistory), \(ViewWidestFaviconsForSites) AS icons WHERE " + "\(TableHistory).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 = BookmarkNodeType.folder.rawValue let root = BookmarkRoots.RootID let titleMobile = NSLocalizedString("Mobile Bookmarks", tableName: "Storage", comment: "The title of the folder that contains mobile bookmarks. This should match bookmarks.folder.mobile.label on Android.") let titleMenu = NSLocalizedString("Bookmarks Menu", tableName: "Storage", comment: "The name of the folder that contains desktop bookmarks in the menu. This should match bookmarks.folder.menu.label on Android.") let titleToolbar = NSLocalizedString("Bookmarks Toolbar", tableName: "Storage", comment: "The name of the folder that contains desktop bookmarks in the toolbar. This should match bookmarks.folder.toolbar.label on Android.") let titleUnsorted = NSLocalizedString("Unsorted Bookmarks", tableName: "Storage", comment: "The name of the folder that contains unsorted desktop bookmarks. This should match bookmarks.folder.unfiled.label on Android.") let args: Args = [ root, BookmarkRoots.RootGUID, type, "Root", root, BookmarkRoots.MobileID, BookmarkRoots.MobileFolderGUID, type, titleMobile, root, BookmarkRoots.MenuID, BookmarkRoots.MenuFolderGUID, type, titleMenu, root, BookmarkRoots.ToolbarID, BookmarkRoots.ToolbarFolderGUID, type, titleToolbar, root, BookmarkRoots.UnfiledID, BookmarkRoots.UnfiledFolderGUID, type, titleUnsorted, root, ] let sql = "INSERT INTO bookmarks (id, guid, type, url, title, parent) VALUES " + "(?, ?, ?, NULL, ?, ?), " + // Root "(?, ?, ?, NULL, ?, ?), " + // Mobile "(?, ?, ?, NULL, ?, ?), " + // Menu "(?, ?, ?, NULL, ?, ?), " + // Toolbar "(?, ?, ?, NULL, ?, ?) " // Unsorted return self.run(db, sql: sql, args: args) } func getHistoryTableCreationString() -> String { return "CREATE TABLE IF NOT EXISTS \(TableHistory) (" + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "guid TEXT NOT NULL UNIQUE, " + // Not null, but the value might be replaced by the server's. "url TEXT UNIQUE, " + // May only be null for deleted records. "title TEXT NOT NULL, " + "server_modified INTEGER, " + // Can be null. Integer milliseconds. "local_modified INTEGER, " + // Can be null. Client clock. In extremis only. "is_deleted TINYINT NOT NULL, " + // Boolean. Locally deleted. "should_upload TINYINT NOT NULL, " + // Boolean. Set when changed or visits added. "domain_id INTEGER REFERENCES \(TableDomains)(id) ON DELETE CASCADE, " + "CONSTRAINT urlOrDeleted CHECK (url IS NOT NULL OR is_deleted = 1)" + ")" } func getDomainsTableCreationString() -> String { return "CREATE TABLE IF NOT EXISTS \(TableDomains) (" + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "domain TEXT NOT NULL UNIQUE, " + "showOnTopSites TINYINT NOT NULL DEFAULT 1" + ")" } func getQueueTableCreationString() -> String { return "CREATE TABLE IF NOT EXISTS \(TableQueuedTabs) (" + "url TEXT NOT NULL UNIQUE, " + "title TEXT" + ") " } 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, " + "date REAL NOT NULL, " + // Microseconds since epoch. "type INTEGER NOT NULL, " + "is_local TINYINT NOT NULL, " + // Some visits are local. Some are remote ('mirrored'). This boolean flag is the split. "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 \(IndexHistoryShouldUpload) " + "ON \(TableHistory) (should_upload) WHERE should_upload = 1" } else { indexShouldUpload = "CREATE INDEX IF NOT EXISTS \(IndexHistoryShouldUpload) " + "ON \(TableHistory) (should_upload)" } let indexSiteIDDate = "CREATE INDEX IF NOT EXISTS \(IndexVisitsSiteIDIsLocalDate) " + "ON \(TableVisits) (siteID, is_local, date)" let faviconSites = "CREATE TABLE IF NOT EXISTS \(TableFaviconSites) (" + "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 \(ViewWidestFaviconsForSites) AS " + "SELECT " + "\(TableFaviconSites).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 \(TableFaviconSites), favicons WHERE " + "\(TableFaviconSites).faviconID = favicons.id " + "GROUP BY siteID " let historyIDsWithIcon = "CREATE VIEW IF NOT EXISTS \(ViewHistoryIDsWithWidestFavicons) AS " + "SELECT history.id AS id, " + "iconID, iconURL, iconDate, iconType, iconWidth " + "FROM history " + "LEFT OUTER JOIN " + "\(ViewWidestFaviconsForSites) ON history.id = \(ViewWidestFaviconsForSites).siteID " let iconForURL = "CREATE VIEW IF NOT EXISTS \(ViewIconForURL) AS " + "SELECT history.url AS url, icons.iconID AS iconID FROM " + "history, \(ViewWidestFaviconsForSites) 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 = BookmarkNodeType.folder.rawValue let root = BookmarkRoots.RootID let titleMobile = NSLocalizedString("Mobile Bookmarks", tableName: "Storage", comment: "The title of the folder that contains mobile bookmarks. This should match bookmarks.folder.mobile.label on Android.") let titleMenu = NSLocalizedString("Bookmarks Menu", tableName: "Storage", comment: "The name of the folder that contains desktop bookmarks in the menu. This should match bookmarks.folder.menu.label on Android.") let titleToolbar = NSLocalizedString("Bookmarks Toolbar", tableName: "Storage", comment: "The name of the folder that contains desktop bookmarks in the toolbar. This should match bookmarks.folder.toolbar.label on Android.") let titleUnsorted = NSLocalizedString("Unsorted Bookmarks", tableName: "Storage", comment: "The name of the folder that contains unsorted desktop bookmarks. This should match bookmarks.folder.unfiled.label on Android.") let args: Args = [ root, BookmarkRoots.RootGUID, type, "Root", root, BookmarkRoots.MobileID, BookmarkRoots.MobileFolderGUID, type, titleMobile, root, BookmarkRoots.MenuID, BookmarkRoots.MenuFolderGUID, type, titleMenu, root, BookmarkRoots.ToolbarID, BookmarkRoots.ToolbarFolderGUID, type, titleToolbar, root, BookmarkRoots.UnfiledID, BookmarkRoots.UnfiledFolderGUID, type, titleUnsorted, root, ] let sql = "INSERT INTO bookmarks (id, guid, type, url, title, parent) VALUES " + "(?, ?, ?, NULL, ?, ?), " + // Root "(?, ?, ?, NULL, ?, ?), " + // Mobile "(?, ?, ?, NULL, ?, ?), " + // Menu "(?, ?, ?, NULL, ?, ?), " + // Toolbar "(?, ?, ?, NULL, ?, ?) " // Unsorted return self.run(db, sql: sql, args: args) } func getHistoryTableCreationString(forVersion version: Int = BrowserSchema.DefaultVersion) -> String { return "CREATE TABLE IF NOT EXISTS history (" + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "guid TEXT NOT NULL UNIQUE, " + // Not null, but the value might be replaced by the server's. "url TEXT UNIQUE, " + // May only be null for deleted records. "title TEXT NOT NULL, " + "server_modified INTEGER, " + // Can be null. Integer milliseconds. "local_modified INTEGER, " + // Can be null. Client clock. In extremis only. "is_deleted TINYINT NOT NULL, " + // Boolean. Locally deleted. "should_upload TINYINT NOT NULL, " + // Boolean. Set when changed or visits added. "domain_id INTEGER REFERENCES \(TableDomains)(id) ON DELETE CASCADE, " + "CONSTRAINT urlOrDeleted CHECK (url IS NOT NULL OR is_deleted = 1)" + ")" } func getDomainsTableCreationString() -> String { return "CREATE TABLE IF NOT EXISTS \(TableDomains) (" + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "domain TEXT NOT NULL UNIQUE, " + "showOnTopSites TINYINT NOT NULL DEFAULT 1" + ")" } func getQueueTableCreationString() -> String { return "CREATE TABLE IF NOT EXISTS \(TableQueuedTabs) (" + "url TEXT NOT NULL UNIQUE, " + "title TEXT" + ") " } 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 \(TableBookmarksMirror) " + // Shared fields. "( id INTEGER PRIMARY KEY AUTOINCREMENT" + ", guid TEXT NOT NULL UNIQUE" + ", type TINYINT NOT NULL" + // Type enum. TODO: BookmarkNodeType needs to be extended. // Record/envelope metadata that'll allow us to do merges. ", server_modified INTEGER NOT NULL" + // Milliseconds. ", is_deleted TINYINT NOT NULL DEFAULT 0" + // Boolean ", hasDupe TINYINT NOT NULL DEFAULT 0" + // Boolean, 0 (false) if deleted. ", parentid TEXT" + // GUID ", 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. ", feedUri TEXT, siteUri TEXT" + // LIVEMARKS ", pos INT" + // SEPARATORS ", title TEXT, description TEXT" + // FOLDERS, BOOKMARKS, QUERIES ", bmkUri TEXT, tags TEXT, keyword TEXT" + // BOOKMARKS, QUERIES ", folderName TEXT, queryId TEXT" + // QUERIES ", 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 { return "CREATE TABLE IF NOT EXISTS \(TableBookmarksMirrorStructure) " + "( parent TEXT NOT NULL REFERENCES \(TableBookmarksMirror)(guid) ON DELETE CASCADE" + ", child TEXT NOT NULL" + // Should be the GUID of a child. ", idx INTEGER NOT NULL" + // Should advance from 0. ")" } 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, " + "date REAL NOT NULL, " + // Microseconds since epoch. "type INTEGER NOT NULL, " + "is_local TINYINT NOT NULL, " + // Some visits are local. Some are remote ('mirrored'). This boolean flag is the split. "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 \(IndexHistoryShouldUpload) " + "ON history (should_upload) WHERE should_upload = 1" } else { indexShouldUpload = "CREATE INDEX IF NOT EXISTS \(IndexHistoryShouldUpload) " + "ON history (should_upload)" } let indexSiteIDDate = "CREATE INDEX IF NOT EXISTS \(IndexVisitsSiteIDIsLocalDate) " + "ON visits (siteID, is_local, date)" let faviconSites = "CREATE TABLE IF NOT EXISTS \(TableFaviconSites) (" + "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 \(ViewWidestFaviconsForSites) AS " + "SELECT " + "\(TableFaviconSites).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 \(TableFaviconSites), favicons WHERE " + "\(TableFaviconSites).faviconID = favicons.id " + "GROUP BY siteID " let historyIDsWithIcon = "CREATE VIEW IF NOT EXISTS \(ViewHistoryIDsWithWidestFavicons) AS " + "SELECT history.id AS id, " + "iconID, iconURL, iconDate, iconType, iconWidth " + "FROM history " + "LEFT OUTER JOIN " + "\(ViewWidestFaviconsForSites) ON history.id = \(ViewWidestFaviconsForSites).siteID " let iconForURL = "CREATE VIEW IF NOT EXISTS \(ViewIconForURL) AS " + "SELECT history.url AS url, icons.iconID AS iconID FROM " + "history, \(ViewWidestFaviconsForSites) 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 \(IndexBookmarksMirrorStructureParentIdx) " + "ON \(TableBookmarksMirrorStructure) (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 db = BrowserDB(filename: "browser.db", files: files) let prefs = MockProfilePrefs() let history = SQLiteHistory(db: db, 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.getSitesByFrecencyWithHistoryLimit(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, table) in sources { let db = BrowserDB(filename: "browser-v\(version).db", files: files) XCTAssertTrue( db.runWithConnection { (conn, err) in XCTAssertTrue(table.create(conn), "Creating browser table version \(version)") // And we can upgrade to the current version. XCTAssertTrue(destination.update(conn, from: table.version), "Upgrading browser table from version \(version)") }.value.isSuccess ) db.forceClose() } } func testUpgradesWithData() { let db = BrowserDB(filename: "browser-v6-data.db", files: files) XCTAssertTrue(db.prepareSchema(BrowserSchemaV6()) == .success, "Creating browser schema version 6") // 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(db.run(queries).value.isSuccess) // And we can upgrade to the current version. XCTAssertTrue(db.prepareSchema(BrowserSchema()) == .success, "Upgrading browser schema from version 6") let prefs = MockProfilePrefs() let history = SQLiteHistory(db: db, prefs: prefs) let results = history.getSitesByLastVisit(10).value.successValue XCTAssertNotNil(results) XCTAssertEqual(results![0]?.url, "http://www.example.com") db.forceClose() } func testDomainUpgrade() { let db = BrowserDB(filename: "browser.db", files: files) let prefs = MockProfilePrefs() let history = SQLiteHistory(db: db, prefs: prefs) let site = Site(url: "http://www.example.com/test1.1", title: "title one") var err: NSError? = nil // Insert something with an invalid domain ID. We have to manually do this since domains are usually hidden. let _ = db.withConnection(&err, callback: { (connection, err) -> Int in let insert = "INSERT INTO \(TableHistory) (guid, url, title, local_modified, is_deleted, should_upload, domain_id) " + "?, ?, ?, ?, ?, ?, ?" let args: Args = [Bytes.generateGUID(), site.url, site.title, Date.now(), 0, 0, -1] err = connection.executeChange(insert, withArgs: args) return 0 }) // Now insert it again. This should update the domain history.addLocalVisit(SiteVisit(site: site, date: Date.nowMicroseconds(), type: VisitType.link)).succeeded() // DomainID isn't normally exposed, so we manually query to get it let results = db.withConnection(&err, callback: { (connection, err) -> Cursor<Int> in let sql = "SELECT domain_id FROM \(TableHistory) WHERE url = ?" let args: Args = [site.url] return connection.executeQuery(sql, factory: IntFactory, withArgs: args) }) XCTAssertNotEqual(results[0]!, -1, "Domain id was updated") } func testDomains() { let db = BrowserDB(filename: "browser.db", files: files) let prefs = MockProfilePrefs() let history = SQLiteHistory(db: db, 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.") history.clearHistory().bind({ success in return all([history.addLocalVisit(SiteVisit(site: site11, date: Date.nowMicroseconds(), type: VisitType.link)), history.addLocalVisit(SiteVisit(site: site12, date: Date.nowMicroseconds(), type: VisitType.link)), history.addLocalVisit(SiteVisit(site: site3, date: Date.nowMicroseconds(), type: VisitType.link))]) }).bind({ (results: [Maybe<()>]) in return history.insertOrUpdatePlace(site13, modified: Date.nowMicroseconds()) }).bind({ guid in XCTAssertEqual(guid.successValue!, initialGuid, "Guid is correct") return history.getSitesByFrecencyWithHistoryLimit(10) }).bind({ (sites: Maybe<Cursor<Site>>) -> Success in XCTAssert(sites.successValue!.count == 2, "2 sites returned") return history.removeSiteFromTopSites(site11) }).bind({ success in XCTAssertTrue(success.isSuccess, "Remove was successful") return history.getSitesByFrecencyWithHistoryLimit(10) }).upon({ (sites: Maybe<Cursor<Site>>) in XCTAssert(sites.successValue!.count == 1, "1 site returned") expectation.fulfill() }) waitForExpectations(timeout: 10.0) { error in return } } func testHistoryIsSynced() { let db = BrowserDB(filename: "historysynced.db", files: files) let prefs = MockProfilePrefs() let history = SQLiteHistory(db: db, 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 db = BrowserDB(filename: "browser.db", files: files) let prefs = MockProfilePrefs() let history = SQLiteHistory(db: db, prefs: prefs) let bookmarks = SQLiteBookmarks(db: db) 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.nowMicroseconds(), type: VisitType.link) let siteVisit2 = SiteVisit(site: site1Changed, date: Date.nowMicroseconds() + 1000, type: VisitType.bookmark) let site2 = Site(url: "http://url2/", title: "title two") let siteVisit3 = SiteVisit(site: site2, date: Date.nowMicroseconds() + 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.getSitesByFrecencyWithHistoryLimit(10) >>== f } } func checkSitesByDate(_ f: @escaping (Cursor<Site>) -> Success) -> () -> Success { return { history.getSitesByLastVisit(10) >>== f } } func checkSitesWithFilter(_ filter: String, f: @escaping (Cursor<Site>) -> Success) -> () -> Success { return { history.getSitesByFrecencyWithHistoryLimit(10, whereURLContains: filter) >>== 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 testFaviconTable() { let db = BrowserDB(filename: "browser.db", files: files) let prefs = MockProfilePrefs() let history = SQLiteHistory(db: db, prefs: prefs) let bookmarks = SQLiteBookmarks(db: db) XCTAssertTrue(db.prepareSchema(BrowserSchema()) == .success) let expectation = self.expectation(description: "First.") func done() -> Success { expectation.fulfill() return succeed() } func updateFavicon() -> Success { let fav = Favicon(url: "http://url2/", date: Date(), type: .icon) fav.id = 1 let site = Site(url: "http://bookmarkedurl/", title: "My Bookmark") return history.addFavicon(fav, forSite: site) >>> succeed } func checkFaviconForBookmarkIsNil() -> Success { return bookmarks.bookmarksByURL("http://bookmarkedurl/".asURL!) >>== { results in XCTAssertEqual(1, results.count) XCTAssertNil(results[0]?.favicon) return succeed() } } func checkFaviconWasSetForBookmark() -> Success { return history.getFaviconsForBookmarkedURL("http://bookmarkedurl/") >>== { results in XCTAssertEqual(1, results.count) if let actualFaviconURL = results[0]??.url { XCTAssertEqual("http://url2/", actualFaviconURL) } return succeed() } } func removeBookmark() -> Success { return bookmarks.testFactory.removeByURL("http://bookmarkedurl/") } func checkFaviconWasRemovedForBookmark() -> Success { return history.getFaviconsForBookmarkedURL("http://bookmarkedurl/") >>== { results in XCTAssertEqual(0, results.count) return succeed() } } history.clearAllFavicons() >>> bookmarks.clearBookmarks >>> { bookmarks.addToMobileBookmarks("http://bookmarkedurl/".asURL!, title: "Title", favicon: nil) } >>> checkFaviconForBookmarkIsNil >>> updateFavicon >>> checkFaviconWasSetForBookmark >>> removeBookmark >>> checkFaviconWasRemovedForBookmark >>> done waitForExpectations(timeout: 10.0) { error in return } } func testTopSitesFrecencyOrder() { let db = BrowserDB(filename: "browser.db", files: files) let prefs = MockProfilePrefs() let history = SQLiteHistory(db: db, prefs: prefs) history.setTopSitesCacheSize(20) history.clearTopSitesCache().value history.clearHistory().value // Lets create some history. This will create 100 sites that will have 21 local and 21 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).value // 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, invalidateHighlights: 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 db = BrowserDB(filename: "browser.db", files: files) let prefs = MockProfilePrefs() let history = SQLiteHistory(db: db, prefs: prefs) history.setTopSitesCacheSize(20) history.clearTopSitesCache().value history.clearHistory().value // 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).value // 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, invalidateHighlights: 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"].index(of: guid)) } XCTAssertEqual(topSites.count, 20) return succeed() } } loadCache() >>> checkTopSitesReturnsResults >>> done waitForExpectations(timeout: 10.0) { error in return } } func testTopSitesCache() { let db = BrowserDB(filename: "browser.db", files: files) let prefs = MockProfilePrefs() let history = SQLiteHistory(db: db, 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, invalidateHighlights: 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, invalidateHighlights: 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, invalidateHighlights: 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 db = BrowserDB(filename: "browser.db", files: files) let prefs = MockProfilePrefs() let history = SQLiteHistory(db: db, 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) >>== { 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 } } } class TestSQLiteHistoryTransactionUpdate: XCTestCase { func testUpdateInTransaction() { let files = MockFiles() let db = BrowserDB(filename: "browser.db", files: files) let prefs = MockProfilePrefs() let history = SQLiteHistory(db: db, prefs: prefs) history.clearHistory().succeeded() let site = Site(url: "http://site/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) } } class TestSQLiteHistoryFilterSplitting: XCTestCase { let history: SQLiteHistory = { let files = MockFiles() let db = BrowserDB(filename: "browser.db", files: files) let prefs = MockProfilePrefs() return SQLiteHistory(db: db, prefs: prefs) }() func testWithSingleWord() { let (fragment, args) = history.computeWhereFragmentWithFilter("foo", perWordFragment: "?", perWordArgs: { [$0] }) XCTAssertEqual(fragment, "?") XCTAssert(stringArgsEqual(args, ["foo"])) } func testWithIdenticalWords() { let (fragment, args) = history.computeWhereFragmentWithFilter("foo fo foo", perWordFragment: "?", perWordArgs: { [$0] }) XCTAssertEqual(fragment, "?") XCTAssert(stringArgsEqual(args, ["foo"])) } func testWithDistinctWords() { let (fragment, args) = history.computeWhereFragmentWithFilter("foo bar", perWordFragment: "?", perWordArgs: { [$0] }) XCTAssertEqual(fragment, "? AND ?") XCTAssert(stringArgsEqual(args, ["foo", "bar"])) } func testWithDistinctWordsAndWhitespace() { let (fragment, args) = history.computeWhereFragmentWithFilter(" foo bar ", perWordFragment: "?", perWordArgs: { [$0] }) XCTAssertEqual(fragment, "? AND ?") XCTAssert(stringArgsEqual(args, ["foo", "bar"])) } func testWithSubstrings() { let (fragment, args) = history.computeWhereFragmentWithFilter("foo bar foobar", perWordFragment: "?", perWordArgs: { [$0] }) XCTAssertEqual(fragment, "?") XCTAssert(stringArgsEqual(args, ["foobar"])) } func testWithSubstringsAndIdenticalWords() { let (fragment, args) = history.computeWhereFragmentWithFilter("foo bar foobar foobar", perWordFragment: "?", perWordArgs: { [$0] }) XCTAssertEqual(fragment, "?") XCTAssert(stringArgsEqual(args, ["foobar"])) } fileprivate func stringArgsEqual(_ one: Args, _ other: Args) -> Bool { return one.elementsEqual(other, by: { (oneElement: Any?, otherElement: Any?) -> Bool in return (oneElement as! String) == (otherElement as! String) }) } } // MARK - Private Test Helper Methods enum VisitOrigin { case local case remote } private func populateHistoryForFrecencyCalculations(_ history: SQLiteHistory, siteCount count: Int) { for i in 0...count { let site = Site(url: "http://s\(i)ite\(i).com/foo", title: "A \(i)") site.guid = "abc\(i)def" let baseMillis: UInt64 = baseInstantInMillis - 20000 history.insertOrUpdatePlace(site.asPlace(), modified: baseMillis).succeeded() for j in 0...20 { let visitTime = advanceMicrosecondTimestamp(baseInstantInMicros, by: (1000000 * i) + (1000 * j)) addVisitForSite(site, intoHistory: history, from: .local, atTime: visitTime) addVisitForSite(site, intoHistory: history, from: .remote, atTime: visitTime - 100) } } } func addVisitForSite(_ site: Site, intoHistory history: SQLiteHistory, from: VisitOrigin, atTime: MicrosecondTimestamp) { let visit = SiteVisit(site: site, date: atTime, type: VisitType.link) switch from { case .local: history.addLocalVisit(visit).succeeded() case .remote: history.storeRemoteVisits([visit], forGUID: site.guid!).succeeded() } }
mpl-2.0
MrDeveloper4/TestProject-GitHubAPI
TestProject-GitHubAPI/Pods/RealmSwift/RealmSwift/SortDescriptor.swift
10
4018
//////////////////////////////////////////////////////////////////////////// // // Copyright 2015 Realm Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////// import Foundation import Realm /** A `SortDescriptor` stores a property name and a sort order for use with `sorted(sortDescriptors:)`. It is similar to `NSSortDescriptor`, but supports only the subset of functionality which can be efficiently run by Realm's query engine. */ public struct SortDescriptor { // MARK: Properties /// The name of the property which the sort descriptor orders results by. public let property: String /// Whether the descriptor sorts in ascending or descending order. public let ascending: Bool /// Converts the receiver to an `RLMSortDescriptor` internal var rlmSortDescriptorValue: RLMSortDescriptor { return RLMSortDescriptor(property: property, ascending: ascending) } // MARK: Initializers /** Initializes a sort descriptor with the given property and sort order values. - parameter property: The name of the property which the sort descriptor orders results by. - parameter ascending: Whether the descriptor sorts in ascending or descending order. */ public init(property: String, ascending: Bool = true) { self.property = property self.ascending = ascending } // MARK: Functions /// Returns a copy of the sort descriptor with the sort order reversed. public func reversed() -> SortDescriptor { return SortDescriptor(property: property, ascending: !ascending) } } // MARK: CustomStringConvertible extension SortDescriptor: CustomStringConvertible { /// Returns a human-readable description of the sort descriptor. public var description: String { let direction = ascending ? "ascending" : "descending" return "SortDescriptor (property: \(property), direction: \(direction))" } } // MARK: Equatable extension SortDescriptor: Equatable {} /// Returns whether the two sort descriptors are equal. public func == (lhs: SortDescriptor, rhs: SortDescriptor) -> Bool { // swiftlint:disable:previous valid_docs return lhs.property == rhs.property && lhs.ascending == lhs.ascending } // MARK: StringLiteralConvertible extension SortDescriptor: StringLiteralConvertible { /// `StringLiteralType`. Required for `StringLiteralConvertible` conformance. public typealias UnicodeScalarLiteralType = StringLiteralType /// `StringLiteralType`. Required for `StringLiteralConvertible` conformance. public typealias ExtendedGraphemeClusterLiteralType = StringLiteralType /** Creates a `SortDescriptor` from a `UnicodeScalarLiteralType`. - parameter unicodeScalarLiteral: Property name literal. */ public init(unicodeScalarLiteral value: UnicodeScalarLiteralType) { self.init(property: value) } /** Creates a `SortDescriptor` from an `ExtendedGraphemeClusterLiteralType`. - parameter extendedGraphemeClusterLiteral: Property name literal. */ public init(extendedGraphemeClusterLiteral value: ExtendedGraphemeClusterLiteralType) { self.init(property: value) } /** Creates a `SortDescriptor` from a `StringLiteralType`. - parameter stringLiteral: Property name literal. */ public init(stringLiteral value: StringLiteralType) { self.init(property: value) } }
mit
tardieu/swift
validation-test/compiler_crashers_fixed/00121-swift-diagnosticengine-diagnose.swift
65
521
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck func j(d: h) -> <k>(() -> k) -> h { return { n n "\(} c i<k : i> { } c i: i { } c e : l { } f = e protocol m : o h = h }
apache-2.0
maqinjun/CoreDataStack
CustomCoreDataStack/CustomCoreDataStackTests/CoreDataTest.swift
1
1359
// // CoreDataTest.swift // CustomCoreDataStack // // Created by maqj on 5/6/16. // Copyright © 2016 maqj. All rights reserved. // import XCTest import CoreData class CoreDataTest: XCTestCase { var coreDataStack: CoreDataStackTest! override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. coreDataStack = CoreDataStackTest() } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() coreDataStack = nil } func testData() -> Void { print("test data") } func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. // XCTAssert(coreDataStack.model != nil) XCTAssert(coreDataStack.psc != nil) XCTAssert(coreDataStack.store != nil) // XCTAssert(coreDataStack.context != nil) } func testPerformanceExample() { // This is an example of a performance test case. self.measureBlock { // Put the code you want to measure the time of here. } } }
mit
antonselyanin/ListenerManagerGenerator
ListenerManagerGenerator/ExampleListener.swift
1
422
// // Created by Anton Selyanin on 04/02/2017. // Copyright (c) 2017 Anton Selyanin. All rights reserved. // import Foundation struct Event1 {} struct Event2 {} protocol ExampleListener: class, AutoListenerManageable { func notify1(event1: Event1) func notify2(event2: Event2) func notify3() func notify4(event1: Event1, event2: Event2) func notify5(_ event1: Event1, event2 theEvent: Event2) }
mit
MateuszKarwat/Napi
Napi/Models/Subtitle Format/Supported Subtitle Formats/TMPlayerSubtitleFormat.swift
1
2581
// // Created by Mateusz Karwat on 06/02/16. // Copyright © 2016 Mateusz Karwat. All rights reserved. // import Foundation /// Represents TMPlayer Subtitle Format. /// TMPlayer Subtitle Format looks like this: /// /// 01:12:33:First line of a text.|Seconds line of a text. struct TMPlayerSubtitleFormat: SubtitleFormat { static let fileExtension = "txt" static let isTimeBased = true static let regexPattern = "(\\d{1,2}):(\\d{1,2}):(\\d{1,2}):(.+)" static func decode(_ aString: String) -> [Subtitle] { var decodedSubtitles = [Subtitle]() self.enumerateMatches(in: aString) { match in let hours = Int(match.capturedSubstrings[0])!.hours let minutes = Int(match.capturedSubstrings[1])!.minutes let seconds = Int(match.capturedSubstrings[2])!.seconds let timestamp = hours + minutes + seconds let newSubtitle = Subtitle(startTimestamp: timestamp, stopTimestamp: timestamp + 5.seconds, text: match.capturedSubstrings[3]) decodedSubtitles.append(newSubtitle) } if decodedSubtitles.count > 1 { for i in 0 ..< decodedSubtitles.count - 1 { let currentStopTimestamp = decodedSubtitles[i].stopTimestamp.baseValue let followingStartTimestamp = decodedSubtitles[i + 1].startTimestamp.baseValue if currentStopTimestamp > followingStartTimestamp { decodedSubtitles[i].stopTimestamp = decodedSubtitles[i + 1].startTimestamp - 1.milliseconds } } } return decodedSubtitles } static func encode(_ subtitles: [Subtitle]) -> [String] { var encodedSubtitles = [String]() for subtitle in subtitles { encodedSubtitles.append("\(subtitle.startTimestamp.stringFormat()):\(subtitle.text)") } return encodedSubtitles } } fileprivate extension Timestamp { /// Returns a `String` which is in format required by TMPlayer Subtitle Format. func stringFormat() -> String { let minutes = self - Timestamp(value: self.numberOfFull(.hours), unit: .hours) let seconds = minutes - Timestamp(value: minutes.numberOfFull(.minutes), unit: .minutes) return "\(self.numberOfFull(.hours).toString(leadingZeros: 2)):" + "\(minutes.numberOfFull(.minutes).toString(leadingZeros: 2)):" + "\(seconds.numberOfFull(.seconds).toString(leadingZeros: 2))" } }
mit
lerigos/music-service
iOS_9/Pods/ImagePicker/Source/ImageGallery/ImageGalleryView.swift
1
7732
import UIKit import Photos protocol ImageGalleryPanGestureDelegate: class { func panGestureDidStart() func panGestureDidChange(translation: CGPoint) func panGestureDidEnd(translation: CGPoint, velocity: CGPoint) } public class ImageGalleryView: UIView { struct Dimensions { static let galleryHeight: CGFloat = 160 static let galleryBarHeight: CGFloat = 24 static let indicatorWidth: CGFloat = 41 static let indicatorHeight: CGFloat = 8 } lazy public var collectionView: UICollectionView = { [unowned self] in let collectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: self.collectionViewLayout) collectionView.translatesAutoresizingMaskIntoConstraints = false collectionView.backgroundColor = Configuration.mainColor collectionView.showsHorizontalScrollIndicator = false collectionView.dataSource = self collectionView.delegate = self return collectionView }() lazy var collectionViewLayout: UICollectionViewLayout = { [unowned self] in let layout = UICollectionViewFlowLayout() layout.scrollDirection = .Horizontal layout.minimumInteritemSpacing = Configuration.cellSpacing layout.minimumLineSpacing = 2 layout.sectionInset = UIEdgeInsetsZero return layout }() lazy var topSeparator: UIView = { [unowned self] in let view = UIView() view.translatesAutoresizingMaskIntoConstraints = false view.addGestureRecognizer(self.panGestureRecognizer) view.backgroundColor = UIColor.blackColor().colorWithAlphaComponent(0.6) return view }() lazy var indicator: UIView = { let view = UIView() view.backgroundColor = UIColor.whiteColor().colorWithAlphaComponent(0.6) view.layer.cornerRadius = Dimensions.indicatorHeight / 2 view.translatesAutoresizingMaskIntoConstraints = false return view }() lazy var panGestureRecognizer: UIPanGestureRecognizer = { [unowned self] in let gesture = UIPanGestureRecognizer() gesture.addTarget(self, action: #selector(handlePanGestureRecognizer(_:))) return gesture }() public lazy var noImagesLabel: UILabel = { [unowned self] in let label = UILabel() label.font = Configuration.noImagesFont label.textColor = Configuration.noImagesColor label.text = Configuration.noImagesTitle label.alpha = 0 label.sizeToFit() self.addSubview(label) return label }() public lazy var selectedStack = ImageStack() lazy var assets = [PHAsset]() weak var delegate: ImageGalleryPanGestureDelegate? var collectionSize: CGSize? var shouldTransform = false var imagesBeforeLoading = 0 var fetchResult: PHFetchResult? var canFetchImages = false var imageLimit = 0 // MARK: - Initializers override init(frame: CGRect) { super.init(frame: frame) backgroundColor = Configuration.mainColor collectionView.registerClass(ImageGalleryViewCell.self, forCellWithReuseIdentifier: CollectionView.reusableIdentifier) [collectionView, topSeparator].forEach { addSubview($0) } topSeparator.addSubview(indicator) imagesBeforeLoading = 0 fetchPhotos() } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Layout public override func layoutSubviews() { super.layoutSubviews() updateNoImagesLabel() } func updateFrames() { let totalWidth = UIScreen.mainScreen().bounds.width frame.size.width = totalWidth let collectionFrame = frame.height == Dimensions.galleryBarHeight ? 100 + Dimensions.galleryBarHeight : frame.height topSeparator.frame = CGRect(x: 0, y: 0, width: totalWidth, height: Dimensions.galleryBarHeight) topSeparator.autoresizingMask = [.FlexibleLeftMargin, .FlexibleRightMargin, .FlexibleWidth] indicator.frame = CGRect(x: (totalWidth - Dimensions.indicatorWidth) / 2, y: (topSeparator.frame.height - Dimensions.indicatorHeight) / 2, width: Dimensions.indicatorWidth, height: Dimensions.indicatorHeight) collectionView.frame = CGRect(x: 0, y: topSeparator.frame.height, width: totalWidth, height: collectionFrame - topSeparator.frame.height) collectionSize = CGSize(width: collectionView.frame.height, height: collectionView.frame.height) collectionView.reloadData() } func updateNoImagesLabel() { let height = CGRectGetHeight(bounds) let threshold = Dimensions.galleryBarHeight * 2 UIView.animateWithDuration(0.25) { if threshold > height || self.collectionView.alpha != 0 { self.noImagesLabel.alpha = 0 } else { self.noImagesLabel.center = CGPoint(x: CGRectGetWidth(self.bounds) / 2, y: height / 2) self.noImagesLabel.alpha = (height > threshold) ? 1 : (height - Dimensions.galleryBarHeight) / threshold } } } // MARK: - Photos handler func fetchPhotos(completion: (() -> Void)? = nil) { ImagePicker.fetch { assets in self.assets.removeAll() self.assets.appendContentsOf(assets) self.collectionView.reloadData() completion?() } } // MARK: - Pan gesture recognizer func handlePanGestureRecognizer(gesture: UIPanGestureRecognizer) { guard let superview = superview else { return } let translation = gesture.translationInView(superview) let velocity = gesture.velocityInView(superview) switch gesture.state { case .Began: delegate?.panGestureDidStart() case .Changed: delegate?.panGestureDidChange(translation) case .Ended: delegate?.panGestureDidEnd(translation, velocity: velocity) default: break } } func displayNoImagesMessage(hideCollectionView: Bool) { collectionView.alpha = hideCollectionView ? 0 : 1 updateNoImagesLabel() } } // MARK: CollectionViewFlowLayout delegate methods extension ImageGalleryView: UICollectionViewDelegateFlowLayout { public func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize { guard let collectionSize = collectionSize else { return CGSizeZero } return collectionSize } } // MARK: CollectionView delegate methods extension ImageGalleryView: UICollectionViewDelegate { public func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { guard let cell = collectionView.cellForItemAtIndexPath(indexPath) as? ImageGalleryViewCell else { return } let asset = assets[indexPath.row] ImagePicker.resolveAsset(asset) { image in guard let _ = image else { return } if cell.selectedImageView.image != nil { UIView.animateWithDuration(0.2, animations: { cell.selectedImageView.transform = CGAffineTransformMakeScale(0.1, 0.1) }) { _ in cell.selectedImageView.image = nil } self.selectedStack.dropAsset(asset) } else if self.imageLimit == 0 || self.imageLimit > self.selectedStack.assets.count { cell.selectedImageView.image = AssetManager.getImage("selectedImageGallery") cell.selectedImageView.transform = CGAffineTransformMakeScale(0, 0) UIView.animateWithDuration(0.2) { _ in cell.selectedImageView.transform = CGAffineTransformIdentity } self.selectedStack.pushAsset(asset) } } } public func collectionView(collectionView: UICollectionView, didEndDisplayingCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) { guard indexPath.row + 10 >= assets.count && indexPath.row < fetchResult?.count && canFetchImages else { return } fetchPhotos() canFetchImages = false } }
apache-2.0
Reality-Virtually-Hackathon/Team-2
WorkspaceAR/Connectivity/ConnectivityManager.swift
1
5951
// // ConnectivityManager.swift // WorkspaceAR // // Created by Joe Crotchett on 10/7/17. // Copyright © 2017 Apple. All rights reserved. // import Foundation import MultipeerConnectivity protocol ConnectivityManagerDelegate { // Called when a peer has changed it's connection status func connectedDevicesChanged(manager : ConnectivityManager, connectedDevices: [String]) // Called when data has been recieved from a peer func dataReceived(manager: ConnectivityManager, data: Data) } class ConnectivityManager : NSObject { let ServiceType = "WorkspaceAR" let myPeerId = MCPeerID(displayName: UIDevice.current.name) var advertiser: MCNearbyServiceAdvertiser? var browser: MCNearbyServiceBrowser? var delegate : ConnectivityManagerDelegate? lazy var session : MCSession = { let session = MCSession(peer: self.myPeerId, securityIdentity: nil, encryptionPreference: .none) session.delegate = self return session }() deinit { if let advertiser = advertiser { advertiser.stopAdvertisingPeer() } if let browser = browser { browser.stopBrowsingForPeers() } } // Act as the host func startAdvertising() { advertiser = MCNearbyServiceAdvertiser(peer: myPeerId, discoveryInfo: nil, serviceType: ServiceType) if let advertiser = advertiser { advertiser.delegate = self advertiser.startAdvertisingPeer() } } // Act as the client func startBrowsing() { browser = MCNearbyServiceBrowser(peer: myPeerId, serviceType: ServiceType) if let browser = browser { browser.delegate = self browser.startBrowsingForPeers() } } // Broadcast data to all peers func sendTestString() { print("Sending test string") if session.connectedPeers.count > 0 { do { try self.session.send("test string".data(using: .utf8)!, toPeers: session.connectedPeers, with: .reliable) } catch let error { print("%@", "Error for sending: \(error)") } } } // Broadcast data to all peers func sendData(data: Data) { if session.connectedPeers.count > 0 { do { try self.session.send(data, toPeers: session.connectedPeers, with: .reliable) } catch let error { print("%@", "Error for sending: \(error)") } } } } //MARK: MCNearbyServiceAdvertiserDelegate extension ConnectivityManager: MCNearbyServiceAdvertiserDelegate { func advertiser(_ advertiser: MCNearbyServiceAdvertiser, didNotStartAdvertisingPeer error: Error) { print("%@", "didNotStartAdvertisingPeer: \(error)") } func advertiser(_ advertiser: MCNearbyServiceAdvertiser, didReceiveInvitationFromPeer peerID: MCPeerID, withContext context: Data?, invitationHandler: @escaping (Bool, MCSession?) -> Void) { print("%@", "didReceiveInvitationFromPeer \(peerID)") invitationHandler(true, self.session) } } //MARK: MCNearbyServiceBrowserDelegate extension ConnectivityManager : MCNearbyServiceBrowserDelegate { func browser(_ browser: MCNearbyServiceBrowser, didNotStartBrowsingForPeers error: Error) { print("%@", "didNotStartBrowsingForPeers: \(error)") } func browser(_ browser: MCNearbyServiceBrowser, foundPeer peerID: MCPeerID, withDiscoveryInfo info: [String : String]?) { print("%@", "foundPeer: \(peerID)") print("%@", "invitePeer: \(peerID)") browser.invitePeer(peerID, to: self.session, withContext: nil, timeout: 10) } func browser(_ browser: MCNearbyServiceBrowser, lostPeer peerID: MCPeerID) { print("%@", "lostPeer: \(peerID)") } } //MARK: MCSessionDelegate extension ConnectivityManager : MCSessionDelegate { func session(_ session: MCSession, peer peerID: MCPeerID, didChange state: MCSessionState) { print("%@", "peer \(peerID) didChangeState: \(state)") self.delegate?.connectedDevicesChanged(manager: self, connectedDevices: session.connectedPeers.map{$0.displayName}) } func session(_ session: MCSession, didReceive data: Data, fromPeer peerID: MCPeerID) { print("%@", "didReceiveData: \(data)") self.delegate?.dataReceived(manager: self, data: data) } func session(_ session: MCSession, didReceive stream: InputStream, withName streamName: String, fromPeer peerID: MCPeerID) { assert(true, "not impelemented") } func session(_ session: MCSession, didStartReceivingResourceWithName resourceName: String, fromPeer peerID: MCPeerID, with progress: Progress) { assert(true, "not impelemented") } func session(_ session: MCSession, didFinishReceivingResourceWithName resourceName: String, fromPeer peerID: MCPeerID, at localURL: URL?, withError error: Error?) { assert(true, "not impelemented") } }
mit
pauljohanneskraft/Math
CoreMath/Classes/Numbers/Numbers.swift
1
968
// // Numbers.swift // Math // // Created by Paul Kraft on 03.08.16. // Copyright © 2016 pauljohanneskraft. All rights reserved. // import Foundation // swiftlint:disable type_name public typealias R = Double public typealias N = UInt public typealias Z = Int // swiftlint:enable type_name public func Z_(_ v: UInt) -> Set<UInt> { return Set<UInt>(0..<v) } public func Z_(_ v: Int) -> Set<Int> { return Set<Int>(0..<v) } public protocol Ordered: Comparable { static var min: Self { get } static var max: Self { get } } extension Ordered { static var range: ClosedRange<Self> { return min...max } } public protocol Randomizable: Comparable { static func random(inside: ClosedRange<Self>) -> Self } infix operator =~ : ComparisonPrecedence extension Double { public static func =~ (lhs: Double, rhs: Double) -> Bool { let inacc = Swift.max(lhs.inaccuracy, rhs.inaccuracy) return (lhs - rhs).abs <= inacc } }
mit
gradyzhuo/GZImageLayoutView
GZImageEditorPositionView.swift
1
7499
// // GZImageEditorPositionView.swift // Flingy // // Created by Grady Zhuo on 7/2/15. // Copyright (c) 2015 Skytiger Studio. All rights reserved. // import Foundation import UIKit internal let GZImageEditorDefaultZoomScale : CGFloat = 1.0 public class GZImageEditorPositionView:GZPositionView { public var minZoomScale : CGFloat = GZImageEditorDefaultZoomScale public var maxZoomScale : CGFloat = 3.0 internal var ratio:CGFloat = 1.0 private var privateObjectInfo = ObjectInfo() public var delegate:GZImageEditorPositionViewDelegate? internal var resizeContentMode:GZImageEditorResizeContentMode = .AspectFill public var metaData:GZPositionViewMetaData{ set{ self.resizeContentMode = newValue.resizeContentMode self.imageMetaData = newValue.imageMetaData self.scrollViewMetaData = newValue.scrollViewMetaData self.privateObjectInfo.metaData = newValue } get{ self.privateObjectInfo.metaData = GZPositionViewMetaData(resizeContentMode: self.resizeContentMode, imageMetaData: self.imageMetaData, scrollViewMetaData: self.scrollViewMetaData) return self.privateObjectInfo.metaData } } public var scrollViewMetaData:GZScrollViewMetaData{ set{ self.scrollView.zoomScale = newValue.zoomScale self.scrollView.contentSize = newValue.contentSize self.scrollView.contentOffset = newValue.contentOffset } get{ return GZScrollViewMetaData(scrollView: self.scrollView, imageRatio: self.ratio) } } public var imageMetaData:GZPositionViewImageMetaData{ set{ self.setImage(self.resizeContentMode ,image: newValue.image, needResetScrollView: true) } get{ return GZPositionViewImageMetaData(identifier: self.identifier, image: self.image) } } public var image:UIImage?{ set{ self.setImage(self.resizeContentMode, image: newValue, needResetScrollView: true) } get{ return self.scrollView.imageView.image } } private lazy var scrollView:GZImageCropperScrollView = { var scrollView = GZImageCropperScrollView(imageEditorPositionView: self) scrollView.scrollsToTop = false scrollView.delaysContentTouches = false scrollView.minimumZoomScale = self.minZoomScale scrollView.maximumZoomScale = self.maxZoomScale return scrollView }() // public internal(set) lazy var imageView:UIImageView = { // // var imageView = UIImageView() // imageView.contentMode = UIViewContentMode.ScaleAspectFill // // // return imageView // }() override func configure(position: GZPosition!) { super.configure(position) self.addSubview(self.scrollView) // self.scrollView.addSubview(self.imageView) self.scrollView.frame = self.bounds } internal override var layoutView:GZImageLayoutView?{ didSet{ let image = layoutView?.imageForPosition(self.identifier) if image == nil && self.image != nil { layoutView?.setImage(self.image, forPosition: self.identifier) } } } public func setImage(resizeContentMode: GZImageEditorResizeContentMode,image:UIImage?, needResetScrollView reset:Bool){ self.scrollView.imageView.image = image if reset{ self.resetScrollView(resizeContentMode, scrollView: self.scrollView, image: image) } if let parentLayoutView = self.layoutView { var imageMetaData = parentLayoutView.imageMetaDataContent if let newImage = image { imageMetaData[self.identifier] = newImage }else{ imageMetaData.removeValueForKey(self.identifier) } parentLayoutView.imageMetaDataContent = imageMetaData } } override public func layoutSubviews() { super.layoutSubviews() self.scrollView.frame = self.bounds let metaData = self.privateObjectInfo.metaData ?? self.metaData self.imageMetaData = metaData.imageMetaData self.scrollViewMetaData = metaData.scrollViewMetaData } struct ObjectInfo { var metaData:GZPositionViewMetaData! = nil } override public func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { super.touchesBegan(touches, withEvent: event) if let touch = touches.first { let point = touch.locationInView(self) let hitView = self.hitTest(point, withEvent: event) if hitView == self.scrollView { self.delegate?.imageEditorPositionViewWillBeginEditing(self) } } } } //MARK: - Crop & Resize support extension GZImageEditorPositionView { internal func resetResizeContentMode(resizeContentMode : GZImageEditorResizeContentMode = .AspectFill){ self.resetScrollView(resizeContentMode, scrollView: self.scrollView, image: self.image) } internal func resetScrollView(resizeContentMode : GZImageEditorResizeContentMode = .AspectFill, scrollView:UIScrollView, image:UIImage?){ self.initializeScrollView(scrollView) if let vaildImage = image{ //預先取出所需的屬性值 let scrollViewWidth = scrollView.frame.width let scrollViewHeight = scrollView.frame.height // let vaildImageWidth = vaildImage.size.width // let vaildImageHeight = vaildImage.size.height var zoomScaleToFillScreen:CGFloat = 1.0 var targetSize = CGSize.zero (self.ratio, targetSize, zoomScaleToFillScreen) = resizeContentMode.targetContentSize(scrollSize: scrollView.frame.size, imageSize: vaildImage.size) scrollView.maximumZoomScale = ceil(zoomScaleToFillScreen) + 2 // scrollView.contentSize = targetSize // self.scrollView.imageView.frame.size = targetSize let xOffsetToCenter:CGFloat = (targetSize.width - scrollViewWidth)/2 let yOffsetToCenter:CGFloat = (targetSize.height - scrollViewHeight)/2 scrollView.contentOffset.x += xOffsetToCenter scrollView.contentOffset.y += yOffsetToCenter scrollView.setZoomScale(zoomScaleToFillScreen, animated: false) } } internal func initializeScrollView(scrollView:UIScrollView, contentSize:CGSize = CGSizeZero){ scrollView.zoomScale = self.minZoomScale scrollView.contentOffset = CGPointZero scrollView.contentSize = CGSizeZero } }
apache-2.0
kaxilisi/DouYu
DYZB/DYZB/Classes/Home/ViewModel/RecommendViewModel.swift
1
3633
// // RecommendViewModel.swift // DYZB // // Created by apple on 2016/10/29. // Copyright © 2016年 apple. All rights reserved. // import UIKit class RecommendViewModel{ lazy var anchorGroups : [AnchorGroup] = [AnchorGroup]() lazy var cycleModels : [CycleModel] = [CycleModel]() fileprivate lazy var bigDataGroup : AnchorGroup = AnchorGroup() fileprivate lazy var prettyGroup : AnchorGroup = AnchorGroup() } //MARK:- 发送网络请求 extension RecommendViewModel{ func requestData(_ finishCallback : @escaping () -> ()){ let parameters = ["limit" : "4","offset":"0","time" : NSDate.getCurrentTime()] //第一部分数据 let dGroup = DispatchGroup() dGroup.enter() NetworkTools.requestData(.get, URLString: "http://capi.douyucdn.cn/api/v1/getbigDataRoom", parameters: ["time": NSDate.getCurrentTime()]) { (result) in guard let resultDict = result as? [String : NSObject] else {return} guard let dataArray = resultDict["data"] as? [[String : NSObject]] else {return} self.bigDataGroup.tag_name = "热门" self.bigDataGroup.icon_name = "home_header_hot" for dict in dataArray{ let anchor = AnchorModel(dict) self.bigDataGroup.anchors.append(anchor) } dGroup.leave() } //第二部分数据 dGroup.enter() NetworkTools.requestData(.get, URLString: "http://capi.douyucdn.cn/api/v1/getVerticalRoom", parameters: parameters) { (result) in guard let resultDict = result as? [String : NSObject] else {return} guard let dataArray = resultDict["data"] as? [[String : NSObject]] else {return} self.prettyGroup.tag_name = "颜值" self.prettyGroup.icon_name = "home_header_phone" for dict in dataArray{ let anchor = AnchorModel(dict) self.prettyGroup.anchors.append(anchor) } dGroup.leave() } //第三部分数据 dGroup.enter() NetworkTools.requestData(.get, URLString: "http://capi.douyucdn.cn/api/v1/getHotCate", parameters: parameters) { (result) in guard let resultDict = result as? [String : NSObject] else {return} guard let dataArray = resultDict["data"] as? [[String : NSObject]] else {return} for dict in dataArray{ let group = AnchorGroup(dict) if group.push_vertical_screen == "0"{ self.anchorGroups.append(group) } } dGroup.leave() } dGroup.notify(queue: DispatchQueue.main) { self.anchorGroups.insert(self.prettyGroup, at: 0) self.anchorGroups.insert(self.bigDataGroup, at: 0) finishCallback() } } func requestCycleData(_ finishCallback : @escaping () -> ()){ NetworkTools.requestData(.get, URLString: "http://capi.douyucdn.cn/api/v1/slide/6", parameters: ["version" : "2.401"]){ (result) in guard let resultDict = result as? [String : NSObject] else {return} guard let dataArray = resultDict["data"] as? [[String : NSObject]] else {return} //字典转模型 for dict in dataArray { self.cycleModels.append(CycleModel(dict)) } finishCallback() } } }
mit
jairoeli/Habit
Zero/Sources/Utils/Reorder/ReorderController+DestinationRow.swift
1
4789
// // Copyright (c) 2016 Adam Shin // // 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 extension CGRect { init(center: CGPoint, size: CGSize) { self.init(x: center.x - (size.width / 2), y: center.y - (size.height / 2), width: size.width, height: size.height) } } extension ReorderController { func updateDestinationRow() { guard case let .reordering(sourceRow, destinationRow, snapshotOffset) = reorderState, let tableView = tableView, let newDestinationRow = newDestinationRow(), newDestinationRow != destinationRow else { return } reorderState = .reordering( sourceRow: sourceRow, destinationRow: newDestinationRow, snapshotOffset: snapshotOffset ) delegate?.tableView(tableView, reorderRowAt: destinationRow, to: newDestinationRow) tableView.beginUpdates() tableView.deleteRows(at: [destinationRow], with: .fade) tableView.insertRows(at: [newDestinationRow], with: .fade) tableView.endUpdates() } func newDestinationRow() -> IndexPath? { guard case let .reordering(_, destinationRow, _) = reorderState, let delegate = delegate, let tableView = tableView, let snapshotView = snapshotView else { return nil } let snapshotFrame = CGRect(center: snapshotView.center, size: snapshotView.bounds.size) let visibleRows = tableView.indexPathsForVisibleRows ?? [] let rowSnapDistances = visibleRows.map { path -> (path: IndexPath, distance: CGFloat) in let rect = tableView.rectForRow(at: path) if destinationRow.compare(path) == .orderedAscending { return (path, abs(snapshotFrame.maxY - rect.maxY)) } else { return (path, abs(snapshotFrame.minY - rect.minY)) } } let sectionIndexes = 0..<tableView.numberOfSections let sectionSnapDistances = sectionIndexes.flatMap { section -> (path: IndexPath, distance: CGFloat)? in let rowsInSection = tableView.numberOfRows(inSection: section) if section > destinationRow.section { let rect: CGRect if rowsInSection == 0 { rect = rectForEmptySection(section) } else { rect = tableView.rectForRow(at: IndexPath(row: 0, section: section)) } let path = IndexPath(row: 0, section: section) return (path, abs(snapshotFrame.maxY - rect.minY)) } else if section < destinationRow.section { let rect: CGRect if rowsInSection == 0 { rect = rectForEmptySection(section) } else { rect = tableView.rectForRow(at: IndexPath(row: rowsInSection - 1, section: section)) } let path = IndexPath(row: rowsInSection, section: section) return (path, abs(snapshotFrame.minY - rect.maxY)) } else { return nil } } let snapDistances = rowSnapDistances + sectionSnapDistances let availableSnapDistances = snapDistances.filter { delegate.tableView(tableView, canReorderRowAt: $0.path) != false } return availableSnapDistances.min(by: { $0.distance < $1.distance })?.path } func rectForEmptySection(_ section: Int) -> CGRect { guard let tableView = tableView else { return .zero } let sectionRect = tableView.rectForHeader(inSection: section) return UIEdgeInsetsInsetRect(sectionRect, UIEdgeInsets(top: sectionRect.height, left: 0, bottom: 0, right: 0)) } }
mit
openxc/openxc-ios-framework
openxc-ios-framework/VehicleMessageUnit.swift
1
1957
// // VehicleMessageUnit.swift // openxc-ios-framework // // Created by Ranjan, Kumar sahu (K.) on 12/03/18. // Copyright © 2018 Ford Motor Company. All rights reserved. // import UIKit open class VehicleMessageUnit: NSObject { static let sharedNetwork = VehicleMessageUnit() // Initialization static open let sharedInstance: VehicleMessageUnit = { let instance = VehicleMessageUnit() return instance }() fileprivate override init() { // connecting = false } public func getMesurementUnit(key:String , value:Any) -> Any{ let stringValue = String(describing: value) let measurementType = key var measurmentUnit : String = "" switch measurementType { case acceleratorPedal: measurmentUnit = stringValue + " %" return measurmentUnit case enginespeed: measurmentUnit = stringValue + " RPM" return measurmentUnit case fuelConsumed: measurmentUnit = stringValue + " L" return measurmentUnit case fuelLevel: measurmentUnit = stringValue + " %" return measurmentUnit case latitude: measurmentUnit = stringValue + " °" return measurmentUnit case longitude: measurmentUnit = stringValue + " °" return measurmentUnit case odometer: measurmentUnit = stringValue + " km" return measurmentUnit case steeringWheelAngle: measurmentUnit = stringValue + " °" return measurmentUnit case torqueTransmission: measurmentUnit = stringValue + " Nm" return measurmentUnit case vehicleSpeed: measurmentUnit = stringValue + " km/hr" return measurmentUnit default: return value } //return value } }
bsd-3-clause
wess/reddift
reddiftSample/UserViewController.swift
1
4883
// // UserViewController.swift // reddift // // Created by sonson on 2015/04/14. // Copyright (c) 2015年 sonson. All rights reserved. // import Foundation import reddift class UserViewController: UITableViewController { var session:Session? @IBOutlet var expireCell:UITableViewCell! override func viewDidLoad() { super.viewDidLoad() } func updateExpireCell(sender:AnyObject?) { println(NSThread.isMainThread()) if let token = session?.token { expireCell.detailTextLabel?.text = NSDate(timeIntervalSinceReferenceDate:token.expiresDate).description } } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: true); if indexPath.row == 2 && indexPath.section == 0 { if let token = session?.token as? OAuth2Token { token.refresh({ (result) -> Void in switch result { case let .Failure: println(result.error) case let .Success: if let newToken = result.value { dispatch_async(dispatch_get_main_queue(), { () -> Void in if var session = self.session { session.token = newToken } self.updateExpireCell(nil) OAuth2TokenRepository.saveIntoKeychainToken(newToken) }) } } }) } } if indexPath.row == 3 && indexPath.section == 0 { if let token = session?.token as? OAuth2Token { token.revoke({ (result) -> Void in switch result { case let .Failure: println(result.error) case let .Success: dispatch_async(dispatch_get_main_queue(), { () -> Void in OAuth2TokenRepository.removeFromKeychainTokenWithName(token.name) self.navigationController?.popToRootViewControllerAnimated(true) }) } }) } } if indexPath.section == 3 { if let vc = self.storyboard?.instantiateViewControllerWithIdentifier("UserContentViewController") as? UserContentViewController { let content = [ UserContent.Overview, UserContent.Submitted, UserContent.Comments, UserContent.Liked, UserContent.Disliked, UserContent.Hidden, UserContent.Saved, UserContent.Gilded ] vc.userContent = content[indexPath.row] vc.session = self.session self.navigationController?.pushViewController(vc, animated: true) } } } override func viewWillAppear(animated: Bool) { updateExpireCell(nil) } override func viewDidAppear(animated: Bool) { println(session) } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "ToProfileViewController" { if let con = segue.destinationViewController as? ProfileViewController { con.session = self.session } } else if segue.identifier == "ToFrontViewController" { if let con = segue.destinationViewController as? LinkViewController { con.session = self.session } } else if segue.identifier == "ToSubredditsListViewController" { if let con = segue.destinationViewController as? SubredditsListViewController { con.session = self.session } } else if segue.identifier == "ToSubredditsViewController" { if let con = segue.destinationViewController as? SubredditsViewController { con.session = self.session } } else if segue.identifier == "OpenInbox" { if let con = segue.destinationViewController as? MessageViewController { con.session = self.session con.messageWhere = .Inbox } } else if segue.identifier == "OpenSent" { if let con = segue.destinationViewController as? MessageViewController { con.session = self.session con.messageWhere = .Sent } } else if segue.identifier == "OpenUnread" { if let con = segue.destinationViewController as? MessageViewController { con.session = self.session con.messageWhere = .Unread } } } }
mit
recurly/recurly-client-ios
RecurlySDK-iOSTests/RecurlySDK-iOSTests.swift
1
5631
// // RecurlySDK-iOSTests.swift // RecurlySDK-iOSTests // // Created by George Andrew Shoemaker on 8/20/22. // import XCTest @testable import RecurlySDK_iOS class RecurlySDK_iOSTests: XCTestCase { // If you are running these tests in Xcode // you should set your public key here. // Otherwise PUBLIC_KEY should be set from the command line let publicKey = getEnviornmentVar("PUBLIC_KEY") ?? "" let paymentHandler = REApplePaymentHandler() // This utility function will setup the TokenizationManager // with valid billingInfo and cardData private func setupTokenizationManager() { RETokenizationManager.shared.setBillingInfo( billingInfo: REBillingInfo( firstName: "David", lastName: "Figueroa", address1: "123 Main St", address2: "", company: "CH2", country: "USA", city: "Miami", state: "Florida", postalCode: "33101", phone: "555-555-5555", vatNumber: "", taxIdentifier: "", taxIdentifierType: "" ) ) RETokenizationManager.shared.cardData.number = "4111111111111111" RETokenizationManager.shared.cardData.month = "12" RETokenizationManager.shared.cardData.year = "2022" RETokenizationManager.shared.cardData.cvv = "123" } func testPublicKeyIsValid() throws { guard !publicKey.isEmpty else { XCTFail("PUBLIC_KEY was not set") return } REConfiguration.shared.initialize(publicKey: publicKey) setupTokenizationManager() let tokenResponseExpectation = expectation(description: "TokenResponse") RETokenizationManager.shared.getTokenId { tokenId, errorResponse in if let errorMessage = errorResponse?.error.message, errorMessage == "Public key not found" { XCTFail(errorMessage + " : Is your public key valid?") return } if let errorResponse = errorResponse { XCTFail(errorResponse.error.message ?? "Something went wrong. No error message arrived with error.") return } XCTAssertFalse(tokenId?.isEmpty ?? true, "tokenID was unexpectedly empty.") tokenResponseExpectation.fulfill() } wait(for: [tokenResponseExpectation], timeout: 5.0) } func testTokenization() throws { //Initialize the SDK REConfiguration.shared.initialize(publicKey: publicKey) setupTokenizationManager() let tokenResponseExpectation = expectation(description: "TokenResponse") RETokenizationManager.shared.getTokenId { tokenId, error in if let errorResponse = error { XCTFail(errorResponse.error.message ?? "") return } XCTAssertNotNil(tokenId) XCTAssertGreaterThan((tokenId?.count ?? 0), 5) tokenResponseExpectation.fulfill() } wait(for: [tokenResponseExpectation], timeout: 5.0) } func testApplePayIsSupported() { XCTAssertTrue(paymentHandler.applePaySupported(), "Apple Pay is not supported") } func testApplePayTokenization() { paymentHandler.isTesting = true let items = [ REApplePayItem(amountLabel: "Foo", amount: 3.80), REApplePayItem(amountLabel: "Bar", amount: 0.99), REApplePayItem(amountLabel: "Tax", amount: 1.53) ] var applePayInfo = REApplePayInfo(purchaseItems: items) applePayInfo.requiredContactFields = [] applePayInfo.merchantIdentifier = "merchant.com.recurly.recurlySDK-iOS" applePayInfo.countryCode = "US" applePayInfo.currencyCode = "USD" let tokenResponseExpectation = expectation(description: "ApplePayTokenResponse") paymentHandler.startApplePayment(with: applePayInfo) { (success, token, nil) in XCTAssertTrue(success, "Apple Pay is not ready") tokenResponseExpectation.fulfill() } wait(for: [tokenResponseExpectation], timeout: 3.0) } func testCardBrandValidator() throws { //Test VISA var ccValidator = CreditCardValidator("4111111111111111") XCTAssertTrue(ccValidator.type == .visa) //Test American Express ccValidator = CreditCardValidator("377813011144444") XCTAssertTrue(ccValidator.type == .amex) } func testValidCreditCard() throws { //Test Valid AE let ccValidator = CreditCardValidator("374245455400126") XCTAssertTrue(ccValidator.isValid) //Test Fake Card XCTAssertFalse(CreditCardValidator("3778111111111").isValid) } func testRecurlyErrorResponse() throws { //Initialize the SDK REConfiguration.shared.initialize(publicKey: publicKey) setupTokenizationManager() // Purposefully set this to empty as if it were missing RETokenizationManager.shared.cardData.month = "" let tokenResponseExpectation = expectation(description: "TokenErrorResponse") RETokenizationManager.shared.getTokenId { tokenId, error in if let errorResponse = error { XCTAssertTrue(errorResponse.error.code == "invalid-parameter") tokenResponseExpectation.fulfill() } } wait(for: [tokenResponseExpectation], timeout: 5.0) } }
mit
taku0/swift3-mode
test/swift-files/declarations.swift
1
4884
// swift3-mode:test:eval (setq-local swift3-mode:basic-offset 4) // swift3-mode:test:eval (setq-local swift3-mode:parenthesized-expression-offset 2) // swift3-mode:test:eval (setq-local swift3-mode:multiline-statement-offset 2) // swift3-mode:test:eval (setq-local swift3-mode:switch-case-offset 0) // Constant declarations let foo .bar = bar .baz class Foo { @ABC open weak let ( x, y ) : ( Int, Int ) = xx @ABC final unowned(safe) fileprivate let Foo .Bar(x) : Foo .Bar = xx let f = g : ( Int, Int ) -> throws [ X ] let x = 1, y = 1, z = 1 let x = 1, y = 1, z = 1 let x = 1 , y = 1 , z = 1 // Declaring multiple variables with single `let` statement doesn't seem to // be popular. Rather, we choose saving columns for the first variable. private final let x = foo .foo // This is intended. .foo, y = foo .then { x // This is intended. in foo return foo } .then { x in foo return foo }, z = foo .foo .foo } // Variable declarations class Foo { internal var x = foo .foo .foo, y = foo .foo .foo, z = foo .foo .foo internal var x : (Int, Int) { foo() return foo() } internal var x : (Int, Int) { @A mutating get { foo() return foo() } @A mutating set (it) { foo() foo(it) } } internal var x : (Int, Int) { @A mutating get @A mutating set } internal var x : (Int, Int) = foo .bar { return thisIsFunctionBlock } { // This is bad, but cannot decide indentation without looking forward // tokens. @A willSet(a) { foo() foo() } @A didSet(a) { foo() foo() } } // This is bad internal var x : (Int, Int) { @A willSet(a) { foo() foo() } @A didSet(a) { foo() foo() } } } // Type alias declaration class Foo { typealias A<B> = C .D @A private typealias A<B> = C .D } // Function declarations @A private final func foo<A, B>( x: Int y: Int = 1 z w: Int ... ) throws -> [A] where A: C, B = C<D> { foo() foo() } func foo() -> @A B { foo() foo() } // Enumeration declarations fileprivate indirect enum Foo<A, B> : X, Y, Z where A: C, B = D<E> { @A case A case B case C, D, E indirect case F( x: X, y: Y ), G, H func foo() { } case I case J } fileprivate enum Foo<A, B> : Int where A: C, B = D<E> { case A = 1, // swift3-mode:test:known-bug B = 2, C = 3 case D = 1, // swift3-mode:test:known-bug E = 2, F = 3 func foo() { } } enum Foo : X, Y, Z { } enum Foo : X , Y , Z { } // Struct declarations @A fileprivate struct Foo<A, B> : Bar<A, B>, Baz<A, B>, AAA<A, B> where A: C, B = D<E> { func foo() func foo() } // Protocol declarations protocol Foo { func foo(x, y) -> throws (A, B) init<A, B>(x: Int) throws where A: C subscript(x: Int) -> Int { get set } associatedtype AAA = BBB convenience init(x: Int, y, Int) } // Operator declarations infix operator +++ : precedenceGroupName prefix operator +++ postfix operator +++ precedencegroup precedenceGroupName { higherThan: lowerGroupName lowerThan: higherGroupName assignment: false associativity: left }
gpl-3.0
Takanu/Pelican
Sources/Pelican/API/Types/FileDownload.swift
1
857
// // FileDownload.swift // Pelican // // Created by Ido Constantine on 22/03/2018. // import Foundation /** Represents a file ready to be downloaded. Use the API method `getFile` to request a FileDownload type. */ public struct FileDownload: Codable { /// Unique identifier for the file. var fileID: String /// The file size, if known var fileSize: Int? /// The path that can be used to download the file, using https://api.telegram.org/file/bot<token>/<file_path>. var filePath: String? /// Coding keys to map values when Encoding and Decoding. enum CodingKeys: String, CodingKey { case fileID = "file_id" case fileSize = "file_size" case filePath = "file_path" } public init(fileID: String, fileSize: Int? = nil, filePath: String? = nil) { self.fileID = fileID self.fileSize = fileSize self.filePath = filePath } }
mit
FuckBoilerplate/RxCache
Tests/internal/persistence/DiskTest.swift
1
5463
// DiskOMTest.swift // RxCache // // Copyright (c) 2016 Victor Albertos https://github.com/VictorAlbertos // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import XCTest import Nimble @testable import RxCache class DiskTest: XCTestCase { fileprivate var diskUT : Disk! fileprivate let KeyRecords = "records", Key1 = "record1", Key2 = "record2" override class func initialize () { Disk().evictAll() } override func setUp() { super.setUp() diskUT = Disk() } func test1SaveRecordsOMMockEntity() { let records = getRecordsMock() var success = diskUT.saveRecord(Key1, record: records[0]) expect(success).to(equal(true)) success = diskUT.saveRecord(Key2, record: records[1]) expect(success).to(equal(true)) let arrayMocks : [Mock] = [records[0].cacheables[0], records[1].cacheables[0]] let recordContainingArray = Record(source: Source.Memory, cacheables: arrayMocks, timeAtWhichWasPersisted : 0, lifeTimeInSeconds: 0) success = diskUT.saveRecord(KeyRecords, record: recordContainingArray) expect(success).to(equal(true)) } func test2RetrieveRecords() { let record1 : Record<Mock> = diskUT.retrieveRecord(Key1)! expect(record1.source.rawValue).to(equal(Source.Memory.rawValue)) expect(record1.cacheables[0].aString).to(equal("1")) let record2 : Record<Mock> = diskUT.retrieveRecord(Key2)! expect(record2.source.rawValue).to(equal(Source.Persistence.rawValue)) expect(record2.cacheables[0].aString).to(equal("2")) expect(record2.cacheables[0].mock!.aString).to(equal("1")) let recordContainingArray : Record<Mock> = diskUT.retrieveRecord(KeyRecords)! expect(record1.source.rawValue).to(equal(Source.Memory.rawValue)) let mockContained1 : Mock = recordContainingArray.cacheables[0] expect(mockContained1.aString).to(equal("1")) let mockContained2 : Mock = recordContainingArray.cacheables[1] expect(mockContained2.aString).to(equal("2")) } func test3OverrideRecords() { let record1 : Record<Mock> = diskUT.retrieveRecord(Key1)! expect(record1.source.rawValue).to(equal(Source.Memory.rawValue)) expect(record1.cacheables[0].aString).to(equal("1")) let success = diskUT.saveRecord(Key1, record: getRecordsMock()[1]) expect(success).to(equal(true)) let record2 : Record<Mock> = diskUT.retrieveRecord(Key1)! expect(record2.source.rawValue).to(equal(Source.Persistence.rawValue)) expect(record2.cacheables[0].aString).to(equal("2")) expect(record2.cacheables[0].mock!.aString).to(equal("1")) } func test4ClearRecords() { test1SaveRecordsOMMockEntity() test2RetrieveRecords() diskUT.evict(KeyRecords) diskUT.evict(Key1) diskUT.evict(Key2) let record1 : Record<Mock>? = diskUT.retrieveRecord(Key1) expect(record1).to(beNil()) let record2 : Record<Mock>? = diskUT.retrieveRecord(Key2) expect(record2).to(beNil()) let recordContainingArray : Record<Mock>? = diskUT.retrieveRecord(KeyRecords) expect(recordContainingArray).to(beNil()) } func test5ClearAllRecords() { test1SaveRecordsOMMockEntity() test2RetrieveRecords() diskUT.evictAll() let record1 : Record<Mock>? = diskUT.retrieveRecord(Key1) expect(record1).to(beNil()) let record2 : Record<Mock>? = diskUT.retrieveRecord(Key2) expect(record2).to(beNil()) let recordContainingArray : Record<Mock>? = diskUT.retrieveRecord(KeyRecords) expect(recordContainingArray).to(beNil()) Disk().evictAll() } func getRecordsMock() -> [Record<Mock>] { let record1 : Record<Mock> = Record(source: Source.Memory, cacheables: [Mock(aString: "1")], timeAtWhichWasPersisted : 2.32, lifeTimeInSeconds: 0) let mock2 = Mock(aString: "2") mock2.mock = record1.cacheables[0] let record2 : Record<Mock> = Record(source: Source.Persistence, cacheables: [mock2], timeAtWhichWasPersisted : 0, lifeTimeInSeconds: 0) return [record1, record2] } }
mit
redlock/JAYSON
JAYSON/Classes/Reflection/Get.swift
2
631
/// Get value for key from instance public func get(_ key: String, from instance: Any) throws -> Any! { // guard let value = try properties(instance).first(where: { $0.key == key })?.value else { // throw ReflectionError.instanceHasNoKey(type: type(of: instance), key: key) // } // return value return nil } /// Get value for key from instance as type `T` public func get<T>(_ key: String, from instance: Any) throws -> T { let any: Any = try get(key, from: instance) guard let value = any as? T else { throw ReflectionError.valueIsNotType(value: any, theType: T.self) } return value }
mit
WhisperSystems/Signal-iOS
Signal/test/util/ImageCacheTest.swift
1
2268
// // Copyright (c) 2018 Open Whisper Systems. All rights reserved. // import XCTest @testable import Signal class ImageCacheTest: SignalBaseTest { var imageCache: ImageCache! let firstVariation = UIImage() let secondVariation = UIImage() let otherImage = UIImage() let cacheKey1 = "cache-key-1" as NSString let cacheKey2 = "cache-key-2" as NSString override func setUp() { super.setUp() self.imageCache = ImageCache() imageCache.setImage(firstVariation, forKey: cacheKey1, diameter: 100) imageCache.setImage(secondVariation, forKey: cacheKey1, diameter: 200) imageCache.setImage(otherImage, forKey: cacheKey2, diameter: 100) } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testSetGet() { XCTAssertEqual(firstVariation, imageCache.image(forKey: cacheKey1, diameter: 100)) XCTAssertEqual(secondVariation, imageCache.image(forKey: cacheKey1, diameter: 200)) XCTAssertNotEqual(secondVariation, imageCache.image(forKey: cacheKey1, diameter: 100)) XCTAssertEqual(otherImage, imageCache.image(forKey: cacheKey2, diameter: 100)) XCTAssertNil(imageCache.image(forKey: cacheKey2, diameter: 200)) } func testRemoveAllForKey() { // sanity check XCTAssertEqual(firstVariation, imageCache.image(forKey: cacheKey1, diameter: 100)) XCTAssertEqual(otherImage, imageCache.image(forKey: cacheKey2, diameter: 100)) imageCache.removeAllImages(forKey: cacheKey1) XCTAssertNil(imageCache.image(forKey: cacheKey1, diameter: 100)) XCTAssertNil(imageCache.image(forKey: cacheKey1, diameter: 200)) XCTAssertEqual(otherImage, imageCache.image(forKey: cacheKey2, diameter: 100)) } func testRemoveAll() { XCTAssertEqual(firstVariation, imageCache.image(forKey: cacheKey1, diameter: 100)) imageCache.removeAllImages() XCTAssertNil(imageCache.image(forKey: cacheKey1, diameter: 100)) XCTAssertNil(imageCache.image(forKey: cacheKey1, diameter: 200)) XCTAssertNil(imageCache.image(forKey: cacheKey2, diameter: 100)) } }
gpl-3.0
shhuangtwn/ProjectLynla
Pods/FacebookLogin/Sources/Login/LoginButtonDelegateBridge.swift
2
2085
// Copyright (c) 2016-present, Facebook, Inc. All rights reserved. // // You are hereby granted a non-exclusive, worldwide, royalty-free license to use, // copy, modify, and distribute this software in source code or binary form for use // in connection with the web services and APIs provided by Facebook. // // As with any software that integrates with the Facebook platform, your use of // this software is subject to the Facebook Developer Principles and Policies // [http://developers.facebook.com/policy/]. This copyright 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 FBSDKLoginKit internal class LoginButtonDelegateBridge: NSObject { internal weak var loginButton: LoginButton? func setupAsDelegateFor(sdkLoginButton: FBSDKLoginButton, loginButton: LoginButton) { self.loginButton = loginButton sdkLoginButton.delegate = self } } extension LoginButtonDelegateBridge: FBSDKLoginButtonDelegate { func loginButton(sdkButton: FBSDKLoginButton!, didCompleteWithResult sdkResult: FBSDKLoginManagerLoginResult?, error: NSError?) { guard let loginButton = loginButton, let delegate = loginButton.delegate else { return } let result = LoginResult(sdkResult: sdkResult, error: error) delegate.loginButtonDidCompleteLogin(loginButton, result: result) } func loginButtonDidLogOut(sdkButton: FBSDKLoginButton!) { guard let loginButton = loginButton, let delegate = loginButton.delegate else { return } delegate.loginButtonDidLogOut(loginButton) } }
mit
shahmishal/swift
test/SILGen/closure_self_recursion.swift
5
703
// RUN: %target-swift-emit-silgen -module-name foo %s | %FileCheck %s // RUN: %target-swift-emit-sil -module-name foo -verify %s // CHECK-LABEL: sil [ossa] @main // CHECK-LABEL: sil private [ossa] @$s3foo5recuryycvgyycfU_ var recur : () -> () { // CHECK-LABEL: function_ref @$s3foo5recuryycvg return { recur() } // expected-warning {{attempting to access 'recur' within its own getter}} } // CHECK-LABEL: sil private [ossa] @$s3foo12recur_harderyyycyyXEcvgyycyyXEcfU_ var recur_harder : (() -> ()) -> (() -> ()) { // CHECK-LABEL: function_ref @$s3foo12recur_harderyyycyyXEcvg return { f in recur_harder(f) } // expected-warning {{attempting to access 'recur_harder' within its own getter}} }
apache-2.0
slxl/ReactKit
ReactKit/Error.swift
1
764
// // Error.swift // ReactKit // // Created by Yasuhiro Inami on 2014/12/02. // Copyright (c) 2014年 Yasuhiro Inami. All rights reserved. // import Foundation public enum ReactKitError: Int { public static let Domain = "ReactKitErrorDomain" case cancelled = 0 case cancelledByDeinit = 1 case cancelledByUpstream = 2 case cancelledByTriggerStream = 3 case cancelledByInternalStream = 4 case rejectedByInternalTask = 1000 } /// helper internal func _RKError(_ error: ReactKitError, _ localizedDescriptionKey: String) -> NSError { return NSError( domain: ReactKitError.Domain, code: error.rawValue, userInfo: [ NSLocalizedDescriptionKey : localizedDescriptionKey ] ) }
mit
Lightstreamer/Lightstreamer-example-MPNStockList-client-ios
Shared/ChartViewDelegate.swift
1
1083
// Converted to Swift 5.4 by Swiftify v5.4.24488 - https://swiftify.com/ // // ChartViewDelegate.swift // StockList Demo for iOS // // Copyright (c) Lightstreamer Srl // // 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 @objc protocol ChartViewDelegate: NSObjectProtocol { func chart(_ chartControllter: ChartViewController?, didAdd threshold: ChartThreshold?) func chart(_ chartControllter: ChartViewController?, didChange threshold: ChartThreshold?) func chart(_ chartControllter: ChartViewController?, didRemove threshold: ChartThreshold?) }
apache-2.0
nathawes/swift
test/SILGen/cf_members.swift
8
14727
// RUN: %target-swift-emit-silgen -I %S/../IDE/Inputs/custom-modules %s -enable-objc-interop -I %S/Inputs/usr/include | %FileCheck %s import ImportAsMember func makeMetatype() -> Struct1.Type { return Struct1.self } // CHECK-LABEL: sil [ossa] @$s10cf_members17importAsUnaryInityyF public func importAsUnaryInit() { // CHECK: function_ref @CCPowerSupplyCreateDangerous : $@convention(c) () -> @owned CCPowerSupply var a = CCPowerSupply(dangerous: ()) let f: (()) -> CCPowerSupply = CCPowerSupply.init(dangerous:) a = f(()) } // CHECK-LABEL: sil [ossa] @$s10cf_members3foo{{[_0-9a-zA-Z]*}}F public func foo(_ x: Double) { // CHECK: bb0([[X:%.*]] : $Double): // CHECK: [[GLOBALVAR:%.*]] = global_addr @IAMStruct1GlobalVar // CHECK: [[READ:%.*]] = begin_access [read] [dynamic] [[GLOBALVAR]] : $*Double // CHECK: [[ZZ:%.*]] = load [trivial] [[READ]] let zz = Struct1.globalVar // CHECK: [[WRITE:%.*]] = begin_access [modify] [dynamic] [[GLOBALVAR]] : $*Double // CHECK: assign [[ZZ]] to [[WRITE]] Struct1.globalVar = zz // CHECK: [[Z:%.*]] = project_box // CHECK: [[FN:%.*]] = function_ref @IAMStruct1CreateSimple // CHECK: apply [[FN]]([[X]]) var z = Struct1(value: x) // The metatype expression should still be evaluated even if it isn't // used. // CHECK: [[MAKE_METATYPE:%.*]] = function_ref @$s10cf_members12makeMetatype{{[_0-9a-zA-Z]*}}F // CHECK: apply [[MAKE_METATYPE]]() // CHECK: [[FN:%.*]] = function_ref @IAMStruct1CreateSimple // CHECK: apply [[FN]]([[X]]) z = makeMetatype().init(value: x) // CHECK: [[FN:%.*]] = function_ref @$s10cf_members3fooyySdFSo10IAMStruct1VSdcfu_ : $@convention(thin) (Double) -> Struct1 // CHECK: [[A:%.*]] = thin_to_thick_function [[FN]] // CHECK: [[BORROWED_A:%.*]] = begin_borrow [[A]] // CHECK: [[A_COPY:%.*]] = copy_value [[BORROWED_A]] // CHECK: [[BORROWED_A2:%.*]] = begin_borrow [[A_COPY]] let a: (Double) -> Struct1 = Struct1.init(value:) // CHECK: apply [[BORROWED_A2]]([[X]]) // CHECK: destroy_value [[A_COPY]] // CHECK: end_borrow [[BORROWED_A]] z = a(x) // TODO: Support @convention(c) references that only capture thin metatype // let b: @convention(c) (Double) -> Struct1 = Struct1.init(value:) // z = b(x) // CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] [[Z]] : $*Struct1 // CHECK: [[FN:%.*]] = function_ref @IAMStruct1InvertInPlace // CHECK: apply [[FN]]([[WRITE]]) z.invert() // CHECK: [[WRITE:%.*]] = begin_access [read] [unknown] [[Z]] : $*Struct1 // CHECK: [[ZVAL:%.*]] = load [trivial] [[WRITE]] // CHECK: store [[ZVAL]] to [trivial] [[ZTMP:%.*]] : // CHECK: [[FN:%.*]] = function_ref @IAMStruct1Rotate : $@convention(c) (@in Struct1, Double) -> Struct1 // CHECK: apply [[FN]]([[ZTMP]], [[X]]) z = z.translate(radians: x) // CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Z]] : $*Struct1 // CHECK: [[ZVAL:%.*]] = load [trivial] [[READ]] // CHECK: [[THUNK:%.*]] = function_ref @$s10cf_members3fooyySdFSo10IAMStruct1VSdcADcfu0_ : $@convention(thin) (Struct1) -> @owned @callee_guaranteed (Double) -> Struct1 // CHECK: [[C:%.*]] = apply [[THUNK]]([[ZVAL]]) // CHECK: [[BORROWED_C:%.*]] = begin_borrow [[C]] // CHECK: [[C_COPY:%.*]] = copy_value [[BORROWED_C]] // CHECK: [[BORROWED_C2:%.*]] = begin_borrow [[C_COPY]] let c: (Double) -> Struct1 = z.translate(radians:) // CHECK: apply [[BORROWED_C2]]([[X]]) // CHECK: destroy_value [[C_COPY]] // CHECK: end_borrow [[BORROWED_C]] z = c(x) // CHECK: [[THUNK:%.*]] = function_ref @$s10cf_members3fooyySdFSo10IAMStruct1VSdcADcfu2_ : $@convention(thin) (Struct1) -> @owned @callee_guaranteed (Double) -> Struct1 // CHECK: [[THICK:%.*]] = thin_to_thick_function [[THUNK]] // CHECK: [[BORROW:%.*]] = begin_borrow [[THICK]] // CHECK: [[COPY:%.*]] = copy_value [[BORROW]] let d: (Struct1) -> (Double) -> Struct1 = Struct1.translate(radians:) // CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Z]] : $*Struct1 // CHECK: [[ZVAL:%.*]] = load [trivial] [[READ]] // CHECK: [[BORROW_COPY:%.*]] = begin_borrow [[COPY]] // CHECK: apply [[BORROW_COPY]]([[ZVAL]]) // CHECK: destroy_value [[COPY]] z = d(z)(x) // TODO: If we implement SE-0042, this should thunk the value Struct1 param // to a const* param to the underlying C symbol. // // let e: @convention(c) (Struct1, Double) -> Struct1 // = Struct1.translate(radians:) // z = e(z, x) // CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Z]] : $*Struct1 // CHECK: [[ZVAL:%.*]] = load [trivial] [[READ]] // CHECK: [[FN:%.*]] = function_ref @IAMStruct1Scale // CHECK: apply [[FN]]([[ZVAL]], [[X]]) z = z.scale(x) // CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Z]] : $*Struct1 // CHECK: [[ZVAL:%.*]] = load [trivial] [[READ]] // CHECK: [[THUNK:%.*]] = function_ref @$s10cf_members3fooyySdFSo10IAMStruct1VSdcADcfu4_ : $@convention(thin) (Struct1) -> @owned @callee_guaranteed (Double) -> Struct1 // CHECK: [[F:%.*]] = apply [[THUNK]]([[ZVAL]]) // CHECK: [[BORROWED_F:%.*]] = begin_borrow [[F]] // CHECK: [[F_COPY:%.*]] = copy_value [[BORROWED_F]] // CHECK: [[BORROWED_F2:%.*]] = begin_borrow [[F_COPY]] let f = z.scale // CHECK: apply [[BORROWED_F2]]([[X]]) // CHECK: destroy_value [[F_COPY]] // CHECK: end_borrow [[BORROWED_F]] z = f(x) // CHECK: [[THUNK:%.*]] = function_ref @$s10cf_members3fooyySdFSo10IAMStruct1VSdcADcfu6_ : $@convention(thin) (Struct1) -> @owned @callee_guaranteed (Double) -> Struct1 // CHECK: thin_to_thick_function [[THUNK]] let g = Struct1.scale // CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Z]] : $*Struct1 // CHECK: [[ZVAL:%.*]] = load [trivial] [[READ]] z = g(z)(x) // TODO: If we implement SE-0042, this should directly reference the // underlying C function. // let h: @convention(c) (Struct1, Double) -> Struct1 = Struct1.scale // z = h(z, x) // CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Z]] : $*Struct1 // CHECK: [[ZVAL:%.*]] = load [trivial] [[READ]] // CHECK: store [[ZVAL]] to [trivial] [[ZTMP:%.*]] : // CHECK: [[ZVAL_2:%.*]] = load [trivial] [[ZTMP]] // CHECK: store [[ZVAL_2]] to [trivial] [[ZTMP_2:%.*]] : // CHECK: [[GET:%.*]] = function_ref @IAMStruct1GetRadius : $@convention(c) (@in Struct1) -> Double // CHECK: apply [[GET]]([[ZTMP_2]]) _ = z.radius // CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Z]] : $*Struct1 // CHECK: [[ZVAL:%.*]] = load [trivial] [[READ]] // CHECK: [[SET:%.*]] = function_ref @IAMStruct1SetRadius : $@convention(c) (Struct1, Double) -> () // CHECK: apply [[SET]]([[ZVAL]], [[X]]) z.radius = x // CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Z]] : $*Struct1 // CHECK: [[ZVAL:%.*]] = load [trivial] [[READ]] // CHECK: [[GET:%.*]] = function_ref @IAMStruct1GetAltitude : $@convention(c) (Struct1) -> Double // CHECK: apply [[GET]]([[ZVAL]]) _ = z.altitude // CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] [[Z]] : $*Struct1 // CHECK: [[SET:%.*]] = function_ref @IAMStruct1SetAltitude : $@convention(c) (@inout Struct1, Double) -> () // CHECK: apply [[SET]]([[WRITE]], [[X]]) z.altitude = x // CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Z]] : $*Struct1 // CHECK: [[ZVAL:%.*]] = load [trivial] [[READ]] // CHECK: [[GET:%.*]] = function_ref @IAMStruct1GetMagnitude : $@convention(c) (Struct1) -> Double // CHECK: apply [[GET]]([[ZVAL]]) _ = z.magnitude // CHECK: [[FN:%.*]] = function_ref @IAMStruct1StaticMethod // CHECK: apply [[FN]]() var y = Struct1.staticMethod() // CHECK: [[SELF:%.*]] = metatype // CHECK: [[THUNK:%.*]] = function_ref @$s10cf_members3fooyySdFs5Int32VycSo10IAMStruct1Vmcfu8_ : $@convention(thin) (@thin Struct1.Type) -> @owned @callee_guaranteed () -> Int32 // CHECK: [[I:%.*]] = apply [[THUNK]]([[SELF]]) // CHECK: [[BORROWED_I:%.*]] = begin_borrow [[I]] // CHECK: [[I_COPY:%.*]] = copy_value [[BORROWED_I]] // CHECK: [[BORROWED_I2:%.*]] = begin_borrow [[I_COPY]] let i = Struct1.staticMethod // CHECK: apply [[BORROWED_I2]]() // CHECK: destroy_value [[I_COPY]] // CHECK: end_borrow [[BORROWED_I]] y = i() // TODO: Support @convention(c) references that only capture thin metatype // let j: @convention(c) () -> Int32 = Struct1.staticMethod // y = j() // CHECK: [[GET:%.*]] = function_ref @IAMStruct1StaticGetProperty // CHECK: apply [[GET]]() _ = Struct1.property // CHECK: [[SET:%.*]] = function_ref @IAMStruct1StaticSetProperty // CHECK: apply [[SET]](%{{[0-9]+}}) Struct1.property = y // CHECK: [[GET:%.*]] = function_ref @IAMStruct1StaticGetOnlyProperty // CHECK: apply [[GET]]() _ = Struct1.getOnlyProperty // CHECK: [[MAKE_METATYPE:%.*]] = function_ref @$s10cf_members12makeMetatype{{[_0-9a-zA-Z]*}}F // CHECK: apply [[MAKE_METATYPE]]() // CHECK: [[GET:%.*]] = function_ref @IAMStruct1StaticGetProperty // CHECK: apply [[GET]]() _ = makeMetatype().property // CHECK: [[MAKE_METATYPE:%.*]] = function_ref @$s10cf_members12makeMetatype{{[_0-9a-zA-Z]*}}F // CHECK: apply [[MAKE_METATYPE]]() // CHECK: [[SET:%.*]] = function_ref @IAMStruct1StaticSetProperty // CHECK: apply [[SET]](%{{[0-9]+}}) makeMetatype().property = y // CHECK: [[MAKE_METATYPE:%.*]] = function_ref @$s10cf_members12makeMetatype{{[_0-9a-zA-Z]*}}F // CHECK: apply [[MAKE_METATYPE]]() // CHECK: [[GET:%.*]] = function_ref @IAMStruct1StaticGetOnlyProperty // CHECK: apply [[GET]]() _ = makeMetatype().getOnlyProperty // CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Z]] : $*Struct1 // CHECK: [[ZVAL:%.*]] = load [trivial] [[READ]] // CHECK: [[FN:%.*]] = function_ref @IAMStruct1SelfComesLast : $@convention(c) (Double, Struct1) -> () // CHECK: apply [[FN]]([[X]], [[ZVAL]]) z.selfComesLast(x: x) // CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Z]] : $*Struct1 // CHECK: [[ZVAL:%.*]] = load [trivial] [[READ]] let k: (Double) -> () = z.selfComesLast(x:) k(x) let l: (Struct1) -> (Double) -> () = Struct1.selfComesLast(x:) // CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Z]] : $*Struct1 // CHECK: [[ZVAL:%.*]] = load [trivial] [[READ]] l(z)(x) // TODO: If we implement SE-0042, this should thunk to reorder the arguments. // let m: @convention(c) (Struct1, Double) -> () = Struct1.selfComesLast(x:) // m(z, x) // CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Z]] : $*Struct1 // CHECK: [[ZVAL:%.*]] = load [trivial] [[READ]] // CHECK: [[FN:%.*]] = function_ref @IAMStruct1SelfComesThird : $@convention(c) (Int32, Float, Struct1, Double) -> () // CHECK: apply [[FN]]({{.*}}, {{.*}}, [[ZVAL]], [[X]]) z.selfComesThird(a: y, b: 0, x: x) let n: (Int32, Float, Double) -> () = z.selfComesThird(a:b:x:) n(y, 0, x) let o: (Struct1) -> (Int32, Float, Double) -> () = Struct1.selfComesThird(a:b:x:) o(z)(y, 0, x) // TODO: If we implement SE-0042, this should thunk to reorder the arguments. // let p: @convention(c) (Struct1, Int, Float, Double) -> () // = Struct1.selfComesThird(a:b:x:) // p(z, y, 0, x) } // CHECK: } // end sil function '$s10cf_members3foo{{[_0-9a-zA-Z]*}}F' // CHECK-LABEL: sil private [ossa] @$s10cf_members3fooyySdFSo10IAMStruct1VSdcfu_ : $@convention(thin) (Double) -> Struct1 { // CHECK: bb0([[X:%.*]] : $Double): // CHECK: [[CFUNC:%.*]] = function_ref @IAMStruct1CreateSimple // CHECK: [[RET:%.*]] = apply [[CFUNC]]([[X]]) // CHECK: return [[RET]] // CHECK-LABEL: sil private [ossa] @$s10cf_members3fooyySdFSo10IAMStruct1VSdcADcfu0_ADSdcfu1_ : $@convention(thin) (Double, Struct1) -> Struct1 { // CHECK: bb0([[X:%.*]] : $Double, [[SELF:%.*]] : $Struct1): // CHECK: store [[SELF]] to [trivial] [[TMP:%.*]] : // CHECK: [[CFUNC:%.*]] = function_ref @IAMStruct1Rotate // CHECK: [[RET:%.*]] = apply [[CFUNC]]([[TMP]], [[X]]) // CHECK: return [[RET]] // CHECK-LABEL: sil private [ossa] @$s10cf_members3fooyySdFSo10IAMStruct1VSdcADcfu4_ADSdcfu5_ : $@convention(thin) (Double, Struct1) -> Struct1 { // CHECK: bb0([[X:%.*]] : $Double, [[SELF:%.*]] : $Struct1): // CHECK: [[CFUNC:%.*]] = function_ref @IAMStruct1Scale // CHECK: [[RET:%.*]] = apply [[CFUNC]]([[SELF]], [[X]]) // CHECK: return [[RET]] // CHECK-LABEL: sil private [ossa] @$s10cf_members3fooyySdFs5Int32VycSo10IAMStruct1Vmcfu8_ADycfu9_ : $@convention(thin) (@thin Struct1.Type) -> Int32 { // CHECK: bb0([[SELF:%.*]] : $@thin Struct1.Type): // CHECK: [[CFUNC:%.*]] = function_ref @IAMStruct1StaticMethod // CHECK: [[RET:%.*]] = apply [[CFUNC]]() // CHECK: return [[RET]] // CHECK-LABEL:sil private [ossa] @$s10cf_members3fooyySdFySdcSo10IAMStruct1Vcfu10_ySdcfu11_ : $@convention(thin) (Double, Struct1) -> () { // CHECK: bb0([[X:%.*]] : $Double, [[SELF:%.*]] : $Struct1): // CHECK: [[CFUNC:%.*]] = function_ref @IAMStruct1SelfComesLast // CHECK: apply [[CFUNC]]([[X]], [[SELF]]) // CHECK-LABEL: sil private [ossa] @$s10cf_members3fooyySdFys5Int32V_SfSdtcSo10IAMStruct1Vcfu14_yAD_SfSdtcfu15_ : $@convention(thin) (Int32, Float, Double, Struct1) -> () { // CHECK: bb0([[X:%.*]] : $Int32, [[Y:%.*]] : $Float, [[Z:%.*]] : $Double, [[SELF:%.*]] : $Struct1): // CHECK: [[CFUNC:%.*]] = function_ref @IAMStruct1SelfComesThird // CHECK: apply [[CFUNC]]([[X]], [[Y]], [[SELF]], [[Z]]) // CHECK-LABEL: sil [ossa] @$s10cf_members3bar{{[_0-9a-zA-Z]*}}F public func bar(_ x: Double) { // CHECK: function_ref @CCPowerSupplyCreate : $@convention(c) (Double) -> @owned CCPowerSupply let ps = CCPowerSupply(watts: x) // CHECK: function_ref @CCRefrigeratorCreate : $@convention(c) (CCPowerSupply) -> @owned CCRefrigerator let fridge = CCRefrigerator(powerSupply: ps) // CHECK: function_ref @CCRefrigeratorOpen : $@convention(c) (CCRefrigerator) -> () fridge.open() // CHECK: function_ref @CCRefrigeratorGetPowerSupply : $@convention(c) (CCRefrigerator) -> @autoreleased CCPowerSupply let ps2 = fridge.powerSupply // CHECK: function_ref @CCRefrigeratorSetPowerSupply : $@convention(c) (CCRefrigerator, CCPowerSupply) -> () fridge.powerSupply = ps2 let a: (Double) -> CCPowerSupply = CCPowerSupply.init(watts:) let _ = a(x) let b: (CCRefrigerator) -> () -> () = CCRefrigerator.open b(fridge)() let c = fridge.open c() } // CHECK-LABEL: sil [ossa] @$s10cf_members28importGlobalVarsAsProperties{{[_0-9a-zA-Z]*}}F public func importGlobalVarsAsProperties() -> (Double, CCPowerSupply, CCPowerSupply?) { // CHECK: global_addr @kCCPowerSupplyDC // CHECK: global_addr @kCCPowerSupplyAC // CHECK: global_addr @kCCPowerSupplyDefaultPower return (CCPowerSupply.defaultPower, CCPowerSupply.AC, CCPowerSupply.DC) }
apache-2.0
MChainZhou/DesignPatterns
Facede/Facede/ViewController.swift
1
496
// // ViewController.swift // Facede // // Created by apple on 2017/8/30. // Copyright © 2017年 apple. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
ngageoint/mage-ios
MageTests/Authentication/SignupViewControllerTests.swift
1
15743
// // SignupViewControllerTests.swift // MAGETests // // Created by Daniel Barela on 10/7/20. // Copyright © 2020 National Geospatial Intelligence Agency. All rights reserved. // import Foundation import Quick import Nimble import OHHTTPStubs import Kingfisher @testable import MAGE @available(iOS 13.0, *) class MockSignUpDelegate: NSObject, SignupDelegate { var signupParameters: [AnyHashable : Any]?; var url: URL?; var signUpCalled = false; var signupCanceledCalled = false; var getCaptchaCalled = false; var captchaUsername: String?; func getCaptcha(_ username: String, completion: @escaping (String) -> Void) { getCaptchaCalled = true; captchaUsername = username; } func signup(withParameters parameters: [AnyHashable : Any], completion: @escaping (HTTPURLResponse) -> Void) { signUpCalled = true; signupParameters = parameters; } func signupCanceled() { signupCanceledCalled = true; } } class SignUpViewControllerTests: KIFSpec { override func spec() { describe("SignUpViewControllerTests") { var window: UIWindow?; var view: SignUpViewController?; var delegate: MockSignUpDelegate?; var navigationController: UINavigationController?; beforeEach { TestHelpers.clearAndSetUpStack(); UserDefaults.standard.baseServerUrl = "https://magetest"; MageCoreDataFixtures.addEvent(); Server.setCurrentEventId(1); delegate = MockSignUpDelegate(); navigationController = UINavigationController(); window = TestHelpers.getKeyWindowVisible(); window!.rootViewController = navigationController; } afterEach { navigationController?.viewControllers = []; window?.rootViewController?.dismiss(animated: false, completion: nil); window?.rootViewController = nil; navigationController = nil; view = nil; delegate = nil; HTTPStubs.removeAllStubs(); TestHelpers.clearAndSetUpStack(); } it("should load the SignUpViewCOntroller server version 5") { view = SignUpViewController_Server5(delegate: delegate, andScheme: MAGEScheme.scheme()); navigationController?.pushViewController(view!, animated: false); expect(navigationController?.topViewController).to(beAnInstanceOf(SignUpViewController_Server5.self)); expect(viewTester().usingLabel("Username")?.view).toNot(beNil()); expect(viewTester().usingLabel("Display Name")?.view).toNot(beNil()); expect(viewTester().usingLabel("Email")?.view).toNot(beNil()); expect(viewTester().usingLabel("Phone")?.view).toNot(beNil()); expect(viewTester().usingLabel("Password")?.view).toNot(beNil()); expect(viewTester().usingLabel("Confirm Password")?.view).toNot(beNil()); expect(viewTester().usingLabel("CANCEL")?.view).toNot(beNil()); expect(viewTester().usingLabel("SIGN UP")?.view).toNot(beNil()); tester().waitForView(withAccessibilityLabel: "Version"); let versionString: String = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as! String; tester().expect(viewTester().usingLabel("Version").view, toContainText: "v\(versionString)"); tester().expect(viewTester().usingLabel("Server URL").view, toContainText: "https://magetest"); } it("should load the SignUpViewController") { view = SignUpViewController(delegate: delegate, andScheme: MAGEScheme.scheme()); navigationController?.pushViewController(view!, animated: false); expect(navigationController?.topViewController).to(beAnInstanceOf(SignUpViewController.self)); expect(viewTester().usingLabel("Username")?.view).toNot(beNil()); expect(viewTester().usingLabel("Display Name")?.view).toNot(beNil()); expect(viewTester().usingLabel("Email")?.view).toNot(beNil()); expect(viewTester().usingLabel("Phone")?.view).toNot(beNil()); expect(viewTester().usingLabel("Password")?.view).toNot(beNil()); expect(viewTester().usingLabel("Confirm Password")?.view).toNot(beNil()); expect(viewTester().usingLabel("CANCEL")?.view).toNot(beNil()); expect(viewTester().usingLabel("SIGN UP")?.view).toNot(beNil()); expect(viewTester().usingLabel("Captcha")?.view).toNot(beNil()); tester().waitForView(withAccessibilityLabel: "Version"); let versionString: String = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as! String; tester().expect(viewTester().usingLabel("Version").view, toContainText: "v\(versionString)"); tester().expect(viewTester().usingLabel("Server URL").view, toContainText: "https://magetest"); } it("should not allow signup without required fields") { view = SignUpViewController(delegate: delegate, andScheme: MAGEScheme.scheme()); navigationController?.pushViewController(view!, animated: false); tester().waitForView(withAccessibilityLabel: "Sign Up"); tester().tapView(withAccessibilityLabel: "Sign Up"); tester().waitForTappableView(withAccessibilityLabel: "Missing Required Fields"); let alert: UIAlertController = (navigationController?.presentedViewController as! UIAlertController); expect(alert.title).to(equal("Missing Required Fields")); expect(alert.message).to(contain("Password")); expect(alert.message).to(contain("Confirm Password")); expect(alert.message).to(contain("Username")); expect(alert.message).to(contain("Display Name")); tester().tapView(withAccessibilityLabel: "OK"); } it("should not allow signup with passwords that do not match") { view = SignUpViewController(delegate: delegate, andScheme: MAGEScheme.scheme()); navigationController?.pushViewController(view!, animated: false); tester().waitForView(withAccessibilityLabel: "Sign Up"); tester().setText("username", intoViewWithAccessibilityLabel: "Username"); tester().setText("display", intoViewWithAccessibilityLabel: "Display Name"); tester().setText("password", intoViewWithAccessibilityLabel: "Password"); tester().setText("passwordsthatdonotmatch", intoViewWithAccessibilityLabel: "Confirm Password"); tester().tapView(withAccessibilityLabel: "Sign Up"); tester().waitForTappableView(withAccessibilityLabel: "Passwords Do Not Match"); let alert: UIAlertController = (navigationController?.presentedViewController as! UIAlertController); expect(alert.title).to(equal("Passwords Do Not Match")); expect(alert.message).to(contain("Please update password fields to match.")); tester().tapView(withAccessibilityLabel: "OK"); } it("should signup") { view = SignUpViewController(delegate: delegate, andScheme: MAGEScheme.scheme()); navigationController?.pushViewController(view!, animated: false); tester().waitForView(withAccessibilityLabel: "Sign Up"); tester().setText("username", intoViewWithAccessibilityLabel: "Username"); tester().setText("display", intoViewWithAccessibilityLabel: "Display Name"); tester().setText("password", intoViewWithAccessibilityLabel: "Password"); tester().setText("password", intoViewWithAccessibilityLabel: "Confirm Password"); tester().enterText("5555555555", intoViewWithAccessibilityLabel: "Phone", traits: .none, expectedResult: "(555) 555-5555"); tester().setText("email@email.com", intoViewWithAccessibilityLabel: "Email"); tester().setText("captcha", intoViewWithAccessibilityLabel: "Captcha"); tester().tapView(withAccessibilityLabel: "Sign Up"); expect(delegate?.signUpCalled).to(beTrue()); expect(delegate?.signupParameters as? [String: String]).to(equal([ "username": "username", "password": "password", "passwordconfirm": "password", "phone": "(555) 555-5555", "email": "email@email.com", "displayName": "display", "captchaText": "captcha" ])) } it("should cancel") { view = SignUpViewController(delegate: delegate, andScheme: MAGEScheme.scheme()); navigationController?.pushViewController(view!, animated: false); tester().waitForView(withAccessibilityLabel: "CANCEL"); tester().tapView(withAccessibilityLabel: "CANCEL"); expect(delegate?.signupCanceledCalled).to(beTrue()); } it("should show the password") { view = SignUpViewController(delegate: delegate, andScheme: MAGEScheme.scheme()); navigationController?.pushViewController(view!, animated: false); tester().waitForView(withAccessibilityLabel: "Show Password"); let passwordField: UITextField = viewTester().usingLabel("Password").view as! UITextField; let passwordConfirmField: UITextField = viewTester().usingLabel("Confirm Password").view as! UITextField; tester().setText("password", intoViewWithAccessibilityLabel: "Password"); tester().setText("password", intoViewWithAccessibilityLabel: "Confirm Password"); expect(passwordField.isSecureTextEntry).to(beTrue()); expect(passwordConfirmField.isSecureTextEntry).to(beTrue()); tester().setOn(true, forSwitchWithAccessibilityLabel: "Show Password"); expect(passwordField.isSecureTextEntry).to(beFalse()); expect(passwordConfirmField.isSecureTextEntry).to(beFalse()); } it("should update the password strength meter") { view = SignUpViewController(delegate: delegate, andScheme: MAGEScheme.scheme()); navigationController?.pushViewController(view!, animated: false); tester().waitForView(withAccessibilityLabel: "Password"); // this is entirely to stop iOS from suggesting a password tester().setOn(true, forSwitchWithAccessibilityLabel: "Show Password"); tester().enterText("turtle", intoViewWithAccessibilityLabel: "Password"); tester().expect(viewTester().usingLabel("Password Strength Label")?.view, toContainText: "Weak"); tester().clearTextFromView(withAccessibilityLabel: "Password"); tester().enterText("Turt", intoViewWithAccessibilityLabel: "Password"); tester().expect(viewTester().usingLabel("Password Strength Label")?.view, toContainText: "Fair"); tester().clearTextFromView(withAccessibilityLabel: "Password"); tester().enterText("Turt3", intoViewWithAccessibilityLabel: "Password"); tester().expect(viewTester().usingLabel("Password Strength Label")?.view, toContainText: "Good"); tester().clearTextFromView(withAccessibilityLabel: "Password"); tester().enterText("Turt3!", intoViewWithAccessibilityLabel: "Password"); tester().expect(viewTester().usingLabel("Password Strength Label")?.view, toContainText: "Strong"); tester().clearTextFromView(withAccessibilityLabel: "Password"); tester().enterText("Turt3!@@", intoViewWithAccessibilityLabel: "Password"); tester().expect(viewTester().usingLabel("Password Strength Label")?.view, toContainText: "Excellent"); } it("should update the phone number field as it is typed") { view = SignUpViewController(delegate: delegate, andScheme: MAGEScheme.scheme()); navigationController?.pushViewController(view!, animated: false); tester().waitForView(withAccessibilityLabel: "Phone"); tester().enterText("5555555555", intoViewWithAccessibilityLabel: "Phone", traits: .none, expectedResult: "(555) 555-5555"); tester().expect(viewTester().usingLabel("Phone")?.view, toContainText: "(555) 555-5555"); } // cannot fully test this due to being unable to disable the password auto-suggest it("should proceed to each field in order") { view = SignUpViewController(delegate: delegate, andScheme: MAGEScheme.scheme()); navigationController?.pushViewController(view!, animated: false); tester().waitForView(withAccessibilityLabel: "Sign Up"); tester().enterText("username\n", intoViewWithAccessibilityLabel: "Username"); tester().waitForFirstResponder(withAccessibilityLabel: "Display Name"); tester().enterText("display\n", intoViewWithAccessibilityLabel: "Display Name"); tester().waitForFirstResponder(withAccessibilityLabel: "Email"); tester().enterText("email@email.com\n", intoViewWithAccessibilityLabel: "Email"); tester().waitForFirstResponder(withAccessibilityLabel: "Phone"); tester().enterText("5555555555", intoViewWithAccessibilityLabel: "Phone", traits: .none, expectedResult: "(555) 555-5555"); tester().setText("password", intoViewWithAccessibilityLabel: "Password"); tester().setText("password", intoViewWithAccessibilityLabel: "Confirm Password"); tester().setText("captcha", intoViewWithAccessibilityLabel: "Captcha"); tester().tapView(withAccessibilityLabel: "Sign Up") expect(delegate?.signUpCalled).to(beTrue()); expect(delegate?.signupParameters as? [String: String]).toEventually(equal([ "username": "username", "password": "password", "passwordconfirm": "password", "phone": "(555) 555-5555", "email": "email@email.com", "displayName": "display", "captchaText": "captcha" ])) } } } }
apache-2.0
iOSDevLog/iOSDevLog
169. Camera/Camera/ExposureViewController.swift
1
3008
// // ExposureViewController.swift // Camera // // Created by Matteo Caldari on 05/02/15. // Copyright (c) 2015 Matteo Caldari. All rights reserved. // import UIKit import CoreMedia class ExposureViewController: UIViewController, CameraControlsViewControllerProtocol, CameraSettingValueObserver { @IBOutlet var modeSwitch:UISwitch! @IBOutlet var biasSlider:UISlider! @IBOutlet var durationSlider:UISlider! @IBOutlet var isoSlider:UISlider! var cameraController:CameraController? { willSet { if let cameraController = cameraController { cameraController.unregisterObserver(self, property: CameraControlObservableSettingExposureTargetOffset) cameraController.unregisterObserver(self, property: CameraControlObservableSettingExposureDuration) cameraController.unregisterObserver(self, property: CameraControlObservableSettingISO) } } didSet { if let cameraController = cameraController { cameraController.registerObserver(self, property: CameraControlObservableSettingExposureTargetOffset) cameraController.registerObserver(self, property: CameraControlObservableSettingExposureDuration) cameraController.registerObserver(self, property: CameraControlObservableSettingISO) } } } override func viewDidLoad() { setInitialValues() } @IBAction func modeSwitchValueChanged(sender:UISwitch) { if sender.on { cameraController?.enableContinuousAutoExposure() } else { cameraController?.setCustomExposureWithDuration(durationSlider.value) } updateSliders() } @IBAction func sliderValueChanged(sender:UISlider) { switch sender { case biasSlider: cameraController?.setExposureTargetBias(sender.value) case durationSlider: cameraController?.setCustomExposureWithDuration(sender.value) case isoSlider: cameraController?.setCustomExposureWithISO(sender.value) default: break } } func cameraSetting(setting: String, valueChanged value: AnyObject) { if setting == CameraControlObservableSettingExposureDuration { if let durationValue = value as? NSValue { let duration = CMTimeGetSeconds(durationValue.CMTimeValue) durationSlider.value = Float(duration) } } else if setting == CameraControlObservableSettingISO { if let iso = value as? Float { isoSlider.value = Float(iso) } } } func setInitialValues() { if isViewLoaded() && cameraController != nil { if let autoExposure = cameraController?.isContinuousAutoExposureEnabled() { modeSwitch.on = autoExposure updateSliders() } if let currentDuration = cameraController?.currentExposureDuration() { durationSlider.value = currentDuration } if let currentISO = cameraController?.currentISO() { isoSlider.value = currentISO } if let currentBias = cameraController?.currentExposureTargetOffset() { biasSlider.value = currentBias } } } func updateSliders() { for slider in [durationSlider, isoSlider] as [UISlider] { slider.enabled = !modeSwitch.on } } }
mit
X140Yu/Lemon
Lemon/Library/Protocol/SharebleViewController.swift
1
1241
import UIKit import RxSwift import RxCocoa protocol Shareble { var shareButton: UIButton { get } var shareItems: [Any] { get set } } class SharebleViewControllerProvider: Shareble { var shareItems = [Any]() private weak var viewController: UIViewController? private let bag = DisposeBag() var shareButton = UIButton() init(viewController: UIViewController) { self.viewController = viewController shareButton.setImage(#imageLiteral(resourceName: "share"), for: .normal) shareButton.rx.controlEvent(.touchUpInside) .filter{ _ in return self.shareItems.count > 0} .map { _ in return self.shareItems } .subscribe(onNext: { [weak self] items in guard let `self` = self else { return } guard let vc = self.viewController else { return } let activityViewController = UIActivityViewController(activityItems: items, applicationActivities: nil) activityViewController.popoverPresentationController?.sourceView = vc.view vc.present(activityViewController, animated: true, completion: nil) }).addDisposableTo(bag) let shareBarButton = UIBarButtonItem(customView: shareButton) viewController.navigationItem.rightBarButtonItem = shareBarButton } }
gpl-3.0
keyeMyria/edx-app-ios
Source/CourseCardViewModel.swift
4
1879
// // CourseCardViewModel.swift // edX // // Created by Michael Katz on 8/31/15. // Copyright (c) 2015 edX. All rights reserved. // import Foundation @objc class CourseCardViewModel : NSObject { class func applyCourse(course: OEXCourse, to infoView: CourseDashboardCourseInfoView) { infoView.course = course infoView.titleText = course.name infoView.detailText = (course.org ?? "") + (course.number != nil ? course.number! + " | " : "") // Show course ced var bannerText: String? = nil // If start date is older than current date if course.isStartDateOld && course.end != nil { let formattedEndDate = OEXDateFormatting.formatAsMonthDayString(course.end) // If Old date is older than current date if course.isEndDateOld { bannerText = OEXLocalizedString("ENDED", nil) + " - " + formattedEndDate } else { bannerText = OEXLocalizedString("ENDING", nil).oex_uppercaseStringInCurrentLocale() + " - " + formattedEndDate } } else { // Start date is newer than current date let error_code = course.courseware_access!.error_code let startDateNil: Bool = course.start_display_info.date == nil let displayInfoTime: Bool = error_code != OEXAccessError.StartDateError || course.start_display_info.type == OEXStartType.Timestamp if !course.isStartDateOld && !startDateNil && displayInfoTime { let formattedStartDate = OEXDateFormatting.formatAsMonthDayString(course.start_display_info.date) bannerText = OEXLocalizedString("STARTING", nil).oex_uppercaseStringInCurrentLocale() + " - " + formattedStartDate } } infoView.bannerText = bannerText infoView.setCoverImage() } }
apache-2.0
cuappdev/eatery
Eatery Watch App Extension/UI/Eateries/CampusEateriesView.swift
1
6277
// // CampusEateriesView.swift // Eatery Watch App Extension // // Created by William Ma on 1/5/20. // Copyright © 2020 CUAppDev. All rights reserved. // import Combine import CoreLocation import SwiftUI private class CampusEateriesData: ObservableObject { @Published var campusEateries: [CampusEatery] = [] @Published var openEateries: [CampusEatery] = [] @Published var closedEateries: [CampusEatery] = [] private let locationProxy = LocationProxy() @Published var userLocation: CLLocation? var cancellables: Set<AnyCancellable> = [] init() { $campusEateries.sink(receiveValue: self.reloadEateries).store(in: &self.cancellables) Timer.publish(every: 60, on: .current, in: .common).autoconnect().sink { _ in self.reloadEateries(self.campusEateries) }.store(in: &self.cancellables) } private func reloadEateries(_ eateries: [CampusEatery]) { self.openEateries = eateries.filter { !EateryStatus.equalsIgnoreAssociatedValue($0.currentStatus(), rhs: .closed) } self.closedEateries = eateries.filter { EateryStatus.equalsIgnoreAssociatedValue($0.currentStatus(), rhs: .closed) } } func fetchCampusEateries(_ presentError: @escaping (Error) -> Void) { NetworkManager.shared.getCampusEateries { [weak self] (campusEateries, error) in guard let self = self else { return } if let campusEateries = campusEateries { self.campusEateries = campusEateries } else if let error = error { presentError(error) } } } func fetchLocation(_ presentError: @escaping (Error) -> Void) { self.locationProxy.fetchLocation { result in switch result { case .success(let location): self.userLocation = location case .failure(let error): presentError(error) } } } } private class ErrorInfo: Identifiable { let title: String let error: Error init(title: String, error: Error) { self.title = title self.error = error } } /// Presents a list of campus eateries, along with sort and filter settings. struct CampusEateriesView: View { @ObservedObject private var viewData = CampusEateriesData() @State private var sortMethod: SortMethod = .name @State private var areaFilter: Area? @State private var errorInfo: ErrorInfo? @State private var firstAppearance = true var body: some View { let openEateries = sorted(filter(self.viewData.openEateries)) let closedEateries = sorted(filter(self.viewData.closedEateries)) return ScrollView { SortMethodView(self.$sortMethod) { if self.sortMethod == .distance { self.viewData.fetchLocation { error in if self.sortMethod == .distance { self.sortMethod = .name self.errorInfo = ErrorInfo(title: "Could not get location.", error: error) } } } } .animation(nil) AreaFilterView(self.$areaFilter).animation(nil) HStack { Text("Open").font(.headline) Spacer() } if !openEateries.isEmpty { self.eateriesView(openEateries) } else { Group { Text("No Open Eateries") } } HStack { Text("Closed").font(.headline) Spacer() } if !closedEateries.isEmpty { self.eateriesView(closedEateries) } else { Group { Text("No Closed Eateries") } } } .navigationBarTitle("Eateries") .animation(.easeOut(duration: 0.25)) .contextMenu { Button(action: { self.viewData.fetchCampusEateries { error in self.errorInfo = ErrorInfo(title: "Could not fetch eateries.", error: error) } }, label: { VStack{ Image(systemName: "arrow.clockwise") .font(.title) Text("Refresh Eateries") } }) } .alert(item: self.$errorInfo) { errorInfo -> Alert in Alert(title: Text("Error: ") + Text(errorInfo.title), message: Text(errorInfo.error.localizedDescription), dismissButton: .default(Text("OK"))) } .onAppear { if self.firstAppearance { self.viewData.fetchCampusEateries { error in self.errorInfo = ErrorInfo(title: "Could not fetch eateries.", error: error) } self.firstAppearance = false } } } func eateriesView(_ eateries: [CampusEatery]) -> some View { ForEach(eateries) { eatery in NavigationLink(destination: CampusEateryView(eatery: eatery)) { CampusEateryRow(eatery: eatery, userLocation: self.sortMethod == .distance ? self.viewData.userLocation : nil) } } } private func filter(_ eateries: [CampusEatery]) -> [CampusEatery] { if let areaFilter = self.areaFilter { return eateries.filter { eatery in eatery.area == areaFilter } } else { return eateries } } private func sorted(_ eateries: [CampusEatery]) -> [CampusEatery] { switch (self.sortMethod, self.viewData.userLocation) { case (.name, _), (.distance, .none): return eateries.sorted { (lhs, rhs) in lhs.displayName < rhs.displayName } case (.distance, .some(let location)): return eateries.sorted { (lhs, rhs) in lhs.location.distance(from: location).converted(to: .meters).value < rhs.location.distance(from: location).converted(to: .meters).value } } } }
mit
kstaring/swift
validation-test/compiler_crashers_fixed/27721-swift-typebase-getcanonicaltype.swift
11
462
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -parse class a<T where T:a{struct B{class a{}class d:a{}}class d<a{{}var f:T
apache-2.0
Mayfleet/SimpleChat
Frontend/iOS/SimpleChat/SimpleChat/Views/CircleButton.swift
1
715
// // Created by Maxim Pervushin on 11/03/16. // Copyright (c) 2016 Maxim Pervushin. All rights reserved. // import UIKit @IBDesignable class CircleButton: UIButton { override func layoutSubviews() { layer.cornerRadius = min(frame.height, frame.width) / 2 super.layoutSubviews() } private func commonInit() { imageEdgeInsets = UIEdgeInsets(top: 4, left: 4, bottom: 4, right: 4) contentEdgeInsets = UIEdgeInsets(top: 4, left: 4, bottom: 4, right: 4) } override init(frame: CGRect) { super.init(frame: frame) commonInit() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } }
mit
wikimedia/wikipedia-ios
Wikipedia/Code/ColumnarCollectionViewControllerLayoutCache.swift
1
3193
private extension CGFloat { var roundedColumnWidth: Int { return Int(self*100) } } class ColumnarCollectionViewControllerLayoutCache { private var cachedHeights: [String: [Int: CGFloat]] = [:] private var cacheKeysByGroupKey: [WMFInMemoryURLKey: Set<String>] = [:] private var cacheKeysByArticleKey: [WMFInMemoryURLKey: Set<String>] = [:] private var groupKeysByArticleKey: [WMFInMemoryURLKey: Set<WMFInMemoryURLKey>] = [:] private func cacheKeyForCellWithIdentifier(_ identifier: String, userInfo: String) -> String { return "\(identifier)-\(userInfo)" } public func setHeight(_ height: CGFloat, forCellWithIdentifier identifier: String, columnWidth: CGFloat, groupKey: WMFInMemoryURLKey? = nil, articleKey: WMFInMemoryURLKey? = nil, userInfo: String) { let cacheKey = cacheKeyForCellWithIdentifier(identifier, userInfo: userInfo) if let groupKey = groupKey { cacheKeysByGroupKey[groupKey, default: []].insert(cacheKey) } if let articleKey = articleKey { cacheKeysByArticleKey[articleKey, default: []].insert(cacheKey) if let groupKey = groupKey { groupKeysByArticleKey[articleKey, default: []].insert(groupKey) } } cachedHeights[cacheKey, default: [:]][columnWidth.roundedColumnWidth] = height } public func cachedHeightForCellWithIdentifier(_ identifier: String, columnWidth: CGFloat, userInfo: String) -> CGFloat? { let cacheKey = cacheKeyForCellWithIdentifier(identifier, userInfo: userInfo) return cachedHeights[cacheKey]?[columnWidth.roundedColumnWidth] } public func removeCachedHeightsForCellWithIdentifier(_ identifier: String, userInfo: String) { let cacheKey = cacheKeyForCellWithIdentifier(identifier, userInfo: userInfo) cachedHeights.removeValue(forKey: cacheKey) } public func reset() { cachedHeights.removeAll(keepingCapacity: true) cacheKeysByArticleKey.removeAll(keepingCapacity: true) cacheKeysByGroupKey.removeAll(keepingCapacity: true) } @discardableResult public func invalidateArticleKey(_ articleKey: WMFInMemoryURLKey?) -> Bool { guard let articleKey = articleKey else { return false } if let cacheKeys = cacheKeysByArticleKey[articleKey] { for cacheKey in cacheKeys { cachedHeights.removeValue(forKey: cacheKey) } cacheKeysByArticleKey.removeValue(forKey: articleKey) } guard let groupKeys = groupKeysByArticleKey[articleKey] else { return false } for groupKey in groupKeys { invalidateGroupKey(groupKey) } return true } public func invalidateGroupKey(_ groupKey: WMFInMemoryURLKey?) { guard let groupKey = groupKey, let cacheKeys = cacheKeysByGroupKey[groupKey] else { return } for cacheKey in cacheKeys { cachedHeights.removeValue(forKey: cacheKey) } cacheKeysByGroupKey.removeValue(forKey: groupKey) } }
mit
ikesyo/Swiftz
Swiftz/Arrow.swift
3
6437
// // Arrow.swift // Swiftz // // Created by Robert Widmann on 1/18/15. // Copyright (c) 2015 TypeLift. All rights reserved. // /// An Arrow is most famous for being a "Generalization of a Monad". They're probably better /// described as a more general view of computation. Where a monad M<A> yields a value of type A /// given some context, an Arrow A<B, C> is a function from B -> C in some context A. Functions are /// the simplest kind of Arrow (pun intended). Their context parameter, A, is essentially empty. /// From there, the B -> C part of the arrow gets alpha-reduced to the A -> B part of the function /// type. /// /// Arrows can be modelled with circuit-esque diagrams, and indeed that can often be a better way to /// envision the various arrow operators. /// /// - >>> a -> [ f ] -> b -> [ g ] -> c /// - <<< a -> [ g ] -> b -> [ f ] -> c /// /// - arr a -> [ f ] -> b /// /// - first a -> [ f ] -> b /// c - - - - - -> c /// /// - second c - - - - - -> c /// a -> [ f ] -> b /// /// /// - *** a - [ f ] -> b - • /// \ /// o - -> (b, d) /// / /// c - [ g ] -> d - • /// /// /// • a - [ f ] -> b - • /// | \ /// - &&& a - o o - -> (b, c) /// | / /// • a - [ g ] -> c - • /// /// Arrows inherit from Category so we can get Composition For Free™. public protocol Arrow : Category { /// Some arbitrary target our arrow can compose with. typealias D /// Some arbitrary target our arrow can compose with. typealias E /// Type of the result of first(). typealias FIRST = K2<(A, D), (B, D)> /// Type of the result of second(). typealias SECOND = K2<(D, A), (D, B)> /// Some arrow with an arbitrary target and source. Used in split(). typealias ADE = K2<D, E> /// Type of the result of ***. typealias SPLIT = K2<(A, D), (B, E)> /// Some arrow from our target to some other arbitrary target. Used in fanout(). typealias ABD = K2<A, D> /// Type of the result of &&&. typealias FANOUT = K2<B, (B, D)> /// Lift a function to an arrow. static func arr(_ : A -> B) -> Self /// Splits the arrow into two tuples that model a computation that applies our Arrow to an /// argument on the "left side" and sends the "right side" through unchanged. /// /// The mirror image of second(). func first() -> FIRST /// Splits the arrow into two tuples that model a computation that applies our Arrow to an /// argument on the "right side" and sends the "left side" through unchanged. /// /// The mirror image of first(). func second() -> SECOND /// Split | Splits two computations and combines the result into one Arrow yielding a tuple of /// the result of each side. func ***(_ : Self, _ : ADE) -> SPLIT /// Fanout | Given two functions with the same source but different targets, this function /// splits the computation and combines the result of each Arrow into a tuple of the result of /// each side. func &&&(_ : Self, _ : ABD) -> FANOUT } /// Arrows that can produce an identity arrow. public protocol ArrowZero : Arrow { /// An arrow from A -> B. Colloquially, the "zero arrow". typealias ABC = K2<A, B> /// The identity arrow. static func zeroArrow() -> ABC } /// A monoid for Arrows. public protocol ArrowPlus : ArrowZero { /// A binary function that combines two arrows. func <+>(_ : ABC, _ : ABC) -> ABC } /// Arrows that permit "choice" or selecting which side of the input to apply themselves to. /// /// - left a - - [ f ] - - > b /// | /// a - [f] -> b - o------EITHER------ /// | /// d - - - - - - - > d /// /// - right d - - - - - - - > d /// | /// a - [f] -> b - o------EITHER------ /// | /// a - - [ f ] - - > b /// /// - +++ a - [ f ] -> b - • • a - [ f ] -> b /// \ | /// o - -> o-----EITHER----- /// / | /// d - [ g ] -> e - • • d - [ g ] -> e /// /// - ||| a - [ f ] -> c - • • a - [ f ] -> c • /// \ | \ /// o - -> o-----EITHER-------o - -> c /// / | / /// b - [ g ] -> c - • • b - [ g ] -> c • /// public protocol ArrowChoice : Arrow { /// The result of left typealias LEFT = K2<Either<A, D>, Either<B, D>> /// The result of right typealias RIGHT = K2<Either<D, A>, Either<D, B>> /// The result of +++ typealias SPLAT = K2<Either<A, D>, Either<B, E>> /// Some arrow from a different source and target for fanin. typealias ACD = K2<B, D> /// The result of ||| typealias FANIN = K2<Either<A, B>, D> /// Feed marked inputs through the argument arrow, passing the rest through unchanged to the /// output. func left() -> LEFT /// The mirror image of left. func right() -> RIGHT /// Splat | Split the input between both argument arrows, then retag and merge their outputs /// into Eithers. func +++(_ : Self, _ : ADE) -> SPLAT /// Fanin | Split the input between two argument arrows and merge their ouputs. func |||(_ : ABD, _ : ACD) -> FANIN } /// Arrows that allow application of arrow inputs to other inputs. Such arrows are equivalent to /// monads. /// /// - app (f : a -> b) - • /// \ /// o - a - [ f ] -> b /// / /// a -------> a - • /// public protocol ArrowApply : Arrow { typealias APP = K2<(Self, A), B> static func app() -> APP } /// Arrows that admit right-tightening recursion. /// /// The 'loop' operator expresses computations in which an output value is fed back as input, /// although the computation occurs only once. /// /// •-------• /// | | /// - loop a - - [ f ] - -> b /// | | /// d-------• /// public protocol ArrowLoop : Arrow { typealias LOOP = K2<(A, D), (B, D)> static func loop(_ : LOOP) -> Self }
bsd-3-clause
systers/PowerUp
Powerup/OOC-Event-Classes/StorySequences.swift
2
18598
import Foundation /** Struct is responsible for retrieving and parsing StorySequences.json into a Swift datatype. It describes all instances of StorySequence. - Author: Cadence Holmes 2018 */ struct StorySequences { // bundle needs to be able to be changed in order to automate testing var bundle = Bundle.main /** Parse `StorySequences.json` and return a formatted `StorySequence`. - Parameter scenario: The `scenarioID` of the target scenario. - Parameter outro: If `true`, searches for the `outro` event type. Otherwise searches for the `intro` event type. - Returns: A formatted `StorySequence`. - Throws: `print(error.localizedDescription)` if unable to retrieve data. */ func getStorySequence(scenario: Int, outro: Int? = nil) -> StorySequence? { var sequence = StorySequence(music: nil, [:]) let scenario = String(scenario) let key = (outro != nil) ? String(outro!) : nil let type = (outro == nil) ? "intros" : "outros" // parse events into the correct types once retrieved from json func parseEvent(event: Dictionary<String, AnyObject?>?) -> StorySequence.Event? { if event == nil { return nil } let p = event?["pos"] as? String let a = event?["ani"] as? String return StorySequence.Event(txt: event?["txt"] as? String, img: event?["img"] as? String, pos: (p != nil) ? StorySequence.ImagePosition(rawValue: p!) : nil, ani: (a != nil) ? StorySequence.ImageAnimation(rawValue: a!) : nil) } // change this to the main json containing all sequences let fileName = "StorySequences" guard let path = bundle.path(forResource: fileName, ofType: "json") else { print("Unable to retrieve Story Sequence JSON.") return nil } do { // retrieve json and map to datatype Dictionary<String, AnyObject> let data = try Data(contentsOf: URL(fileURLWithPath: path), options: .mappedIfSafe) let json = try JSONSerialization.jsonObject(with: data, options: .mutableLeaves) if let json = json as? Dictionary<String, AnyObject> { // retrieve the collection of sequences based on type guard let sequences = json[type] as? Dictionary<String, AnyObject?> else { print("Unable to retrieve sequences of type: \(type).") return nil } var seq: Dictionary<String, AnyObject?> // handle intros and outros if key != nil { // if there's a secondary key, then it's an outro - retrieve outros for scenario, then correct outro let i = key! guard let outros = sequences[scenario] as? Dictionary<String, AnyObject?> else { print("Unable to retrieve outro sequences for scenario: \(scenario).") return nil } guard let outro = outros[i] as? Dictionary<String, AnyObject?> else { print("Unable to retrieve outro sequence for scenario - key: \(scenario) - \(i).") return nil } seq = outro } else { // if there's no secondary key, then it's an intro - retrieve intro for scenario guard let intro = sequences[scenario] as? Dictionary<String, AnyObject?> else { print("Unable to retrieve intro sequence for scenario: \(scenario).") return nil } seq = intro } sequence.music = seq["music"] as? String guard let steps = seq["steps"] as? Dictionary<String, AnyObject?> else { print("Unable to retrieve steps for: \(type) - \(scenario) - \(String(describing: key)).") return nil } for step in steps { guard let i = Int(step.key) else { print("Key is not an Int") return nil } guard let events = step.value as? Dictionary<String, AnyObject?> else { print("Unable to retrieve step for key: \(i)") continue } let lft = events["lftEvent"] as? Dictionary<String, AnyObject?> let rgt = events["rgtEvent"] as? Dictionary<String, AnyObject?> let lftEvent = parseEvent(event: lft) let rgtEvent = parseEvent(event: rgt) let newStep = StorySequence.Step(lftEvent: lftEvent, rgtEvent: rgtEvent) sequence.steps[i] = newStep } } } catch let error { print(error.localizedDescription) } return sequence } } // MARK: Example data sets /* Example Datasets While StorySequencePlayer expects to parse a file called StorySequences.json, which is created in an external tool, the resultant Swift dataset ultimately looks like the following examples. - define each story sequence as a private let, named descriptively - a StorySequence is a dictionary of StorySequenceStep, keys must be an Int - a StorySequenceStep describes two StorySequenceEvent, a left event and a right event. - A StorySequenceEvent describes the text, image, and image position. - if any properties are left nil, there will be no change from the previous step - you can nil the entire event as well (for no change from the previous step) */ /* private let pos = StorySequence.ImagePosition.self private let ani = StorySequence.ImageAnimation.self private let testChar = StorySequence.Images().testChar private let testChar2 = StorySequence.Images().testChar2 private let misc = StorySequence.Images().misc private let home: StorySequence = StorySequence(music: Sounds().scenarioMusic[5]?.intro, [ 0: StorySequence.Step(lftEvent: StorySequence.Event(txt: "Hey, this is an intro sequence!", img: testChar.happy, pos: pos.near, ani: ani.shake), rgtEvent: nil ), 1: StorySequence.Step(lftEvent: nil, rgtEvent: StorySequence.Event(txt: "You can change the images in each step, and each side is independent.", img: testChar2.normal, pos: pos.near, ani: ani.tiltLeft) ), 2: StorySequence.Step(lftEvent: StorySequence.Event(txt: "The images can move to different positions.", img: nil, pos: pos.mid, ani: ani.tiltRight), rgtEvent: StorySequence.Event(txt: nil, img: testChar2.upset, pos: nil, ani: ani.jiggle) ), 3: StorySequence.Step(lftEvent: StorySequence.Event(txt: "You describe it in a model of steps and events. Passing nil to a value tells it to stay the same.", img: testChar.talking, pos: pos.near, ani: ani.flip), rgtEvent: nil ), 4: StorySequence.Step(lftEvent: nil, rgtEvent: StorySequence.Event(txt: "See? The left image didn't move or change!", img: testChar2.scared, pos: pos.far, ani: nil) ), 5: StorySequence.Step(lftEvent: StorySequence.Event(txt: "Things can happen on one or both sides.", img: nil, pos: pos.hidden, ani: nil), rgtEvent: StorySequence.Event(txt: "Now both images are hidden!", img: nil, pos: pos.hidden, ani: nil) ), 6: StorySequence.Step(lftEvent: StorySequence.Event(txt: "A `StorySequence` is just a collection of `Steps`!", img: testChar.normal, pos: pos.far, ani: nil), rgtEvent: nil ), 7: StorySequence.Step(lftEvent: StorySequence.Event(txt: "This is what the data looks like for a single step. It's two events, left and right.", img: testChar.scared, pos: pos.mid, ani: nil), rgtEvent: StorySequence.Event(txt: nil, img: misc.dataExample, pos: pos.near, ani: nil) ), 8: StorySequence.Step(lftEvent: StorySequence.Event(txt: nil, img: testChar.normal, pos: pos.near, ani: nil), rgtEvent: StorySequence.Event(txt: "It's not that bad!", img: nil, pos: pos.far, ani: nil) ), 9: StorySequence.Step(lftEvent: StorySequence.Event(txt: "Oh yea! There's also predefined animations to give your characters some character.", img: testChar.talking, pos: pos.near, ani: nil), rgtEvent: StorySequence.Event(txt: nil, img: nil, pos: pos.hidden, ani: nil) ), 10: StorySequence.Step(lftEvent: StorySequence.Event(txt: "But that's it for now! Thanks for listening!", img: testChar.normal, pos: pos.mid, ani: nil), rgtEvent: StorySequence.Event(txt: nil, img: "minesweeper_abstinence_heart", pos: pos.far, ani: nil) ) ]) */ /** ************** */ // Example outro /* private let testChar3 = StorySequence.Images().testChar3 private let homeOutro: StorySequence = StorySequence(music: Sounds().scenarioMusic[5]?.goodEnding, [ 0: StorySequence.Step(lftEvent: StorySequence.Event(txt: "Hi everyone, we're back!", img: testChar2.smiling, pos: pos.mid, ani: nil), rgtEvent: StorySequence.Event(txt: nil, img: testChar.happy, pos: pos.mid, ani: nil) ), 1: StorySequence.Step(lftEvent: StorySequence.Event(txt: nil, img: testChar2.normal, pos: pos.near, ani: nil), rgtEvent: StorySequence.Event(txt: "Outro sequences are just like an intro sequence, except they are triggered by the PopupID value.", img: testChar.lecturing, pos: nil, ani: nil) ), 2: StorySequence.Step(lftEvent: StorySequence.Event(txt: "When an answer record has a positive int, it looks for a popup.", img: testChar2.talking, pos: nil, ani: nil), rgtEvent: StorySequence.Event(txt: nil, img: testChar.normal, pos: pos.near, ani: nil) ), 3: StorySequence.Step(lftEvent: StorySequence.Event(txt: nil, img: testChar2.normal, pos: nil, ani: nil), rgtEvent: StorySequence.Event(txt: "But when it has a negative int, it looks to end the scenario with an outro sequence!", img: testChar.talking, pos: pos.far, ani: nil) ), 4: StorySequence.Step(lftEvent: StorySequence.Event(txt: "We think all of these story sequences can be used in different ways.", img: testChar2.lecturing, pos: nil, ani: nil), rgtEvent: StorySequence.Event(txt: nil, img: testChar.scared, pos: pos.near, ani: ani.jiggle) ), 5: StorySequence.Step(lftEvent: StorySequence.Event(txt: "We might be characters in the story, and we could just continue the scene with a script.", img: testChar2.talking, pos: pos.mid, ani: nil), rgtEvent: StorySequence.Event(txt: nil, img: testChar.happy, pos: nil, ani: ani.tiltLeft) ), 6: StorySequence.Step(lftEvent: StorySequence.Event(txt: nil, img: nil, pos: pos.hidden, ani: nil), rgtEvent: StorySequence.Event(txt: "We could also address the player directly and be truly Out-Of-Character.", img: testChar.talking, pos: pos.far, ani: nil) ), 7: StorySequence.Step(lftEvent: StorySequence.Event(txt: "Or introduce new characters of authority to talk about important things!", img: testChar3.normal, pos: pos.mid, ani: nil), rgtEvent: StorySequence.Event(txt: nil, img: testChar.dazed, pos: pos.near, ani: ani.shake) ), 8: StorySequence.Step(lftEvent: StorySequence.Event(txt: nil, img: nil, pos: pos.hidden, ani: ani.flip), rgtEvent: StorySequence.Event(txt: "Soon, we'll have some more concrete examples of what these scenes could look like.", img: testChar.whatever, pos: nil, ani: nil) ), 9: StorySequence.Step(lftEvent: StorySequence.Event(txt: "As well as documentation on exactly how to build the models to make these scenes work!", img: testChar2.smiling, pos: pos.near, ani: ani.tiltRight), rgtEvent: StorySequence.Event(txt: "Thanks!", img: testChar.smiling, pos: pos.near, ani: ani.tiltLeft) ) ]) */
gpl-2.0
bcylin/QuickTableViewController
Source/Views/SwitchCell.swift
1
4032
// // SwitchCell.swift // QuickTableViewController // // Created by Ben on 03/09/2015. // Copyright (c) 2015 bcylin. // // 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 /// The `SwitchCellDelegate` protocol allows the adopting delegate to respond to the UI interaction. Not available on tvOS. @available(tvOS, unavailable, message: "SwitchCellDelegate is not available on tvOS.") public protocol SwitchCellDelegate: AnyObject { /// Tells the delegate that the switch control is toggled. func switchCell(_ cell: SwitchCell, didToggleSwitch isOn: Bool) } // MARK: - /// A `UITableViewCell` subclass that shows a `UISwitch` as the `accessoryView`. open class SwitchCell: UITableViewCell, Configurable { #if os(iOS) /// A `UISwitch` as the `accessoryView`. Not available on tvOS. @available(tvOS, unavailable, message: "switchControl is not available on tvOS.") public private(set) lazy var switchControl: UISwitch = { let control = UISwitch() control.addTarget(self, action: #selector(SwitchCell.didToggleSwitch(_:)), for: .valueChanged) return control }() #endif /// The switch cell's delegate object, which should conform to `SwitchCellDelegate`. Not available on tvOS. @available(tvOS, unavailable, message: "SwitchCellDelegate is not available on tvOS.") open weak var delegate: SwitchCellDelegate? // MARK: - Initializer /** Overrides `UITableViewCell`'s designated initializer. - parameter style: A constant indicating a cell style. - parameter reuseIdentifier: A string used to identify the cell object if it is to be reused for drawing multiple rows of a table view. - returns: An initialized `SwitchCell` object. */ public override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) setUpAppearance() } /** Overrides the designated initializer that returns an object initialized from data in a given unarchiver. - parameter aDecoder: An unarchiver object. - returns: `self`, initialized using the data in decoder. */ public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setUpAppearance() } // MARK: - Configurable /// Set up the switch control (iOS) or accessory type (tvOS) with the provided row. open func configure(with row: Row & RowStyle) { #if os(iOS) if let row = row as? SwitchRowCompatible { switchControl.isOn = row.switchValue } accessoryView = switchControl #elseif os(tvOS) accessoryView = nil accessoryType = row.accessoryType #endif } // MARK: - Private @available(tvOS, unavailable, message: "UISwitch is not available on tvOS.") @objc private func didToggleSwitch(_ sender: UISwitch) { delegate?.switchCell(self, didToggleSwitch: sender.isOn) } private func setUpAppearance() { textLabel?.numberOfLines = 0 detailTextLabel?.numberOfLines = 0 } }
mit
Daniel-Lopez/EZSwiftExtensions
Sources/UIViewControllerExtensions.swift
1
8271
// // UIViewControllerExtensions.swift // EZSwiftExtensions // // Created by Goktug Yilmaz on 15/07/15. // Copyright (c) 2015 Goktug Yilmaz. All rights reserved. // import UIKit extension UIViewController { // MARK: - Notifications //TODO: Document this part public func addNotificationObserver(name: String, selector: Selector) { NSNotificationCenter.defaultCenter().addObserver(self, selector: selector, name: name, object: nil) } public func removeNotificationObserver(name: String) { NSNotificationCenter.defaultCenter().removeObserver(self, name: name, object: nil) } public func removeNotificationObserver() { NSNotificationCenter.defaultCenter().removeObserver(self) } public func addKeyboardWillShowNotification() { self.addNotificationObserver(UIKeyboardWillShowNotification, selector: #selector(UIViewController.keyboardWillShowNotification(_:))) } public func addKeyboardDidShowNotification() { self.addNotificationObserver(UIKeyboardDidShowNotification, selector: #selector(UIViewController.keyboardDidShowNotification(_:))) } public func addKeyboardWillHideNotification() { self.addNotificationObserver(UIKeyboardWillHideNotification, selector: #selector(UIViewController.keyboardWillHideNotification(_:))) } public func addKeyboardDidHideNotification() { self.addNotificationObserver(UIKeyboardDidHideNotification, selector: #selector(UIViewController.keyboardDidHideNotification(_:))) } public func removeKeyboardWillShowNotification() { self.removeNotificationObserver(UIKeyboardWillShowNotification) } public func removeKeyboardDidShowNotification() { self.removeNotificationObserver(UIKeyboardDidShowNotification) } public func removeKeyboardWillHideNotification() { self.removeNotificationObserver(UIKeyboardWillHideNotification) } public func removeKeyboardDidHideNotification() { self.removeNotificationObserver(UIKeyboardDidHideNotification) } public func keyboardDidShowNotification(notification: NSNotification) { if let nInfo = notification.userInfo, let value = nInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue { let frame = value.CGRectValue() keyboardDidShowWithFrame(frame) } } public func keyboardWillShowNotification(notification: NSNotification) { if let nInfo = notification.userInfo, let value = nInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue { let frame = value.CGRectValue() keyboardWillShowWithFrame(frame) } } public func keyboardWillHideNotification(notification: NSNotification) { if let nInfo = notification.userInfo, let value = nInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue { let frame = value.CGRectValue() keyboardWillHideWithFrame(frame) } } public func keyboardDidHideNotification(notification: NSNotification) { if let nInfo = notification.userInfo, let value = nInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue { let frame = value.CGRectValue() keyboardDidHideWithFrame(frame) } } public func keyboardWillShowWithFrame(frame: CGRect) { } public func keyboardDidShowWithFrame(frame: CGRect) { } public func keyboardWillHideWithFrame(frame: CGRect) { } public func keyboardDidHideWithFrame(frame: CGRect) { } //EZSE: Makes the UIViewController register tap events and hides keyboard when clicked somewhere in the ViewController. public func hideKeyboardWhenTappedAround() { let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(UIViewController.dismissKeyboard)) view.addGestureRecognizer(tap) } public func dismissKeyboard() { view.endEditing(true) } // MARK: - VC Container /// EZSwiftExtensions public var top: CGFloat { get { if let me = self as? UINavigationController, let visibleViewController = me.visibleViewController { return visibleViewController.top } if let nav = self.navigationController { if nav.navigationBarHidden { return view.top } else { return nav.navigationBar.bottom } } else { return view.top } } } /// EZSwiftExtensions public var bottom: CGFloat { get { if let me = self as? UINavigationController, let visibleViewController = me.visibleViewController { return visibleViewController.bottom } if let tab = tabBarController { if tab.tabBar.hidden { return view.bottom } else { return tab.tabBar.top } } else { return view.bottom } } } /// EZSwiftExtensions public var tabBarHeight: CGFloat { get { if let me = self as? UINavigationController, let visibleViewController = me.visibleViewController { return visibleViewController.tabBarHeight } if let tab = self.tabBarController { return tab.tabBar.frame.size.height } return 0 } } /// EZSwiftExtensions public var navigationBarHeight: CGFloat { get { if let me = self as? UINavigationController, let visibleViewController = me.visibleViewController { return visibleViewController.navigationBarHeight } if let nav = self.navigationController { return nav.navigationBar.h } return 0 } } /// EZSwiftExtensions public var navigationBarColor: UIColor? { get { if let me = self as? UINavigationController, let visibleViewController = me.visibleViewController { return visibleViewController.navigationBarColor } return navigationController?.navigationBar.tintColor } set(value) { navigationController?.navigationBar.barTintColor = value } } /// EZSwiftExtensions public var navBar: UINavigationBar? { get { return navigationController?.navigationBar } } /// EZSwiftExtensions public var applicationFrame: CGRect { get { return CGRect(x: view.x, y: top, width: view.w, height: bottom - top) } } // MARK: - VC Flow /// EZSwiftExtensions public func pushVC(vc: UIViewController) { navigationController?.pushViewController(vc, animated: true) } /// EZSwiftExtensions public func popVC() { navigationController?.popViewControllerAnimated(true) } /// EZSwiftExtensions public func presentVC(vc: UIViewController) { presentViewController(vc, animated: true, completion: nil) } /// EZSwiftExtensions public func dismissVC(completion completion: (() -> Void)? ) { dismissViewControllerAnimated(true, completion: completion) } /// EZSwiftExtensions public func addAsChildViewController(vc: UIViewController, toView: UIView) { toView.addSubview(vc.view) self.addChildViewController(vc) vc.didMoveToParentViewController(self) } ///EZSE: Adds image named: as a UIImageView in the Background func setBackgroundImage(named: String) { let image = UIImage(named: named) let imageView = UIImageView(frame: view.frame) imageView.image = image view.addSubview(imageView) view.sendSubviewToBack(imageView) } ///EZSE: Adds UIImage as a UIImageView in the Background @nonobjc func setBackgroundImage(image: UIImage) { let imageView = UIImageView(frame: view.frame) imageView.image = image view.addSubview(imageView) view.sendSubviewToBack(imageView) } }
mit
wircho/SwiftyNotification
SwiftyNotification/SwiftyNotification.swift
1
1979
//--- import Foundation // MARK: Notification Protocol public protocol Notification { associatedtype P static var name:String { get } static func note(params:P) throws -> NSNotification static func parameters(note:NSNotification) throws -> P } extension Notification { public static func note(params:P) throws -> NSNotification { throw NotificationError.MethodNotImplemented } public static func register<T:AnyObject>(listener:T, object:AnyObject? = nil, queue: NSOperationQueue? = nil, closure:(T,P)->Void) -> NotificationToken { var token:NotificationToken? = nil let observer = NSNotificationCenter.defaultCenter().addObserverForName(name, object: object, queue: queue) { note in guard let actualToken = token else { return } guard let listener = actualToken.listener as? T else { actualToken.cancel() token = nil return } guard let params = try? parameters(note) else { return } closure(listener,params) } token = NotificationToken(listener: listener, observer: observer) return token! } public static func post(params:P) throws -> Void { let note = try self.note(params) NSNotificationCenter.defaultCenter().postNotification(note) } } // MARK: Notification Token public class NotificationToken { private weak var listener:AnyObject? private var observer:NSObjectProtocol? private init(listener:AnyObject, observer:NSObjectProtocol) { self.listener = listener self.observer = observer } deinit { self.cancel() } func cancel() { guard let observer = observer else { return } self.observer = nil NSNotificationCenter.defaultCenter().removeObserver(observer) } } // MARK: Notification Error public enum NotificationError: ErrorType { case MethodNotImplemented }
mit
eburns1148/CareKit
testing/OCKTest/OCKTest/LoremIpsum.swift
2
11419
/* Copyright (c) 2016, Apple Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder(s) nor the names of any contributors may be used to endorse or promote products derived from this software without specific prior written permission. No license is granted to the trademarks of the copyright holders even if such marks are included in this software. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ let LoremIpsum = "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. \n **New Line**Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pr etium.\n **New Line** Integer tincidunt. Cras dapibus.\n **New Line** Vivamus elementum semper nisi. Aenean vulputate eleifend tellus. Aenean leo ligula, porttitor eu, consequat vitae, eleifend ac, enim. Aliquam lorem ante, dapibus in, viverra quis, feugiat a, tellus. Phasellus viverra nulla ut metus varius laoreet. Quisque rutrum. Aenean imperdiet. Etiam ultricies nisi vel augue. Curabitur ullamcorper ultricies nisi. Nam eget dui. Etiam rhoncus. Maecenas tempus, tellus eget condimentum rhoncus, sem quam semper libero, sit amet adipiscing sem neque sed ipsum. Nam quam nunc, blandit vel, luctus pulvinar, hendrerit id, lorem. Maecenas nec odio et ante tincidunt tempus. Donec vitae sapien ut libero venenatis faucibus. Nullam quis ante. Etiam sit amet orci eget eros \n **New Line**faucibus tincidunt. Duis leo. Sed fringilla mauris sit amet nibh. Donec sodales sagittis magna. Sed consequat, leo eget bibendum sodales, augue velit cursus nuncLorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.\n **New Line**Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. \n **New Line**Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pr etium.\n Integer tincidunt. Cras dapibus.\n **New Line** Vivamus elementum semper nisi. Aenean vulputate eleifend tellus. Aenean leo ligula, porttitor eu, consequat vitae, eleifend ac, enim. Aliquam lorem ante, dapibus in, viverra quis, feugiat a, tellus. Phasellus viverra nulla ut metus varius laoreet. Quisque rutrum. Aenean imperdiet. Etiam ultricies nisi vel augue. Curabitur ullamcorper ultricies nisi. Nam eget dui. Etiam rhoncus. Maecenas tempus, tellus eget condimentum rhoncus, sem quam semper libero, sit amet adipiscing sem neque sed ipsum. Nam quam nunc, blandit vel, luctus pulvinar, hendrerit id, lorem. Maecenas nec odio et ante tincidunt tempus. Donec vitae sapien ut libero venenatis faucibus. Nullam quis ante. Etiam sit amet orci eget eros \n **New Line**faucibus tincidunt. Duis leo. Sed fringilla mauris sit amet nibh. Donec sodales sagittis magna. Sed consequat, leo eget bibendum sodales, augue velit cursus nuncLorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.\n **New Line**Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. \n**New Line**Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pr etium.\n Integer tincidunt. Cras dapibus.\n **New Line** Vivamus elementum semper nisi. Aenean vulputate eleifend tellus. Aenean leo ligula, porttitor eu, consequat vitae, eleifend ac, enim. Aliquam lorem ante, dapibus in, viverra quis, feugiat a, tellus. Phasellus viverra nulla ut metus varius laoreet. Quisque rutrum. Aenean imperdiet. Etiam ultricies nisi vel augue. Curabitur ullamcorper ultricies nisi. Nam eget dui. Etiam rhoncus. Maecenas tempus, tellus eget condimentum rhoncus, sem quam semper libero, sit amet adipiscing sem neque sed ipsum. Nam quam nunc, blandit vel, luctus pulvinar, hendrerit id, lorem. Maecenas nec odio et ante tincidunt tempus. Donec vitae sapien ut libero venenatis faucibus. Nullam quis ante. Etiam sit amet orci eget eros \n **New Line**faucibus tincidunt. Duis leo. Sed fringilla mauris sit amet nibh. Donec sodales sagittis magna. Sed consequat, leo eget bibendum sodales, augue velit cursus nuncLorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.\n **New Line**Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. \n**New Line**Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pr etium.\n Integer tincidunt. Cras dapibus.\n **New Line** Vivamus elementum semper nisi. Aenean vulputate eleifend tellus. Aenean leo ligula, porttitor eu, consequat vitae, eleifend ac, enim. Aliquam lorem ante, dapibus in, viverra quis, feugiat a, tellus. Phasellus viverra nulla ut metus varius laoreet. Quisque rutrum. Aenean imperdiet. Etiam ultricies nisi vel augue. Curabitur ullamcorper ultricies nisi. Nam eget dui. Etiam rhoncus. Maecenas tempus, tellus eget condimentum rhoncus, sem quam semper libero, sit amet adipiscing sem neque sed ipsum. Nam quam nunc, blandit vel, luctus pulvinar, hendrerit id, lorem. Maecenas nec odio et ante tincidunt tempus. Donec vitae sapien ut libero venenatis faucibus. Nullam quis ante. Etiam sit amet orci eget eros \n **New Line**faucibus tincidunt. Duis leo. Sed fringilla mauris sit amet nibh. Donec sodales sagittis magna. Sed consequat, leo eget bibendum sodales, augue velit cursus nuncLorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.\n **New Line**Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. \n **New Line**Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pr etium.\n **New Line** Integer tincidunt. Cras dapibus.\n **New Line** Vivamus elementum semper nisi. Aenean vulputate eleifend tellus. Aenean leo ligula, porttitor eu, consequat vitae, eleifend ac, enim. Aliquam lorem ante, dapibus in, viverra quis, feugiat a, tellus. Phasellus viverra nulla ut metus varius laoreet. Quisque rutrum. Aenean imperdiet. Etiam ultricies nisi vel augue. Curabitur ullamcorper ultricies nisi. Nam eget dui. Etiam rhoncus. Maecenas tempus, tellus eget condimentum rhoncus, sem quam semper libero, sit amet adipiscing sem neque sed ipsum. Nam quam nunc, blandit vel, luctus pulvinar, hendrerit id, lorem. Maecenas nec odio et ante tincidunt tempus. Donec vitae sapien ut libero venenatis faucibus. Nullam quis ante. Etiam sit amet orci eget eros \n **New Line**faucibus tincidunt. Duis leo. Sed fringilla mauris sit amet nibh. Donec sodales sagittis magna. Sed consequat, leo eget bibendum sodales, augue velit cursus nuncLorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.\n **New Line**Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. \n **New Line**Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pr etium.\n **New Line**Integer tincidunt. Cras dapibus.\n **New Line** Vivamus elementum semper nisi. Aenean vulputate eleifend tellus. Aenean leo ligula, porttitor eu, consequat vitae, eleifend ac, enim. Aliquam lorem ante, dapibus in, viverra quis, feugiat a, tellus. Phasellus viverra nulla ut metus varius laoreet. Quisque rutrum. Aenean imperdiet. Etiam ultricies nisi vel augue. Curabitur ullamcorper ultricies nisi. Nam eget dui. Etiam rhoncus. Maecenas tempus, tellus eget condimentum rhoncus, sem quam semper libero, sit amet adipiscing sem neque sed ipsum. Nam quam nunc, blandit vel, luctus pulvinar, hendrerit id, lorem. Maecenas nec odio et ante tincidunt tempus. Donec vitae sapien ut libero venenatis faucibus. Nullam quis ante. Etiam sit amet orci eget eros \n **New Line**faucibus tincidunt. Duis leo. Sed fringilla mauris sit amet nibh. Donec sodales sagittis magna. Sed consequat, leo eget bibendum sodales, augue velit cursus nuncLorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.\n **New Line**"
bsd-3-clause
kingslay/KSJSONHelp
Core/Source/PropertyData.swift
1
5102
// // PropertyData.swift // SwiftyDB // // Created by Øyvind Grimnes on 20/12/15. // import Foundation internal struct PropertyData { internal let isOptional: Bool internal var type: Any.Type internal var bindingType: Binding.Type? internal var name: String? lazy internal var bindingValue: Binding? = self.toBinding(self.value) internal let value: Any internal var isValid: Bool { return name != nil } internal init(property: Mirror.Child) { self.name = property.label let mirror = Mirror(reflecting: property.value) self.type = mirror.subjectType isOptional = mirror.displayStyle == .optional if isOptional { if mirror.children.count == 1 { self.value = mirror.children.first!.value }else{ self.value = property.value } }else{ self.value = property.value } bindingType = typeForMirror(mirror) } internal func typeForMirror(_ mirror: Mirror) -> Binding.Type? { if !isOptional { if mirror.displayStyle == .collection { return NSArray.self } if mirror.displayStyle == .dictionary { return NSDictionary.self } return mirror.subjectType as? Binding.Type } // TODO: Find a better way to unwrap optional types // Can easily be done using mirror if the encapsulated value is not nil switch mirror.subjectType { case is Optional<String>.Type: return String.self case is Optional<NSString>.Type: return NSString.self case is Optional<Character>.Type: return Character.self case is Optional<Date>.Type: return Date.self case is Optional<NSNumber>.Type: return NSNumber.self case is Optional<Data>.Type: return Data.self case is Optional<Bool>.Type: return Bool.self case is Optional<Int>.Type: return Int.self case is Optional<Int8>.Type: return Int8.self case is Optional<Int16>.Type: return Int16.self case is Optional<Int32>.Type: return Int32.self case is Optional<Int64>.Type: return Int64.self case is Optional<UInt>.Type: return UInt.self case is Optional<UInt8>.Type: return UInt8.self case is Optional<UInt16>.Type: return UInt16.self case is Optional<UInt32>.Type: return UInt32.self case is Optional<UInt64>.Type: return UInt64.self case is Optional<Float>.Type: return Float.self case is Optional<Double>.Type: return Double.self case is Optional<NSArray>.Type: return NSArray.self case is Optional<NSDictionary>.Type: return NSDictionary.self default: return nil } } /** Unwraps any value - parameter value: The value to unwrap */ fileprivate func toBinding(_ value: Any) -> Binding? { let mirror = Mirror(reflecting: value) if mirror.displayStyle == .collection { return NSKeyedArchiver.archivedData(withRootObject: value as! NSArray) } if mirror.displayStyle == .dictionary { return NSKeyedArchiver.archivedData(withRootObject: value as! NSDictionary) } /* Raw value */ if mirror.displayStyle != .optional { return value as? Binding } /* The encapsulated optional value if not nil, otherwise nil */ if let value = mirror.children.first?.value { return toBinding(value) }else{ return nil } } } extension PropertyData { internal static func validPropertyDataForObject (_ object: Any) -> [PropertyData] { var ignoredProperties = Set<String>() return validPropertyDataForMirror(Mirror(reflecting: object), ignoredProperties: &ignoredProperties) } fileprivate static func validPropertyDataForMirror(_ mirror: Mirror, ignoredProperties: inout Set<String>) -> [PropertyData] { if mirror.subjectType is IgnoredPropertieProtocol.Type { ignoredProperties = ignoredProperties.union((mirror.subjectType as! IgnoredPropertieProtocol.Type).ignoredProperties()) } var propertyData: [PropertyData] = [] if let superclassMirror = mirror.superclassMirror { propertyData += validPropertyDataForMirror(superclassMirror, ignoredProperties: &ignoredProperties) } /* Map children to property data and filter out ignored or invalid properties */ propertyData += mirror.children.map { PropertyData(property: $0) }.filter({ $0.isValid && !ignoredProperties.contains($0.name!) }) return propertyData } }
mit
hoowang/SWiftQRScanner
SWiftQRScanner/SWiftQRScanner/QRCodeScanner/QRCodeScannerController.swift
1
1129
// // QRCodeScannerController.swift // WKWeibo // // Created by hooge on 15/9/16. // Copyright © 2015年 hoowang. All rights reserved. // import UIKit class QRCodeScannerController: UIViewController { @IBOutlet weak var scanLineView: UIImageView! @IBOutlet weak var scanLineTopConstraint: NSLayoutConstraint! override func viewDidLoad() { super.viewDidLoad() } @IBAction func CloseScanner(sender: AnyObject) { dismissViewControllerAnimated(true, completion: nil) } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) startScanAnimation() } private func startScanAnimation() { let basicAnimation = CABasicAnimation() basicAnimation.keyPath = "position.y" basicAnimation.toValue = scanLineView.bounds.height basicAnimation.fromValue = 0.0 basicAnimation.duration = 1.0 basicAnimation.repeatCount = MAXFLOAT basicAnimation.removedOnCompletion = false scanLineView.layer.addAnimation(basicAnimation, forKey: "") scanLineView.startAnimating() } }
mit
kirsteins/BigInteger
Source/Operators.swift
1
4810
// // Operators.swift // BigInteger // // Created by Jānis Kiršteins on 17/09/14. // Copyright (c) 2014 Jānis Kiršteins. All rights reserved. // // MARK: - comparison public func == (lhs: Int, rhs: BigInteger) -> Bool { return BigInteger(lhs) == rhs } public func == (lhs: BigInteger, rhs: Int) -> Bool { return lhs == BigInteger(rhs) } public func >= (lhs: Int, rhs: BigInteger) -> Bool { return BigInteger(lhs) >= rhs } public func >= (lhs: BigInteger, rhs: Int) -> Bool { return lhs >= BigInteger(rhs) } public func <= (lhs: Int, rhs: BigInteger) -> Bool { return BigInteger(lhs) <= rhs } public func <= (lhs: BigInteger, rhs: Int) -> Bool { return lhs <= BigInteger(rhs) } public func > (lhs: Int, rhs: BigInteger) -> Bool { return BigInteger(lhs) > rhs } public func > (lhs: BigInteger, rhs: Int) -> Bool { return lhs > BigInteger(rhs) } public func < (lhs: Int, rhs: BigInteger) -> Bool { return BigInteger(lhs) < rhs } public func < (lhs: BigInteger, rhs: Int) -> Bool { return lhs < BigInteger(rhs) } // MARK: - add public func + (lhs: BigInteger, rhs: BigInteger) -> BigInteger { return lhs.add(rhs) } public func + (lhs: BigInteger, rhs: Int) -> BigInteger { return lhs.add(rhs) } public func + (lhs: Int, rhs: BigInteger) -> BigInteger { return rhs.add(lhs) } public func += (inout lhs: BigInteger, rhs: BigInteger) { lhs = lhs.add(rhs) } public func += (inout lhs: BigInteger, rhs: Int) { lhs = lhs.add(rhs) } // MARK: - subtract public func - (lhs: BigInteger, rhs: BigInteger) -> BigInteger { return lhs.subtract(rhs) } public func - (lhs: BigInteger, rhs: Int) -> BigInteger { return lhs.subtract(rhs) } public func - (lhs: Int, rhs: BigInteger) -> BigInteger { return rhs.negate().add(lhs) } public func -= (inout lhs: BigInteger, rhs: BigInteger) { lhs = lhs.subtract(rhs) } public func -= (inout lhs: BigInteger, rhs: Int) { lhs = lhs.subtract(rhs) } // MARK: - multiply public func * (lhs: BigInteger, rhs: BigInteger) -> BigInteger { return lhs.multiplyBy(rhs) } public func * (lhs: BigInteger, rhs: Int) -> BigInteger { return lhs.multiplyBy(rhs) } public func * (lhs: Int, rhs: BigInteger) -> BigInteger { return rhs.multiplyBy(lhs) } public func *= (inout lhs: BigInteger, rhs: BigInteger) { lhs = lhs.multiplyBy(rhs) } public func *= (inout lhs: BigInteger, rhs: Int) { lhs = lhs.multiplyBy(rhs) } // MARK: - divide public func / (lhs: BigInteger, rhs: BigInteger) -> BigInteger? { return lhs.divideBy(rhs) } public func / (lhs: BigInteger, rhs: Int) -> BigInteger? { return lhs.divideBy(rhs) } // MARK: - reminder public func % (lhs: BigInteger, rhs: BigInteger) -> BigInteger? { return lhs.reminder(rhs) } public func % (lhs: BigInteger, rhs: Int) -> BigInteger? { return lhs.reminder(rhs) } // MARK: - negate public prefix func - (operand: BigInteger) -> BigInteger { return operand.negate() } // MARK: - xor public func ^ (lhs: BigInteger, rhs: BigInteger) -> BigInteger { return lhs.bitwiseXor(rhs) } public func ^ (lhs: BigInteger, rhs: Int) -> BigInteger { return lhs.bitwiseXor(rhs) } public func ^ (lhs: Int, rhs: BigInteger) -> BigInteger { return rhs.bitwiseXor(lhs) } public func ^= (inout lhs: BigInteger, rhs: BigInteger) { lhs = lhs.bitwiseXor(rhs) } public func ^= (inout lhs: BigInteger, rhs: Int) { lhs = lhs.bitwiseXor(rhs) } // MARK: - or public func | (lhs: BigInteger, rhs: BigInteger) -> BigInteger { return lhs.bitwiseOr(rhs) } public func | (lhs: BigInteger, rhs: Int) -> BigInteger { return lhs.bitwiseOr(rhs) } public func | (lhs: Int, rhs: BigInteger) -> BigInteger { return rhs.bitwiseOr(lhs) } public func |= (inout lhs: BigInteger, rhs: BigInteger) { lhs = lhs.bitwiseOr(rhs) } public func |= (inout lhs: BigInteger, rhs: Int) { lhs = lhs.bitwiseOr(rhs) } // MARK: - and public func & (lhs: BigInteger, rhs: BigInteger) -> BigInteger { return lhs.bitwiseAnd(rhs) } public func & (lhs: BigInteger, rhs: Int) -> BigInteger { return lhs.bitwiseAnd(rhs) } public func & (lhs: Int, rhs: BigInteger) -> BigInteger { return rhs.bitwiseAnd(lhs) } public func &= (inout lhs: BigInteger, rhs: BigInteger) { lhs = lhs.bitwiseAnd(rhs) } public func &= (inout lhs: BigInteger, rhs: Int) { lhs = lhs.bitwiseAnd(rhs) } // MARK: - shiftLeft public func << (lhs: BigInteger, rhs: Int32) -> BigInteger { return lhs.shiftLeft(rhs) } public func <<= (inout lhs: BigInteger, rhs: Int32) { lhs = lhs.shiftLeft(rhs) } // MARK: - shiftRight public func >> (lhs: BigInteger, rhs: Int32) -> BigInteger { return lhs.shiftRight(rhs) } public func >>= (inout lhs: BigInteger, rhs: Int32) { lhs = lhs.shiftRight(rhs) }
mit
square/wire
wire-library/wire-runtime-swift/src/main/swift/ProtoCodable.swift
1
2699
/* * Copyright 2020 Square Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // MARK: - /** A protocol which defines a type as being deserializable from protocol buffer data. */ public protocol ProtoDecodable { static var protoSyntax: ProtoSyntax? { get } init(from reader: ProtoReader) throws } // MARK: - /** A protocol which defines a type as being serializable into protocol buffer data. */ public protocol ProtoEncodable { /** The wire type to use in the key for this field */ static var protoFieldWireType: FieldWireType { get } static var protoSyntax: ProtoSyntax? { get } func encode(to writer: ProtoWriter) throws } public extension ProtoEncodable { /** The vast majority of fields, including all messages, use a length-delimited wire type, so make it the default. */ static var protoFieldWireType: FieldWireType { .lengthDelimited } } // MARK: - /** A convenience protocol which defines a type as being both encodable and decodable as protocol buffer data. */ public typealias ProtoCodable = ProtoDecodable & ProtoEncodable // MARK: - /** A marker protocol indicating that a given struct was generated from a .proto file that was using the Proto2 specification */ public protocol Proto2Codable: ProtoCodable {} extension Proto2Codable { public static var protoSyntax: ProtoSyntax? { .proto2 } } /** A marker protocol indicating that a given struct was generated from a .proto file that was using the Proto3 specification */ public protocol Proto3Codable: ProtoCodable {} extension Proto3Codable { public static var protoSyntax: ProtoSyntax? { .proto3 } } // MARK: - extension ProtoDecodable { /** A convenience function used with required fields that throws an error if the field is null, or unwraps the nullable value if not. */ public static func checkIfMissing<T>(_ value: T?, _ fieldName: String) throws -> T { guard let value = value else { throw ProtoDecoder.Error.missingRequiredField( typeName: String(describing: self), fieldName: fieldName ) } return value } }
apache-2.0
moozzyk/SignalR-Client-Swift
Examples/Playground/Playground.playground/Contents.swift
1
1762
import Cocoa import SignalRClient let hubConnection = HubConnectionBuilder(url: URL(string: "http://localhost:5000/playground")!) .withLogging(minLogLevel: .info) .build() hubConnection.on(method: "AddMessage") {(user: String, message: String) in print(">>> \(user): \(message)") } hubConnection.start() // NOTE: break here before to make this sample work and prevent errors // caused by trying to invoke server side methods before starting the // connection completed // invoking a hub method and receiving a result hubConnection.invoke(method: "Add", 2, 3, resultType: Int.self) { result, error in if let error = error { print("error: \(error)") } else { print("Add result: \(result!)") } } // invoking a hub method that does not return a result hubConnection.invoke(method: "Broadcast", "Playground user", "Sending a message") { error in if let error = error { print("error: \(error)") } else { print("Broadcast invocation completed without errors") } } hubConnection.send(method: "Broadcast", "Playground user", "Testing send") { error in if let error = error { print("Send failed: \(error)") } } let streamHandle = hubConnection.stream(method: "StreamNumbers", 1, 10000, streamItemReceived: { (item: Int) in print(">>> \(item)") }) { error in print("Stream closed.") if let error = error { print("Error: \(error)") } } DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(2)) { hubConnection.cancelStreamInvocation(streamHandle: streamHandle) { error in print("Canceling stream invocation failed: \(error)") } } DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(3)) { hubConnection.stop() }
mit
Eonil/EditorLegacy
Modules/EditorFileTreeNavigationFeature/EditorFileTreeNavigationFeature/FileNavigating/FileTreeViewController.swift
2
4019
//// //// FileTreeViewController.swift //// RustCodeEditor //// //// Created by Hoon H. on 11/11/14. //// Copyright (c) 2014 Eonil. All rights reserved. //// // //import Foundation //import AppKit // //class FileTreeViewController : NSViewController, NSOutlineViewDataSource, NSOutlineViewDelegate { // // let userIsWantingToEditFileAtPath = Notifier<String>() // // private var _root:FileNode1? // // var pathRepresentation:String? { // get { // return self.representedObject as String? // } // set(v) { // self.representedObject = v // } // } // override var representedObject:AnyObject? { // get { // return super.representedObject // } // set(v) { // precondition(v is String) // super.representedObject = v // // if let v2 = v as String? { // _root = FileNode1(path: pathRepresentation!) // } else { // _root = nil // } // // self.outlineView.reloadData() // } // } // // var outlineView:NSOutlineView { // get { // return self.view as NSOutlineView // } // set(v) { // self.view = v // } // } // // override func loadView() { // super.view = NSOutlineView() // } // override func viewDidLoad() { // super.viewDidLoad() // // let col1 = NSTableColumn(identifier: NAME, title: "Name", width: 100) // // outlineView.focusRingType = NSFocusRingType.None // outlineView.headerView = nil // outlineView.addTableColumn <<< col1 // outlineView.outlineTableColumn = col1 // outlineView.rowSizeStyle = NSTableViewRowSizeStyle.Small // outlineView.selectionHighlightStyle = NSTableViewSelectionHighlightStyle.SourceList // outlineView.sizeLastColumnToFit() // // outlineView.setDataSource(self) // outlineView.setDelegate(self) // // } // // // // //// func outlineView(outlineView: NSOutlineView, heightOfRowByItem item: AnyObject) -> CGFloat { //// return 16 //// } // // func outlineView(outlineView: NSOutlineView, numberOfChildrenOfItem item: AnyObject?) -> Int { // let n1 = item as FileNode1? // if let n2 = n1 { // if let ns3 = n2.subnodes { // return ns3.count // } else { // return 0 // } // } else { // return _root == nil ? 0 : 1 // } // } // func outlineView(outlineView: NSOutlineView, child index: Int, ofItem item: AnyObject?) -> AnyObject { // let n1 = item as FileNode1? // if let n2 = n1 { // let ns3 = n2.subnodes! // return ns3[index] // } else { // return _root! // } // } //// func outlineView(outlineView: NSOutlineView, isGroupItem item: AnyObject) -> Bool { //// let n1 = item as FileNode1 //// let ns2 = n1.subnodes //// return ns2 != nil //// } // func outlineView(outlineView: NSOutlineView, isItemExpandable item: AnyObject) -> Bool { // let n1 = item as FileNode1 // let ns2 = n1.subnodes // return ns2 != nil // } //// func outlineView(outlineView: NSOutlineView, objectValueForTableColumn tableColumn: NSTableColumn?, byItem item: AnyObject?) -> AnyObject? { //// let n1 = item as FileNode1 //// return n1.relativePath //// } // func outlineView(outlineView: NSOutlineView, viewForTableColumn tableColumn: NSTableColumn?, item: AnyObject) -> NSView? { // let tv1 = NSTextField() // let iv1 = NSImageView() // let cv1 = NSTableCellView() // cv1.textField = tv1 // cv1.imageView = iv1 // cv1.addSubview(tv1) // cv1.addSubview(iv1) // // let n1 = item as FileNode1 // assert(n1.existing) // iv1.image = NSWorkspace.sharedWorkspace().iconForFile(n1.absolutePath) // cv1.textField!.stringValue = n1.displayName // cv1.textField!.bordered = false // cv1.textField!.backgroundColor = NSColor.clearColor() // cv1.textField!.editable = false // (cv1.textField!.cell() as NSCell).lineBreakMode = NSLineBreakMode.ByTruncatingHead // return cv1 // } // // // // func outlineViewSelectionDidChange(notification: NSNotification) { // let idx1 = self.outlineView.selectedRow // let n1 = self.outlineView.itemAtRow(idx1) as FileNode1 // userIsWantingToEditFileAtPath.signal(n1.absolutePath) // } //} // // // // // // // // //private let NAME = "NAME" //
mit
benlangmuir/swift
validation-test/compiler_crashers_fixed/00962-swift-protocoltype-canonicalizeprotocols.swift
65
505
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck struct h { func e() { } protocol f { } funcB<T>) { } } struct d<f : e, g: e where g.h == f.h> { func f<T>(
apache-2.0
benlangmuir/swift
validation-test/compiler_crashers_fixed/28033-swift-configureconstructortype.swift
65
483
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck func c{ class a{{{{{ }}}}class S{ class a{class S{func b{enum B{enum A{class b<f:f.c
apache-2.0
malaonline/iOS
mala-ios/View/OrderForm/OrderFormOperatingView.swift
1
9522
// // OrderFormOperatingView.swift // mala-ios // // Created by 王新宇 on 16/5/13. // Copyright © 2016年 Mala Online. All rights reserved. // import UIKit public protocol OrderFormOperatingViewDelegate: class { /// 立即支付 func orderFormPayment() /// 再次购买 func orderFormBuyAgain() /// 取消订单 func orderFormCancel() /// 申请退费 func requestRefund() } class OrderFormOperatingView: UIView { // MARK: - Property /// 需支付金额 var price: Int = 0 { didSet{ priceLabel.text = price.amountCNY } } /// 订单详情模型 var model: OrderForm? { didSet { /// 渲染底部视图UI isTeacherPublished = model?.isTeacherPublished orderStatus = model?.orderStatus ?? .confirm price = isForConfirm ? MalaCurrentCourse.getAmount() ?? 0 : model?.amount ?? 0 } } /// 标识是否为确认订单状态 var isForConfirm: Bool = false { didSet { /// 渲染底部视图UI if isForConfirm { orderStatus = .confirm } } } /// 订单状态 var orderStatus: MalaOrderStatus = .canceled { didSet { DispatchQueue.main.async { self.changeDisplayMode() } } } /// 老师上架状态标记 var isTeacherPublished: Bool? weak var delegate: OrderFormOperatingViewDelegate? // MARK: - Components /// 价格容器 private lazy var priceContainer: UIView = { let view = UIView(UIColor.white) return view }() /// 合计标签 private lazy var stringLabel: UILabel = { let label = UILabel( text: "合计:", font: FontFamily.PingFangSC.Light.font(13), textColor: UIColor(named: .ArticleTitle) ) return label }() /// 金额标签 private lazy var priceLabel: UILabel = { let label = UILabel( text: "¥0.00", font: FontFamily.PingFangSC.Light.font(18), textColor: UIColor(named: .ThemeRed) ) return label }() /// 确定按钮(确认支付、再次购买、重新购买) private lazy var confirmButton: UIButton = { let button = UIButton() button.titleLabel?.font = UIFont.systemFont(ofSize: 15) return button }() /// 取消按钮(取消订单) private lazy var cancelButton: UIButton = { let button = UIButton() button.titleLabel?.font = UIFont.systemFont(ofSize: 15) return button }() // MARK: - Constructed override init(frame: CGRect) { super.init(frame: frame) setupUserInterface() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Private method private func setupUserInterface() { // Style backgroundColor = UIColor.white // SubViews addSubview(priceContainer) priceContainer.addSubview(stringLabel) priceContainer.addSubview(priceLabel) addSubview(cancelButton) addSubview(confirmButton) // Autolayout priceContainer.snp.makeConstraints{ (maker) -> Void in maker.top.equalTo(self) maker.left.equalTo(self) maker.width.equalTo(self).multipliedBy(0.44) maker.height.equalTo(44) maker.bottom.equalTo(self) } stringLabel.snp.makeConstraints { (maker) in maker.right.equalTo(priceLabel.snp.left) maker.centerY.equalTo(priceContainer) maker.height.equalTo(18.5) } priceLabel.snp.makeConstraints { (maker) in maker.centerY.equalTo(priceContainer) maker.centerX.equalTo(priceContainer).offset(17) maker.height.equalTo(25) } confirmButton.snp.makeConstraints { (maker) in maker.right.equalTo(self) maker.centerY.equalTo(self) maker.width.equalTo(self).multipliedBy(0.28) maker.height.equalTo(self) } cancelButton.snp.makeConstraints { (maker) in maker.right.equalTo(confirmButton.snp.left) maker.centerY.equalTo(self) maker.width.equalTo(self).multipliedBy(0.28) maker.height.equalTo(self) } } /// 根据当前订单状态,渲染对应UI样式 private func changeDisplayMode() { // 仅当订单金额已支付, 课程类型为一对一课程时 // 老师下架状态才会生效 if let isLiveCourse = model?.isLiveCourse, isLiveCourse == false && isTeacherPublished == false && orderStatus != .penging && orderStatus != .confirm { setTeacherDisable() return } switch orderStatus { case .penging: setOrderPending() case .paid: setOrderPaid() case .paidRefundable: setOrderPaidRefundable() case .finished: setOrderFinished() case .refunding: setOrderRefunding() case .refund: setOrderRefund() case .canceled: setOrderCanceled() case .confirm: setOrderConfirm() } } /// 待支付样式 private func setOrderPending() { cancelButton.isHidden = false cancelButton.setTitle(L10n.cancelOrder, for: .normal) cancelButton.setTitleColor(UIColor.white, for: .normal) cancelButton.setBackgroundImage(UIImage.withColor(UIColor(named: .ThemeBlue)), for: .normal) cancelButton.addTarget(self, action: #selector(OrderFormOperatingView.cancelOrderForm), for: .touchUpInside) setButton("去支付", UIColor(named: .ThemeBlue), enabled: false, action: #selector(OrderFormOperatingView.pay), relayout: false) } /// 进行中不可退费样式(only for private tuition) private func setOrderPaid() { setButton("再次购买", UIColor(named: .ThemeRed), action: #selector(OrderFormOperatingView.buyAgain)) } /// 进行中可退费样式(only for live course) private func setOrderPaidRefundable() { setButton("申请退费", UIColor(named: .ThemeGreen), action: #selector(OrderFormOperatingView.requestRefund)) } /// 已完成样式(only for live course) private func setOrderFinished() { setButton("再次购买", UIColor(named: .ThemeRed), hidden: true, action: #selector(OrderFormOperatingView.buyAgain)) cancelButton.isHidden = true } /// 退费审核中样式(only for live course) private func setOrderRefunding() { setButton("审核中...", UIColor(named: .Disabled), enabled: false) } /// 已退费样式 private func setOrderRefund() { setButton("已退费", UIColor(named: .ThemeGreen), enabled: false) } /// 已取消样式 private func setOrderCanceled() { var color = UIColor(named: .Disabled) var action: Selector? var enable = true var string = "重新购买" if let isLive = model?.isLiveCourse, isLive == true { string = "订单已关闭" enable = false }else { color = UIColor(named: .ThemeRed) action = #selector(OrderFormOperatingView.buyAgain) } setButton(string, color, enabled: enable, action: action) } /// 订单预览样式 private func setOrderConfirm() { setButton("提交订单", UIColor(named: .ThemeRed), action: #selector(OrderFormOperatingView.pay)) } /// 教师已下架样式 private func setTeacherDisable() { setButton("该老师已下架", UIColor(named: .Disabled), enabled: false) } private func setButton( _ title: String, _ bgColor: UIColor, _ titleColor: UIColor = UIColor.white, enabled: Bool? = nil, hidden: Bool = false, action: Selector? = nil, relayout: Bool = true) { cancelButton.isHidden = true confirmButton.isHidden = hidden if let enabled = enabled { confirmButton.isEnabled = enabled } if let action = action { confirmButton.addTarget(self, action: action, for: .touchUpInside) } confirmButton.setTitle(title, for: .normal) confirmButton.setBackgroundImage(UIImage.withColor(bgColor), for: .normal) confirmButton.setTitleColor(titleColor, for: .normal) guard relayout == true else { return } confirmButton.snp.remakeConstraints { (maker) in maker.right.equalTo(self) maker.centerY.equalTo(self) maker.width.equalTo(self).multipliedBy(0.5) maker.height.equalTo(self) } } // MARK: - Event Response /// 立即支付 @objc func pay() { delegate?.orderFormPayment() } /// 再次购买 @objc func buyAgain() { delegate?.orderFormBuyAgain() } /// 取消订单 @objc func cancelOrderForm() { delegate?.orderFormCancel() } /// 申请退费 @objc func requestRefund() { delegate?.requestRefund() } deinit { println("Order Form Operation View Deinit") } }
mit
futomtom/DynoOrder
Dyno/DynoOrder/ItemCell.swift
1
907
// // ItemCell.swift // DynoOrder // // Created by alexfu on 10/20/16. // Copyright © 2016 Alex. All rights reserved. // import UIKit class ItemCell: UICollectionViewCell { @IBOutlet weak var imageV: UIImageView! @IBOutlet weak var name: UILabel! @IBOutlet weak var stepper: UIStepper! @IBOutlet weak var number: UILabel! let colors = [UIColor.blue, UIColor.red, UIColor.yellow, UIColor.cyan, UIColor.gray,UIColor.brown, UIColor.orange ] override func awakeFromNib() { layer.borderColor=UIColor.darkGray.cgColor layer.borderWidth=1 layer.cornerRadius = 4 } func setData(item: Product, index:Int) { // imageV.image = UIImage(name: " ") name.text = NSLocalizedString("my book",comment:"") stepper.tag = index // backgroundColor = colors[index%colors.count] } }
mit
polymr/polymyr-api
Sources/App/Utility/Sanitizable.swift
1
200
import Vapor /// A request-extractable `Model`. public protocol Sanitizable { /// Fields that are permitted to be deserialized from a Request's JSON. static var permitted: [String] { get } }
mit
mbeloded/beaconDemo
PassKitApp/PassKitApp/Classes/Managers/CoreDataManager/CoreDataManager.swift
1
12527
// // CoreDataManager.swift // PassKitApp // // Created by Alexandr Chernyy on 10/6/14. // Copyright (c) 2014 Alexandr Chernyy. All rights reserved. // import UIKit import CoreData class CoreDataManager: NSManagedObject { class var sharedManager : CoreDataManager { struct Static { static var onceToken : dispatch_once_t = 0 static var instance : CoreDataManager? = nil } dispatch_once(&Static.onceToken) { Static.instance = CoreDataManager() } return Static.instance! } //var appDelegate:AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate var contxt:NSManagedObjectContext! = (UIApplication.sharedApplication().delegate as AppDelegate).managedObjectContext! init() { self.contxt = (UIApplication.sharedApplication().delegate as AppDelegate).managedObjectContext! } func start() { // self.appDelegate = UIApplication.sharedApplication().delegate as AppDelegate // self.contxt = appDelegate.managedObjectContext } func initNewObject(requestType:RequestType)->AnyObject { var object:AnyObject! switch(requestType) { case RequestType.VERSION: let en = NSEntityDescription.entityForName("Version", inManagedObjectContext: self.contxt) object = en break; default: break; } return object } func saveData(saveArray savedArray:Array<AnyObject>, requestType:RequestType) { switch(requestType) { case .VERSION: self.removeData(.VERSION) for object in savedArray { let en = NSEntityDescription.entityForName("Version", inManagedObjectContext: self.contxt) var newItem = Version(entity: en!, insertIntoManagedObjectContext: contxt) newItem.version = (object as PFObject)["version"] as String newItem.createdAt = (object as PFObject).createdAt newItem.updatedAt = (object as PFObject).updatedAt } break; case .CATEGORY: self.removeData(.CATEGORY) for object in savedArray { let en = NSEntityDescription.entityForName("CategoryModel", inManagedObjectContext: self.contxt) var newItem = CategoryModel(entity: en!, insertIntoManagedObjectContext: contxt) var object1:PFObject = (object as PFObject) var icon:PFFile = (object as PFObject)["icon"] as PFFile var pngPath:NSString = NSHomeDirectory().stringByAppendingPathComponent("Documents/\(icon.name)"); var imageData:NSData = icon.getData() imageData.writeToFile(pngPath, atomically: true) newItem.id = (object as PFObject).objectId newItem.name = (object as PFObject)["name"] as? String newItem.icon = ((object as PFObject)["icon"] as? PFFile)?.url newItem.createdAt = (object as PFObject).createdAt newItem.updatedAt = (object as PFObject).updatedAt } break; case .MALL: self.removeData(.MALL) for object in savedArray { let en = NSEntityDescription.entityForName("MallModel", inManagedObjectContext: self.contxt) var newItem = MallModel(entity: en!, insertIntoManagedObjectContext: contxt) var object1:PFObject = (object as PFObject) newItem.id = (object as PFObject).objectId newItem.name = (object as PFObject)["name"] as? String newItem.beacon_id = (object as PFObject)["beacon_id"] as? String newItem.information = (object as PFObject)["information"] as? String newItem.location = (object as PFObject)["location"] as? String newItem.createdAt = (object as PFObject).createdAt newItem.updatedAt = (object as PFObject).updatedAt } break; case .BANNER: self.removeData(.BANNER) for object in savedArray { let en = NSEntityDescription.entityForName("BannerModel", inManagedObjectContext: self.contxt) var newItem = BannerModel(entity: en!, insertIntoManagedObjectContext: contxt) var object1:PFObject = (object as PFObject) var icon:PFFile = (object as PFObject)["image"] as PFFile var pngPath:NSString = NSHomeDirectory().stringByAppendingPathComponent("Documents/\(icon.name)"); var imageData:NSData = icon.getData() imageData.writeToFile(pngPath, atomically: true) newItem.id = (object as PFObject).objectId newItem.type_id = (object as PFObject)["type_id"] as? String newItem.image = ((object as PFObject)["image"] as? PFFile)?.url newItem.createdAt = (object as PFObject).createdAt newItem.updatedAt = (object as PFObject).updatedAt } break; case .MALL_BANNER: self.removeData(.MALL_BANNER) for object in savedArray { let en = NSEntityDescription.entityForName("MallBannerModel", inManagedObjectContext: self.contxt) var newItem = MallBannerModel(entity: en!, insertIntoManagedObjectContext: contxt) newItem.id = (object as PFObject).objectId newItem.mall_id = (object as PFObject)["mall_id"] as? String newItem.banner_id = (object as PFObject)["banner_id"] as? String newItem.createdAt = (object as PFObject).createdAt newItem.updatedAt = (object as PFObject).updatedAt } break; case .STORE: self.removeData(.STORE) for object in savedArray { let en = NSEntityDescription.entityForName("StoreModel", inManagedObjectContext: self.contxt) var newItem = StoreModel(entity: en!, insertIntoManagedObjectContext: contxt) newItem.id = (object as PFObject).objectId newItem.name = (object as PFObject)["name"] as? String newItem.details = (object as PFObject)["details"] as? String newItem.banner_id = (object as PFObject)["banner_id"] as? String newItem.beacon_id = (object as PFObject)["beacon_id"] as? String newItem.location = (object as PFObject)["location"] as? String newItem.category_id = (object as PFObject)["category_id"] as? String newItem.createdAt = (object as PFObject).createdAt newItem.updatedAt = (object as PFObject).updatedAt } break; default: break; } contxt.save(nil) } func loadData(requestType:RequestType)->Array<AnyObject> { var data:Array<AnyObject>? = [] var freq:NSFetchRequest! switch(requestType) { case RequestType.VERSION: freq = NSFetchRequest(entityName: "Version") break; case .CATEGORY: freq = NSFetchRequest(entityName: "CategoryModel") break; case .MALL: freq = NSFetchRequest(entityName: "MallModel") break; case .BANNER: freq = NSFetchRequest(entityName: "BannerModel") break; case .MALL_BANNER: freq = NSFetchRequest(entityName: "MallBannerModel") break; case .STORE: freq = NSFetchRequest(entityName: "StoreModel") break; default: break; } if self.contxt != nil { data = self.contxt.executeFetchRequest(freq, error: nil)! } return data! } func loadData(requestType:RequestType, key:String)->Array<AnyObject> { var data:Array<AnyObject>? = [] var freq:NSFetchRequest! switch(requestType) { case RequestType.VERSION: freq = NSFetchRequest(entityName: "Version") break; case .CATEGORY: freq = NSFetchRequest(entityName: "CategoryModel") break; case .MALL: freq = NSFetchRequest(entityName: "MallModel") break; case .BANNER: freq = NSFetchRequest(entityName: "BannerModel") let predicate = NSPredicate(format: "id == %@", key) println(predicate) freq.predicate = predicate break; case .MALL_BANNER: freq = NSFetchRequest(entityName: "MallBannerModel") let predicate = NSPredicate(format: "mall_id == %@", key) println(predicate) freq.predicate = predicate break; case .STORE: freq = NSFetchRequest(entityName: "StoreModel") let predicate = NSPredicate(format: "category_id == %@", key) println(predicate) freq.predicate = predicate break; default: break; } if self.contxt != nil { data = self.contxt.executeFetchRequest(freq, error: nil)! } return data! } func removeData(requestType:RequestType) { var freq:NSFetchRequest! switch(requestType) { case RequestType.VERSION: freq = NSFetchRequest(entityName: "Version") var results:NSArray = self.contxt.executeFetchRequest(freq, error: nil)! if(results.count > 0) { for object in results { self.contxt.deleteObject(object as NSManagedObject) self.contxt.save(nil) } } break; case .CATEGORY: freq = NSFetchRequest(entityName: "CategoryModel") var results:NSArray = self.contxt.executeFetchRequest(freq, error: nil)! if(results.count > 0) { for object in results { self.contxt.deleteObject(object as NSManagedObject) self.contxt.save(nil) } } break; case .MALL: freq = NSFetchRequest(entityName: "MallModel") var results:NSArray = self.contxt.executeFetchRequest(freq, error: nil)! if(results.count > 0) { for object in results { self.contxt.deleteObject(object as NSManagedObject) self.contxt.save(nil) } } break; case .BANNER: freq = NSFetchRequest(entityName: "BannerModel") var results:NSArray = self.contxt.executeFetchRequest(freq, error: nil)! if(results.count > 0) { for object in results { self.contxt.deleteObject(object as NSManagedObject) self.contxt.save(nil) } } break; case .MALL_BANNER: freq = NSFetchRequest(entityName: "MallBannerModel") var results:NSArray = self.contxt.executeFetchRequest(freq, error: nil)! if(results.count > 0) { for object in results { self.contxt.deleteObject(object as NSManagedObject) self.contxt.save(nil) } } break; case .STORE: freq = NSFetchRequest(entityName: "StoreModel") var results:NSArray = self.contxt.executeFetchRequest(freq, error: nil)! if(results.count > 0) { for object in results { self.contxt.deleteObject(object as NSManagedObject) self.contxt.save(nil) } } break; default: break; } } }
gpl-2.0
malaonline/iOS
mala-ios/Extension/Extension+UIColor.swift
1
742
// // Extension+UIColor.swift // mala-ios // // Created by Elors on 15/12/20. // Copyright © 2015年 Mala Online. All rights reserved. // import UIKit // MARK: - Convenience extension UIColor { /// Convenience Function to Create UIColor With Hex RGBValue /// /// - parameter rgbHexValue: Hex RGBValue /// - parameter alpha: Alpha /// /// - returns: UIColor convenience init(rgbHexValue: UInt32 = 0xFFFFFF, alpha: Double = 1.0) { let red = CGFloat((rgbHexValue & 0xFF0000) >> 16)/256.0 let green = CGFloat((rgbHexValue & 0xFF00) >> 8)/256.0 let blue = CGFloat(rgbHexValue & 0xFF)/256.0 self.init(red:red, green:green, blue:blue, alpha:CGFloat(alpha)) } }
mit
wireapp/wire-ios
Wire-iOS/Sources/UserInterface/Components/Controllers/DefaultNavigationBar.swift
1
3776
// // Wire // Copyright (C) 2016 Wire Swiss GmbH // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // import UIKit import WireCommonComponents class DefaultNavigationBar: UINavigationBar, DynamicTypeCapable { func redrawFont() { titleTextAttributes?[.font] = FontSpec.smallSemiboldFont.font! } override init(frame: CGRect) { super.init(frame: frame) configure() } @available(*, unavailable) required init?(coder aDecoder: NSCoder) { fatalError("init?(coder aDecoder: NSCoder) is not implemented") } var colorSchemeVariant: ColorSchemeVariant { return ColorScheme.default.variant } func configure() { tintColor = SemanticColors.Label.textDefault titleTextAttributes = DefaultNavigationBar.titleTextAttributes(for: colorSchemeVariant) configureBackground() let backIndicatorInsets = UIEdgeInsets(top: 0, left: 4, bottom: 2.5, right: 0) backIndicatorImage = StyleKitIcon.backArrow.makeImage(size: .tiny, color: SemanticColors.Icon.foregroundDefault).with(insets: backIndicatorInsets, backgroundColor: .clear) backIndicatorTransitionMaskImage = StyleKitIcon.backArrow.makeImage(size: .tiny, color: SemanticColors.Icon.foregroundDefault).with(insets: backIndicatorInsets, backgroundColor: .clear) } func configureBackground() { isTranslucent = false barTintColor = SemanticColors.View.backgroundDefault shadowImage = UIImage.singlePixelImage(with: UIColor.clear) } static func titleTextAttributes(for variant: ColorSchemeVariant) -> [NSAttributedString.Key: Any] { return [.font: FontSpec.smallSemiboldFont.font!, .foregroundColor: SemanticColors.Label.textDefault, .baselineOffset: 1.0] } static func titleTextAttributes(for color: UIColor) -> [NSAttributedString.Key: Any] { return [.font: FontSpec.smallSemiboldFont.font!, .foregroundColor: color, .baselineOffset: 1.0] } } extension UIViewController { func wrapInNavigationController(navigationControllerClass: UINavigationController.Type = RotationAwareNavigationController.self, navigationBarClass: AnyClass? = DefaultNavigationBar.self, setBackgroundColor: Bool = false) -> UINavigationController { let navigationController = navigationControllerClass.init(navigationBarClass: navigationBarClass, toolbarClass: nil) navigationController.setViewControllers([self], animated: false) if #available(iOS 15, *), setBackgroundColor { navigationController.view.backgroundColor = SemanticColors.View.backgroundDefault } return navigationController } // MARK: - present func wrapInNavigationControllerAndPresent(from viewController: UIViewController) -> UINavigationController { let navigationController = wrapInNavigationController() navigationController.modalPresentationStyle = .formSheet viewController.present(navigationController, animated: true) return navigationController } }
gpl-3.0
wireapp/wire-ios
Wire-iOS Tests/FilePreviewGeneratorTests.swift
1
2125
// // Wire // Copyright (C) 2017 Wire Swiss GmbH // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // import XCTest import WireCommonComponents @testable import Wire import MobileCoreServices final class FilePreviewGeneratorTests: XCTestCase { func testThatItDoesNotBreakOn0x0PDF() { // given let pdfPath = Bundle(for: type(of: self)).path(forResource: "0x0", ofType: "pdf")! let sut = PDFFilePreviewGenerator(callbackQueue: OperationQueue.main, thumbnailSize: CGSize(width: 100, height: 100)) // when let expectation = self.expectation(description: "Finished generating the preview") sut.generatePreview(URL(fileURLWithPath: pdfPath), UTI: kUTTypePDF as String) { image in XCTAssertNil(image) expectation.fulfill() } // then self.waitForExpectations(timeout: 2, handler: nil) } func testThatItDoesNotBreakOnHugePDF() { // given let pdfPath = Bundle(for: type(of: self)).path(forResource: "huge", ofType: "pdf")! let sut = PDFFilePreviewGenerator(callbackQueue: OperationQueue.main, thumbnailSize: CGSize(width: 100, height: 100)) // when let expectation = self.expectation(description: "Finished generating the preview") sut.generatePreview(URL(fileURLWithPath: pdfPath), UTI: kUTTypePDF as String) { image in XCTAssertNil(image) expectation.fulfill() } // then self.waitForExpectations(timeout: 2, handler: nil) } }
gpl-3.0
danbennett/DBRepo
DBRepo/Repo/CoreData/NSManagedObjectContext+RepoLifetimeType.swift
1
1035
// // NSManagedObjectContext+RepoLifetimeType.swift // DBRepo // // Created by Daniel Bennett on 09/07/2016. // Copyright © 2016 Dan Bennett. All rights reserved. // import Foundation import CoreData extension NSManagedObjectContext : RepoLifetimeType { public func addEntity<T : EntityType>(type : T.Type) throws -> T { guard let managedObject = NSEntityDescription.insertNewObjectForEntityForName(type.className, inManagedObjectContext: self) as? T else { throw NSError(domain: "co.uk.danbennett", code: 8001, userInfo: [NSLocalizedDescriptionKey : "No entity matches name \(type.className)"]) } return managedObject } public func removeEntity<T : EntityType>(entity : T) throws { guard let managedObject = entity as? NSManagedObject else { throw NSError(domain: "co.uk.danbennett", code: 8001, userInfo: [NSLocalizedDescriptionKey : "None NSManagedObject used in context \(entity)"]) } self.deleteObject(managedObject) } }
mit
steelwheels/KiwiControls
UnitTest/iOS/UTTerminal/ViewController.swift
1
263
// // ViewController.swift // UTTerminal // // Created by Tomoo Hamada on 2020/09/21. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } }
lgpl-2.1
EasySwift/EasySwift
Carthage/Checkouts/YXJXibView/testYXJXibView/testYXJXibView/TestXibView1.swift
2
446
// // TestXibView1.swift // testYXJXibView // // Created by yuanxiaojun on 16/7/5. // Copyright © 2016年 袁晓钧. All rights reserved. // import UIKit import YXJXibView class TestXibView1: YXJXibView { /* // Only override drawRect: if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func drawRect(rect: CGRect) { // Drawing code } */ }
apache-2.0
jatoben/RocksDB
Tests/RocksDBTests/AllTests.swift
1
3772
/* * AllTests.swift * Copyright (c) 2016 Ben Gollmer. * * 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 XCTest @testable import RocksDB let DBPath = "/tmp/rocksdb-test" let PI = ProcessInfo.processInfo let FM = FileManager.default class RocksDBTests: XCTestCase { var backupPath = DBPath + "/backups" var dbPath = DBPath + "/db" var db: Database! /* When running tests from Xcode, the working directory is changed and the SRCROOT env var * isn't available by default, but we need it to find the ramdisk scripts. To fix that, edit * the test scheme and in the Arguments pane, set an env var of SRCROOT to the value $SRCROOT, * and choose to expand variables based on the RocksDB product. * * Swift Package Manager doesn't change the working dir, so we can just use the * currentDirectoryPath when testing in that environment. */ class func sourcePath() -> String { return PI.environment["SRCROOT"] ?? FM.currentDirectoryPath } /* Mount a RAM disk to store database files during a test run */ override class func setUp() { #if os(OSX) let task = Process.launchedProcess(launchPath: sourcePath() + "/script/create-ramdisk-macos", arguments: [DBPath]) task.waitUntilExit() assert(task.terminationStatus == 0) #endif } /* Nuke the RAM disk */ override class func tearDown() { #if os(OSX) let task = Process.launchedProcess(launchPath: sourcePath() + "/script/remove-ramdisk-macos", arguments: [DBPath]) task.waitUntilExit() assert(task.terminationStatus == 0) #endif } override func setUp() { try! FM.createDirectory(atPath: backupPath, withIntermediateDirectories: true, attributes: nil) try! FM.createDirectory(atPath: dbPath, withIntermediateDirectories: true, attributes: nil) db = try! Database(path: dbPath) } override func tearDown() { db = nil try! FM.removeItem(atPath: backupPath) try! FM.removeItem(atPath: dbPath) } static var allTests: [(String, (RocksDBTests) -> () throws -> Void)] { return [ /* RocksDBTests */ ("testOpenFail", testOpenFail), ("testOpenForWriteFail", testOpenForWriteFail), ("testOpenForReadOnly", testOpenForReadOnly), ("testWriteFail", testWriteFail), ("testGetAndPut", testGetAndPut), ("testNilGet", testNilGet), ("testPutOverwrite", testPutOverwrite), ("testDelete", testDelete), /* DBBackupEngineTests */ ("testCreateBackup", testCreateBackup), ("testPurgeOldBackups", testPurgeOldBackups), ("testRestoreBackup", testRestoreBackup), ("testRestoreNonExistentBackup", testRestoreNonExistentBackup), /* DBBatchTests */ ("testBatchWrite", testBatchWrite), ("testBatchMultiWrite", testBatchWrite), /* DBIteratorTests */ ("testIterate", testIterate), ("testIteratePrefix", testIteratePrefix), /* DBPropertyTests */ ("testGetProperty", testGetProperty), ("testGetCustomProperty", testGetCustomProperty), ("testGetInvalidProperty", testGetInvalidProperty), /* DBOptionsTests */ ("testStatistics", testStatistics), /* DBReadSnapshotTests */ ("testReadSnapshot", testReadSnapshot) ] } }
apache-2.0
davidf2281/ColorTempToRGB
Sample Project/AppDelegate.swift
1
398
// // Created by David Fearon on 13/12/2015. // Copyright © 2015 David Fearon. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions:[UIApplication.LaunchOptionsKey: Any]?) -> Bool { return true } }
mit
eTilbudsavis/native-ios-eta-sdk
Sources/EventsTracker/UniqueViewTokenizer.swift
1
2944
// // ┌────┬─┐ ┌─────┐ // │ ──┤ └─┬───┬───┤ ┌──┼─┬─┬───┐ // ├── │ ╷ │ · │ · │ ╵ │ ╵ │ ╷ │ // └────┴─┴─┴───┤ ┌─┴─────┴───┴─┴─┘ // └─┘ // // Copyright (c) 2018 ShopGun. All rights reserved. import Foundation /// The signature of a Tokenize function, for converting a string to a different string. typealias Tokenizer = (String) -> String /// A struct for generating a unique view token, based on a salt and a content string. /// Given the same salt & content, the same viewToken will be generated. struct UniqueViewTokenizer { let salt: String /** Create a new UniqueViewTokenizer. Will fail if the provided salt is empty. */ init?(salt: String) { guard salt.isEmpty == false else { return nil } self.salt = salt } /** Takes a content string, combines with the Tokenizer's salt, and hashes into a new string. - parameter content: A string that will be tokenized. */ func tokenize(_ content: String) -> String { let str = salt + content let data = str.data(using: .utf8, allowLossyConversion: true) ?? Data() return Data(Array(data.md5()).prefix(8)).base64EncodedString() } } extension UniqueViewTokenizer { /// The key to access the salt from the dataStore. This is named as such for legacy reasons. private static let saltKey = "ShopGunSDK.EventsTracker.ClientId" /** Loads the ViewTokenizer whose `salt` is cached in the dataStore. If no salt exist, then creates a new one and saves it to the store. If no store is provided then a new salt will be generated, but not stored. - parameter dataStore: An instance of a ShopGunSDKDataStore, from which the salt is read, and into which new salts are written. */ static func load(from dataStore: ShopGunSDKDataStore?) -> UniqueViewTokenizer { let salt: String if let storedSalt = dataStore?.get(for: self.saltKey), storedSalt.isEmpty == false { salt = storedSalt } else { // Make a new salt salt = UUID().uuidString dataStore?.set(value: salt, for: self.saltKey) } // we are sure salt is non-empty at this point, so no exceptions. return UniqueViewTokenizer(salt: salt)! } /** First resets the cached salt in the dataStore, then uses `load(from:)` to create a new one. - parameter dataStore: An instance of a ShopGunSDKDataStore, from which the salt is read, and into which new salts are written. */ static func reload(from dataStore: ShopGunSDKDataStore?) -> UniqueViewTokenizer { dataStore?.set(value: nil, for: self.saltKey) return load(from: dataStore) } }
mit
phatblat/realm-cocoa
examples/installation/ios/swift/CarthageExample/CarthageExample/AppDelegate.swift
1
1347
//////////////////////////////////////////////////////////////////////////// // // Copyright 2014 Realm Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////// import UIKit import RealmSwift public class MyModel: Object { @objc dynamic var requiredProperty: String? } @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? #if swift(>=4.2) func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil) -> Bool { return true } #else func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]? = nil) -> Bool { return true } #endif }
apache-2.0
tomokitakahashi/ParallaxPagingViewController
ParallaxPagingViewControllerExample/ParallaxPagingViewControllerExample/AppDelegate.swift
1
2228
// // AppDelegate.swift // ParallaxPagingViewControllerExample // // Created by takahashi tomoki on 2017/07/06. // Copyright © 2017年 TomokiTakahashi. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { window?.rootViewController = ParallaxPagingParentViewController() return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
mit
jhabbbbb/ClassE
ClassETests/ClassETests.swift
1
967
// // ClassETests.swift // ClassETests // // Created by JinHongxu on 2016/12/14. // Copyright © 2016年 JinHongxu. All rights reserved. // import XCTest @testable import ClassE class ClassETests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } }
mit
woodcockjosh/FastContact
FastContact/Constant.swift
1
766
// // Constant.swift // FastContact // // Created by Josh Woodcock on 8/23/15. // Copyright (c) 2015 Connecting Open Time, LLC. All rights reserved. // import UIKit public struct FastContactConstant { public static let IOS_MAIN_VERSION: Double = { var systemVersion = UIDevice.currentDevice().systemVersion; var numbers = split(systemVersion) {$0 == "."} var numStrings = Array<String>(); var i = 0; for num in numbers { i++; if(i <= 2) { numStrings.append(num); }else{ break; } } var numString = ".".join(numStrings); var numNum = (numString as NSString).doubleValue; return numNum; }(); }
mit
tsolomko/SWCompression
Sources/swcomp/Archives/LZ4Command.swift
1
3901
// Copyright (c) 2022 Timofey Solomko // Licensed under MIT License // // See LICENSE for license information import Foundation import SWCompression import SwiftCLI final class LZ4Command: Command { let name = "lz4" let shortDescription = "Creates or extracts a LZ4 archive" @Flag("-c", "--compress", description: "Compress an input file into a LZ4 archive") var compress: Bool @Flag("-d", "--decompress", description: "Decompress a LZ4 archive") var decompress: Bool @Flag("--dependent-blocks", description: "(Compression only) Use dependent blocks") var dependentBlocks: Bool @Flag("--block-checksums", description: "(Compression only) Save checksums for compressed blocks") var blockChecksums: Bool @Flag("--no-content-checksum", description: "(Compression only) Don't save the checksum of the uncompressed data") var noContentChecksum: Bool @Flag("--content-size", description: "(Compression only) Save the size of the uncompressed data") var contentSize: Bool @Key("--block-size", description: "(Compression only) Use specified block size (in bytes; default and max: 4194304)") var blockSize: Int? @Key("-D", "--dict", description: "Path to a dictionary to use in decompression or compression") var dictionary: String? @Key("--dictID", description: "Optional dictionary ID (max: 4294967295)") var dictionaryID: Int? var optionGroups: [OptionGroup] { return [.exactlyOne($compress, $decompress)] } @Param var input: String @Param var output: String? func execute() throws { let dictID: UInt32? if let dictionaryID = dictionaryID { guard dictionaryID <= UInt32.max else { swcompExit(.lz4BigDictId) } dictID = UInt32(truncatingIfNeeded: dictionaryID) } else { dictID = nil } let dictData: Data? if let dictionary = dictionary { dictData = try Data(contentsOf: URL(fileURLWithPath: dictionary), options: .mappedIfSafe) } else { dictData = nil } guard dictID == nil || dictData != nil else { swcompExit(.lz4NoDict) } if decompress { let inputURL = URL(fileURLWithPath: self.input) let outputURL: URL if let outputPath = output { outputURL = URL(fileURLWithPath: outputPath) } else if inputURL.pathExtension == "lz4" { outputURL = inputURL.deletingPathExtension() } else { swcompExit(.noOutputPath) } let fileData = try Data(contentsOf: inputURL, options: .mappedIfSafe) let decompressedData = try LZ4.decompress(data: fileData, dictionary: dictData, dictionaryID: dictID) try decompressedData.write(to: outputURL) } else if compress { let inputURL = URL(fileURLWithPath: self.input) let outputURL: URL if let outputPath = output { outputURL = URL(fileURLWithPath: outputPath) } else { outputURL = inputURL.appendingPathExtension("lz4") } let bs: Int if let blockSize = blockSize { guard blockSize < 4194304 else { swcompExit(.lz4BigBlockSize) } bs = blockSize } else { bs = 4 * 1024 * 1024 } let fileData = try Data(contentsOf: inputURL, options: .mappedIfSafe) let compressedData = LZ4.compress(data: fileData, independentBlocks: !dependentBlocks, blockChecksums: blockChecksums, contentChecksum: !noContentChecksum, contentSize: contentSize, blockSize: bs, dictionary: dictData, dictionaryID: dictID) try compressedData.write(to: outputURL) } } }
mit
muukii/NextGrowingTextView
Package.swift
1
442
// swift-tools-version:5.5 // The swift-tools-version declares the minimum version of Swift required to build this package. import PackageDescription let package = Package( name: "NextGrowingTextView", platforms: [ .iOS(.v10) ], products: [ .library(name: "NextGrowingTextView", targets: ["NextGrowingTextView"]) ], targets: [ .target( name: "NextGrowingTextView", path: "NextGrowingTextView" ) ] )
mit
vivekvpandya/GetSwifter
FunChallengeDetailsVC.swift
2
5106
// // FunChallengeDetailsVC.swift // GetSwifter // // Created by Vivek Pandya on 9/20/14. // Copyright (c) 2014 Vivek Pandya. All rights reserved. // import UIKit import Alamofire class FunChallengeDetailsVC: UIViewController, UIAlertViewDelegate { @IBOutlet weak var activityIndicator: UIActivityIndicatorView! @IBOutlet weak var challengeLabel: UILabel! @IBOutlet weak var regEndDateLabel: UILabel! @IBOutlet weak var subEndDateLabel: UILabel! @IBOutlet weak var technologyLabel: UILabel! @IBOutlet weak var detailsWebView: UIWebView! @IBOutlet weak var platformLabel: UILabel! @IBOutlet weak var registerButton: UIButton! var serviceEndPoint : String = "http://api.topcoder.com/v2/develop/challenges/" // here challenge id will be appended at the end var challengeID : NSString = "" // This value will be set by prepareForSegue method of RealWorldChallengesTVC var directURL : NSString = "" // this will be used to open topcoder challenge page in Safari override func viewDidLoad() { super.viewDidLoad() self.registerButton.enabled = false getChallengeDetails() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func getChallengeDetails(){ activityIndicator.startAnimating() UIApplication.sharedApplication().networkActivityIndicatorVisible = true var apiURLString = "\(serviceEndPoint)\(challengeID)" println(apiURLString) Alamofire.request(.GET,apiURLString, encoding : .JSON).responseJSON { (request,response,JSON,error) in UIApplication.sharedApplication().networkActivityIndicatorVisible = false if (error == nil){ if response?.statusCode == 200{ self.activityIndicator.stopAnimating() var challengeDetails : NSDictionary = JSON as NSDictionary self.directURL = challengeDetails.objectForKey("directUrl") as NSString println(challengeDetails) self.challengeLabel.text = challengeDetails.objectForKey("challengeName") as NSString self.technologyLabel.text = (challengeDetails.objectForKey("technology") as NSArray).componentsJoinedByString(",") self.platformLabel.text = (challengeDetails.objectForKey("platforms") as NSArray).componentsJoinedByString(",") self.detailsWebView.loadHTMLString(challengeDetails.objectForKey("detailedRequirements") as NSString, baseURL:nil) var dateFormater : NSDateFormatter = NSDateFormatter() dateFormater.dateFormat = "M dd yyyy , hh:mm " dateFormater.timeZone = NSTimeZone(name:"UTC") // var regEnd:NSDate = dateFormater.dateFromString( challengeDetails.objectForKey("registrationEndDate") as NSString!)! // self.regEndDateLabel.text = dateFormater.stringFromDate(regEnd) self.registerButton.enabled = true } else{ self.activityIndicator.stopAnimating() var alert = UIAlertView(title:"Error" , message:"Sorry! error in details loading. " , delegate:self, cancelButtonTitle:"Dismiss") alert.show() } } else{ self.activityIndicator.stopAnimating() var alert = UIAlertView(title:"Error" , message:"Sorry! error in details loading. " , delegate:self, cancelButtonTitle:"Dismiss") alert.show() } } } /* // 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. } */ @IBAction func registerForChallenge(sender: AnyObject) { if self.directURL != ""{ println("in") var url = NSURL(string: self.directURL) UIApplication.sharedApplication().openURL(url) } } func alertView(alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int) { self.navigationController?.popViewControllerAnimated(true) } }
mit
natecook1000/swift-compiler-crashes
crashes-duplicates/15012-swift-sourcemanager-getmessage.swift
11
266
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing if true { { { end as S ( { [ { { protocol b { extension Array { var b { { { { { { } class case ,
mit
airspeedswift/swift-compiler-crashes
crashes-fuzzing/00907-c-t.swift
1
235
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing var b { { } println , { { } } protocol A { func f typealias e : e
mit
airspeedswift/swift-compiler-crashes
crashes-duplicates/00214-swift-typebase-gettypeofmember.swift
12
2557
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing func f<m>() -> (m, m -> m) -> m { e c e.i = { } { m) { n } } protocol f { class func i() } class e: f{ class func i {} func n<j>() -> (j, j -> j) -> j { var m: ((j> j)! f m } protocol k { typealias m } struct e<j : k> {n: j let i: j.m } l func f() { ({}) } protocol f : f { } func h<d { enum h { func e var _ = e } } protocol e { e func e() } struct h { var d: e.h func e() { d.e() ol A { typealias B } class C<D> { init <A: A where A.B == D>(e: A.B) { } } } class d { func l<j where j: h, j: d>(l: j) { l.k() } func i(k: b) -> <j>(() -> j) -> b { f { m m "\(k): \(m())" } } protocol h func r<t>() { f f { i i } } struct i<o : u> { o f: o } func r<o>() -> [i<o>] { p [] } class g<t : g> { } class g: g { } class n : h { } typealias h = n protocol g { func i() -> l func o() -> m { q"" } } func j<t k t: g, t: n>(s: t) { s.i() } protocol r { } protocol f : r { } protocol i : r { } j var x1 =I Bool !(a) } func prefix(with: Strin) -> <T>(() -> T) in // Distributed under the terms of the MIT license d) func e(h: b) -> <f>(() -> f) -> b { return { c):h())" } } protocol a { typealias d typealias e = d typealias f = d } class b<h : c, i : c where h.g == i> : a { } clas-> i) -> i) { b { (h -> i) d $k } let e: Int = 1, 1) class g<j :g protocol p { class func g() } class h: p { class func g() { } } (h() as p).dynamicType.g() protocol p { } protocol h : p { } protocol g : p { } protocol n { o t = p } struct h : n { t : n q m.t == m> (h: m) { } func q<t : n q t.t == g> (h: t) { ) e protocol g : e { func e import Foundation class m<j>k i<g : g, e : f k(f: l) { } i(()) class h { typealias g = g n) func f<o>() -> (o, o -> o) -> o { o m o.j = { } { o) { r } } p q) { } o m = j m() class m { func r((Any, m))(j: (Any, AnyObject)) { r(j) } } func m< f { class func n() } class l: f{ class func n {} func a<i>() { b b { l j } } class a<f : b, l : b m f.l == l> { } protocol b { typ typealias k } struct j<n : b> : b { typealias l = n typealias k = a<j<n>, l> } a } struct e : f { i f = g } func i<g : g, e : g> : g { typealias f = h typealias e = a<c<h>, f> func b<d { enum b { func c var _ = c } }
mit
liufengting/FTChatMessageDemoProject
FTChatMessage/FTChatMessageHeader/FTChatMessageHeader.swift
1
3018
// // FTChatMessageHeader.swift // FTChatMessage // // Created by liufengting on 16/2/28. // Copyright © 2016年 liufengting <https://github.com/liufengting>. All rights reserved. // import UIKit protocol FTChatMessageHeaderDelegate { func ft_chatMessageHeaderDidTappedOnIcon(_ messageSenderModel : FTChatMessageUserModel) } class FTChatMessageHeader: UILabel { var iconButton : UIButton! var messageSenderModel : FTChatMessageUserModel! var headerViewDelegate : FTChatMessageHeaderDelegate? lazy var messageSenderNameLabel: UILabel! = { let label = UILabel(frame: CGRect.zero) label.font = FTDefaultTimeLabelFont label.textAlignment = .center label.textColor = UIColor.lightGray return label }() convenience init(frame: CGRect, senderModel: FTChatMessageUserModel ) { self.init(frame : frame) messageSenderModel = senderModel; self.setupHeader( senderModel, isSender: senderModel.isUserSelf) } fileprivate func setupHeader(_ user : FTChatMessageUserModel, isSender: Bool){ self.backgroundColor = UIColor.clear let iconRect = isSender ? CGRect(x: self.frame.width-FTDefaultMargin-FTDefaultIconSize, y: FTDefaultMargin, width: FTDefaultIconSize, height: FTDefaultIconSize) : CGRect(x: FTDefaultMargin, y: FTDefaultMargin, width: FTDefaultIconSize, height: FTDefaultIconSize) iconButton = UIButton(frame: iconRect) iconButton.backgroundColor = isSender ? FTDefaultOutgoingColor : FTDefaultIncomingColor iconButton.layer.cornerRadius = FTDefaultIconSize/2; iconButton.clipsToBounds = true iconButton.isUserInteractionEnabled = true iconButton.addTarget(self, action: #selector(self.iconTapped), for: UIControlEvents.touchUpInside) self.addSubview(iconButton) if (user.senderIconUrl != nil) { // iconButton.kf.setBackgroundImage(with: URL(string : user.senderIconUrl!), for: .normal, placeholder: nil, options: nil, progressBlock: nil, completionHandler: nil) } // var nameLabelRect = CGRect( x: 0, y: 0 , width: FTScreenWidth - (FTDefaultMargin*2 + FTDefaultIconSize), height: FTDefaultSectionHeight) // var nameLabelTextAlignment : NSTextAlignment = .right // // if isSender == false { // nameLabelRect.origin.x = FTDefaultMargin + FTDefaultIconSize + FTDefaultMargin // nameLabelTextAlignment = .left // } // // messageSenderNameLabel.frame = nameLabelRect // messageSenderNameLabel.text = user.senderName // messageSenderNameLabel.textAlignment = nameLabelTextAlignment // self.addSubview(messageSenderNameLabel) } @objc func iconTapped() { if (headerViewDelegate != nil) { headerViewDelegate?.ft_chatMessageHeaderDidTappedOnIcon(messageSenderModel) } } }
mit
xcadaverx/ABPlayer
Example/Example/ViewController.swift
1
1583
// // ViewController.swift // Example // // Copyright © 2016 Dandom. All rights reserved. // import UIKit import ABPlayer import AVFoundation class ViewController: UIViewController { @IBOutlet weak var abPlayerView: ABPlayerView! @IBAction func tap(sender: UIButton) { // let config = ABPlayerConfiguration(sliderViewWidth: 20, labelPadding: 10, sliderViewBackgroundColor: .green, beforeText: "beforez", beforeColor: .purple, afterText: "aftaazz", afterColor: .green) // // abPlayerView.set(configuration: config) abPlayerView.play() } override func viewDidLoad() { super.viewDidLoad() guard let sampleAPath = Bundle.main.path(forResource: "sampleA", ofType: "mp4") else { return } guard let sampleBPath = Bundle.main.path(forResource: "sampleB", ofType: "mov") else { return } let sampleAURL = URL(fileURLWithPath: sampleAPath) let sampleBURL = URL(fileURLWithPath: sampleBPath) let playerItemA = AVPlayerItem(url: sampleAURL) let playerItemB = AVPlayerItem(url: sampleBURL) abPlayerView.load(playerItemA, playerItemB, usingVolumeFrom: .playerA) let config = ABPlayerConfiguration(sliderViewWidth: 10, labelPadding: 20, sliderViewBackgroundColor: .blue, beforeText: "befo", beforeColor: .red, afterText: "afta", afterColor: .purple) abPlayerView.set(configuration: config) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) abPlayerView.play() } }
mit
iscriptology/swamp
Example/Pods/CryptoSwift/Sources/CryptoSwift/CSArrayType+Extensions.swift
2
2133
// // _ArrayType+Extensions.swift // CryptoSwift // // Created by Marcin Krzyzanowski on 08/10/15. // Copyright © 2015 Marcin Krzyzanowski. All rights reserved. // public protocol CSArrayType: Collection, RangeReplaceableCollection { func cs_arrayValue() -> [Iterator.Element] } extension Array: CSArrayType { public func cs_arrayValue() -> [Iterator.Element] { return self } } public extension CSArrayType where Iterator.Element == UInt8 { public func toHexString() -> String { return self.lazy.reduce("") { var s = String($1, radix: 16) if s.characters.count == 1 { s = "0" + s } return $0 + s } } } public extension CSArrayType where Iterator.Element == UInt8 { public func md5() -> [Iterator.Element] { return Digest.md5(cs_arrayValue()) } public func sha1() -> [Iterator.Element] { return Digest.sha1(cs_arrayValue()) } public func sha224() -> [Iterator.Element] { return Digest.sha224(cs_arrayValue()) } public func sha256() -> [Iterator.Element] { return Digest.sha256(cs_arrayValue()) } public func sha384() -> [Iterator.Element] { return Digest.sha384(cs_arrayValue()) } public func sha512() -> [Iterator.Element] { return Digest.sha512(cs_arrayValue()) } public func crc32(seed: UInt32? = nil, reflect : Bool = true) -> UInt32 { return Checksum.crc32(cs_arrayValue(), seed: seed, reflect: reflect) } public func crc16(seed: UInt16? = nil) -> UInt16 { return Checksum.crc16(cs_arrayValue(), seed: seed) } public func encrypt(cipher: Cipher) throws -> [Iterator.Element] { return try cipher.encrypt(cs_arrayValue()) } public func decrypt(cipher: Cipher) throws -> [Iterator.Element] { return try cipher.decrypt(cs_arrayValue()) } public func authenticate<A: Authenticator>(with authenticator: A) throws -> [Iterator.Element] { return try authenticator.authenticate(cs_arrayValue()) } }
mit
tinmnguyen/swiftLIFX
SwiftLifx/DetailViewController.swift
1
3776
// // DetailViewController.swift // SwiftLifx // // Created by Tin Nguyen on 10/4/14. // Copyright (c) 2014 Tin Nguyen. All rights reserved. // import UIKit public class DetailViewController: UIViewController, LFXLightObserver { public var light: LFXLight! @IBOutlet var brightnessSlider: UISlider! @IBOutlet var powerButton: UIButton! @IBOutlet var colorPicker: HRColorMapView! override public func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.whiteColor() // Do any additional setup after loading the view. } override public func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) self.updateBrightnessSlider() if light.powerState() == LFXPowerState.Off { self.powerButton.setTitle("Power on", forState: .Normal) } else { self.powerButton.setTitle("Power off", forState: .Normal) } self.title = light.label() colorPicker.addTarget(self, action: "colorChanged:" , forControlEvents: UIControlEvents.ValueChanged) colorPicker.brightness = 1.0 } override public func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) light.addLightObserver(self) } override public func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func sliderValueDidChange(slider: UISlider) { self.light.setColor(self.light.color().colorWithBrightness(CGFloat(slider.value))) if light.powerState() == .Off { self.light.setPowerState(.On) self.powerButton.setTitle("Power off", forState: .Normal) } } @IBAction func powerButtonDidPress(button: UIButton) { if self.light.powerState() == .Off { self.light.setPowerState(.On) self.updateBrightnessSlider() self.powerButton.setTitle("Power off", forState: .Normal) } else { self.light.setPowerState(.Off) self.powerButton.setTitle("Power on", forState: .Normal) self.brightnessSlider.setValue(0.0, animated: true) } var color = UIColor.blueColor() var hsv = color.getHSV() } func updateBrightnessSlider() { let color = light.color() self.brightnessSlider.setValue(Float(color.brightness), animated: true) self.colorPicker.color = UIColor(hue: color.hue / LFXHSBKColorMaxHue, saturation: color.saturation, brightness: color.brightness, alpha: 1.0) } public func light(light: LFXLight!, didChangeReachability reachability: LFXDeviceReachability) { switch reachability { case LFXDeviceReachability.Unreachable: println("disconnected") case LFXDeviceReachability.Reachable: println("yo") default: println("no") } } func colorChanged(mapView: HRColorMapView) { var hsv = mapView.color.getHSV() var hsbk: LFXHSBKColor = light.color() hsbk.hue = hsv.hue hsbk.brightness = hsv.value hsbk.saturation = hsv.saturation self.light.setColor(hsbk) } /* // 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
zhixingxi/JJA_Swift
JJA_Swift/JJA_Swift/AppDelegate/AppDelegate.swift
1
3863
// // AppDelegate.swift // JJA_Swift // // Created by MQL-IT on 2017/5/16. // Copyright © 2017年 MQL-IT. All rights reserved. // // _ooOoo_ // o8888888o // 88" . "88 // (| -_- |) // O\ = /O // ____/`---'\____ // . ' \\| |// `. // / \\||| : |||// \ // / _||||| -:- |||||- \ // | | \\\ - /// | | // | \_| ''\---/'' | | // \ .-\__ `-` ___/-. / // ___`. .' /--.--\ `. . __ // ."" '< `.___\_<|>_/___.' >'"". // | | : `- \`.;`\ _ /`;.`/ - ` : | | // \ \ `-. \_ __\ /__ _/ .-` / / // ======`-.____`-.___\_____/___.-`____.-'====== // `=---=' // // ............................................. // 佛祖镇楼 BUG辟易 // 佛曰: // 写字楼里写字间,写字间里程序员; // 程序人员写程序,又拿程序换酒钱。 // 酒醒只在网上坐,酒醉还来网下眠; // 酒醉酒醒日复日,网上网下年复年。 // 但愿老死电脑间,不愿鞠躬老板前; // 奔驰宝马贵者趣,公交自行程序员。 // 别人笑我忒疯癫,我笑自己命太贱; // 不见满街漂亮妹,哪个归得程序员? import UIKit import HandyJSON @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { window = UIWindow(frame: UIScreen.main.bounds) window?.backgroundColor = UIColor.white window?.rootViewController = MainTabBarController() loadAppConfigerInformation() setupAdditions() window?.makeKeyAndVisible() return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
mit
jkolb/midnightbacon
MidnightBacon/Modules/Submit/TextFieldCell.swift
1
4072
// // TextFieldTableViewCell.swift // MidnightBacon // // Copyright (c) 2015 Justin Kolb - http://franticapparatus.net // // 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 DrapierLayout class TextFieldCell : UITableViewCell { let textField = UITextField() let separatorView = UIView() let insets = UIEdgeInsets(top: 16.0, left: 8.0, bottom: 16.0, right: 0.0) var separatorHeight: CGFloat = 0.0 override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) contentView.addSubview(textField) contentView.addSubview(separatorView) textField.keyboardType = .Default textField.autocapitalizationType = .None textField.autocorrectionType = .No textField.spellCheckingType = .No textField.enablesReturnKeyAutomatically = false textField.clearButtonMode = .WhileEditing } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) contentView.addSubview(textField) contentView.addSubview(separatorView) textField.keyboardType = .Default textField.autocapitalizationType = .None textField.autocorrectionType = .No textField.spellCheckingType = .No textField.enablesReturnKeyAutomatically = false textField.clearButtonMode = .WhileEditing } deinit { textField.delegate = nil textField.removeTarget(nil, action: nil, forControlEvents: .AllEvents) } override func prepareForReuse() { super.prepareForReuse() textField.delegate = nil textField.removeTarget(nil, action: nil, forControlEvents: .AllEvents) } override func layoutSubviews() { super.layoutSubviews() let layout = generateLayout(contentView.bounds) textField.frame = layout.textFieldFrame separatorView.frame = layout.separatorFrame } override func sizeThatFits(size: CGSize) -> CGSize { let layout = generateLayout(size.rect()) let fitSize = CGSizeMake(size.width, layout.separatorFrame.bottom) return fitSize } private struct ViewLayout { let textFieldFrame: CGRect let separatorFrame: CGRect } private func generateLayout(bounds: CGRect) -> ViewLayout { let textFieldFrame = textField.layout( Leading(equalTo: bounds.leading(insets)), Trailing(equalTo: bounds.trailing(insets)), Top(equalTo: bounds.top(insets)) ) let separatorFrame = separatorView.layout( Leading(equalTo: bounds.leading(insets)), Trailing(equalTo: bounds.trailing), Bottom(equalTo: textFieldFrame.bottom + insets.bottom), Height(equalTo: separatorHeight) ) return ViewLayout( textFieldFrame: textFieldFrame, separatorFrame: separatorFrame ) } }
mit
thisjeremiah/all-ashore
AllAshore/AppDelegate.swift
1
6224
// // AppDelegate.swift // AllAshore // // Created by Jeremiah Montoya on 4/24/15. // Copyright (c) 2015 Jeremiah Montoya. All rights reserved. // import UIKit import CoreData // declare globals var taxonomy : [String: [String:[String]]] = Taxonomy().model @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and 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:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var applicationDocumentsDirectory: NSURL = { // The directory the application uses to store the Core Data store file. This code uses a directory named "me.jeremiahmontoya.AllAshore" in the application's documents Application Support directory. let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count-1] as! NSURL }() lazy var managedObjectModel: NSManagedObjectModel = { // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. let modelURL = NSBundle.mainBundle().URLForResource("AllAshore", withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = { // The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. // Create the coordinator and store var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("AllAshore.sqlite") var error: NSError? = nil var failureReason = "There was an error creating or loading the application's saved data." if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil, error: &error) == nil { coordinator = nil // Report any error we got. var dict = [String: AnyObject]() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" dict[NSLocalizedFailureReasonErrorKey] = failureReason dict[NSUnderlyingErrorKey] = error error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) // Replace this with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(error), \(error!.userInfo)") abort() } return coordinator }() lazy var managedObjectContext: NSManagedObjectContext? = { // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. let coordinator = self.persistentStoreCoordinator if coordinator == nil { return nil } var managedObjectContext = NSManagedObjectContext() managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support func saveContext () { if let moc = self.managedObjectContext { var error: NSError? = nil if moc.hasChanges && !moc.save(&error) { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(error), \(error!.userInfo)") abort() } } } }
mit
pmlbrito/WeatherExercise
WeatherExercise/Presentation/Map/AddLocationMapPresenter.swift
1
1137
// // AddLocationMapPresenter.swift // WeatherExercise // // Created by Pedro Brito on 11/05/2017. // Copyright © 2017 BringGlobal. All rights reserved. // import Foundation import MapKit import UIKit protocol AddLocationPresenterProtocol: BasePresenterProtocol { func saveLocation(location: LocationModel) } class AddLocationMapPresenter: AddLocationPresenterProtocol { var view: AddLocationMapViewController? func saveLocation(location: LocationModel) { //save and go back if self.view == nil { return } (self.view! as UIViewController).showLoadingOverlay() DispatchQueue.global(qos: .userInitiated).async { SharedPreferencesStorageManager.shared.addLocation(location: location) DispatchQueue.main.async { (self.view! as UIViewController).hideLoadingOverlay() self.view?.locationSaved() } } } } extension AddLocationMapPresenter { func bindView(view: UIViewController) { self.view = view as? AddLocationMapViewController } }
mit
Gunmer/EmojiLog
EmojiLog/Classes/EmojiMap.swift
1
674
public protocol EmojiMap { init() func map(level: LogLevel) -> String } class EmojiMapDefault: EmojiMap { required init() {} func map(level: LogLevel) -> String { switch level { case .debug: return "💬" case .info: return "🖥" case .waring: return "⚠️" case .error: return "‼️" } } } public final class SmileEmojiMap: EmojiMap { public init() {} public func map(level: LogLevel) -> String { switch level { case .debug: return "🤓" case .info: return "😎" case .waring: return "😨" case .error: return "😱" } } }
mit
artemkalinovsky/JSQCoreDataKit
JSQCoreDataKit/JSQCoreDataKit/CoreDataExtensions.swift
1
6098
// // Created by Jesse Squires // http://www.jessesquires.com // // // Documentation // http://www.jessesquires.com/JSQCoreDataKit // // // GitHub // https://github.com/jessesquires/JSQCoreDataKit // // // License // Copyright (c) 2015 Jesse Squires // Released under an MIT license: http://opensource.org/licenses/MIT // import Foundation import CoreData /// A tuple value that describes the results of saving a managed object context. /// /// :param: success A boolean value indicating whether the save succeeded. It is `true` if successful, otherwise `false`. /// :param: error An error object if an error occurred, otherwise `nil`. public typealias ContextSaveResult = (success:Bool, error:NSError?) /// Attempts to commit unsaved changes to registered objects to the specified context's parent store. /// This method is performed *synchronously* in a block on the context's queue. /// If the context returns `false` from `hasChanges`, this function returns immediately. /// /// :param: context The managed object context to save. /// /// :returns: A `ContextSaveResult` instance indicating the result from saving the context. public func saveContextAndWait(context: NSManagedObjectContext) -> ContextSaveResult { if !context.hasChanges { return (true, nil) } var success = false var error: NSError? context.performBlockAndWait { () -> Void in success = context.save(&error) if !success { println("*** ERROR: [\(__LINE__)] \(__FUNCTION__) Could not save managed object context: \(error)") } } return (success, error) } /// Attempts to commit unsaved changes to registered objects to the specified context's parent store. /// This method is performed *asynchronously* in a block on the context's queue. /// If the context returns `false` from `hasChanges`, this function returns immediately. /// /// :param: context The managed object context to save. /// :param: completion The closure to be executed when the save operation completes. public func saveContext(context: NSManagedObjectContext, completion: (ContextSaveResult) -> Void) { if !context.hasChanges { completion((true, nil)) return } context.performBlock { () -> Void in var error: NSError? let success = context.save(&error) if !success { println("*** ERROR: [\(__LINE__)] \(__FUNCTION__) Could not save managed object context: \(error)") } completion((success, error)) } } /// Returns the entity with the specified name from the managed object model associated with the specified managed object context’s persistent store coordinator. /// /// :param: name The name of an entity. /// :param: context The managed object context to use. /// /// :returns: The entity with the specified name from the managed object model associated with context’s persistent store coordinator. public func entity(#name: String, #context: NSManagedObjectContext) -> NSEntityDescription { return NSEntityDescription.entityForName(name, inManagedObjectContext: context)! } /// An instance of `FetchRequest <T: NSManagedObject>` describes search criteria used to retrieve data from a persistent store. /// This is a subclass of `NSFetchRequest` that adds a type parameter specifying the type of managed objects for the fetch request. /// The type parameter acts as a phantom type. public class FetchRequest<T:NSManagedObject>: NSFetchRequest { /// Constructs a new `FetchRequest` instance. /// /// :param: entity The entity description for the entities that this request fetches. /// /// :returns: A new `FetchRequest` instance. public init(entity: NSEntityDescription) { super.init() self.entity = entity } } /// A `FetchResult` represents the result of executing a fetch request. /// It has one type parameter that specifies the type of managed objects that were fetched. public struct FetchResult<T:NSManagedObject> { /// Specifies whether or not the fetch succeeded. public let success: Bool /// An array of objects that meet the criteria specified by the fetch request. /// If the fetch is unsuccessful, this array will be empty. public let objects: [T] /// If unsuccessful, specifies an error that describes the problem executing the fetch. Otherwise, this value is `nil`. public let error: NSError? } /// Executes the fetch request in the given context and returns the result. /// /// :param: request A fetch request that specifies the search criteria for the fetch. /// :param: context The managed object context in which to search. /// /// :returns: A instance of `FetchResult` describing the results of executing the request. public func fetch<T:NSManagedObject>(#request: FetchRequest<T>, inContext context: NSManagedObjectContext) -> FetchResult<T> { var error: NSError? var results: [AnyObject]? context.performBlockAndWait { () -> Void in results = context.executeFetchRequest(request, error: &error) } if let results = results { return FetchResult(success: true, objects: map(results, { $0 as! T }), error: error) } else { println("*** ERROR: [\(__LINE__)] \(__FUNCTION__) Error while executing fetch request: \(error)") } return FetchResult(success: false, objects: [], error: error) } /// Deletes the objects from the specified context. /// When changes are committed, the objects will be removed from their persistent store. /// You must save the context after calling this function to remove objects from the store. /// /// :param: objects The managed objects to be deleted. /// :param: context The context to which the objects belong. public func deleteObjects<T:NSManagedObject>(objects: [T], inContext context: NSManagedObjectContext) { if objects.count == 0 { return } context.performBlockAndWait { () -> Void in for each in objects { context.deleteObject(each) } } }
mit
fl0549/UberManagerSwift
Pod/Classes/Models/Payment.swift
1
1058
// // Payment.swift // UberManagerSwift // // Created by Florian Pygmalion on 25/02/2016. // Copyright © 2016 Florian Pygmalion. All rights reserved. // import UIKit import SwiftyJSON public class Payment { public var description = "" public var payment_method_id = "" public var type = "" } extension Payment { private func fillWithDict(hash: JSON) { if hash["description"].object as? String != nil { description = hash["description"].stringValue } if hash["payment_method_id"].object as? String != nil { payment_method_id = hash["payment_method_id"].stringValue } if hash["type"].object as? String != nil { type = hash["type"].stringValue } } class func createPaymentFromJSON(hash: JSON) -> Payment? { if hash.type == .Dictionary { let payment = Payment() payment.fillWithDict(hash) return payment } return nil } }
mit
posix88/AMDragDrop
AMDragDropExample/ViewController.swift
1
1010
// // ViewController.swift // AMDragDrop // // Created by Antonino Francesco Musolino on 11/15/2016. // Copyright (c) 2016 Antonino Francesco Musolino. All rights reserved. // import UIKit class ViewController: UIViewController, AMDragDropDelegate { @IBOutlet weak var otherDropView: AMDragDropView! @IBOutlet weak var dragView: AMDragDropView! @IBOutlet weak var dropView: UIView! override func viewDidLoad() { super.viewDidLoad() dragView.enableDragging(dragDelegate: self, dropViews: [(dropView)]) otherDropView.enableDragging(dragDelegate: self, dropViews: nil) otherDropView.saveInitialPosition(flag: true) otherDropView.modify(DragMode: .RestrictX) otherDropView.modifyAnimation(withDuration: 1) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func view(_ view: UIView, wasDroppedOnDrop drop: UIView!) { print("I was dropped on a Drop View") } func viewShouldReturn(ToInitialPosition view: UIView) -> Bool { return true } }
mit
kzaher/RxFeedback
Examples/Examples/Todo.swift
1
2736
// // Todo.swift // RxFeedback // // Created by Krunoslav Zaher on 5/11/17. // Copyright © 2017 Krunoslav Zaher. All rights reserved. // import struct Foundation.UUID import struct Foundation.Date enum SyncState { case syncing case success case failed(Error) } struct Task { let id: UUID let created: Date var title: String var isCompleted: Bool var isArchived: Bool // we never delete anything ;) var state: SyncState static func create(title: String, date: Date) -> Task { return Task(id: UUID(), created: date, title: title, isCompleted: false, isArchived: false, state: .syncing) } } struct Todo { enum Event { case created(Version<Task>) case toggleCompleted(Version<Task>) case archive(Version<Task>) case synchronizationChanged(Version<Task>, SyncState) case toggleEditingMode } var tasks: Storage<Version<Task>> = Storage() var isEditing: Bool = false } extension Todo { static func reduce(state: Todo, event: Event) -> Todo { switch event { case .created(let task): return state.map(task: task, transform: Version<Task>.mutate { _ in }) case .toggleCompleted(let task): return state.map(task: task, transform: Version<Task>.mutate { $0.isCompleted = !$0.isCompleted }) case .archive(let task): return state.map(task: task, transform: Version<Task>.mutate { $0.isArchived = true }) case .synchronizationChanged(let task, let synchronizationState): return state.map(task: task, transform: Version<Task>.mutate { $0.state = synchronizationState }) case .toggleEditingMode: return state.map { $0.isEditing = !$0.isEditing } } } } extension Todo { static func `for`(tasks: [Task]) -> Todo { return tasks.reduce(Todo()) { (all, task) in Todo.reduce(state: all, event: .created(Version(task))) } } } // queries extension Todo { var tasksByDate: [Version<Task>] { return self.tasks .sorted(key: { $0.value.created }) } var completedTasks: [Version<Task>] { return tasksByDate .filter { $0.value.isCompleted && !$0.value.isArchived } } var unfinishedTasks: [Version<Task>] { return tasksByDate .filter { !$0.value.isCompleted && !$0.value.isArchived } } var tasksToSynchronize: Set<Version<Task>> { return Set(self.tasksByDate.filter { $0.value.needsSynchronization }.prefix(1)) } } extension Task { var needsSynchronization: Bool { if case .syncing = self.state { return true } return false } }
mit
AlexLittlejohn/ALCameraViewController
ALCameraViewController/Utilities/Utilities.swift
1
4214
// // ALUtilities.swift // ALCameraViewController // // Created by Alex Littlejohn on 2015/06/25. // Copyright (c) 2015 zero. All rights reserved. // import UIKit import AVFoundation internal func radians(_ degrees: CGFloat) -> CGFloat { return degrees / 180 * .pi } internal func localizedString(_ key: String) -> String { var bundle: Bundle { if Bundle.main.path(forResource: CameraGlobals.shared.stringsTable, ofType: "strings") != nil { return Bundle.main } return CameraGlobals.shared.bundle } return NSLocalizedString(key, tableName: CameraGlobals.shared.stringsTable, bundle: bundle, comment: key) } internal func currentRotation(_ oldOrientation: UIInterfaceOrientation, newOrientation: UIInterfaceOrientation) -> CGFloat { switch oldOrientation { case .portrait: switch newOrientation { case .landscapeLeft: return 90 case .landscapeRight: return -90 case .portraitUpsideDown: return 180 default: return 0 } case .landscapeLeft: switch newOrientation { case .portrait: return -90 case .landscapeRight: return 180 case .portraitUpsideDown: return 90 default: return 0 } case .landscapeRight: switch newOrientation { case .portrait: return 90 case .landscapeLeft: return 180 case .portraitUpsideDown: return -90 default: return 0 } default: return 0 } } internal func largestPhotoSize() -> CGSize { let scale = UIScreen.main.scale let screenSize = UIScreen.main.bounds.size let size = CGSize(width: screenSize.width * scale, height: screenSize.height * scale) return size } internal func errorWithKey(_ key: String, domain: String) -> NSError { let errorString = localizedString(key) let errorInfo = [NSLocalizedDescriptionKey: errorString] let error = NSError(domain: domain, code: 0, userInfo: errorInfo) return error } internal func normalizedRect(_ rect: CGRect, orientation: UIImage.Orientation) -> CGRect { let normalizedX = rect.origin.x let normalizedY = rect.origin.y let normalizedWidth = rect.width let normalizedHeight = rect.height var normalizedRect: CGRect switch orientation { case .up, .upMirrored: normalizedRect = CGRect(x: normalizedX, y: normalizedY, width: normalizedWidth, height: normalizedHeight) case .down, .downMirrored: normalizedRect = CGRect(x: 1-normalizedX-normalizedWidth, y: 1-normalizedY-normalizedHeight, width: normalizedWidth, height: normalizedHeight) case .left, .leftMirrored: normalizedRect = CGRect(x: 1-normalizedY-normalizedHeight, y: normalizedX, width: normalizedHeight, height: normalizedWidth) case .right, .rightMirrored: normalizedRect = CGRect(x: normalizedY, y: 1-normalizedX-normalizedWidth, width: normalizedHeight, height: normalizedWidth) @unknown default: normalizedRect = .zero } return normalizedRect } internal func flashImage(_ mode: AVCaptureDevice.FlashMode) -> String { let image: String switch mode { case .auto: image = "flashAutoIcon" case .on: image = "flashOnIcon" case .off: image = "flashOffIcon" @unknown default: image = "flashOffIcon" } return image } struct ScreenSize { static let SCREEN_WIDTH = UIScreen.main.bounds.size.width static let SCREEN_HEIGHT = UIScreen.main.bounds.size.height static let SCREEN_MAX_LENGTH = max(ScreenSize.SCREEN_WIDTH, ScreenSize.SCREEN_HEIGHT) } struct DeviceConfig { static let SCREEN_MULTIPLIER : CGFloat = { if UIDevice.current.userInterfaceIdiom == .phone { switch ScreenSize.SCREEN_MAX_LENGTH { case 568.0: return 1.5 case 667.0: return 2.0 case 736.0: return 4.0 default: return 1.0 } } else { return 1.0 } }() }
mit
GerryLaplante/Emoji-Dictionary
Emoji Dictionary/AppDelegate.swift
1
2154
// // AppDelegate.swift // Emoji Dictionary // // Created by Paul Wright on 9/25/15. // Copyright © 2015 Gerry Laplante. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and 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:. } }
unlicense
crexista/KabuKit
KabuKitTests/Mock/MockTransitionRequest.swift
1
148
// // Copyright © 2017年 DWANGO Co., Ltd. // import Foundation import KabuKit class MockTransitionRequest: TransitionRequest<String, String>{}
mit
werner-freytag/DockTime
ClockBundle-Subway/ClockView.swift
1
3240
// The MIT License // // Copyright 2012-2021 Werner Freytag // // 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 AppKit class ClockView: NSView { lazy var bundle = Bundle(for: type(of: self)) let defaults = UserDefaults.shared override func draw(_: NSRect) { let components = Calendar.current.dateComponents([.hour, .minute, .second], from: Date()) var imageName: String var image: NSImage image = bundle.image(named: "Background")! image.draw(at: .init(x: 9, y: 8), from: .zero, operation: .copy, fraction: 1) imageName = String(format: "%ld", components.hour! / 10) image = bundle.image(named: imageName)! image.draw(at: CGPoint(x: 28, y: 50), from: .zero, operation: .sourceOver, fraction: 1) imageName = String(format: "%ld", components.hour! % 10) image = bundle.image(named: imageName)! image.draw(at: CGPoint(x: 45, y: 50), from: .zero, operation: .sourceOver, fraction: 1) imageName = String(format: "%ld", components.minute! / 10) image = bundle.image(named: imageName)! image.draw(at: CGPoint(x: 67, y: 50), from: .zero, operation: .sourceOver, fraction: 1) imageName = String(format: "%ld", components.minute! % 10) image = bundle.image(named: imageName)! image.draw(at: CGPoint(x: 84, y: 50), from: .zero, operation: .sourceOver, fraction: 1) if defaults.showSeconds { image = bundle.image(named: "Dot")! let center = CGPoint(x: 62.5, y: 62.5) for i in 0 ... components.second! { let angle = CGFloat(i) * .pi * 2 / 60 image.draw(at: center.applying(angle: angle, distance: 42), from: .zero, operation: .sourceOver, fraction: 1) if i % 5 == 0 { image.draw(at: center.applying(angle: angle, distance: 46), from: .zero, operation: .sourceOver, fraction: 1) } } } } } extension CGPoint { func applying(angle: CGFloat, distance: CGFloat) -> CGPoint { let x = sin(angle) * distance let y = cos(angle) * distance return applying(.init(translationX: x, y: y)) } }
mit
schluchter/berlin-transport
berlin-transport/berlin-trnsprtTests/BTConReqBuilderTests.swift
1
1077
import Quick import Nimble import berlin_trnsprt class BTConReqBuilderTests: QuickSpec { override func spec() { describe("The date and time printer") { context("when given my birthday") { let comps = NSDateComponents() let calendar = NSCalendar.currentCalendar() comps.year = 1980 comps.month = 1 comps.day = 1 comps.hour = 11 comps.minute = 15 comps.second = 30 let date = calendar.dateFromComponents(comps) println(date) let output = BTRequestBuilder.requestDataFromDate(date!) // it("should print the correct date string") { // expect(output.day).to(equal("19800101")) // } // // it("should print the correct time string") { // expect(output.time).to(equal("11:15:30")) // } } } } }
mit
CUITCHE/printc
Tests/printcTests/printcTests.swift
1
398
import XCTest @testable import printc class printcTests: XCTestCase { func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct // results. XCTAssertEqual(printc().text, "Hello, World!") } static var allTests = [ ("testExample", testExample), ] }
mit
shu223/watchOS-2-Sampler
watchOS2Sampler WatchKit Extension/SwipeInterfaceController.swift
1
510
// // SwipeInterfaceController.swift // watchOS2Sampler // // Created by Shuichi Tsutsumi on 1/7/16. // Copyright © 2016 Shuichi Tsutsumi. All rights reserved. // import WatchKit import Foundation class SwipeInterfaceController: WKInterfaceController { override func awake(withContext context: Any?) { super.awake(withContext: context) } override func willActivate() { super.willActivate() } override func didDeactivate() { super.didDeactivate() } }
mit
siuying/SignalKit
SignalKit/Utilities/IncrementalKeyGenerator.swift
1
1193
// // IncrementalKeyGenerator.swift // SignalKit // // Created by Yanko Dimitrov on 7/15/15. // Copyright (c) 2015 Yanko Dimitrov. All rights reserved. // import Foundation /** Generates an incremental unique sequence of tokens based on the number of generated tokens and a step limit. For example a generator with step limit of <3> will produce the following sequence of tokens: ["1", "2", "3", "31", "32", "33", "331"...]. */ internal struct IncrementalKeyGenerator: TokenGeneratorType { private let stepLimit: UInt16 private var counter: UInt16 = 0 private var tokenPrefix = "" private var token: Token { return tokenPrefix + String(counter) } init(stepLimit: UInt16) { assert(stepLimit > 0, "Step limit should be greather than zero") self.stepLimit = stepLimit } init() { self.init(stepLimit: UInt16.max) } mutating func nextToken() -> Token { if counter >= stepLimit { tokenPrefix += String(stepLimit) counter = 0 } counter += 1 return token } }
mit
KrishMunot/swift
test/DebugInfo/prologue.swift
6
531
// RUN: %target-swift-frontend -primary-file %s -S -g -o - | FileCheck %s // REQUIRES: CPU=x86_64 func markUsed<T>(_ t: T) {} // CHECK: .file [[F:[0-9]+]] "{{.*}}prologue.swift" func bar<T, U>(_ x: T, y: U) { markUsed("bar") } // CHECK: _TF8prologue3baru0_rFTx1yq__T_: // CHECK: .loc [[F]] 0 0 prologue_end // Make sure there is no allocation happening between the end of // prologue and the beginning of the function body. // CHECK-NOT: callq * // CHECK: .loc [[F]] [[@LINE-6]] {{.}} // CHECK: callq {{.*}}builtinStringLiteral
apache-2.0
evering7/iSpeak8
Pods/FeedKit/Sources/FeedKit/Dates/ISO8601DateFormatter.swift
2
2082
// // ISO8601DateFormatter.swift // // Copyright (c) 2017 Nuno Manuel Dias // // 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 /// Converts date and time textual representations within the ISO8601 /// date specification into `Date` objects class ISO8601DateFormatter: DateFormatter { let dateFormats = [ "yyyy-mm-dd'T'hh:mm", "yyyy-MM-dd'T'HH:mm:ssZZZZZ", "yyyy-MM-dd'T'HH:mm:ss.SSZZZZZ", "yyyy-MM-dd'T'HH:mmSSZZZZZ" ] override init() { super.init() self.timeZone = TimeZone(secondsFromGMT: 0) self.locale = Locale(identifier: "en_US_POSIX") } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) not supported") } override func date(from string: String) -> Date? { for dateFormat in self.dateFormats { self.dateFormat = dateFormat if let date = super.date(from: string) { return date } } return nil } }
mit
tonyarnold/Differ
Sources/Differ/ExtendedDiff.swift
1
7629
/// A sequence of deletions, insertions, and moves where deletions point to locations in the source and insertions point to locations in the output. /// Examples: /// ``` /// "12" -> "": D(0)D(1) /// "" -> "12": I(0)I(1) /// ``` /// - SeeAlso: Diff public struct ExtendedDiff: DiffProtocol { public typealias Index = Int public enum Element { case insert(at: Int) case delete(at: Int) case move(from: Int, to: Int) } /// Returns the position immediately after the given index. /// /// - Parameters: /// - i: A valid index of the collection. `i` must be less than /// `endIndex`. /// - Returns: The index value immediately after `i`. public func index(after i: Int) -> Int { return i + 1 } /// Diff used to compute an instance public let source: Diff /// An array which holds indices of diff elements in the source diff (i.e. diff without moves). let sourceIndex: [Int] /// An array which holds indices of diff elements in a diff where move's subelements (deletion and insertion) are ordered accordingly let reorderedIndex: [Int] /// An array of particular diff operations public let elements: [ExtendedDiff.Element] let moveIndices: Set<Int> } extension ExtendedDiff.Element { init(_ diffElement: Diff.Element) { switch diffElement { case let .delete(at): self = .delete(at: at) case let .insert(at): self = .insert(at: at) } } } public extension Collection { /// Creates an extended diff between the callee and `other` collection /// /// - Complexity: O((N+M)*D). There's additional cost of O(D^2) to compute the moves. /// /// - Parameters: /// - other: a collection to compare the callee to /// - isEqual: instance comparator closure /// - Returns: ExtendedDiff between the callee and `other` collection func extendedDiff(_ other: Self, isEqual: EqualityChecker<Self>) -> ExtendedDiff { return extendedDiff(from: diff(other, isEqual: isEqual), other: other, isEqual: isEqual) } /// Creates an extended diff between the callee and `other` collection /// /// - Complexity: O(D^2). where D is number of elements in diff. /// /// - Parameters: /// - diff: source diff /// - other: a collection to compare the callee to /// - isEqual: instance comparator closure /// - Returns: ExtendedDiff between the callee and `other` collection func extendedDiff(from diff: Diff, other: Self, isEqual: EqualityChecker<Self>) -> ExtendedDiff { var elements: [ExtendedDiff.Element] = [] var moveOriginIndices = Set<Int>() var moveTargetIndices = Set<Int>() // It maps indices after reordering (e.g. bringing move origin and target next to each other in the output) to their positions in the source Diff var sourceIndex = [Int]() // Complexity O(d^2) where d is the length of the diff /* * 1. Iterate all objects * 2. For every iteration find the next matching element a) if it's not found insert the element as is to the output array b) if it's found calculate move as in 3 * 3. Calculating the move. We call the first element a *candidate* and the second element a *match* 1. The position of the candidate never changes 2. The position of the match is equal to its initial position + m where m is equal to -d + i where d = deletions between candidate and match and i = insertions between candidate and match * 4. Remove the candidate and match and insert the move in the place of the candidate * */ for candidateIndex in diff.indices { if !moveTargetIndices.contains(candidateIndex) && !moveOriginIndices.contains(candidateIndex) { let candidate = diff[candidateIndex] let match = firstMatch(diff, dirtyIndices: moveTargetIndices.union(moveOriginIndices), candidate: candidate, candidateIndex: candidateIndex, other: other, isEqual: isEqual) if let match = match { switch match.0 { case let .move(from, _): if from == candidate.at() { sourceIndex.append(candidateIndex) sourceIndex.append(match.1) moveOriginIndices.insert(candidateIndex) moveTargetIndices.insert(match.1) } else { sourceIndex.append(match.1) sourceIndex.append(candidateIndex) moveOriginIndices.insert(match.1) moveTargetIndices.insert(candidateIndex) } default: fatalError() } elements.append(match.0) } else { sourceIndex.append(candidateIndex) elements.append(ExtendedDiff.Element(candidate)) } } } let reorderedIndices = flip(array: sourceIndex) return ExtendedDiff( source: diff, sourceIndex: sourceIndex, reorderedIndex: reorderedIndices, elements: elements, moveIndices: moveOriginIndices ) } func firstMatch( _ diff: Diff, dirtyIndices: Set<Diff.Index>, candidate: Diff.Element, candidateIndex: Diff.Index, other: Self, isEqual: EqualityChecker<Self> ) -> (ExtendedDiff.Element, Diff.Index)? { for matchIndex in (candidateIndex + 1) ..< diff.endIndex { if !dirtyIndices.contains(matchIndex) { let match = diff[matchIndex] if let move = createMatch(candidate, match: match, other: other, isEqual: isEqual) { return (move, matchIndex) } } } return nil } func createMatch(_ candidate: Diff.Element, match: Diff.Element, other: Self, isEqual: EqualityChecker<Self>) -> ExtendedDiff.Element? { switch (candidate, match) { case (.delete, .insert): if isEqual(itemOnStartIndex(advancedBy: candidate.at()), other.itemOnStartIndex(advancedBy: match.at())) { return .move(from: candidate.at(), to: match.at()) } case (.insert, .delete): if isEqual(itemOnStartIndex(advancedBy: match.at()), other.itemOnStartIndex(advancedBy: candidate.at())) { return .move(from: match.at(), to: candidate.at()) } default: return nil } return nil } } public extension Collection where Element: Equatable { /// - SeeAlso: `extendedDiff(_:isEqual:)` func extendedDiff(_ other: Self) -> ExtendedDiff { return extendedDiff(other, isEqual: { $0 == $1 }) } } extension Collection { func itemOnStartIndex(advancedBy n: Int) -> Element { return self[self.index(startIndex, offsetBy: n)] } } func flip(array: [Int]) -> [Int] { return zip(array, array.indices) .sorted { $0.0 < $1.0 } .map { $0.1 } } extension ExtendedDiff.Element: CustomDebugStringConvertible { public var debugDescription: String { switch self { case let .delete(at): return "D(\(at))" case let .insert(at): return "I(\(at))" case let .move(from, to): return "M(\(from),\(to))" } } }
mit