repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
fitpay/fitpay-ios-sdk | FitpaySDKTests/Rest/Models/EncryptionKeyTests.swift | 1 | 2135 | import XCTest
import Nimble
@testable import FitpaySDK
class EncryptionKeyTests: XCTestCase {
let mockModels = MockModels()
func testEncryptionKeyParsing() {
let encryptionKey = mockModels.getEncryptionKey()
expect(encryptionKey?.keyId).to(equal(mockModels.someId))
expect(encryptionKey?.created).to(equal(mockModels.someDate))
expect(encryptionKey?.createdEpoch).to(equal(NSTimeIntervalTypeTransform().transform(mockModels.timeEpoch)))
expect(encryptionKey?.expiration).to(equal(mockModels.someDate))
expect(encryptionKey?.expirationEpoch).to(equal(NSTimeIntervalTypeTransform().transform(mockModels.timeEpoch)))
expect(encryptionKey?.serverPublicKey).to(equal("someKey"))
expect(encryptionKey?.clientPublicKey).to(equal("someKey"))
expect(encryptionKey?.active).to(equal(true))
let json = encryptionKey?.toJSON()
expect(json?["keyId"] as? String).to(equal(mockModels.someId))
expect(json?["createdTs"] as? String).to(equal(mockModels.someDate))
expect(json?["createdTsEpoch"] as? Int64).to(equal(mockModels.timeEpoch))
expect(json?["expirationTs"] as? String).to(equal(mockModels.someDate))
expect(json?["expirationTsEpoch"] as? Int64).to(equal(mockModels.timeEpoch))
expect(json?["serverPublicKey"] as? String).to(equal("someKey"))
expect(json?["clientPublicKey"] as? String).to(equal("someKey"))
expect(json?["active"] as? Bool).to(equal(true))
}
func testIsExpired() {
let encryptionKey = mockModels.getEncryptionKey()
expect(encryptionKey?.isExpired).to(beTrue())
let date = Date()
var components = DateComponents()
components.setValue(2100, for: .year)
let futureDate = Calendar.current.date(byAdding: components, to: date)
encryptionKey?.expirationEpoch = futureDate?.timeIntervalSince1970
expect(encryptionKey?.isExpired).to(beFalse())
encryptionKey?.expirationEpoch = nil
expect(encryptionKey?.isExpired).to(beFalse())
}
}
| mit | 8ebacd461bf1895b8da97e3f06bd3dcf | 40.057692 | 119 | 0.679625 | 4.765625 | false | true | false | false |
radvansky-tomas/SwiftPhotosAPI | Album/AppDelegate.swift | 1 | 2740 | //
// AppDelegate.swift
// Album
//
// Created by Tomas Radvansky on 31/08/2015.
// Copyright © 2015 Radvansky Solutions. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var selectedAlbum:String?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// create viewController code...
let storyboard:UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let leftViewController:LeftViewController = storyboard.instantiateViewControllerWithIdentifier("LeftVC") as! LeftViewController
let navVC:UINavigationController = storyboard.instantiateViewControllerWithIdentifier("MainNavVC") as! UINavigationController
let slideMenuController = SlideMenuController(mainViewController: navVC, leftMenuViewController: leftViewController)
self.window?.rootViewController = slideMenuController
self.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 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:.
}
}
| gpl-2.0 | 6772c24a409f2ba1347abb50ea27372b | 50.679245 | 285 | 0.759036 | 5.82766 | false | false | false | false |
itsaboutcode/WordPress-iOS | WordPress/Classes/Services/CommentServiceRemoteFactory.swift | 2 | 1281 | import Foundation
import WordPressKit
/// Provides service remote instances for CommentService
@objc class CommentServiceRemoteFactory: NSObject {
/// Returns a CommentServiceRemote for a given Blog object
///
/// - Parameter blog: A valid Blog object
/// - Returns: A CommentServiceRemote instance
@objc func remote(blog: Blog) -> CommentServiceRemote? {
if blog.supports(.wpComRESTAPI),
let api = blog.wordPressComRestApi(),
let dotComID = blog.dotComID {
return CommentServiceRemoteREST(wordPressComRestApi: api, siteID: dotComID)
}
if let api = blog.xmlrpcApi,
let username = blog.username,
let password = blog.password {
return CommentServiceRemoteXMLRPC(api: api, username: username, password: password)
}
return nil
}
/// Returns a REST remote for a given site ID.
///
/// - Parameters:
/// - siteID: A valid siteID
/// - api: An instance of WordPressComRestAPI
/// - Returns: An instance of CommentServiceRemoteREST
@objc func restRemote(siteID: NSNumber, api: WordPressComRestApi) -> CommentServiceRemoteREST {
return CommentServiceRemoteREST(wordPressComRestApi: api, siteID: siteID)
}
}
| gpl-2.0 | 4ee790f34ba7ef9ef615916fa20a57f8 | 32.710526 | 99 | 0.662763 | 5.165323 | false | false | false | false |
itsaboutcode/WordPress-iOS | WordPress/Classes/ViewRelated/Pages/PageListTableViewHandler.swift | 2 | 5993 | import Foundation
final class PageListTableViewHandler: WPTableViewHandler {
var isSearching: Bool = false
var status: PostListFilter.Status = .published
var groupResults: Bool {
if isSearching {
return true
}
return status == .scheduled
}
private var pages: [Page] = []
private let blog: Blog
private lazy var publishedResultController: NSFetchedResultsController<NSFetchRequestResult> = {
let publishedFilter = PostListFilter.publishedFilter()
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: Page.entityName())
let predicate = NSPredicate(format: "\(#keyPath(Page.blog)) = %@ && \(#keyPath(Page.revision)) = nil", blog)
let predicates = [predicate, publishedFilter.predicateForFetchRequest]
fetchRequest.predicate = NSCompoundPredicate(andPredicateWithSubpredicates: predicates)
fetchRequest.sortDescriptors = publishedFilter.sortDescriptors
return resultsController(with: fetchRequest, context: managedObjectContext(), performFetch: false)
}()
private lazy var searchResultsController: NSFetchedResultsController<NSFetchRequestResult> = {
return resultsController(with: fetchRequest(), context: managedObjectContext(), keyPath: BasePost.statusKeyPath, performFetch: false)
}()
private lazy var groupedResultsController: NSFetchedResultsController<NSFetchRequestResult> = {
return resultsController(with: fetchRequest(), context: managedObjectContext(), keyPath: sectionNameKeyPath())
}()
private lazy var flatResultsController: NSFetchedResultsController<NSFetchRequestResult> = {
return resultsController(with: fetchRequest(), context: managedObjectContext())
}()
init(tableView: UITableView, blog: Blog) {
self.blog = blog
super.init(tableView: tableView)
}
override var resultsController: NSFetchedResultsController<NSFetchRequestResult> {
if isSearching {
return searchResultsController
}
return groupResults ? groupedResultsController : flatResultsController
}
override func refreshTableView() {
refreshTableView(at: nil)
}
func refreshTableView(at indexPath: IndexPath?) {
super.clearCachedRowHeights()
do {
try resultsController.performFetch()
pages = setupPages()
} catch {
DDLogError("Error fetching pages after refreshing the table: \(error)")
}
if let indexPath = indexPath {
tableView.reloadSections(IndexSet(integer: indexPath.section), with: .fade)
} else {
tableView.reloadData()
}
}
// MARK: - Public methods
func page(at indexPath: IndexPath) -> Page {
guard groupResults else {
return pages[indexPath.row]
}
guard let page = resultsController.object(at: indexPath) as? Page else {
// Retrieveing anything other than a post object means we have an app with an invalid
// state. Ignoring this error would be counter productive as we have no idea how this
// can affect the App. This controlled interruption is intentional.
//
// - Diego Rey Mendez, May 18 2016
//
fatalError("Expected a Page object.")
}
return page
}
func index(for page: Page) -> Int? {
return pages.firstIndex(of: page)
}
func removePage(from index: Int?) -> [Page] {
guard let index = index, status == .published else {
do {
try publishedResultController.performFetch()
if let pages = publishedResultController.fetchedObjects as? [Page] {
return pages.setHomePageFirst().hierarchySort()
}
} catch {
DDLogError("Error fetching pages after refreshing the table: \(error)")
}
return []
}
return pages.remove(from: index)
}
// MARK: - Override TableView Datasource
override func numberOfSections(in tableView: UITableView) -> Int {
return groupResults ? super.numberOfSections(in: tableView) : 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return groupResults ? super.tableView(tableView, numberOfRowsInSection: section) : pages.count
}
// MARK: - Private methods
private func resultsController(with request: NSFetchRequest<NSFetchRequestResult>?,
context: NSManagedObjectContext?,
keyPath: String? = nil,
performFetch: Bool = true) -> NSFetchedResultsController<NSFetchRequestResult> {
guard let request = request, let context = context else {
fatalError("A request and a context must exist")
}
let controller = NSFetchedResultsController(fetchRequest: request, managedObjectContext: context, sectionNameKeyPath: keyPath, cacheName: nil)
if performFetch {
do {
try controller.performFetch()
} catch {
DDLogError("Error fetching pages after refreshing the table: \(error)")
}
}
return controller
}
private func fetchRequest() -> NSFetchRequest<NSFetchRequestResult>? {
return delegate?.fetchRequest()
}
private func managedObjectContext() -> NSManagedObjectContext? {
return delegate?.managedObjectContext()
}
private func sectionNameKeyPath() -> String? {
return delegate?.sectionNameKeyPath!()
}
private func setupPages() -> [Page] {
guard !groupResults, let pages = resultsController.fetchedObjects as? [Page] else {
return []
}
return status == .published ? pages.setHomePageFirst().hierarchySort() : pages
}
}
| gpl-2.0 | bfd283a2d51ab3f89fb6bb8e0e3226a4 | 34.672619 | 150 | 0.64008 | 5.835443 | false | false | false | false |
Bauer312/ProjectEuler | Sources/Problem/Problem9.swift | 1 | 852 | import Multiples
import Sums
public class Problem9 : Problem {
public var name: String
public var text: String
public var url: String
private(set) public var answer: String
public func solve() {
let sd = Sums()
let mult = Multiples()
for a in 1..<1000 {
for b in (a + 1)..<1000 {
for c in (b + 1)..<1000 {
if sd.tripleSum(a: a, b: b, c: c) == 1000 {
if mult.isPythagoreanTriplet(a: a, b: b, c: c) == true {
answer = String(a * b * c)
return
}
}
}
}
}
answer = "Unable to solve."
}
public init () {
name = "Problem 9"
text = "There exists exactly one Pythagorean triplet for which a + b + c = 1000. Find the product abc."
url = "https://projecteuler.net/problem=9"
answer = "Not yet solved."
}
}
| mit | c4dfc16142d34ac97ad3b9b27f3dff98 | 23.342857 | 108 | 0.537559 | 3.579832 | false | false | false | false |
pixelmaid/DynamicBrushes | swift/Palette-Knife/models/primitives/Color.swift | 1 | 1788 | //
// Color.swift
// Palette-Knife
//
// Created by JENNIFER MARY JACOBS on 5/5/16.
// Copyright © 2016 pixelmaid. All rights reserved.
//
import Foundation
import UIKit
struct Color {
var red:Float
var green:Float
var blue:Float
var hue:Float
var saturation:Float
var lightness:Float
var alpha:Float
var uiColor:UIColor
init(h:Float,s:Float,l:Float, a:Float){
hue = h;
saturation = s;
lightness = l;
alpha = a;
uiColor = UIColor(hue: CGFloat(hue), saturation: CGFloat(saturation), brightness: CGFloat(lightness), alpha: CGFloat(alpha))
let cgColor = uiColor.cgColor;
let components = cgColor.components
red = Float(components![0]);
green = Float(components![1]);
blue = Float(components![2]);
}
init(r:Float,g:Float,b:Float,a:Float){
red = r;
blue = b;
green = g;
alpha = a;
self.uiColor = UIColor(red: CGFloat(r), green: CGFloat(g), blue: CGFloat(b), alpha: CGFloat(alpha))
var _hue = CGFloat(0)
var _saturation = CGFloat(0)
var _brightness = CGFloat(0)
var _alpha = CGFloat(0)
_ = self.uiColor.getHue(&_hue, saturation: &_saturation, brightness: &_brightness, alpha: &_alpha)
self.hue = Float(_hue)
self.saturation = Float(_saturation)
self.lightness = Float(_brightness)
}
func toCGColor()->CGColor{
return self.uiColor.cgColor;
}
func toUIColor()->UIColor{
return UIColor(hue: CGFloat(hue), saturation: CGFloat(saturation), brightness: CGFloat(lightness), alpha: CGFloat(self.alpha))
}
}
| mit | 80fe0b96e4c682bfa33f1e917ac22074 | 25.279412 | 135 | 0.566312 | 4.089245 | false | false | false | false |
Whyllee/fingertips | FingerTips/TipsTableViewController.swift | 1 | 2394 | //
// TipsTableViewController.swift
// fingertips
//
// Created by Yin Li on 7/12/14.
// Copyright (c) 2014 Whyllee. All rights reserved.
//
import UIKit
class TipsTableViewController: UITableViewController, UITableViewDelegate {
let min:Float = 0;
let max:Float = 1000.0;
var scale:Float = 0.25;
var current:Float = 30;
override func viewDidLoad() {
super.viewDidLoad()
self.clearsSelectionOnViewWillAppear = false
self.tableView.registerClass(UITableViewCell.classForCoder(), forCellReuseIdentifier: "tipsCell");
self.tableView.selectRowAtIndexPath(_valueToIndex(current), animated: true, scrollPosition: .Middle)
}
override func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) {
self.current = Float(indexPath.row);
self.tableView.scrollToRowAtIndexPath(indexPath, atScrollPosition: .Middle, animated: true)
}
// #pragma mark - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView?) -> Int {
return 1
}
override func tableView(tableView: UITableView?, numberOfRowsInSection section: Int) -> Int {
assert(self.max > self.min)
assert(self.scale > 0)
return Int((self.max - self.min) / self.scale);
}
override func tableView(tableView: UITableView?, cellForRowAtIndexPath indexPath: NSIndexPath?) -> UITableViewCell? {
let cell = self.tableView.dequeueReusableCellWithIdentifier("tipsCell", forIndexPath: indexPath) as UITableViewCell;
let value = self._indexToValue(indexPath);
cell.textLabel.text = "\(_formatValue(value))"
return cell
}
func _formatValue(value:Float) -> String {
return NSString(format:"%.2f", value);
}
func _indexToValue(indexPath:NSIndexPath!) -> Float {
return Float(indexPath.row) * self.scale + self.min
}
func _valueToIndex(value:Float) -> NSIndexPath {
return NSIndexPath(forRow: Int((value - self.min)/self.scale), inSection: 0)
}
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView?, canEditRowAtIndexPath indexPath: NSIndexPath?) -> Bool {
// Return NO if you do not want the specified item to be editable.
return true
}
*/
}
| mit | d44b722de707d7d82e2704af26f3c0f7 | 33.695652 | 124 | 0.674185 | 4.75 | false | false | false | false |
Felix0805/Notes | Notes/Notes/NotesMainViewController.swift | 1 | 12165 | //
// NotesMainViewController.swift
// Notes
//
// Created by FelixXiao on 2017/1/12.
// Copyright © 2017年 FelixXiao. All rights reserved.
//
import UIKit
/*var folderList: [FoldersModel] = [FoldersModel(name: "AFolder", notes: notesList),FoldersModel(name: "BFolder", notes:notesList)]*/
var folderList : [FoldersModel] = []
var filterFolderList: [FoldersModel] = []
class NotesMainViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UISearchResultsUpdating {
@IBOutlet weak var notesMainTableView: UITableView!
@IBAction func longPress(_ sender: UILongPressGestureRecognizer) {
let touchPoint = sender.location(in: self.notesMainTableView)
if notesMainTableView.indexPathForRow(at: touchPoint) != nil {
let indexPath = notesMainTableView.indexPathForRow(at: touchPoint)
let str = folderList[(indexPath?.row)!].name
// print(indexPath?.row)
let alertController = UIAlertController(title: "Rename Folder", message: "Enter a new name for this folder", preferredStyle: UIAlertControllerStyle.alert)
let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel, handler: nil)
let okAction = UIAlertAction(title: "Save", style: UIAlertActionStyle.default) {
(action: UIAlertAction!) -> Void in
let login = (alertController.textFields?.first)! as UITextField
if let temp = login.text {
if !temp.isEmpty {
folderList[(indexPath?.row)!].name = temp
let filePath = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)[0] + "/notes.dat"
var array = NSMutableArray()
var num = 0
for item in folderList {
array.insert(item.name, at: num)
num = num + 1
array.insert(item.notes.count.description, at: num)
num = num + 1
for var i in 0 ..< item.notes.count {
array.insert(item.notes[i].title, at: num)
num = num + 1
array.insert(item.notes[i].content, at: num)
num = num + 1
i = i + 1
}
}
NSKeyedArchiver.archiveRootObject(array, toFile: filePath)
self.notesMainTableView.reloadData()
}
}
}
alertController.addTextField {
(textField: UITextField!) -> Void in
textField.placeholder = str
}
alertController.addAction(cancelAction)
alertController.addAction(okAction)
self.present(alertController, animated: true, completion: nil)
}
}
let searchController = UISearchController(searchResultsController: nil)
override func viewDidLoad() {
super.viewDidLoad()
let filePath = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)[0] + "/notes.dat"
if let result : NSMutableArray = NSKeyedUnarchiver.unarchiveObject(withFile: filePath) as? NSMutableArray{
var folder : String = ""
var notesList : [NotesModel] = []
var title_t : String = ""
var content_t : String = ""
var count : Int
var i : Int
i = 0
while i < result.count {
notesList = []
folder = result[i] as! String
i = i + 1
count = Int((result[i] as! NSString).intValue)
i = i + 1
for j in 0 ..< count {
title_t = result[i] as! String
i = i + 1
content_t = result[i] as! String
i = i + 1
notesList.append(NotesModel(title: title_t, content: content_t))
}
folderList.append(FoldersModel(name: folder, notes: notesList))
}
}
else {
folderList = [FoldersModel(name: "folder1", notes: [NotesModel(title: "file1", content: "file1 content"),NotesModel(title: "file2", content: "file2 content")]),
FoldersModel(name: "folder2", notes: [NotesModel(title: "file1", content: "file1 content"),NotesModel(title: "file2", content: "file2 content")])
]
}
notesMainTableView.delegate = self
notesMainTableView.dataSource = self
navigationItem.leftBarButtonItem = editButtonItem
searchController.searchResultsUpdater = self
searchController.dimsBackgroundDuringPresentation = false
searchController.searchBar.frame.size.height = 40
definesPresentationContext = true
notesMainTableView.tableHeaderView = searchController.searchBar
// hide the search bar
var contentOffset = notesMainTableView.contentOffset
contentOffset.y += searchController.searchBar.frame.size.height
notesMainTableView.contentOffset = contentOffset
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if searchController.isActive && searchController.searchBar.text != "" {
return filterFolderList.count
}
else {
return folderList.count
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = self.notesMainTableView.dequeueReusableCell(withIdentifier: "NotesCell")! as UITableViewCell
let title = cell.viewWithTag(101) as! UILabel
var temp: FoldersModel
if searchController.isActive && searchController.searchBar.text != "" {
temp = filterFolderList[indexPath.row]
}
else {
temp = folderList[indexPath.row]
}
title.text = temp.name
return cell
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "showNotes" {
let notes = segue.destination as! NotesSecondViewController
let indexPath = notesMainTableView.indexPathForSelectedRow
if let index = indexPath {
showList = folderList[index.row].notes
notes.folderIndex = index.row
}
}
}
@IBAction func edit(_ sender: Any) {
let alertController = UIAlertController(title: "New Folder", message: "Enter a name for this folder", preferredStyle: UIAlertControllerStyle.alert)
let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel, handler: nil)
let okAction = UIAlertAction(title: "Save", style: UIAlertActionStyle.default) {
(action: UIAlertAction!) -> Void in
let login = (alertController.textFields?.first)! as UITextField
if let temp = login.text {
if !temp.isEmpty {
folderList.append(FoldersModel(name: temp, notes: []))
let filePath = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)[0] + "/notes.dat"
var array = NSMutableArray()
var num = 0
for item in folderList {
array.insert(item.name, at: num)
num = num + 1
array.insert(item.notes.count.description, at: num)
num = num + 1
for var i in 0 ..< item.notes.count {
array.insert(item.notes[i].title, at: num)
num = num + 1
array.insert(item.notes[i].content, at: num)
num = num + 1
i = i + 1
}
}
NSKeyedArchiver.archiveRootObject(array, toFile: filePath)
self.notesMainTableView.reloadData()
}
}
}
alertController.addTextField {
(textField: UITextField!) -> Void in
textField.placeholder = "Name"
}
alertController.addAction(cancelAction)
alertController.addAction(okAction)
self.present(alertController, animated: true, completion: nil)
}
override func setEditing(_ editing: Bool, animated: Bool) {
super.setEditing(editing, animated: animated)
notesMainTableView.setEditing(editing, animated: animated)
}
func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
return self.isEditing
}
func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
let folder = folderList.remove(at: sourceIndexPath.row)
folderList.insert(folder, at: destinationIndexPath.row)
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == UITableViewCellEditingStyle.delete {
folderList.remove(at: indexPath.row)
let filePath = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)[0] + "/notes.dat"
print(filePath)
var array = NSMutableArray()
var num = 0
for item in folderList {
array.insert(item.name, at: num)
num = num + 1
array.insert(item.notes.count.description, at: num)
num = num + 1
for var i in 0 ..< item.notes.count {
array.insert(item.notes[i].title, at: num)
num = num + 1
array.insert(item.notes[i].content, at: num)
num = num + 1
i = i + 1
}
}
NSKeyedArchiver.archiveRootObject(array, toFile: filePath)
tableView.deleteRows(at: [indexPath], with: UITableViewRowAnimation.automatic)
}
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 40
}
@IBAction func close(_ segue: UIStoryboardSegue) {
//print("closed!")
}
func updateSearchResults(for searchController: UISearchController) {
filterContent(searchText: self.searchController.searchBar.text! )
}
func filterContent(searchText:String) {
filterFolderList = folderList.filter { n in
let name = n.name
return (name.contains(searchText))
}
notesMainTableView.reloadData()
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit | 6866276fc39cd5369132e392e6a1b477 | 39.949495 | 198 | 0.568245 | 5.667288 | false | false | false | false |
adrianodiasx93/TBEmptyDataSet | Example/DemoViewController.swift | 2 | 3659 | //
// DemoViewController.swift
// TBEmptyDataSetExample
//
// Created by 洪鑫 on 15/11/26.
// Copyright © 2015年 Teambition. All rights reserved.
//
import UIKit
public struct EmptyData {
static let images = [#imageLiteral(resourceName: "icon-empty-photos"), #imageLiteral(resourceName: "icon-empty-events"), #imageLiteral(resourceName: "icon-empty-message")]
static let titles = ["无照片", "无日程", "无新消息"]
static let descriptions = ["你可以添加一些照片哦,让生活更精彩!", "暂时没有日程哦,添加一些日程吧!", "没有新消息哦,去找朋友聊聊天吧!"]
}
class DemoViewController: UITableViewController {
// MARK: - Structs
fileprivate struct Data {
static let examples = ["Empty Photos", "Empty Events", "Empty Message"]
static let sectionTitles = ["TableView", "CollectionView"]
}
fileprivate struct SegueIdentifier {
static let showTableView = "ShowEmptyDataDemoTableView"
static let showCollectionView = "ShowEmptyDataDemoCollectionView"
}
fileprivate struct CellIdentifier {
static let reuseIdentifier = "Cell"
}
// MARK: - Properties
var selectedIndexPath = IndexPath()
// MARK: - View life cycle
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.title = "EmptyDataSet Example"
let backButton = UIBarButtonItem()
backButton.title = "Back"
navigationItem.backBarButtonItem = backButton
tableView.tableFooterView = UIView()
}
// MARK: - Table view data source and delegate
override func numberOfSections(in tableView: UITableView) -> Int {
return Data.sectionTitles.count
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return Data.examples.count
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return Data.sectionTitles[section]
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCell(withIdentifier: CellIdentifier.reuseIdentifier)
if cell == nil {
cell = UITableViewCell(style: .default, reuseIdentifier: CellIdentifier.reuseIdentifier)
}
cell!.accessoryType = .disclosureIndicator
cell!.textLabel!.text = Data.examples[indexPath.row]
return cell!
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
selectedIndexPath = indexPath
if indexPath.section == 0 {
performSegue(withIdentifier: SegueIdentifier.showTableView, sender: self)
} else if indexPath.section == 1 {
performSegue(withIdentifier: SegueIdentifier.showCollectionView, sender: self)
}
tableView.deselectRow(at: indexPath, animated: true)
}
// MARK: - Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == SegueIdentifier.showTableView {
if let emptyDataDemoTableViewController = segue.destination as? EmptyDataDemoTableViewController {
emptyDataDemoTableViewController.indexPath = selectedIndexPath
}
} else if segue.identifier == SegueIdentifier.showCollectionView {
if let emptyDataDemoCollectionViewController = segue.destination as? EmptyDataDemoCollectionViewController {
emptyDataDemoCollectionViewController.indexPath = selectedIndexPath
}
}
}
}
| mit | 3860d9e562fc2efa35defad1eada9266 | 36.595745 | 175 | 0.687323 | 5.166667 | false | false | false | false |
iosprogrammingwithswift/iosprogrammingwithswift | 04_Swift2015.playground/Pages/05_Control Flow.xcplaygroundpage/Contents.swift | 1 | 5405 | //: [Previous](@previous) | [Next](@next)
//: ## Control Flow
//:
//: Use `if` and `switch` to make conditionals, and use `for`-`in`, `for`, `while`, and `repeat`-`while` to make loops. Parentheses around the condition or loop variable are optional. Braces around the body are required.
//:
let individualScores = [75, 43, 103, 87, 12]
var teamScore = 0
for score in individualScores {
}
print(teamScore)
for index in 1...5 {
print("\(index) times 5 is \(index * 5)")
}
let base = 3
let power = 10
var answer = 1
print("\(base) to the power of \(power) is \(answer)")
// prints "3 to the power of 10 is 59049"
let names = ["Anna", "Alex", "Brian", "Jack"]
var airports: [String:String] = [
"YYZ":"Toronto Pearson",
"DUB": "Dublin Airport",
"LHR": "London Heathrow"]
//: Iterating
// airportCodes is ["YYZ", "LHR"]
// airportNames is ["Toronto Pearson", "London Heathrow"]
// Airport code: YYZ
// Airport code: LHR
//: In an `if` statement, the conditional must be a Boolean expression—this means that code such as `if score { ... }` is an error, not an implicit comparison to zero.
//:
//: You can use `if` and `let` together to work with values that might be missing. These values are represented as optionals. An optional value either contains a value or contains `nil` to indicate that a value is missing. Write a question mark (`?`) after the type of a value to mark the value as optional.
//:
//: > **Experiment**:
//: > Change `optionalName` to `nil`. What greeting do you get? Add an `else` clause that sets a different greeting if `optionalName` is `nil`.
//:
//: If the optional value is `nil`, the conditional is `false` and the code in braces is skipped. Otherwise, the optional value is unwrapped and assigned to the constant after `let`, which makes the unwrapped value available inside the block of code.
//:
//: Another way to handle optional values is to provide a default value using the `??` operator. If the optional value is missing, the default value is used instead.
//:
let nickName: String? = nil
let fullName: String = "Andreas Wittmann"
//: Switches support any kind of data and a wide variety of comparison operations—they aren’t limited to integers and tests for equality.
//:
let vegetable = "red pepper"
//: > **Experiment**:
//: > Try removing the default case. What error do you get?
//:
//: Notice how `let` can be used in a pattern to assign the value that matched that part of a pattern to a constant.
//:
//: After executing the code inside the switch case that matched, the program exits from the switch statement. Execution doesn’t continue to the next case, so there is no need to explicitly break out of the switch at the end of each case’s code.
//:
let approximateCount = 62
let countedThings = "moons orbiting Saturn"
var naturalCount: String!
print("There are \(naturalCount) \(countedThings).")
// prints "There are dozens of moons orbiting Saturn."
//: You use `for`-`in` to iterate over items in a dictionary by providing a pair of names to use for each key-value pair. Dictionaries are an unordered collection, so their keys and values are iterated over in an arbitrary order.
//:
let interestingNumbers = [
"Prime": [2, 3, 5, 7, 11, 13],
"Fibonacci": [1, 1, 2, 3, 5, 8],
"Square": [1, 4, 9, 16, 25],
]
var largest = 0
print(largest)
//: > **Experiment**:
//: > Add another variable to keep track of which kind of number was the largest, as well as what that largest number was.
//:
//: Use `while` to repeat a block of code until a condition changes. The condition of a loop can be at the end instead, ensuring that the loop is run at least once.
//:
var n = 2
print(n)
var m = 2
print(m)
//: You can keep an index in a loop—either by using `..<` to make a range of indexes or by writing an explicit initialization, condition, and increment. These two loops do the same thing:
//:
var firstForLoop = 0
print(firstForLoop)
var secondForLoop = 0
print(secondForLoop)
//: Use `..<` to make a range that omits its upper value, and use `...` to make a range that includes both values.
//:
//: Control Transfer Statements
/*:
* * continue
* * break
* * fallthrough
* * return
* * throw
*/
//: Early Exit Guard
func greet(person: [String: String]) {
}
greet(["name": "John"])
// prints "Hello John!"
// prints "I hope the weather is nice near you."
greet(["name": "Jane", "location": "Cupertino"])
// prints "Hello Jane!"
// prints "I hope the weather is nice in Cupertino."
//: difference guard & let
func awesomeFunctionWithGuard(name:String?) {
print("All good \(name)")
}
func awesomeFunctionWithLet(name:String?) {
// this won't work – name doesn't exist here!
//print("Your username is \(name)")
}
//: Checking API Availability
if #available(iOS 9, OSX 10.10, *) {
// Use iOS 9 APIs on iOS, and use OS X v10.10 APIs on OS X
} else {
// Fall back to earlier iOS and OS X APIs
}
/*:
largely Based of [Apple's Swift Language Guide: Control Flow](https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/ControlFlow.html#//apple_ref/doc/uid/TP40014097-CH9-ID120 ) & [Apple's A Swift Tour](https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/GuidedTour.html#//apple_ref/doc/uid/TP40014097-CH2-ID1 )
*/
//: [Previous](@previous) | [Next](@next)
| mit | 50f8be69252124ab15ded3f5168ff465 | 29.457627 | 399 | 0.692636 | 3.715369 | false | false | false | false |
WhisperSystems/Signal-iOS | SignalMessaging/Views/ImageEditor/ImageEditorModel.swift | 1 | 11258 | //
// Copyright (c) 2019 Open Whisper Systems. All rights reserved.
//
import UIKit
// Used to represent undo/redo operations.
//
// Because the image editor's "contents" and "items"
// are immutable, these operations simply take a
// snapshot of the current contents which can be used
// (multiple times) to preserve/restore editor state.
private class ImageEditorOperation: NSObject {
let operationId: String
let contents: ImageEditorContents
required init(contents: ImageEditorContents) {
self.operationId = UUID().uuidString
self.contents = contents
}
}
// MARK: -
@objc
public protocol ImageEditorModelObserver: class {
// Used for large changes to the model, when the entire
// model should be reloaded.
func imageEditorModelDidChange(before: ImageEditorContents,
after: ImageEditorContents)
// Used for small narrow changes to the model, usually
// to a single item.
func imageEditorModelDidChange(changedItemIds: [String])
}
// MARK: -
@objc
public class ImageEditorModel: NSObject {
@objc
public let srcImagePath: String
@objc
public let srcImageSizePixels: CGSize
private var contents: ImageEditorContents
private var transform: ImageEditorTransform
private var undoStack = [ImageEditorOperation]()
private var redoStack = [ImageEditorOperation]()
// We don't want to allow editing of images if:
//
// * They are invalid.
// * We can't determine their size / aspect-ratio.
@objc
public required init(srcImagePath: String) throws {
self.srcImagePath = srcImagePath
let srcFileName = (srcImagePath as NSString).lastPathComponent
let srcFileExtension = (srcFileName as NSString).pathExtension
guard let mimeType = MIMETypeUtil.mimeType(forFileExtension: srcFileExtension) else {
Logger.error("Couldn't determine MIME type for file.")
throw ImageEditorError.invalidInput
}
guard MIMETypeUtil.isImage(mimeType),
!MIMETypeUtil.isAnimated(mimeType) else {
Logger.error("Invalid MIME type: \(mimeType).")
throw ImageEditorError.invalidInput
}
let srcImageSizePixels = NSData.imageSize(forFilePath: srcImagePath, mimeType: mimeType)
guard srcImageSizePixels.width > 0, srcImageSizePixels.height > 0 else {
Logger.error("Couldn't determine image size.")
throw ImageEditorError.invalidInput
}
self.srcImageSizePixels = srcImageSizePixels
self.contents = ImageEditorContents()
self.transform = ImageEditorTransform.defaultTransform(srcImageSizePixels: srcImageSizePixels)
super.init()
}
public func renderOutput() -> UIImage? {
return ImageEditorCanvasView.renderForOutput(model: self, transform: currentTransform())
}
public func currentTransform() -> ImageEditorTransform {
return transform
}
@objc
public func isDirty() -> Bool {
if itemCount() > 0 {
return true
}
return transform != ImageEditorTransform.defaultTransform(srcImageSizePixels: srcImageSizePixels)
}
@objc
public func itemCount() -> Int {
return contents.itemCount()
}
@objc
public func items() -> [ImageEditorItem] {
return contents.items()
}
@objc
public func itemIds() -> [String] {
return contents.itemIds()
}
@objc
public func has(itemForId itemId: String) -> Bool {
return item(forId: itemId) != nil
}
@objc
public func item(forId itemId: String) -> ImageEditorItem? {
return contents.item(forId: itemId)
}
@objc
public func canUndo() -> Bool {
return !undoStack.isEmpty
}
@objc
public func canRedo() -> Bool {
return !redoStack.isEmpty
}
@objc
public func currentUndoOperationId() -> String? {
guard let operation = undoStack.last else {
return nil
}
return operation.operationId
}
// MARK: - Observers
private var observers = [Weak<ImageEditorModelObserver>]()
@objc
public func add(observer: ImageEditorModelObserver) {
observers.append(Weak(value: observer))
}
private func fireModelDidChange(before: ImageEditorContents,
after: ImageEditorContents) {
// We could diff here and yield a more narrow change event.
for weakObserver in observers {
guard let observer = weakObserver.value else {
continue
}
observer.imageEditorModelDidChange(before: before,
after: after)
}
}
private func fireModelDidChange(changedItemIds: [String]) {
// We could diff here and yield a more narrow change event.
for weakObserver in observers {
guard let observer = weakObserver.value else {
continue
}
observer.imageEditorModelDidChange(changedItemIds: changedItemIds)
}
}
// MARK: -
@objc
public func undo() {
guard let undoOperation = undoStack.popLast() else {
owsFailDebug("Cannot undo.")
return
}
let redoOperation = ImageEditorOperation(contents: contents)
redoStack.append(redoOperation)
let oldContents = self.contents
self.contents = undoOperation.contents
// We could diff here and yield a more narrow change event.
fireModelDidChange(before: oldContents, after: self.contents)
}
@objc
public func redo() {
guard let redoOperation = redoStack.popLast() else {
owsFailDebug("Cannot redo.")
return
}
let undoOperation = ImageEditorOperation(contents: contents)
undoStack.append(undoOperation)
let oldContents = self.contents
self.contents = redoOperation.contents
// We could diff here and yield a more narrow change event.
fireModelDidChange(before: oldContents, after: self.contents)
}
@objc
public func append(item: ImageEditorItem) {
performAction({ (oldContents) in
let newContents = oldContents.clone()
newContents.append(item: item)
return newContents
}, changedItemIds: [item.itemId])
}
@objc
public func replace(item: ImageEditorItem,
suppressUndo: Bool = false) {
performAction({ (oldContents) in
let newContents = oldContents.clone()
newContents.replace(item: item)
return newContents
}, changedItemIds: [item.itemId],
suppressUndo: suppressUndo)
}
@objc
public func remove(item: ImageEditorItem) {
performAction({ (oldContents) in
let newContents = oldContents.clone()
newContents.remove(item: item)
return newContents
}, changedItemIds: [item.itemId])
}
@objc
public func replace(transform: ImageEditorTransform) {
self.transform = transform
// The contents haven't changed, but this event prods the
// observers to reload everything, which is necessary if
// the transform changes.
fireModelDidChange(before: self.contents, after: self.contents)
}
// MARK: - Temp Files
private var temporaryFilePaths = [String]()
@objc
public func temporaryFilePath(withFileExtension fileExtension: String) -> String {
AssertIsOnMainThread()
let filePath = OWSFileSystem.temporaryFilePath(withFileExtension: fileExtension)
temporaryFilePaths.append(filePath)
return filePath
}
deinit {
AssertIsOnMainThread()
let temporaryFilePaths = self.temporaryFilePaths
DispatchQueue.global(qos: .background).async {
for filePath in temporaryFilePaths {
guard OWSFileSystem.deleteFile(filePath) else {
Logger.error("Could not delete temp file: \(filePath)")
continue
}
}
}
}
private func performAction(_ action: (ImageEditorContents) -> ImageEditorContents,
changedItemIds: [String]?,
suppressUndo: Bool = false) {
if !suppressUndo {
let undoOperation = ImageEditorOperation(contents: contents)
undoStack.append(undoOperation)
redoStack.removeAll()
}
let oldContents = self.contents
let newContents = action(oldContents)
contents = newContents
if let changedItemIds = changedItemIds {
fireModelDidChange(changedItemIds: changedItemIds)
} else {
fireModelDidChange(before: oldContents,
after: self.contents)
}
}
// MARK: - Utilities
// Returns nil on error.
private class func crop(imagePath: String,
unitCropRect: CGRect) -> UIImage? {
// TODO: Do we want to render off the main thread?
AssertIsOnMainThread()
guard let srcImage = UIImage(contentsOfFile: imagePath) else {
owsFailDebug("Could not load image")
return nil
}
let srcImageSize = srcImage.size
// Convert from unit coordinates to src image coordinates.
let cropRect = CGRect(x: round(unitCropRect.origin.x * srcImageSize.width),
y: round(unitCropRect.origin.y * srcImageSize.height),
width: round(unitCropRect.size.width * srcImageSize.width),
height: round(unitCropRect.size.height * srcImageSize.height))
guard cropRect.origin.x >= 0,
cropRect.origin.y >= 0,
cropRect.origin.x + cropRect.size.width <= srcImageSize.width,
cropRect.origin.y + cropRect.size.height <= srcImageSize.height else {
owsFailDebug("Invalid crop rectangle.")
return nil
}
guard cropRect.size.width > 0,
cropRect.size.height > 0 else {
// Not an error; indicates that the user tapped rather
// than dragged.
Logger.warn("Empty crop rectangle.")
return nil
}
let hasAlpha = NSData.hasAlpha(forValidImageFilePath: imagePath)
UIGraphicsBeginImageContextWithOptions(cropRect.size, !hasAlpha, srcImage.scale)
defer { UIGraphicsEndImageContext() }
guard let context = UIGraphicsGetCurrentContext() else {
owsFailDebug("context was unexpectedly nil")
return nil
}
context.interpolationQuality = .high
// Draw source image.
let dstFrame = CGRect(origin: CGPointInvert(cropRect.origin), size: srcImageSize)
srcImage.draw(in: dstFrame)
let dstImage = UIGraphicsGetImageFromCurrentImageContext()
if dstImage == nil {
owsFailDebug("could not generate dst image.")
}
return dstImage
}
}
| gpl-3.0 | f489690275fe819aa7ace7b842298606 | 30.359331 | 105 | 0.619026 | 5.345679 | false | false | false | false |
brentsimmons/Frontier | BeforeTheRename/FrontierVerbs/FrontierVerbsTests/Math.swift | 1 | 3701 | //
// Math.swift
// FrontierVerbs
//
// Created by Brent Simmons on 4/23/17.
// Copyright © 2017 Ranchero Software. All rights reserved.
//
import XCTest
@testable import FrontierVerbs
import FrontierData
class Math: XCTestCase, VerbAppDelegate {
func testMin() {
var params = VerbParams([true, false])
var result = try! MathVerbs.evaluate("min", params, self)
if let oneResult = result as? Bool {
XCTAssertTrue(oneResult == false)
}
else {
XCTAssert(false, "Result must be a Bool")
}
params = VerbParams([5, true])
result = try! MathVerbs.evaluate("min", params, self)
if let oneResult = result as? Bool {
XCTAssertTrue(oneResult == true)
}
else {
XCTAssert(false, "Result must be a Bool")
}
params = VerbParams([5, 1000.384])
result = try! MathVerbs.evaluate("min", params, self)
if let oneResult = result as? Int {
XCTAssertTrue(oneResult == 5)
}
else {
XCTAssert(false, "Result must be an Int")
}
params = VerbParams(["foo", "apples"])
result = try! MathVerbs.evaluate("min", params, self)
if let oneResult = result as? String {
XCTAssertTrue(oneResult == "apples")
}
else {
XCTAssert(false, "Result must be a String")
}
let d1 = Date(timeIntervalSince1970: 5000.5)
let d2 = Date(timeIntervalSince1904: 5000.5)
params = VerbParams([d1, d2])
result = try! MathVerbs.evaluate("min", params, self)
if let oneResult = result as? Date {
XCTAssertTrue(oneResult == d2)
}
else {
XCTAssert(false, "Result must be a Date")
}
}
func testMax() {
var params = VerbParams([true, false])
var result = try! MathVerbs.evaluate("max", params, self)
if let oneResult = result as? Bool {
XCTAssertTrue(oneResult == true)
}
else {
XCTAssert(false, "Result must be a Bool")
}
params = VerbParams([5, true])
result = try! MathVerbs.evaluate("max", params, self)
if let oneResult = result as? Int {
XCTAssertTrue(oneResult == 5)
}
else {
XCTAssert(false, "Result must be an Int")
}
params = VerbParams([5, 1000.384])
result = try! MathVerbs.evaluate("max", params, self)
if let oneResult = result as? Double {
XCTAssertTrue(oneResult == 1000.384)
}
else {
XCTAssert(false, "Result must be a Double")
}
params = VerbParams(["foo", "apples"])
result = try! MathVerbs.evaluate("max", params, self)
if let oneResult = result as? String {
XCTAssertTrue(oneResult == "foo")
}
else {
XCTAssert(false, "Result must be a String")
}
let d1 = Date(timeIntervalSince1970: 5000.5)
let d2 = Date(timeIntervalSince1904: 5000.5)
params = VerbParams([d1, d2])
result = try! MathVerbs.evaluate("max", params, self)
if let oneResult = result as? Date {
XCTAssertTrue(oneResult == d1)
}
else {
XCTAssert(false, "Result must be a Date")
}
}
func testSqrt() {
var params = VerbParams([4])
var result = try! MathVerbs.evaluate("sqrt", params, self)
if let oneResult = result as? Double {
XCTAssertTrue(oneResult == 2.0)
}
else {
XCTAssert(false, "Result must be a Double")
}
let largeishNumber = 239845874
params = VerbParams([largeishNumber * largeishNumber])
result = try! MathVerbs.evaluate("sqrt", params, self)
if let oneResult = result as? Double {
XCTAssertTrue(oneResult == Double(largeishNumber))
}
else {
XCTAssert(false, "Result must be a Double")
}
let largeishDouble = 239845.874
params = VerbParams([largeishDouble * largeishDouble])
result = try! MathVerbs.evaluate("sqrt", params, self)
if let oneResult = result as? Double {
XCTAssertTrue(oneResult == largeishDouble)
}
else {
XCTAssert(false, "Result must be a Double")
}
}
}
| gpl-2.0 | 6218247128c62d2ec7f24853bc07ff85 | 24.170068 | 60 | 0.661622 | 3.372835 | false | false | false | false |
a2/Gulliver | Gulliver Tests/Source/SourceKindSpec.swift | 1 | 4524 | import AddressBook
import Gulliver
import Nimble
import Quick
class SortKindSpec: QuickSpec {
override func spec() {
describe("Local") {
it("has the correct rawValue") {
let correctValue: ABSourceType = numericCast(kABSourceTypeLocal)
expect(SourceKind.Local.rawValue) == correctValue
}
it("can be created with an ABSourceType value") {
let kind = SourceKind(rawValue: numericCast(kABSourceTypeLocal))
expect(kind).notTo(beNil())
expect(kind) == SourceKind.Local
}
it("is not searchable") {
expect(SourceKind.Local.isSearchable) == false
}
}
describe("Exchange") {
it("has the correct rawValue") {
let correctValue: ABSourceType = numericCast(kABSourceTypeExchange)
expect(SourceKind.Exchange.rawValue) == correctValue
}
it("can be created with an ABSourceType value") {
let kind = SourceKind(rawValue: numericCast(kABSourceTypeExchange))
expect(kind).notTo(beNil())
expect(kind) == SourceKind.Exchange
}
it("is not searchable") {
expect(SourceKind.Exchange.isSearchable) == false
}
}
describe("ExchangeGAL") {
it("has the correct rawValue") {
let correctValue: ABSourceType = numericCast(kABSourceTypeExchangeGAL)
expect(SourceKind.ExchangeGAL.rawValue) == correctValue
}
it("can be created with an ABSourceType value") {
let kind = SourceKind(rawValue: numericCast(kABSourceTypeExchangeGAL))
expect(kind).notTo(beNil())
expect(kind) == SourceKind.ExchangeGAL
}
it("is searchable") {
expect(SourceKind.ExchangeGAL.isSearchable) == true
}
}
describe("MobileMe") {
it("has the correct rawValue") {
let correctValue: ABSourceType = numericCast(kABSourceTypeMobileMe)
expect(SourceKind.MobileMe.rawValue) == correctValue
}
it("can be created with an ABSourceType value") {
let kind = SourceKind(rawValue: numericCast(kABSourceTypeMobileMe))
expect(kind).notTo(beNil())
expect(kind) == SourceKind.MobileMe
}
it("is not searchable") {
expect(SourceKind.MobileMe.isSearchable) == false
}
}
describe("LDAP") {
it("has the correct rawValue") {
let correctValue: ABSourceType = numericCast(kABSourceTypeLDAP)
expect(SourceKind.LDAP.rawValue) == correctValue
}
it("can be created with an ABSourceType value") {
let kind = SourceKind(rawValue: numericCast(kABSourceTypeLDAP))
expect(kind).notTo(beNil())
expect(kind) == SourceKind.LDAP
}
it("is searchable") {
expect(SourceKind.LDAP.isSearchable) == true
}
}
describe("CardDAV") {
it("has the correct rawValue") {
let correctValue: ABSourceType = numericCast(kABSourceTypeCardDAV)
expect(SourceKind.CardDAV.rawValue) == correctValue
}
it("can be created with an ABSourceType value") {
let kind = SourceKind(rawValue: numericCast(kABSourceTypeCardDAV))
expect(kind).notTo(beNil())
expect(kind) == SourceKind.CardDAV
}
it("is not searchable") {
expect(SourceKind.CardDAV.isSearchable) == false
}
}
describe("CardDAVSearch") {
it("has the correct rawValue") {
let correctValue: ABSourceType = numericCast(kABSourceTypeCardDAVSearch)
expect(SourceKind.CardDAVSearch.rawValue) == correctValue
}
it("can be created with an ABSourceType value") {
let kind = SourceKind(rawValue: numericCast(kABSourceTypeCardDAVSearch))
expect(kind).notTo(beNil())
expect(kind) == SourceKind.CardDAVSearch
}
it("is searchable") {
expect(SourceKind.CardDAVSearch.isSearchable) == true
}
}
}
}
| mit | 55fc345dcc12ca902aa7fb6d941bc43d | 34.622047 | 88 | 0.547745 | 5.807445 | false | false | false | false |
tinypass/piano-sdk-for-ios | PianoAPI/API/OauthAPI.swift | 1 | 1995 | import Foundation
@objc(PianoAPIOauthAPI)
public class OauthAPI: NSObject {
/// OAuth 2.0 authorize
/// - Parameters:
/// - clientId: Client ID of OAuth authorize
/// - clientSecret: Client secret of OAuth authorize
/// - code: OAuth code of OAuth authorize
/// - refreshToken: OAuth refresh token of OAuth authorize
/// - grantType: Grant type of OAuth authorize
/// - redirectUri: Redirect URI of OAuth authorize
/// - username: Username
/// - password: Password
/// - state: State
/// - deviceId: Device ID
/// - callback: Operation callback
@objc public func authToken(
clientId: String,
clientSecret: String? = nil,
code: String? = nil,
refreshToken: String? = nil,
grantType: String? = nil,
redirectUri: String? = nil,
username: String? = nil,
password: String? = nil,
state: String? = nil,
deviceId: String? = nil,
completion: @escaping (OAuthToken?, Error?) -> Void) {
guard let client = PianoAPI.shared.client else {
completion(nil, PianoAPIError("PianoAPI not initialized"))
return
}
var params = [String:String]()
params["client_id"] = clientId
if let v = clientSecret { params["client_secret"] = v }
if let v = code { params["code"] = v }
if let v = refreshToken { params["refresh_token"] = v }
if let v = grantType { params["grant_type"] = v }
if let v = redirectUri { params["redirect_uri"] = v }
if let v = username { params["username"] = v }
if let v = password { params["password"] = v }
if let v = state { params["state"] = v }
if let v = deviceId { params["device_id"] = v }
client.request(
path: "/api/v3/oauth/authToken",
method: PianoAPI.HttpMethod.from("POST"),
params: params,
completion: completion
)
}
}
| apache-2.0 | 1b148f384ddb574d2fb6702942a6dbae | 35.944444 | 70 | 0.565414 | 4.299569 | false | false | false | false |
isaced/NSPress | Sources/App/Tags/TruncatecharsTag.swift | 1 | 479 | import Leaf
// class Truncatechars: BasicTag {
// let name = "Truncatechars"
// func run(arguments: [Argument]) throws -> Node? {
// guard arguments.count == 2, let string = arguments.first?.value?.string, let maxLength = arguments[1].value?.int else {
// return arguments.first?.value
// }
// let startIndex = string.index(string.startIndex, offsetBy: maxLength)
// return Node(string.substring(to: startIndex))
// }
// }
| mit | df5e8c9cb5a7235458708b2c013fae1a | 35.846154 | 130 | 0.620042 | 3.832 | false | false | false | false |
gaowanli/PinGo | PinGo/PinGo/Discover/ImageCarouselView.swift | 1 | 4223 | //
// ImageCarouselView.swift
// PinGo
//
// Created by GaoWanli on 16/2/1.
// Copyright © 2016年 GWL. All rights reserved.
//
import UIKit
private let kCellReuseIdentifier = "imageCarouselCell"
class ImageCarouselView: UIView {
@IBOutlet fileprivate weak var collectionView: UICollectionView!
@IBOutlet fileprivate weak var layout: UICollectionViewFlowLayout!
@IBOutlet fileprivate weak var pageControl: UIPageControl!
fileprivate var kNumberOfSections = 0
fileprivate var timer: Timer?
var bannerList: [Banner]? {
didSet {
collectionView.reloadData()
if (bannerList?.count)! <= 1 {
collectionView.isScrollEnabled = false
kNumberOfSections = 1
}else {
collectionView.isScrollEnabled = true
kNumberOfSections = 100
collectionViewScrollToCenter()
startTimer()
}
pageControl.numberOfPages = bannerList?.count ?? 0
pageControl.currentPage = 0
}
}
override func awakeFromNib() {
super.awakeFromNib()
collectionView.register(UINib.nibWithName("ImageCarouselCell"), forCellWithReuseIdentifier: kCellReuseIdentifier)
}
override func layoutSubviews() {
super.layoutSubviews()
layout.itemSize = bounds.size
}
fileprivate func collectionViewScrollToCenter() {
guard bannerList != nil else {
return
}
collectionView.scrollToItem(at: IndexPath(item: 0, section: Int(kNumberOfSections / 2)), at: .left, animated: false)
}
func scrollImage() {
let offsetX = collectionView.contentOffset.x
let toOffsetX = offsetX + collectionView.bounds.width
if toOffsetX < collectionView.contentSize.width {
collectionView.setContentOffset(CGPoint(x: toOffsetX, y: 0), animated: true)
}else {
collectionViewScrollToCenter()
}
}
func startTimer() {
guard timer == nil else {
return
}
timer = Timer.scheduledTimer(timeInterval: 3.0, target: self, selector: #selector(ImageCarouselView.scrollImage), userInfo: nil, repeats: true)
RunLoop.current.add(timer!, forMode: RunLoopMode.commonModes)
}
func stopTimer() {
timer?.invalidate()
timer = nil
}
class func loadFromNib() -> ImageCarouselView {
return Bundle.main.loadNibNamed("ImageCarousel", owner: self, options: nil)!.last as! ImageCarouselView
}
}
extension ImageCarouselView: UICollectionViewDataSource {
func numberOfSections(in collectionView: UICollectionView) -> Int {
return kNumberOfSections
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return bannerList?.count ?? 0
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kCellReuseIdentifier, for: indexPath) as! ImageCarouselCell
cell.bannner = bannerList![indexPath.item]
return cell
}
}
extension ImageCarouselView: UICollectionViewDelegate {
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
stopTimer()
}
func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
startTimer()
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let page = Int(scrollView.contentOffset.x / scrollView.bounds.width + 0.5) % bannerList!.count
pageControl.currentPage = page
}
}
class ImageCarouselCell: UICollectionViewCell {
@IBOutlet fileprivate weak var imageView: UIImageView!
var bannner: Banner? {
didSet {
if let urlStr = bannner?.imageUrl {
if let url = URL(string: urlStr) {
imageView.kf.setImage(with: url)
}
}
}
}
}
| mit | fd7cdc79424ced3bece08ec690c36304 | 29.57971 | 151 | 0.626303 | 5.619174 | false | false | false | false |
nerdycat/Cupcake | Cupcake/Color.swift | 1 | 3339 | //
// Color.swift
// Cupcake
//
// Created by nerdycat on 2017/3/17.
// Copyright © 2017 nerdycat. All rights reserved.
//
import UIKit
/**
* Create UIColor Object.
* Color argument can be:
1) UIColor object
2) UIImage object, return a pattern image color
3) "red", "green", "blue", "clear", etc. (any system color)
5) "random": randomColor
6) "255,0,0": RGB color
7) "#FF0000" or "0xF00": Hex color
* All the string representation can have an optional alpha value.
* Usages:
Color([UIColor redColor])
Color("red")
Color("red,0.1") //with alpha
Color("255,0,0)
Color("255,0,0,1") //with alpha
Color("#FF0000")
Color("#F00,0.1") //with alpha
Color("random,0.5")
Color(Img("image")) //using image
...
*/
public func Color(_ any: Any?) -> UIColor? {
if any == nil {
return nil
}
if let color = any as? UIColor {
return color;
}
if let image = any as? UIImage {
return UIColor(patternImage: image)
}
guard any is String else {
return nil
}
var alpha: CGFloat = 1
var components = (any as! String).components(separatedBy: ",")
if components.count == 2 || components.count == 4 {
alpha = min(CGFloat(Float(components.last!) ?? 1), 1)
components.removeLast()
}
var r: Int?, g: Int? , b: Int?
if components.count == 1 {
let string = components.first!
let sel = NSSelectorFromString(string + "Color")
//system color
if let color = UIColor.cpk_safePerform(selector: sel) as? UIColor {
return (alpha == 1 ? color : color.withAlphaComponent(alpha))
}
if string == "random" {
// generate cryptographically secure random bytes
// avoid warnings reported by security scans like Veracode
// https://developer.apple.com/documentation/security/1399291-secrandomcopybytes
var bytes = [UInt8](repeating: 0, count: 3)
let status = SecRandomCopyBytes(kSecRandomDefault, bytes.count, &bytes)
if status == errSecSuccess {
r = Int(bytes[0])
g = Int(bytes[1])
b = Int(bytes[2])
} else {
r = 0
g = 0
b = 0
}
} else if string.hasPrefix("#") {
if string.cpk_length() == 4 {
r = Int(string.subAt(1), radix:16)! * 17
g = Int(string.subAt(2), radix:16)! * 17
b = Int(string.subAt(3), radix:16)! * 17
} else if string.cpk_length() == 7 {
r = Int(string.subAt(1...2), radix:16)
g = Int(string.subAt(3...4), radix:16)
b = Int(string.subAt(5...6), radix:16)
}
}
} else if components.count == 3 {
r = Int(components[0])
g = Int(components[1])
b = Int(components[2])
}
if r != nil && g != nil && b != nil {
return UIColor(red: CGFloat(r!) / 255.0,
green: CGFloat(g!) / 255.0,
blue: CGFloat(b!) / 255.0,
alpha: alpha)
}
return nil
}
| mit | 4c7c36d20c7f37d2e2189b4dc143f115 | 27.529915 | 92 | 0.501198 | 3.954976 | false | false | false | false |
peferron/algo | EPI/Greedy Algorithms and Invariants/Compute the maximum water trapped by a pair of vertical lines/swift/main.swift | 1 | 636 | public func maxPair(lineHeights: [Int]) -> (Int, Int) {
var start = 0
var end = lineHeights.count - 1
var bestPair = (start, end)
var bestQuantity = 0
while start < end {
let startHeight = lineHeights[start]
let endHeight = lineHeights[end]
let quantity = (end - start) * min(startHeight, endHeight)
if quantity > bestQuantity {
bestPair = (start, end)
bestQuantity = quantity
}
if startHeight <= endHeight {
start += 1
}
if startHeight >= endHeight {
end -= 1
}
}
return bestPair
}
| mit | a762c2c2054ac649572fd0b729673c8a | 22.555556 | 66 | 0.536164 | 4.356164 | false | false | false | false |
mssun/passforios | pass/Controllers/PasswordNavigationViewController.swift | 2 | 20180 | //
// PasswordNavigationViewController.swift
// pass
//
// Created by Mingshen Sun on 17/1/2021.
// Copyright © 2021 Bob Sun. All rights reserved.
//
import passKit
import SVProgressHUD
import UIKit
import UserNotifications
extension UIStoryboard {
static var passwordNavigationViewController: PasswordNavigationViewController {
UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "passwordNavigation") as! PasswordNavigationViewController
}
}
class PasswordNavigationViewController: UIViewController {
@IBOutlet var tableView: UITableView!
var dataSource: PasswordNavigationDataSource?
var parentPasswordEntity: PasswordEntity?
var viewingUnsyncedPasswords = false
var tapTabBarTime: TimeInterval = 0
lazy var passwordManager = PasswordManager(viewController: self)
lazy var searchController: UISearchController = {
let uiSearchController = UISearchController(searchResultsController: nil)
uiSearchController.searchBar.isTranslucent = true
uiSearchController.obscuresBackgroundDuringPresentation = false
uiSearchController.searchBar.sizeToFit()
uiSearchController.searchBar.returnKeyType = .done
if #available(iOS 13.0, *) {
uiSearchController.searchBar.searchTextField.clearButtonMode = .whileEditing
}
return uiSearchController
}()
lazy var searchBar: UISearchBar = self.searchController.searchBar
lazy var refreshControl: UIRefreshControl = {
let refreshControl = UIRefreshControl()
refreshControl.addTarget(self, action: #selector(handleRefreshControl), for: .valueChanged)
return refreshControl
}()
lazy var addPasswordUIBarButtonItem: UIBarButtonItem = {
var addPasswordUIBarButtonItem = UIBarButtonItem()
if #available(iOS 13.0, *) {
let addPasswordButton = UIButton(type: .system)
let plusImage = UIImage(systemName: "plus.circle", withConfiguration: UIImage.SymbolConfiguration(weight: .regular))
addPasswordButton.setImage(plusImage, for: .normal)
addPasswordButton.addTarget(self, action: #selector(self.addPasswordAction), for: .touchDown)
addPasswordUIBarButtonItem.customView = addPasswordButton
} else {
addPasswordUIBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(self.addPasswordAction))
}
return addPasswordUIBarButtonItem
}()
lazy var gestureRecognizer: UILongPressGestureRecognizer = {
let recognizer = UILongPressGestureRecognizer(target: self, action: #selector(longPressAction))
recognizer.minimumPressDuration = 0.6
return recognizer
}()
override func viewDidLoad() {
super.viewDidLoad()
searchBar.delegate = self
configureTableView(in: parentPasswordEntity)
configureNotification()
configureSearchBar()
configureNavigationBar()
requestNotificationPermission()
}
private func requestNotificationPermission() {
// Ask for permission to receive notifications
let notificationCenter = UNUserNotificationCenter.current()
let permissionOptions = UNAuthorizationOptions(arrayLiteral: .alert)
notificationCenter.requestAuthorization(options: permissionOptions) { _, _ in }
// Register notification action
let copyAction = UNNotificationAction(
identifier: Globals.otpNotificationCopyAction,
title: "CopyToPasteboard".localize(),
options: UNNotificationActionOptions(rawValue: 0)
)
let otpCategory = UNNotificationCategory(
identifier: Globals.otpNotificationCategory,
actions: [copyAction],
intentIdentifiers: [],
hiddenPreviewsBodyPlaceholder: "",
options: []
)
notificationCenter.setNotificationCategories([otpCategory])
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
tabBarController?.delegate = self
configureNavigationItem()
configureTabBarItem()
configureNavigationBar()
}
private func configureSearchBar() {
if Defaults.isShowFolderOn {
searchBar.scopeButtonTitles = SearchBarScope.allCases.map(\.localizedName)
} else {
searchBar.scopeButtonTitles = nil
}
}
private func configureTableView(in dir: PasswordEntity?) {
configureTableViewDataSource(in: dir, isShowFolder: Defaults.isShowFolderOn)
tableView.addGestureRecognizer(gestureRecognizer)
tableView.delegate = self
let atribbutedTitle = "LastSynced".localize() + ": \(PasswordStore.shared.lastSyncedTimeString)"
refreshControl.attributedTitle = NSAttributedString(string: atribbutedTitle)
tableView.refreshControl = refreshControl
}
private func configureTableViewDataSource(in dir: PasswordEntity?, isShowFolder: Bool) {
var passwordTableEntries: [PasswordTableEntry]
if isShowFolder {
passwordTableEntries = PasswordStore.shared.fetchPasswordEntityCoreData(parent: dir).compactMap { PasswordTableEntry($0) }
} else {
passwordTableEntries = PasswordStore.shared.fetchPasswordEntityCoreData(withDir: false).compactMap { PasswordTableEntry($0) }
}
dataSource = PasswordNavigationDataSource(entries: passwordTableEntries)
tableView.dataSource = dataSource
}
private func configureTabBarItem() {
guard let tabBarItem = navigationController?.tabBarItem else {
return
}
let numberOfLocalCommits = PasswordStore.shared.numberOfLocalCommits
if numberOfLocalCommits != 0 {
tabBarItem.badgeValue = "\(numberOfLocalCommits)"
} else {
tabBarItem.badgeValue = nil
}
}
private func configureNavigationItem() {
if isRootViewController() {
navigationItem.largeTitleDisplayMode = .automatic
navigationItem.title = "PasswordStore".localize()
} else {
navigationItem.largeTitleDisplayMode = .never
navigationItem.title = parentPasswordEntity?.getName()
}
if viewingUnsyncedPasswords {
navigationItem.title = "Unsynced"
}
navigationItem.hidesSearchBarWhenScrolling = false
navigationItem.rightBarButtonItem = addPasswordUIBarButtonItem
navigationItem.searchController = searchController
}
private func configureNavigationBar() {
guard let navigationBar = navigationController?.navigationBar else {
return
}
guard PasswordStore.shared.numberOfLocalCommits != 0 else {
return
}
let tapNavigationBarGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(didTapNavigationBar))
tapNavigationBarGestureRecognizer.cancelsTouchesInView = false
navigationBar.addGestureRecognizer(tapNavigationBarGestureRecognizer)
}
private func isRootViewController() -> Bool {
navigationController?.viewControllers.count == 1
}
private func configureNotification() {
let notificationCenter = NotificationCenter.default
// Reset the data table if some password (maybe another one) has been updated.
notificationCenter.addObserver(self, selector: #selector(actOnReloadTableViewRelatedNotification), name: .passwordStoreUpdated, object: nil)
// Reset the data table if the disaply settings have been changed.
notificationCenter.addObserver(self, selector: #selector(actOnReloadTableViewRelatedNotification), name: .passwordDisplaySettingChanged, object: nil)
// Search entrypoint for home screen quick action.
notificationCenter.addObserver(self, selector: #selector(actOnSearchNotification), name: .passwordSearch, object: nil)
// A Siri shortcut can change the state of the app in the background. Hence, reload when opening the app.
notificationCenter.addObserver(self, selector: #selector(actOnReloadTableViewRelatedNotification), name: UIApplication.willEnterForegroundNotification, object: nil)
}
@objc
func addPasswordAction(_: Any?) {
if shouldPerformSegue(withIdentifier: "addPasswordSegue", sender: self) {
performSegue(withIdentifier: "addPasswordSegue", sender: self)
}
}
@objc
func didTapNavigationBar(_ sender: UITapGestureRecognizer) {
let location = sender.location(in: navigationController?.navigationBar)
let hitView = navigationController?.navigationBar.hitTest(location, with: nil)
guard String(describing: hitView).contains("UINavigationBarContentView") else {
return
}
let alertController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
let allAction = UIAlertAction(title: "All Passwords", style: .default) { _ in
self.configureTableView(in: self.parentPasswordEntity)
self.tableView.reloadData()
self.viewingUnsyncedPasswords = false
self.configureNavigationItem()
}
let unsyncedAction = UIAlertAction(title: "Unsynced Passwords", style: .default) { _ in
self.dataSource?.showUnsyncedTableEntries()
self.tableView.reloadData()
self.viewingUnsyncedPasswords = true
self.configureNavigationItem()
}
let cancelAction = UIAlertAction.cancel()
alertController.addAction(allAction)
alertController.addAction(unsyncedAction)
alertController.addAction(cancelAction)
present(alertController, animated: true)
}
@objc
func longPressAction(_ gesture: UILongPressGestureRecognizer) {
if gesture.state == UIGestureRecognizer.State.began {
let touchPoint = gesture.location(in: tableView)
if let indexPath = tableView.indexPathForRow(at: touchPoint) {
guard let dataSource = dataSource else {
return
}
let passwordTableEntry = dataSource.getPasswordTableEntry(at: indexPath)
if passwordTableEntry.isDir {
return
}
passwordManager.providePasswordPasteboard(with: passwordTableEntry.passwordEntity.getPath())
}
}
}
@objc
func actOnSearchNotification() {
searchBar.becomeFirstResponder()
}
@objc
func handleRefreshControl() {
syncPasswords()
DispatchQueue.main.async {
self.refreshControl.endRefreshing()
}
}
}
extension PasswordNavigationViewController: UITableViewDelegate {
func tableView(_: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
guard let dataSource = dataSource else {
return
}
let entry = dataSource.getPasswordTableEntry(at: indexPath)
if entry.isDir {
showDir(in: entry)
} else {
showPasswordDetail(at: entry)
}
searchController.isActive = false
}
func showDir(in entry: PasswordTableEntry) {
let passwordNavigationViewController = UIStoryboard.passwordNavigationViewController
passwordNavigationViewController.parentPasswordEntity = entry.passwordEntity
navigationController?.pushViewController(passwordNavigationViewController, animated: true)
}
func showPasswordDetail(at entry: PasswordTableEntry) {
let segueIdentifier = "showPasswordDetail"
let sender = entry.passwordEntity
if shouldPerformSegue(withIdentifier: segueIdentifier, sender: sender) {
performSegue(withIdentifier: segueIdentifier, sender: sender)
}
}
func tableView(_: UITableView, estimatedHeightForRowAt _: IndexPath) -> CGFloat {
UITableView.automaticDimension
}
func tableView(_: UITableView, heightForRowAt _: IndexPath) -> CGFloat {
UITableView.automaticDimension
}
}
extension PasswordNavigationViewController {
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "showPasswordDetail" {
if let viewController = segue.destination as? PasswordDetailTableViewController {
viewController.passwordEntity = sender as? PasswordEntity
}
} else if segue.identifier == "addPasswordSegue" {
if let navController = segue.destination as? UINavigationController,
let viewController = navController.topViewController as? AddPasswordTableViewController,
let path = parentPasswordEntity?.getPath() {
viewController.defaultDirPrefix = "\(path)/"
}
}
}
override func shouldPerformSegue(withIdentifier identifier: String, sender _: Any?) -> Bool {
if identifier == "showPasswordDetail" {
guard Defaults.isYubiKeyEnabled || PGPAgent.shared.isPrepared else {
Utils.alert(title: "CannotShowPassword".localize(), message: "PgpKeyNotSet.".localize(), controller: self)
return false
}
} else if identifier == "addPasswordSegue" {
guard PGPAgent.shared.isPrepared, PasswordStore.shared.storeRepository != nil else {
Utils.alert(title: "CannotAddPassword".localize(), message: "MakeSurePgpAndGitProperlySet.".localize(), controller: self)
return false
}
}
return true
}
@IBAction
private func cancelAddPassword(segue _: UIStoryboardSegue) {}
@IBAction
private func cancelEditPassword(segue _: UIStoryboardSegue) {}
@IBAction
private func saveEditPassword(segue _: UIStoryboardSegue) {}
@IBAction
private func saveAddPassword(segue: UIStoryboardSegue) {
if let controller = segue.source as? AddPasswordTableViewController {
passwordManager.addPassword(with: controller.password!)
}
}
}
extension PasswordNavigationViewController {
@objc
func actOnReloadTableViewRelatedNotification() {
DispatchQueue.main.async {
self.navigationController?.popToRootViewController(animated: true)
self.resetViews()
}
}
func resetViews() {
configureTableView(in: parentPasswordEntity)
tableView.reloadData()
configureNavigationItem()
configureTabBarItem()
configureNavigationBar()
configureSearchBar()
}
}
extension PasswordNavigationViewController: UISearchBarDelegate {
func search(matching text: String) {
dataSource?.showTableEntries(matching: text)
tableView.reloadData()
}
func activateSearch(_ selectedScope: Int?) {
if selectedScope == SearchBarScope.all.rawValue {
configureTableViewDataSource(in: nil, isShowFolder: false)
} else {
configureTableViewDataSource(in: parentPasswordEntity, isShowFolder: true)
}
dataSource?.isSearchActive = true
tableView.reloadData()
}
func searchBar(_ searchBar: UISearchBar, selectedScopeButtonIndexDidChange selectedScope: Int) {
activateSearch(selectedScope)
search(matching: searchBar.text ?? "")
}
func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
if Defaults.searchDefault == .all {
searchBar.selectedScopeButtonIndex = SearchBarScope.all.rawValue
} else {
searchBar.selectedScopeButtonIndex = SearchBarScope.current.rawValue
}
activateSearch(searchBar.selectedScopeButtonIndex)
}
func searchBar(_: UISearchBar, textDidChange searchText: String) {
search(matching: searchText)
}
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
searchBar.resignFirstResponder()
}
func searchBarCancelButtonClicked(_: UISearchBar) {
cancelSearch()
}
func cancelSearch() {
configureTableView(in: parentPasswordEntity)
dataSource?.isSearchActive = false
tableView.reloadData()
}
}
extension PasswordNavigationViewController: UITabBarControllerDelegate {
func tabBarController(_: UITabBarController, didSelect viewController: UIViewController) {
if viewController == navigationController {
let currentTime = Date().timeIntervalSince1970
let duration = currentTime - tapTabBarTime
tapTabBarTime = currentTime
if duration < 0.35, tableView.numberOfSections > 0 {
let topIndexPath = IndexPath(row: 0, section: 0)
tableView.scrollToRow(at: topIndexPath, at: .bottom, animated: true)
tapTabBarTime = 0
}
}
}
}
extension PasswordNavigationViewController: PasswordAlertPresenter {
private func syncPasswords() {
guard PasswordStore.shared.repositoryExists() else {
DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(800)) {
Utils.alert(title: "Error".localize(), message: "NoPasswordStore.".localize(), controller: self, completion: nil)
}
return
}
SVProgressHUD.setDefaultMaskType(.black)
SVProgressHUD.setDefaultStyle(.light)
SVProgressHUD.show(withStatus: "SyncingPasswordStore".localize())
let keychain = AppKeychain.shared
var gitCredential: GitCredential {
GitCredential.from(
authenticationMethod: Defaults.gitAuthenticationMethod,
userName: Defaults.gitUsername,
keyStore: keychain
)
}
DispatchQueue.global(qos: .userInitiated).async { [unowned self] in
do {
let pullOptions = gitCredential.getCredentialOptions(passwordProvider: self.present)
try PasswordStore.shared.pullRepository(options: pullOptions) { git_transfer_progress, _ in
DispatchQueue.main.async {
SVProgressHUD.showProgress(Float(git_transfer_progress.pointee.received_objects) / Float(git_transfer_progress.pointee.total_objects), status: "PullingFromRemoteRepository".localize())
}
}
if PasswordStore.shared.numberOfLocalCommits > 0 {
let pushOptions = gitCredential.getCredentialOptions(passwordProvider: self.present)
try PasswordStore.shared.pushRepository(options: pushOptions) { current, total, _, _ in
DispatchQueue.main.async {
SVProgressHUD.showProgress(Float(current) / Float(total), status: "PushingToRemoteRepository".localize())
}
}
}
DispatchQueue.main.async {
SVProgressHUD.showSuccess(withStatus: "Done".localize())
SVProgressHUD.dismiss(withDelay: 1)
}
} catch {
gitCredential.delete()
DispatchQueue.main.async {
SVProgressHUD.dismiss()
let error = error as NSError
var message = error.localizedDescription
if let underlyingError = error.userInfo[NSUnderlyingErrorKey] as? NSError {
message = message | "UnderlyingError".localize(underlyingError.localizedDescription)
if underlyingError.localizedDescription.contains("WrongPassphrase".localize()) {
message = message | "RecoverySuggestion.".localize()
}
}
DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(800)) {
Utils.alert(title: "Error".localize(), message: message, controller: self, completion: nil)
}
}
}
}
}
}
| mit | bbbe4d0bd709e1b2dd19dcf6afa0e633 | 39.931034 | 208 | 0.665395 | 5.956021 | false | true | false | false |
josefdolezal/fit-cvut | BI-IOS/semester-project/What2Do/What2Do/Notify.swift | 1 | 763 | //
// Notification.swift
// What2Do
//
// Created by Josef Dolezal on 16/02/16.
// Copyright © 2016 Josef Dolezal. All rights reserved.
//
import Foundation
import UIKit
class Notify {
static func schedule(body: String, data:[String:String]? = nil, slider: String? = nil) {
let localNotification = UILocalNotification()
localNotification.fireDate = NSDate(timeIntervalSinceNow: 5)
localNotification.alertBody = "\(body)"
if let usrData = data {
localNotification.userInfo = usrData
}
if let action = slider {
localNotification.alertAction = action
}
UIApplication.sharedApplication().scheduleLocalNotification(localNotification)
}
}
| mit | fa0e340c582bff561337739d58c25024 | 26.214286 | 92 | 0.639108 | 4.980392 | false | false | false | false |
wireapp/wire-ios | Wire-iOS/Sources/UserInterface/Helpers/UIView+Zeta.swift | 1 | 4525 | //
// Wire
// Copyright (C) 2020 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
private let WireLastCachedKeyboardHeightKey = "WireLastCachedKeyboardHeightKey"
extension UIView {
/// Provides correct handling for animating alongside a keyboard animation
class func animate(withKeyboardNotification notification: Notification?,
in view: UIView,
delay: TimeInterval = 0,
animations: @escaping (_ keyboardFrameInView: CGRect) -> Void,
completion: ResultHandler? = nil) {
let keyboardFrame = self.keyboardFrame(in: view, forKeyboardNotification: notification)
if let currentFirstResponder = UIResponder.currentFirst {
let keyboardSize = CGSize(width: keyboardFrame.size.width, height: keyboardFrame.size.height - (currentFirstResponder.inputAccessoryView?.bounds.size.height ?? 0))
setLastKeyboardSize(keyboardSize)
}
let userInfo = notification?.userInfo
let animationLength: TimeInterval = (userInfo?[UIResponder.keyboardAnimationDurationUserInfoKey] as? NSNumber)?.doubleValue ?? 0
let animationCurve: AnimationCurve = AnimationCurve(rawValue: (userInfo?[UIResponder.keyboardAnimationCurveUserInfoKey] as AnyObject).intValue ?? 0) ?? .easeInOut
var animationOptions: UIView.AnimationOptions = .beginFromCurrentState
switch animationCurve {
case .easeIn:
animationOptions.insert(.curveEaseIn)
case .easeInOut:
animationOptions.insert(.curveEaseInOut)
case .easeOut:
animationOptions.insert(.curveEaseOut)
case .linear:
animationOptions.insert(.curveLinear)
default:
break
}
UIView.animate(withDuration: animationLength, delay: delay, options: animationOptions, animations: {
animations(keyboardFrame)
}, completion: completion)
}
class func setLastKeyboardSize(_ lastSize: CGSize) {
UserDefaults.standard.set(NSCoder.string(for: lastSize), forKey: WireLastCachedKeyboardHeightKey)
}
class var lastKeyboardSize: CGSize {
if let currentLastValue = UserDefaults.standard.object(forKey: WireLastCachedKeyboardHeightKey) as? String {
var keyboardSize = NSCoder.cgSize(for: currentLastValue)
// If keyboardSize value is clearly off we need to pull default value
if keyboardSize.height < 150 {
keyboardSize.height = KeyboardHeight.current
}
return keyboardSize
}
return CGSize(width: UIScreen.main.bounds.size.width, height: KeyboardHeight.current)
}
class func keyboardFrame(in view: UIView, forKeyboardNotification notification: Notification?) -> CGRect {
let userInfo = notification?.userInfo
return keyboardFrame(in: view, forKeyboardInfo: userInfo)
}
class func keyboardFrame(in view: UIView, forKeyboardInfo keyboardInfo: [AnyHashable: Any]?) -> CGRect {
let screenRect = keyboardInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect
let windowRect = view.window?.convert(screenRect ?? CGRect.zero, from: nil)
let viewRect = view.convert(windowRect ?? CGRect.zero, from: nil)
let intersection = viewRect.intersection(view.bounds)
return intersection
}
}
// MARK: - factory methods
extension UIView {
static func shieldView() -> UIView {
let loadedObjects = UINib(nibName: "LaunchScreen", bundle: nil).instantiate(withOwner: .none, options: .none)
let nibView = loadedObjects.first as! UIView
return nibView
}
}
extension UIVisualEffectView {
static func blurView() -> UIVisualEffectView {
let blurEffect = UIBlurEffect(style: .dark)
return UIVisualEffectView(effect: blurEffect)
}
}
| gpl-3.0 | 9e37a61c75b9606b82aeee160f2af5e2 | 38.347826 | 175 | 0.689503 | 5.201149 | false | false | false | false |
tbointeractive/bytes | Sources/bytes/Device.swift | 1 | 8411 | //
// Device.swift
// bytes
//
// Created by Cornelius Horstmann on 04.01.17.
// Copyright © 2017 TBO INTERACTIVE GmbH & Co. KG. All rights reserved.
//
#if canImport(UIKit)
import UIKit
import Foundation
/// The Device Struct holds important information about a Device.
public struct Device {
/// The platform name of the device i.e. "iPhone1,1" or "iPad3,6"
public let platform: String
/// The version number of the OS as String i.e. "1.2" or "9.4"
public let osVersion: String
public init(platform: String, osVersion: String) {
self.platform = platform
self.osVersion = osVersion
}
/// The current device.
static public let current = Device.currentDevice()
static private func currentDevice() -> Device {
var size = 0
sysctlbyname("hw.machine", nil, &size, nil, 0)
var machine = [CChar](repeating: 0, count: Int(size))
sysctlbyname("hw.machine", &machine, &size, nil, 0)
let platform = String(cString: machine)
let osVersion = UIDevice.current.systemVersion
return Device(platform: platform, osVersion: osVersion)
}
/// A human readable version of the platform name i.e. "iPhone 6 Plus" or "iPad Air 2 (WiFi)"
/// Or nil in case no human readable name was found.
public var humanReadablePlatform: String? {
switch platform {
// iPhone
case "iPhone1,1": return "iPhone 1G"
case "iPhone1,2": return "iPhone 3G"
case "iPhone2,1": return "iPhone 3GS"
case "iPhone3,1": return "iPhone 4"
case "iPhone3,2": return "iPhone 4 (Revision A)"
case "iPhone3,3": return "Verizon iPhone 4"
case "iPhone4,1": return "iPhone 4S"
case "iPhone5,1": return "iPhone 5 (GSM)"
case "iPhone5,2": return "iPhone 5 (GSM+CDMA)"
case "iPhone5,3": return "iPhone 5c (GSM)"
case "iPhone5,4": return "iPhone 5c (Global)"
case "iPhone6,1": return "iPhone 5s (GSM)"
case "iPhone6,2": return "iPhone 5s (Global)"
case "iPhone7,1": return "iPhone 6 Plus"
case "iPhone7,2": return "iPhone 6"
case "iPhone8,1": return "iPhone 6s"
case "iPhone8,2": return "iPhone 6s Plus"
case "iPhone8,4": return "iPhone SE"
case "iPhone9,1": return "iPhone 7 (GSM+CDMA)"
case "iPhone9,2": return "iPhone 7 Plus (GSM+CDMA)"
case "iPhone9,3": return "iPhone 7 (Global)"
case "iPhone9,4": return "iPhone 7 Plus (Global)"
case "iPhone10,1": return "iPhone 8 (GSM+CDMA)"
case "iPhone10,2": return "iPhone 8 Plus (GSM+CDMA)"
case "iPhone10,3": return "iPhone X (GSM+CDMA)"
case "iPhone10,4": return "iPhone 8 (Global)"
case "iPhone10,5": return "iPhone 8 Plus (Global)"
case "iPhone10,6": return "iPhone X (Global)"
case "iPhone11,2": return "iPhone XS"
case "iPhone11,4": return "iPhone XS Max (China)"
case "iPhone11,6": return "iPhone XS Max"
case "iPhone11,8": return "iPhone XR"
case "iPhone12,1": return "iPhone 11"
case "iPhone12,3": return "iPhone 11 Pro"
case "iPhone12,5": return "iPhone 11 Pro Max"
// iPod
case "iPod1,1": return "iPod Touch 1st Gen"
case "iPod2,1": return "iPod Touch 2nd Gen"
case "iPod3,1": return "iPod Touch 3rd Gen"
case "iPod4,1": return "iPod Touch 4th Gen"
case "iPod5,1": return "iPod Touch 5th Gen"
case "iPod7,1": return "iPod Touch 6th Gen"
case "iPod9,1": return "iPod Touch 7th Gen"
// iPad
case "iPad1,1": return "iPad 1"
case "iPad2,1": return "iPad 2 (WiFi)"
case "iPad2,2": return "iPad 2 (GSM)"
case "iPad2,3": return "iPad 2 (CDMA)"
case "iPad2,4": return "iPad 2 (WiFi)"
case "iPad2,5": return "iPad Mini 1 (WiFi)"
case "iPad2,6": return "iPad Mini 1 (GSM)"
case "iPad2,7": return "iPad Mini 1 (GSM+CDMA)"
case "iPad3,1": return "iPad 3 (WiFi)"
case "iPad3,2": return "iPad 3 (GSM+CDMA)"
case "iPad3,3": return "iPad 3 (GSM)"
case "iPad3,4": return "iPad 4 (WiFi)"
case "iPad3,5": return "iPad 4 (GSM)"
case "iPad3,6": return "iPad 4 (GSM+CDMA)"
case "iPad4,1": return "iPad Air 1 (WiFi)"
case "iPad4,2": return "iPad Air 1 (Cellular)"
case "iPad4,3": return "iPad Air"
case "iPad4,4": return "iPad Mini 2 (WiFi)"
case "iPad4,5": return "iPad Mini 2 (Cellular)"
case "iPad4,6": return "iPad Mini 2 (Rev)"
case "iPad4,7": return "iPad Mini 3 (WiFi)"
case "iPad4,8": return "iPad Mini 3 (A1600)"
case "iPad4,9": return "iPad Mini 3 (A1601)"
case "iPad5,1": return "iPad Mini 4 (WiFi)"
case "iPad5,2": return "iPad Mini 4 (Cellular)"
case "iPad5,3": return "iPad Air 2 (WiFi)"
case "iPad5,4": return "iPad Air 2 (Cellular)"
case "iPad6,3": return "iPad Pro 9.7 (WiFi)"
case "iPad6,4": return "iPad Pro 9.7 (Cellular)"
case "iPad6,7": return "iPad Pro 12.9 (WiFi)"
case "iPad6,8": return "iPad Pro 12.9 (Cellular)"
case "iPad6,11": return "iPad (2017)"
case "iPad6,12": return "iPad (2017)"
case "iPad7,1": return "iPad Pro 12.9 2nd generation (WiFi)"
case "iPad7,2": return "iPad Pro 12.9 2nd generation (Cellular)"
case "iPad7,3": return "iPad Pro 10.5 (WiFi)"
case "iPad7,4": return "iPad Pro 10.5 (Cellular)"
case "iPad7,5": return "iPad 6th Gen (WiFi)"
case "iPad7,6": return "iPad 6th Gen (WiFi+Cellular)"
case "iPad8,1": return "iPad Pro 3rd Gen (11 inch, WiFi)"
case "iPad8,2": return "iPad Pro 3rd Gen (11 inch, 1TB, WiFi)"
case "iPad8,3": return "iPad Pro 3rd Gen (11 inch, WiFi+Cellular)"
case "iPad8,4": return "iPad Pro 3rd Gen (11 inch, 1TB, WiFi+Cellular)"
case "iPad8,5": return "iPad Pro 3rd Gen (12.9 inch, WiFi)"
case "iPad8,6": return "iPad Pro 3rd Gen (12.9 inch, 1TB, WiFi)"
case "iPad8,7": return "iPad Pro 3rd Gen (12.9 inch, WiFi+Cellular)"
case "iPad8,8": return "iPad Pro 3rd Gen (12.9 inch, 1TB, WiFi+Cellular)"
case "iPad11,1": return "iPad mini 5th Gen (WiFi)"
case "iPad11,2": return "iPad mini 5th Gen"
case "iPad11,3": return "iPad Air 3rd Gen (WiFi)"
case "iPad11,4": return "iPad Air 3rd Gen"
case "i386": return "Simulator"
case "x86_64": return "Simulator"
case "Watch1,1": return "Apple Watch 38mm case"
case "Watch1,2": return "Apple Watch 42mm case"
case "Watch2,6": return "Apple Watch Series 1 38mm case"
case "Watch2,7": return "Apple Watch Series 1 42mm case"
case "Watch2,3": return "Apple Watch Series 2 38mm case"
case "Watch2,4": return "Apple Watch Series 2 42mm case"
case "Watch3,1": return "Apple Watch Series 3 38mm case (GPS+Cellular)"
case "Watch3,2": return "Apple Watch Series 3 42mm case (GPS+Cellular)"
case "Watch3,3": return "Apple Watch Series 3 38mm case (GPS)"
case "Watch3,4": return "Apple Watch Series 3 42mm case (GPS)"
case "Watch4,1": return "Apple Watch Series 4 40mm case (GPS)"
case "Watch4,2": return "Apple Watch Series 4 44mm case (GPS)"
case "Watch4,3": return "Apple Watch Series 4 40mm case (GPS+Cellular)"
case "Watch4,4": return "Apple Watch Series 4 44mm case (GPS+Cellular)"
case "Watch5,1": return "Apple Watch Series 5 40mm case (GPS)"
case "Watch5,2": return "Apple Watch Series 5 44mm case (GPS)"
case "Watch5,3": return "Apple Watch Series 5 40mm case (GPS+Cellular)"
case "Watch5,4": return "Apple Watch Series 5 44mm case (GPS+Cellular)"
default: return nil
}
}
}
#endif
| mit | cf766033ac0430f80c70a1e2656fa222 | 48.763314 | 97 | 0.561593 | 3.505627 | false | false | false | false |
A752575700/HOMEWORK | Day1_1/MyPlayground.playground/Contents.swift | 1 | 1331 |
var str = "Hello, playground"
println("Hi")
println(str)
var a=3
var b:Int
b=4
var c:Int=5
//announce variable
let d=4
//announce invariable
var sentence:String="Hi"
var mimi:Double=2.5
//unable to change type
//cannot be announced as a variable without exact type
//optional:!拆箱 ?装箱
/*var optional_k : Int?
println(optional_k)
var optional_l : Int?
println(optional_l)*/
if(a<10) {a=a-1
println(a)}
var mood = "happy"
var date = "Saturday"
//if 循环
if mood == "happy"{
println("go to school")
}else if mood == "so happy"{
println("go to cinema")
}else {
println("stay in bed")}
if mood == "happy" && date != "Sunday" {
println("go to school")
} else if mood == "so happy" || date == "Saturday" {
println("go to cinema")
} else {
println("stay in bed")
}
//for循环
//有利多层
for var i=0; i<10;i++ {
println(i)
}
println()
//while
//可以改变变化的条件
var j=0
while j<10 {
println(j)
j++
}
println()
var Num = [1,2,3]
Num[0]=1
Num.count
Num.append(7)
//Num.removeAtIndex(6)
Num.count
//遍历数组
var item = 2
for item in Num{
println(item)
}
//字典 箭指对 //Java map
var Bob = ["name":"Bob","age":"12","gender":"male"]
var Tim=
["name":"Tim","age":"15","gender":"male"]
var CEO = [Tim, Bob]
println(CEO[0]["name"])
| mit | e18ae7a32ec349bacec125dd73694341 | 12.061856 | 54 | 0.607735 | 2.612371 | false | false | false | false |
woodcockjosh/FastContact | Core/FastContactListManager.swift | 1 | 2550 | //
// FastContactDelegate.swift
// FastContact
//
// Created by Josh Woodcock on 8/22/15.
// Copyright (c) 2015 Connecting Open Time, LLC. All rights reserved.
//
import UIKit
public class FastContactListManager {
private var _onBuildListFilterBlocks: Array<()->Void> = Array();
private var _updateBlock: ()->Void;
private var _onBuildListGroupingBlocks: Array<()->Void> = Array();
private var _lists: Array<Array<Array<IListItem>>> = Array<Array<Array<IListItem>>>();
private var _itemsBeforeEmptyListMax: Int;
public init(listCount: Int, itemsBeforeEmptyListMax: Int, updateBlock: ()->Void) {
self._updateBlock = updateBlock;
self._itemsBeforeEmptyListMax = itemsBeforeEmptyListMax;
self._lists = self._getDefaultLists(listCount);
}
public func setItemsInListForState(listIndex: Int, list: Array<Array<IListItem>>, state: FastContactViewState) {
var listToSet = list;
// Add a fillter empty cell
if(state == .ManyWithAccessAndFiller || state == .ManyNoAccess || state == .ManyBlockedAccess){
if(listToSet.count == 0){
listToSet.append(Array<IListItem>());
}
if(list[0].count <= _itemsBeforeEmptyListMax) {
listToSet[0].append(EmptyListItem());
}else{
listToSet[0].insert(EmptyListItem(), atIndex: 0);
}
}
_lists[listIndex] = listToSet;
self.updateListsForState(state);
}
public func updateListsForState(state: FastContactViewState) {
self._updateBlock();
}
public func getLists() -> Array<Array<Array<IListItem>>> {
return _lists;
}
private func _getDefaultLists(listCount: Int)->Array<Array<Array<IListItem>>> {
var lists = Array<Array<Array<IListItem>>>();
for (var i = 0; i < listCount; i++) {
var list = Array<Array<IListItem>>();
var oneEmptyListSection = Array<IListItem>();
var oneEmptyListItem = EmptyListItem();
oneEmptyListSection.append(oneEmptyListItem);
list.append(oneEmptyListSection);
lists.append(list);
}
return lists;
}
private func _listIsEmpty(list: Array<Array<IListItem>>)->Bool{
if((list.count == 0 && list[0].count == 0 && list[0][0] is EmptyListItem) || list.count == 0) {
return true;
}else{
return false;
}
}
} | mit | 359cf08445145e63160dd58407865382 | 33.013333 | 116 | 0.59098 | 4.442509 | false | false | false | false |
ksco/swift-algorithm-club-cn | Bit Set/BitSet.playground/Contents.swift | 1 | 2153 | //: Playground - noun: a place where people can play
// Create a bit set that stores 140 bits
var bits = BitSet(size: 140)
// Initially, it looks like all zeros:
// 0000000000000000000000000000000000000000000000000000000000000000
// 0000000000000000000000000000000000000000000000000000000000000000
// 0000000000000000000000000000000000000000000000000000000000000000
print(bits)
bits[2] = true
bits[99] = true
bits[128] = true
bits.cardinality // 3
// 0010000000000000000000000000000000000000000000000000000000000000
// 0000000000000000000000000000000000010000000000000000000000000000
// 1000000000000000000000000000000000000000000000000000000000000000
print(bits)
bits.setAll()
bits.cardinality // 140
// 1111111111111111111111111111111111111111111111111111111111111111
// 1111111111111111111111111111111111111111111111111111111111111111
// 1111111111110000000000000000000000000000000000000000000000000000
print(bits)
print("")
// Bitwise operations
var a = BitSet(size: 4)
var b = BitSet(size: 8)
a.setAll()
a.cardinality // 4
a[1] = false
a[2] = false
a[3] = false
b[2] = true
b[6] = true
b[7] = true
print(a) // 1000000000000000000000000000000000000000000000000000000000000000
print(b) // 0010001100000000000000000000000000000000000000000000000000000000
let c = a | b
c.size // 8
print(c) // 1010001100000000000000000000000000000000000000000000000000000000
a.cardinality // 1
b.cardinality // 3
c.cardinality // 4
print("")
print(~a) // 0111000000000000000000000000000000000000000000000000000000000000
print(~b) // 1101110000000000000000000000000000000000000000000000000000000000
print(~c) // 0101110000000000000000000000000000000000000000000000000000000000
(~a).cardinality // 3
(~b).cardinality // 5
(~c).cardinality // 4
var z = BitSet(size: 66)
z.all0() // true
z.all1() // false
z[45] = true
z.any1() // true
z.all0() // false
z[45] = false
z.any1() // false
z.all0() // true
z[65] = true
z.any1() // true
z.setAll()
z.all1() // true
z[65] = false
z.all1() // false
//var bigBits = BitSet(size: 10000)
//print(bigBits)
| mit | c01b2b48f9934d0d1c2be77a89272d8f | 20.53 | 79 | 0.740362 | 4.085389 | false | false | false | false |
zype/ZypeAppleTVBase | ZypeAppleTVBase/ViewControllers/RegisterVC.swift | 1 | 6944 | //
// RegisterVC.swift
// ZypeAppleTVBase
//
// Created by Eric Chang on 7/20/17.
// Copyright © 2017 Zype. All rights reserved.
//
import Foundation
class RegisterVC: UIViewController {
// MARK: - Properties
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var emailTextField: UITextField!
@IBOutlet weak var passwordTextField: UITextField!
@IBOutlet weak var registerButton: UIButton!
@IBOutlet weak var tosCheckbox: UIButton!
@IBOutlet weak var tosLabel: UILabel!
static let validateTosKey = "validate_tos"
var tosChecked: Bool = true
var checkedBoxImage: UIImage?
var uncheckedBoxImage: UIImage?
var subscribeDelegate: SubscriptionDelegate? = nil
// MARK: - View Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
if shouldValidateTos() {
setupTosCheckbox()
} else {
hideTos()
}
}
// MARK: - Actions
@IBAction func onRegister(_ sender: UIButton) {
guard self.validateFields() else { return }
let consumer = ConsumerModel(name: emailTextField.text!,
email: emailTextField.text!,
password: passwordTextField.text!)
ZypeAppleTVBase.sharedInstance.createConsumer(consumer) { (success, error) in
if success {
ZypeAppleTVBase.sharedInstance.login(consumer.emailString, passwd: consumer.passwordString, completion: { (loggedIn, error) in
if loggedIn {
UserDefaults.standard.set(consumer.emailString, forKey: kUserEmail)
UserDefaults.standard.set(consumer.passwordString, forKey: kUserPassword)
UserDefaults.standard.set(true, forKey: kDeviceLinkedStatus)
NotificationCenter.default.post(name: Notification.Name(rawValue: kZypeReloadScreenNotification), object: nil)
let presentingViewController = self.presentingViewController
self.dismiss(animated: false, completion: {
presentingViewController!.dismiss(animated: true)
})
if (self.subscribeDelegate != nil) {
self.subscribeDelegate?.loginComplete()
}
}
else {
if let error = error?.localizedDescription {
self.presentAlertWithText(error)
}
}
})
}
// could not create consumer
else {
if let error = error?.localizedDescription {
self.presentAlertWithText(error)
}
else {
self.presentAlertWithText("Oops! Something went wrong. Could not register.")
}
}
}
}
@IBAction func onTosClick(_ sender: UIButton) {
if tosChecked {
sender.setBackgroundImage(uncheckedBoxImage, for: .normal)
sender.setBackgroundImage(uncheckedBoxImage, for: .highlighted)
sender.setBackgroundImage(uncheckedBoxImage, for: .selected)
tosChecked = false
} else {
sender.setBackgroundImage(checkedBoxImage, for: .normal)
sender.setBackgroundImage(checkedBoxImage, for: .highlighted)
sender.setBackgroundImage(checkedBoxImage, for: .selected)
tosChecked = true
}
}
// MARK: - Utilities
fileprivate func validateFields() -> Bool {
if let email = emailTextField.text, let password = passwordTextField.text {
guard !email.isEmpty else {
self.presentAlertWithText("Please enter your email.")
return false
}
guard isValid(email: email) else {
self.presentAlertWithText("Please enter a valid email")
return false
}
guard !password.isEmpty else {
self.presentAlertWithText("Please create a password.")
return false
}
if shouldValidateTos() && !tosChecked {
self.presentAlertWithText("You must agree with the terms of service in order to proceed.")
return false
}
return true
}
print("Field no valid")
return false
}
fileprivate func presentAlertWithText(_ message: String) {
let alertController = UIAlertController(title: "Error", message: message, preferredStyle: .alert)
let ignoreAction = UIAlertAction(title: "Ok", style: .cancel) { _ in }
alertController.addAction(ignoreAction)
self.present(alertController, animated: true, completion: nil)
}
fileprivate func isValid(email:String) -> Bool {
let emailRegEx = "^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$"
let emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegEx)
return emailTest.evaluate(with: email)
}
fileprivate func shouldValidateTos() -> Bool {
if UserDefaults.standard.bool(forKey: RegisterVC.validateTosKey) {
return true
}
return false
}
fileprivate func setupTosCheckbox() -> Void {
let podBundle = Bundle(for: ZypeAppleTVBase.self)
guard let bundleURL = podBundle.url(forResource: "ZypeAppleTVBaseResources", withExtension: "bundle") else {
hideTos()
return
}
guard let bundle = Bundle(url: bundleURL) else {
hideTos()
return
}
guard let checkedBox = UIImage(named: "checkedBox.png", in: bundle, compatibleWith: nil),
let uncheckedBox = UIImage(named: "uncheckedBox.png", in: bundle, compatibleWith: nil) else {
hideTos()
return
}
checkedBoxImage = checkedBox
uncheckedBoxImage = uncheckedBox
tosCheckbox.setBackgroundImage(checkedBoxImage, for: .normal)
tosCheckbox.setBackgroundImage(checkedBoxImage, for: .selected)
tosCheckbox.setBackgroundImage(checkedBoxImage, for: .highlighted)
tosChecked = true
showTos()
}
fileprivate func showTos() -> Void {
tosCheckbox.isHidden = false
tosLabel.isHidden = false
}
fileprivate func hideTos() -> Void {
tosCheckbox.isHidden = true
tosLabel.isHidden = true
}
@IBAction func onSignIn(_ sender: Any) {
ZypeUtilities.presentLoginVC(self, true)
}
}
| mit | 981b1b1b85b398c52752c5ea4f847498 | 35.930851 | 160 | 0.566182 | 5.419984 | false | false | false | false |
muvetian/acquaintest00 | ChatRoom/ChatRoom/AvatarTableViewCell.swift | 1 | 1289 | //
// AvatarTableViewCell.swift
// ChatRoom
//
// Created by Mutian on 4/21/17.
// Copyright © 2017 Binwei Xu. All rights reserved.
//
import UIKit
class AvatarTableViewCell: UITableViewCell {
@IBOutlet weak var avatarImageView: UIImageView!
@IBOutlet weak var nicknameLabel: UILabel!
@IBOutlet weak var chatIDLabel: UILabel!
/**
Prepares the receiver for service after it has been loaded from an Interface Builder archive, or nib file.
@param None
@return None
*/
override func awakeFromNib() {
super.awakeFromNib()
self.accessoryType = .disclosureIndicator
self.avatarImageView.layer.masksToBounds = true
self.avatarImageView.layer.cornerRadius = self.avatarImageView.bounds.size.width/2/180 * 30
self.avatarImageView.layer.borderWidth = 0.5
self.avatarImageView.layer.borderColor = UIColor.lightGray.cgColor
// Initialization code
}
/**
Configure the view for the selected state
@param None
@return None
*/
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| mit | 074290cbea0eb56a6e10e933c6e163af | 27.622222 | 114 | 0.652174 | 4.953846 | false | false | false | false |
CryptoKitten/CryptoEssentials | Sources/ArrayProtocol.swift | 1 | 3465 | // Originally based on CryptoSwift by Marcin Krzyżanowski <[email protected]>
// Copyright (C) 2014 Marcin Krzyżanowski <[email protected]>
// This software is provided 'as-is', without any express or implied warranty.
//
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions:
//
// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required.
// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
// - This notice may not be removed or altered from any source or binary distribution.
import Foundation
public protocol ArrayProtocol: RangeReplaceableCollection, ExpressibleByArrayLiteral {
func arrayValue() -> [Generator.Element]
}
extension Array: ArrayProtocol {
public func arrayValue() -> [Iterator.Element] {
return self
}
}
public extension ArrayProtocol where Iterator.Element == UInt8 {
public var hexString: String {
#if os(Linux)
return self.lazy.reduce("") { $0 + (NSString(format:"%02x", $1).description) }
#else
let s = self.lazy.reduce("") { $0 + String(format:"%02x", $1) }
return s
#endif
}
public var checksum: UInt16? {
guard let bytesArray = self as? [UInt8] else {
return nil
}
var s:UInt32 = 0
for i in 0..<bytesArray.count {
s = s + UInt32(bytesArray[i])
}
s = s % 65536
return UInt16(s)
}
public var base64: String {
let bytesArray = self as? [UInt8] ?? []
#if os(Linux)
return NSData(bytes: bytesArray).base64EncodedString([])
#else
return NSData(bytes: bytesArray).base64EncodedString(options: [])
#endif
}
public init(base64: String) {
self.init()
guard let decodedData = NSData(base64: base64) else {
return
}
self.append(contentsOf: decodedData.byteArray)
}
public init(hexString: String) {
var data = [UInt8]()
var gen = hexString.characters.makeIterator()
while let c1 = gen.next(), let c2 = gen.next() {
let s = String([c1, c2])
guard let d = UInt8(s, radix: 16) else {
break
}
data.append(d)
}
self.init(data)
}
}
extension Array {
/** split in chunks with given chunk size */
public func chunks(chunkSize: Int) -> [Array<Element>] {
var words = [[Element]]()
words.reserveCapacity(self.count / chunkSize)
for idx in stride(from: chunkSize, through: self.count, by: chunkSize) {
let word = Array(self[idx - chunkSize..<idx]) // this is slow for large table
words.append(word)
}
let reminder = Array(self.suffix(self.count % chunkSize))
if (reminder.count > 0) {
words.append(reminder)
}
return words
}
}
| mit | 1ce1fab1f81c49c0af874191f0ad25f2 | 32.621359 | 216 | 0.602368 | 4.509115 | false | false | false | false |
iWeslie/Ant | Ant/Ant/LunTan/Detials/View/Menu.swift | 2 | 1860 | //
// Menu.swift
// DetialsOfAntDemo
//
// Created by Weslie on 2017/7/18.
// Copyright © 2017年 Weslie. All rights reserved.
//
import UIKit
class Menu: UIView {
var view:UIView?
// var wechatID: String = ""
var phoneURL: String = ""
var emailURL: String = ""
var qqURL: String = ""
@IBAction func favourite(_ sender: UIButton) {
}
@IBAction func wechat(_ sender: UIButton) {
jumpToApp(URLString: "wechat://")
}
@IBAction func talk(_ sender: UIButton) {
}
@IBAction func phoneCall(_ sender: UIButton) {
jumpToApp(URLString: "tel://\(phoneURL)")
}
@IBOutlet weak var name: UILabel!
@IBOutlet weak var phoneNumber: UILabel!
//初始化方法。
func initFromXib(){
//获取Xib文件名字
let xibName = NSStringFromClass(self.classForCoder)
let xibClassName = xibName.characters.split{$0 == "."}.map(String.init).last
//使用Xib初始化一个View
let view = Bundle.main.loadNibNamed(xibClassName!, owner: self, options: nil)?.first as! UIView
view.frame = self.bounds
view.translatesAutoresizingMaskIntoConstraints = true
view.autoresizingMask = [.flexibleWidth,.flexibleHeight]
self.addSubview(view)
self.view = view
}
override init(frame: CGRect) {
super.init(frame: frame)
initFromXib()
}
required init(coder aDecoder: NSCoder) {
super.init(coder:aDecoder)!
initFromXib()
}
var viewModel: LunTanDetialModel? {
didSet {
if let phone = viewModel?.contact_phone {
self.phoneNumber.text = phone
}
if let name = viewModel?.contact_name {
self.name.text = name
}
}
}
}
| apache-2.0 | d7506eef37c27693a9ce90db320547fb | 23.581081 | 103 | 0.575591 | 4.341289 | false | false | false | false |
ryuichis/swift-lint | Sources/Lint/Reporter/HTMLReporter.swift | 2 | 3445 | /*
Copyright 2017 Ryuichi Laboratories and the Yanagiba project contributors
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 Source
class HTMLReporter : Reporter {
func handle(issues: [Issue]) -> String {
if issues.isEmpty {
return ""
}
var issuesText = """
<hr />
<table>
<thead>
<tr>
<th>File</th>
<th>Location</th>
<th>Rule Identifier</th>
<th>Rule Category</th>
<th>Severity</th>
<th>Message</th>
</tr>
</thead>
<tbody>
"""
issuesText += issues.map({ $0.htmlString }).joined(separator: separator)
issuesText += "</tbody></table>"
return issuesText
}
func handle(numberOfTotalFiles: Int, issueSummary: IssueSummary) -> String {
let numberOfIssueFiles = issueSummary.numberOfFiles
var summaryHtml = """
<table>
<thead>
<tr>
<th>Total Files</th>
<th>Files with Issues</th>
"""
summaryHtml += Issue.Severity.allSeverities
.map({ "<th>\($0.rawValue.capitalized)</th>" }).joined(separator: "\n")
summaryHtml += """
</tr>
</thead>
<tbody>
<tr>
<td>\(numberOfTotalFiles)</td>
<td>\(numberOfIssueFiles)</td>
"""
summaryHtml += Issue.Severity.allSeverities.map({
let count = issueSummary.numberOfIssues(withSeverity: $0)
return "<th class=\"severity-\($0)\">\(count)</th>"
}).joined(separator: "\n")
summaryHtml += """
</tr>
</tbody>
</table>
"""
return summaryHtml
}
var header: String {
return """
<!DOCTYPE html>
<html>
<head>
<title>Yanagiba's swift-lint Report</title>
<style type='text/css'>
.severity-critical, .severity-major, .severity-minor, .severity-cosmetic {
font-weight: bold;
text-align: center;
color: #BF0A30;
}
.severity-critical { background-color: #FFC200; }
.severity-major { background-color: #FFD3A6; }
.severity-minor { background-color: #FFEEB5; }
.severity-cosmetic { background-color: #FFAAB5; }
table {
border: 2px solid gray;
border-collapse: collapse;
-moz-box-shadow: 3px 3px 4px #AAA;
-webkit-box-shadow: 3px 3px 4px #AAA;
box-shadow: 3px 3px 4px #AAA;
}
td, th {
border: 1px solid #D3D3D3;
padding: 4px 20px 4px 20px;
}
th {
text-shadow: 2px 2px 2px white;
border-bottom: 1px solid gray;
background-color: #E9F4FF;
}
</style>
</head>
<body>
<h1>Yanagiba's swift-lint report</h1>
<hr />
"""
}
var footer: String {
let versionInfo = "Yanagiba's \(SWIFT_LINT) v\(SWIFT_LINT_VERSION)"
return """
<hr />
<p>
\(Date().formatted)
|
Generated with <a href='http://yanagiba.org/swift-lint'>\(versionInfo)</a>.
</p>
</body>
</html>
"""
}
}
| apache-2.0 | ff11a46d1b5ffcdcbcea8ea6474fa41e | 24.708955 | 81 | 0.58926 | 3.708288 | false | false | false | false |
microlimbic/Matrix | MatrixDemo.playground/Pages/求解聯立方程組.xcplaygroundpage/Contents.swift | 1 | 762 | //: Playground - noun: a place where people can play
import UIKit
import Accelerate
import TWMLMatrix
/*
* 求解聯立方程組:
x + 2y = 6
3 + 4y = 10
| 1 2 | | x | | 6 |
=> | | | | = | |
| 3 4 | | y | | 10 |
寫成 擴充矩陣
| 1 2 | 6 |
=> | | |
| 3 4 | 10 |
| 1 0 | -2 |
欲求解 => | | |
| 0 1 | 4 |
*/
do{
let m = try Matrix(entries: [[1,2],[2,3]])
var v:Matrix = Matrix(vectorWithEntries: [6, 10])
let result = m.solved(by: v)
print(result)
//or
let result2 = try m ~> v
print(result2)
}catch {
print("error:\(error)")
}
//: [Next](@next)
| mit | 1784dd0168fef2530de8231b4a27490b | 14.826087 | 53 | 0.380495 | 2.778626 | false | false | false | false |
mercadopago/px-ios | MercadoPagoSDK/MercadoPagoSDK/Flows/OneTap/UI/NewPaymentMethods/PXNewPaymentMethodViewController.swift | 1 | 9875 | import UIKit
protocol ContinueButtonDelegate: AnyObject {
func triggerDeeplink(deeplink: String?)
func goToCardForm()
func goToWebPay()
}
class PXNewPaymentMethodViewController: UIViewController {
private var tableView = UITableView()
private var buttonContainerView = UIView()
private var titleLabel = UILabel()
private var viewModel: PXNewPaymentMethodViewModel
private var shouldAddBottomLineInCell = true
weak var continueButtonDelegate: ContinueButtonDelegate?
struct Sizes {
static let buttonCornerRadius: CGFloat = 6
static let separatorLineHeight: CGFloat = 1
}
override func viewDidLoad() {
super.viewDidLoad()
setupViews()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
tableView.translatesAutoresizingMaskIntoConstraints = false
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
viewModel.initPaymentMethods()
shouldAddBottomLineInCell = false
tableView.reloadData()
}
init(viewModel: PXNewPaymentMethodViewModel) {
self.viewModel = viewModel
super.init(nibName: nil, bundle: nil)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setupViews() {
view.backgroundColor = UIColor.Andes.white
let containerScrollView = buildScrollView()
containerScrollView.backgroundColor = UIColor.Andes.white
containerScrollView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(containerScrollView)
NSLayoutConstraint.activate([
containerScrollView.leftAnchor.constraint(equalTo: view.leftAnchor),
containerScrollView.rightAnchor.constraint(equalTo: view.rightAnchor),
containerScrollView.topAnchor.constraint(equalTo: view.topAnchor),
containerScrollView.bottomAnchor.constraint(equalTo: view.bottomAnchor)
])
configureTableView()
}
private func buildScrollView() -> UIScrollView {
let stackView = buildStackView()
let scrollView = UIScrollView()
scrollView.addSubview(stackView)
stackView.addArrangedSubview(buildTitleContainer())
stackView.addArrangedSubview(buildTableViewContainer())
stackView.addArrangedSubview(configureButtonContainerView())
NSLayoutConstraint.activate([
stackView.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor),
stackView.trailingAnchor.constraint(equalTo: scrollView.trailingAnchor),
stackView.topAnchor.constraint(equalTo: scrollView.topAnchor),
stackView.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor),
stackView.widthAnchor.constraint(equalTo: scrollView.widthAnchor)
])
return scrollView
}
private func buildStackView() -> UIStackView {
let stackView = UIStackView(frame: .zero)
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.axis = .vertical
stackView.alignment = .fill
stackView.spacing = 10
return stackView
}
private func buildTableViewContainer() -> UIView {
let containerView = UIView(forAutoLayout: ())
containerView.autoSetDimension(.height, toSize: viewModel.heightForRows() * CGFloat(viewModel.getNumberOfRows()))
containerView.addSubview(tableView)
NSLayoutConstraint.activate([
tableView.leadingAnchor.constraint(equalTo: containerView.leadingAnchor),
tableView.trailingAnchor.constraint(equalTo: containerView.trailingAnchor),
tableView.topAnchor.constraint(equalTo: containerView.topAnchor),
tableView.bottomAnchor.constraint(equalTo: containerView.bottomAnchor)
])
return containerView
}
private func buildTitleContainer() -> UIView {
let titleContainerView = UIView()
titleContainerView.backgroundColor = UIColor.Andes.white
titleContainerView.addSubview(titleLabel)
NSLayoutConstraint.activate([
titleLabel.trailingAnchor.constraint(equalTo: titleContainerView.trailingAnchor, constant: -PXLayout.M_MARGIN),
titleLabel.leadingAnchor.constraint(equalTo: titleContainerView.leadingAnchor, constant: PXLayout.M_MARGIN),
titleLabel.topAnchor.constraint(equalTo: titleContainerView.topAnchor, constant: PXLayout.XS_MARGIN),
titleLabel.bottomAnchor.constraint(equalTo: titleContainerView.bottomAnchor)
])
setupTitleLabel()
return titleContainerView
}
private func setupTitleLabel() {
let title = viewModel.headerTitleForBottomSheet()
titleLabel.translatesAutoresizingMaskIntoConstraints = false
titleLabel.lineBreakStrategy = NSParagraphStyle.LineBreakStrategy()
titleLabel.numberOfLines = 2
titleLabel.attributedText = title?.getAttributedString(fontSize: PXLayout.M_FONT)
}
private func configureButtonContainerView() -> UIView {
let buttonContainerView = UIView(forAutoLayout: ())
buttonContainerView.backgroundColor = UIColor.Andes.white
let continueButton = createContinueButton()
buttonContainerView.addSubview(continueButton)
NSLayoutConstraint.activate([
continueButton.topAnchor.constraint(equalTo: buttonContainerView.topAnchor, constant: PXLayout.S_MARGIN),
continueButton.leadingAnchor.constraint(equalTo: buttonContainerView.leadingAnchor, constant: PXLayout.M_MARGIN),
continueButton.trailingAnchor.constraint(equalTo: buttonContainerView.trailingAnchor, constant: -PXLayout.M_MARGIN),
continueButton.bottomAnchor.constraint(equalTo: buttonContainerView.bottomAnchor, constant: -getContinueButtonMargin()),
continueButton.heightAnchor.constraint(equalToConstant: PXLayout.XXXL_MARGIN)
])
return buttonContainerView
}
private func configureTitle() {
let title = viewModel.headerTitleForBottomSheet()
titleLabel.lineBreakStrategy = NSParagraphStyle.LineBreakStrategy()
titleLabel.numberOfLines = 2
titleLabel.attributedText = title?.getAttributedString(fontSize: PXLayout.M_FONT)
}
private func configureTableView() {
tableView.register(PXPaymentMethodsCell.self, forCellReuseIdentifier: PXPaymentMethodsCell.identifier)
tableView.delegate = self
tableView.dataSource = self
tableView.bounces = false
tableView.showsVerticalScrollIndicator = false
tableView.showsHorizontalScrollIndicator = false
tableView.separatorStyle = .none
tableView.backgroundColor = UIColor.Andes.white
tableView.reloadData()
}
private func createContinueButton() -> UIButton {
let continueButton = UIButton()
continueButton.addTarget(self, action: #selector(tappedContinue), for: .touchUpInside)
continueButton.setTitle(viewModel.getButtonTitle(), for: .normal)
continueButton.titleLabel?.font = UIFont.ml_regularSystemFont(ofSize: PXLayout.S_FONT)
continueButton.translatesAutoresizingMaskIntoConstraints = false
continueButton.backgroundColor = UIColor.Andes.blueMP500
continueButton.layer.cornerRadius = Sizes.buttonCornerRadius
return continueButton
}
@objc
func tappedContinue() {
if let index = viewModel.selectedIndex {
switch viewModel.dataForCell(at: index).actionType {
case .deeplink:
continueButtonDelegate?.triggerDeeplink(deeplink: viewModel.getDeeplink(forIndex: index))
case .standard:
continueButtonDelegate?.goToCardForm()
case .webPay:
continueButtonDelegate?.goToWebPay()
case .none:
break
}
self.dismiss(animated: true)
}
}
private func addSeparatorLineIfNeeded(inCell cell: UITableViewCell, atIndex index: Int) {
if index < viewModel.getNumberOfRows() - 1, shouldAddBottomLineInCell {
cell.addSeparatorLineToBottom(height: Sizes.separatorLineHeight, color: UIColor.Andes.gray100)
}
}
private func getContinueButtonMargin() -> CGFloat {
let safeAreaBottomHeight = PXLayout.getSafeAreaBottomInset()
if safeAreaBottomHeight > 0 {
return PXLayout.XXS_MARGIN + safeAreaBottomHeight
}
if UIDevice.isSmallDevice() {
return PXLayout.XS_MARGIN
}
return PXLayout.M_MARGIN
}
}
extension PXNewPaymentMethodViewController: UITableViewDelegate, UITableViewDataSource, UIScrollViewDelegate {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
viewModel.getNumberOfRows()
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
viewModel.selectedIndex = indexPath
shouldAddBottomLineInCell = false
tableView.reloadData()
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let cell = tableView.dequeueReusableCell(
withIdentifier: PXPaymentMethodsCell.identifier,
for: indexPath
) as? PXPaymentMethodsCell {
let data = viewModel.dataForCell(at: indexPath)
cell.selectionStyle = .none
cell.render(data: data)
addSeparatorLineIfNeeded(inCell: cell, atIndex: indexPath.row)
return cell
}
return UITableViewCell()
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
viewModel.heightForRows()
}
}
| mit | 13a64c8aa3a295fabc11ee76d73e0524 | 37.574219 | 132 | 0.700456 | 5.959565 | false | false | false | false |
Dev1an/Bond | Bond/iOS/Bond+UIButton.swift | 2 | 5573 | //
// Bond+UIButton.swift
// Bond
//
// The MIT License (MIT)
//
// Copyright (c) 2015 Srdan Rasic (@srdanrasic)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import UIKit
class ButtonDynamicHelper
{
weak var control: UIButton?
var listener: (UIControlEvents -> Void)?
init(control: UIButton) {
self.control = control
control.addTarget(self, action: Selector("touchDown:"), forControlEvents: .TouchDown)
control.addTarget(self, action: Selector("touchUpInside:"), forControlEvents: .TouchUpInside)
control.addTarget(self, action: Selector("touchUpOutside:"), forControlEvents: .TouchUpOutside)
control.addTarget(self, action: Selector("touchCancel:"), forControlEvents: .TouchCancel)
}
func touchDown(control: UIButton) {
self.listener?(.TouchDown)
}
func touchUpInside(control: UIButton) {
self.listener?(.TouchUpInside)
}
func touchUpOutside(control: UIButton) {
self.listener?(.TouchUpOutside)
}
func touchCancel(control: UIButton) {
self.listener?(.TouchCancel)
}
deinit {
control?.removeTarget(self, action: nil, forControlEvents: .AllEvents)
}
}
class ButtonDynamic<T>: InternalDynamic<UIControlEvents>
{
let helper: ButtonDynamicHelper
init(control: UIButton) {
self.helper = ButtonDynamicHelper(control: control)
super.init()
self.helper.listener = { [unowned self] in
self.value = $0
}
}
}
private var eventDynamicHandleUIButton: UInt8 = 0;
private var enabledDynamicHandleUIButton: UInt8 = 0;
private var titleDynamicHandleUIButton: UInt8 = 0;
private var imageForNormalStateDynamicHandleUIButton: UInt8 = 0;
extension UIButton /*: Dynamical, Bondable */ {
public var dynEvent: Dynamic<UIControlEvents> {
if let d: AnyObject = objc_getAssociatedObject(self, &eventDynamicHandleUIButton) {
return (d as? Dynamic<UIControlEvents>)!
} else {
let d = ButtonDynamic<UIControlEvents>(control: self)
objc_setAssociatedObject(self, &eventDynamicHandleUIButton, d, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
return d
}
}
public var dynEnabled: Dynamic<Bool> {
if let d: AnyObject = objc_getAssociatedObject(self, &enabledDynamicHandleUIButton) {
return (d as? Dynamic<Bool>)!
} else {
let d = InternalDynamic<Bool>(self.enabled)
let bond = Bond<Bool>() { [weak self] v in if let s = self { s.enabled = v } }
d.bindTo(bond, fire: false, strongly: false)
d.retain(bond)
objc_setAssociatedObject(self, &enabledDynamicHandleUIButton, d, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
return d
}
}
public var dynTitle: Dynamic<String> {
if let d: AnyObject = objc_getAssociatedObject(self, &titleDynamicHandleUIButton) {
return (d as? Dynamic<String>)!
} else {
let d = InternalDynamic<String>(self.titleLabel?.text ?? "")
let bond = Bond<String>() { [weak self] v in if let s = self { s.setTitle(v, forState: .Normal) } }
d.bindTo(bond, fire: false, strongly: false)
d.retain(bond)
objc_setAssociatedObject(self, &titleDynamicHandleUIButton, d, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
return d
}
}
public var dynImageForNormalState: Dynamic<UIImage?> {
if let d: AnyObject = objc_getAssociatedObject(self, &imageForNormalStateDynamicHandleUIButton) {
return (d as? Dynamic<UIImage?>)!
} else {
let d = InternalDynamic<UIImage?>(self.imageForState(.Normal))
let bond = Bond<UIImage?>() { [weak self] img in if let s = self { s.setImage(img, forState: .Normal) } }
d.bindTo(bond, fire: false, strongly: false)
d.retain(bond)
objc_setAssociatedObject(self, &imageForNormalStateDynamicHandleUIButton, d, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
return d
}
}
public var designatedDynamic: Dynamic<UIControlEvents> {
return self.dynEvent
}
public var designatedBond: Bond<Bool> {
return self.dynEnabled.valueBond
}
}
public func ->> (left: UIButton, right: Bond<UIControlEvents>) {
left.designatedDynamic ->> right
}
public func ->> <U: Bondable where U.BondType == UIControlEvents>(left: UIButton, right: U) {
left.designatedDynamic ->> right.designatedBond
}
public func ->> <T: Dynamical where T.DynamicType == Bool>(left: T, right: UIButton) {
left.designatedDynamic ->> right.designatedBond
}
public func ->> (left: Dynamic<Bool>, right: UIButton) {
left ->> right.designatedBond
}
| mit | dbd7d10c925a8b9dea5e00f383c0b575 | 34.272152 | 140 | 0.708774 | 4.260703 | false | false | false | false |
r4phab/ECAB | ECAB/VisualSearchFactory.swift | 1 | 14408 | //
// RedAppleBoard.swift
// ECAB
//
// Created by Boris Yurkevich on 25/01/2015.
// Copyright (c) 2015 Oliver Braddick and Jan Atkinson. All rights reserved.
//
import Foundation
enum VisualSearchEasyModeView: Int {
case TrainingOne = 0
case TrainingTwo = 1
case TrainingThree = 2
case MotorOne = 3
case MotorTwo = 4
case MotorThree = 5
case One = 6
case Two = 7
case Three = 8
}
enum VisualSearchHardModeView: Int {
case TrainingOne = 11
case TrainingTwo = 12
case TrainingThree = 13
case MotorOne = 14
case MotorTwo = 15
case One = 16
case Two = 17
}
struct VisualSearchTargets {
static let easyMode = [1, 1, 2, 6, 6, 6, 6, 6, 6]
static let hardMode = [1, 1, 2, 9, 9, 9, 9]
}
struct VisualSearchSpeed {
static let easyMode = 20.0
static let hardMode = 30.0 // Default value, can be changed in CoreData
}
class VisualSearchFactory {
var numberOfCells = 0
private var numberOfObjectTypes = 3
var data = Array<VisualSearchFruit>()
private var apples = 0
private var whiteApples = 0
private var strawberries = 0
init(stage number: Int) { // From 1 to 3
generateDefaultPattern(forScreen: number)
numberOfCells = data.count
}
let t = VisualSearchFruit(type: .🍎) // target (red apple)
let w = VisualSearchFruit(type: .🍏) // white apple
let s = VisualSearchFruit(type: .🍓) // strawverry
func generateDefaultPattern(forScreen section: Int){
var f = [VisualSearchFruit]()
// This is complicated patters copied from PDF file. I separated matrix
// of fruits in the files to 4 different sections, 5 rows each,
// 9 fruits in each row
// Typical game will have 3 screens. Which means we have to devide all fruits on three screens.
// screen == 0 means we wil add all fruits
switch section {
case VisualSearchEasyModeView.TrainingOne.rawValue:
f.append(s); f.append(w); f.append(t);
case VisualSearchEasyModeView.TrainingTwo.rawValue:
f.append(s); f.append(w); f.append(t);
f.append(w); f.append(s); f.append(w);
f.append(w); f.append(s); f.append(s);
case VisualSearchEasyModeView.TrainingThree.rawValue:
f.append(s); f.append(t); f.append(w); f.append(s); f.append(w); f.append(s);
f.append(w); f.append(s); f.append(s); f.append(w); f.append(s); f.append(w);
f.append(w); f.append(s); f.append(w); f.append(s); f.append(t); f.append(w);
case VisualSearchEasyModeView.MotorOne.rawValue:
f.append(w); f.append(w); f.append(w);
f.append(w); f.append(w); f.append(t);
f.append(w); f.append(w); f.append(w);
f.append(w);
f.append(w); f.append(w); f.append(w);
f.append(w); f.append(w); f.append(w);
f.append(t); f.append(w); f.append(w);
f.append(w);
f.append(w); f.append(w); f.append(w);
f.append(w); f.append(w); f.append(w);
f.append(w); f.append(t); f.append(w);
f.append(t);
f.append(w); f.append(w); f.append(w);
f.append(w); f.append(w); f.append(w);
f.append(w); f.append(w); f.append(w);
f.append(w);
f.append(w); f.append(w); f.append(w);
f.append(w); f.append(w); f.append(w);
f.append(w); f.append(w); f.append(w);
f.append(w);
f.append(t); f.append(w); f.append(w);
f.append(w); f.append(t); f.append(w);
f.append(w); f.append(w); f.append(w);
f.append(w);
case VisualSearchEasyModeView.MotorTwo.rawValue:
f.append(w); f.append(w); f.append(w);
f.append(w); f.append(w); f.append(w);
f.append(w); f.append(w); f.append(w);
f.append(w);
f.append(t); f.append(w); f.append(w);
f.append(w); f.append(t); f.append(w);
f.append(w); f.append(w); f.append(t);
f.append(w);
f.append(w); f.append(w); f.append(w);
f.append(w); f.append(w); f.append(w);
f.append(w); f.append(w); f.append(w);
f.append(w);
f.append(w); f.append(w); f.append(w);
f.append(w); f.append(w); f.append(w);
f.append(w); f.append(t); f.append(w);
f.append(w);
f.append(w); f.append(t); f.append(w);
f.append(w); f.append(w); f.append(w);
f.append(w); f.append(w); f.append(w);
f.append(w);
f.append(w); f.append(w); f.append(w);
f.append(w); f.append(w); f.append(w);
f.append(t); f.append(w); f.append(w);
f.append(w);
case VisualSearchEasyModeView.MotorThree.rawValue:
f.append(w); f.append(w); f.append(w);
f.append(w); f.append(w); f.append(w);
f.append(w); f.append(w); f.append(w);
f.append(w);
f.append(w); f.append(w); f.append(w);
f.append(w); f.append(w); f.append(w);
f.append(t); f.append(w); f.append(w);
f.append(t);
f.append(w); f.append(w); f.append(w);
f.append(w); f.append(w); f.append(w);
f.append(w); f.append(w); f.append(w);
f.append(w);
f.append(w); f.append(w); f.append(w);
f.append(w); f.append(w); f.append(w);
f.append(w); f.append(w); f.append(w);
f.append(w);
f.append(w); f.append(t); f.append(w);
f.append(w); f.append(w); f.append(w);
f.append(w); f.append(t); f.append(w);
f.append(w);
f.append(w); f.append(t); f.append(w);
f.append(w); f.append(t); f.append(w);
f.append(w); f.append(w); f.append(w);
f.append(w);
case VisualSearchEasyModeView.One.rawValue:
f.append(t); f.append(s); f.append(s);
f.append(w); f.append(w); f.append(s);
f.append(w); f.append(s); f.append(w);
f.append(s);
f.append(w); f.append(t); f.append(w);
f.append(s); f.append(w); f.append(s);
f.append(s); f.append(w); f.append(w);
f.append(s);
f.append(w); f.append(w); f.append(s);
f.append(s); f.append(s); f.append(w);
f.append(w); f.append(s); f.append(s);
f.append(t);
f.append(w); f.append(s); f.append(s);
f.append(w); f.append(w); f.append(w);
f.append(t); f.append(s); f.append(s);
f.append(w);
f.append(t); f.append(w); f.append(s);
f.append(s); f.append(s); f.append(s);
f.append(w); f.append(s); f.append(t);
f.append(w);
f.append(s); f.append(w); f.append(s);
f.append(w); f.append(s); f.append(w);
f.append(w); f.append(w); f.append(s);
f.append(s);
case VisualSearchEasyModeView.Two.rawValue:
f.append(s); f.append(w); f.append(s);
f.append(s); f.append(w); f.append(s);
f.append(s); f.append(s); f.append(s);
f.append(s);
f.append(s);f.append(s); f.append(w);
f.append(s); f.append(w); f.append(s);
f.append(t); f.append(w); f.append(t);
f.append(s);
f.append(w); f.append(s); f.append(s);
f.append(t); f.append(w); f.append(s);
f.append(s); f.append(w); f.append(w);
f.append(s);
f.append(s); f.append(w); f.append(t);
f.append(w); f.append(w); f.append(w);
f.append(w); f.append(s); f.append(w);
f.append(s);
f.append(s); f.append(s); f.append(s);
f.append(w); f.append(w); f.append(w);
f.append(s); f.append(w); f.append(s);
f.append(t);
f.append(s); f.append(s); f.append(w);
f.append(s); f.append(w); f.append(w);
f.append(t); f.append(s); f.append(s);
f.append(w);
case VisualSearchEasyModeView.Three.rawValue:
f.append(t); f.append(s); f.append(w);
f.append(s); f.append(w); f.append(w);
f.append(w); f.append(s); f.append(w);
f.append(w);
f.append(w); f.append(s); f.append(w);
f.append(w); f.append(t); f.append(w);
f.append(w); f.append(t); f.append(s);
f.append(s);
f.append(s); f.append(w); f.append(w);
f.append(s); f.append(s); f.append(s);
f.append(w); f.append(s); f.append(w);
f.append(s);
f.append(s); f.append(s); f.append(w);
f.append(s); f.append(w); f.append(w);
f.append(s); f.append(s); f.append(s);
f.append(w);
f.append(w); f.append(t); f.append(w);
f.append(s); f.append(w); f.append(w);
f.append(s); f.append(w); f.append(w);
f.append(w);
f.append(t); f.append(s); f.append(w);
f.append(t); f.append(w); f.append(w);
f.append(s); f.append(w); f.append(w);
f.append(w);
case 10:
break
case VisualSearchHardModeView.TrainingOne.rawValue:
f.append(s); f.append(w); f.append(t);
case VisualSearchHardModeView.TrainingTwo.rawValue:
f.append(s); f.append(w); f.append(t);
f.append(w); f.append(s); f.append(w);
f.append(w); f.append(s); f.append(s);
case VisualSearchHardModeView.TrainingThree.rawValue:
f.append(s); f.append(t); f.append(w); f.append(s); f.append(w); f.append(s);
f.append(w); f.append(s); f.append(s); f.append(w); f.append(s); f.append(w);
f.append(w); f.append(s); f.append(w); f.append(s); f.append(t); f.append(w);
case VisualSearchHardModeView.MotorOne.rawValue:
f.append(w); f.append(w); f.append(w);
f.append(w); f.append(w); f.append(t);
f.append(w); f.append(w); f.append(w);
f.append(w);
f.append(w); f.append(w); f.append(w);
f.append(w); f.append(w); f.append(w);
f.append(t); f.append(w); f.append(w);
f.append(w);
f.append(w); f.append(w); f.append(w);
f.append(w); f.append(w); f.append(w);
f.append(w); f.append(t); f.append(w);
f.append(t);
f.append(w); f.append(w); f.append(w);
f.append(w); f.append(w); f.append(w);
f.append(w); f.append(w); f.append(w);
f.append(w);
f.append(w); f.append(w); f.append(w);
f.append(w); f.append(w); f.append(w);
f.append(w); f.append(w); f.append(w);
f.append(w);
f.append(t); f.append(w); f.append(w);
f.append(w); f.append(t); f.append(w);
f.append(w); f.append(w); f.append(w);
f.append(w);
f.append(w); f.append(w); f.append(w);
f.append(w); f.append(w); f.append(w);
f.append(w); f.append(w); f.append(w);
f.append(w);
f.append(t); f.append(w); f.append(w);
f.append(w); f.append(t); f.append(w);
f.append(w); f.append(w); f.append(t);
f.append(w);
f.append(w); f.append(w); f.append(w);
f.append(w); f.append(w); f.append(w);
f.append(w); f.append(w); f.append(w);
f.append(w);
case VisualSearchHardModeView.MotorTwo.rawValue:
f.append(w); f.append(w); f.append(w);
f.append(w); f.append(w); f.append(w);
f.append(w); f.append(t); f.append(w);
f.append(w);
f.append(w); f.append(t); f.append(w);
f.append(w); f.append(w); f.append(w);
f.append(w); f.append(w); f.append(w);
f.append(w);
f.append(w); f.append(w); f.append(w);
f.append(w); f.append(w); f.append(w);
f.append(t); f.append(w); f.append(w);
f.append(w);
f.append(w); f.append(w); f.append(w);
f.append(w); f.append(w); f.append(w);
f.append(w); f.append(w); f.append(w);
f.append(w);
f.append(w); f.append(w); f.append(w);
f.append(w); f.append(w); f.append(w);
f.append(t); f.append(w); f.append(w);
f.append(t);
f.append(w); f.append(w); f.append(w);
f.append(w); f.append(w); f.append(w);
f.append(w); f.append(w); f.append(w);
f.append(w);
f.append(w); f.append(w); f.append(w);
f.append(w); f.append(w); f.append(w);
f.append(w); f.append(w); f.append(w);
f.append(w);
f.append(w); f.append(t); f.append(w);
f.append(w); f.append(w); f.append(w);
f.append(w); f.append(t); f.append(w);
f.append(w);
f.append(w); f.append(t); f.append(w);
f.append(w); f.append(t); f.append(w);
f.append(w); f.append(w); f.append(w);
f.append(w);
case VisualSearchHardModeView.One.rawValue:
f.append(t); f.append(s); f.append(s);
f.append(w); f.append(w); f.append(s);
f.append(w); f.append(s); f.append(w);
f.append(s);
f.append(w); f.append(t); f.append(w);
f.append(s); f.append(w); f.append(s);
f.append(s); f.append(w); f.append(w);
f.append(s);
f.append(w); f.append(w); f.append(s);
f.append(s); f.append(s); f.append(w);
f.append(w); f.append(s); f.append(s);
f.append(t);
f.append(w); f.append(s); f.append(s);
f.append(w); f.append(w); f.append(w);
f.append(t); f.append(s); f.append(s);
f.append(w);
f.append(t); f.append(w); f.append(s);
f.append(s); f.append(s); f.append(s);
f.append(w); f.append(s); f.append(t);
f.append(w);
f.append(s); f.append(w); f.append(s);
f.append(w); f.append(s); f.append(w);
f.append(w); f.append(w); f.append(s);
f.append(s);
f.append(s); f.append(w); f.append(s);
f.append(s); f.append(w); f.append(s);
f.append(s); f.append(s); f.append(s);
f.append(s);
f.append(s);f.append(s); f.append(w);
f.append(s); f.append(w); f.append(s);
f.append(t); f.append(w); f.append(t);
f.append(s);
f.append(w); f.append(s); f.append(s);
f.append(t); f.append(w); f.append(s);
f.append(s); f.append(w); f.append(w);
f.append(s);
case VisualSearchHardModeView.Two.rawValue:
f.append(s); f.append(w); f.append(t);
f.append(w); f.append(w); f.append(w);
f.append(w); f.append(s); f.append(w);
f.append(s);
f.append(s); f.append(s); f.append(s);
f.append(w); f.append(w); f.append(w);
f.append(s); f.append(w); f.append(s);
f.append(t);
f.append(s); f.append(s); f.append(w);
f.append(s); f.append(w); f.append(w);
f.append(t); f.append(s); f.append(s);
f.append(w);
f.append(t); f.append(s); f.append(w);
f.append(s); f.append(w); f.append(w);
f.append(w); f.append(s); f.append(w);
f.append(w);
f.append(w); f.append(s); f.append(w);
f.append(w); f.append(t); f.append(w);
f.append(w); f.append(t); f.append(s);
f.append(s);
f.append(s); f.append(w); f.append(w);
f.append(s); f.append(s); f.append(s);
f.append(w); f.append(s); f.append(w);
f.append(s);
f.append(s); f.append(s); f.append(w);
f.append(s); f.append(w); f.append(w);
f.append(s); f.append(s); f.append(s);
f.append(w);
f.append(w); f.append(t); f.append(w);
f.append(s); f.append(w); f.append(w);
f.append(s); f.append(w); f.append(w);
f.append(w);
f.append(t); f.append(s); f.append(w);
f.append(t); f.append(w); f.append(w);
f.append(s); f.append(w); f.append(w);
f.append(w);
default:
print("⛔️ Set correct screen!")
}
data = f
}
}
| mit | 9769c046bb141a133b5a8c5a3a1d3fc7 | 29.052192 | 103 | 0.571518 | 2.420955 | false | false | false | false |
Erik-J-D/SYDE361-AutomotiveIOT-PhoneApp-Sensors | iOS/Pods/Charts/Charts/Classes/Charts/ChartViewBase.swift | 1 | 32380 | //
// ChartViewBase.swift
// Charts
//
// Created by Daniel Cohen Gindi on 23/2/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
//
// Based on https://github.com/PhilJay/MPAndroidChart/commit/c42b880
import Foundation
import UIKit;
@objc
public protocol ChartViewDelegate
{
/// Called when a value has been selected inside the chart.
/// :entry: The selected Entry.
/// :dataSetIndex: The index in the datasets array of the data object the Entrys DataSet is in.
optional func chartValueSelected(chartView: ChartViewBase, entry: ChartDataEntry, dataSetIndex: Int, highlight: ChartHighlight);
// Called when nothing has been selected or an "un-select" has been made.
optional func chartValueNothingSelected(chartView: ChartViewBase);
}
public class ChartViewBase: UIView, ChartAnimatorDelegate
{
// MARK: - Properties
/// custom formatter that is used instead of the auto-formatter if set
internal var _valueFormatter = NSNumberFormatter()
/// the default value formatter
internal var _defaultValueFormatter = NSNumberFormatter()
/// object that holds all data that was originally set for the chart, before it was modified or any filtering algorithms had been applied
internal var _data: ChartData!
/// If set to true, chart continues to scroll after touch up
public var dragDecelerationEnabled = true
/// Deceleration friction coefficient in [0 ; 1] interval, higher values indicate that speed will decrease slowly, for example if it set to 0, it will stop immediately.
/// 1 is an invalid value, and will be converted to 0.999 automatically.
private var _dragDecelerationFrictionCoef: CGFloat = 0.9
/// font object used for drawing the description text in the bottom right corner of the chart
public var descriptionFont: UIFont? = UIFont(name: "HelveticaNeue", size: 9.0)
internal var _descriptionTextColor: UIColor! = UIColor.blackColor()
/// font object for drawing the information text when there are no values in the chart
internal var _infoFont: UIFont! = UIFont(name: "HelveticaNeue", size: 12.0)
internal var _infoTextColor: UIColor! = UIColor(red: 247.0/255.0, green: 189.0/255.0, blue: 51.0/255.0, alpha: 1.0) // orange
/// description text that appears in the bottom right corner of the chart
public var descriptionText = "Description"
/// flag that indicates if the chart has been fed with data yet
internal var _dataNotSet = true
/// if true, units are drawn next to the values in the chart
internal var _drawUnitInChart = false
/// the number of x-values the chart displays
internal var _deltaX = CGFloat(1.0)
internal var _chartXMin = Float(0.0)
internal var _chartXMax = Float(0.0)
/// if true, value highlightning is enabled
public var highlightEnabled = true
/// the legend object containing all data associated with the legend
internal var _legend: ChartLegend!;
/// delegate to receive chart events
public weak var delegate: ChartViewDelegate?
/// text that is displayed when the chart is empty
public var noDataText = "No chart data available."
/// text that is displayed when the chart is empty that describes why the chart is empty
public var noDataTextDescription: String?
internal var _legendRenderer: ChartLegendRenderer!
/// object responsible for rendering the data
public var renderer: ChartDataRendererBase?
/// object that manages the bounds and drawing constraints of the chart
internal var _viewPortHandler: ChartViewPortHandler!
/// object responsible for animations
internal var _animator: ChartAnimator!
/// flag that indicates if offsets calculation has already been done or not
private var _offsetsCalculated = false
/// array of Highlight objects that reference the highlighted slices in the chart
internal var _indicesToHightlight = [ChartHighlight]()
/// if set to true, the marker is drawn when a value is clicked
public var drawMarkers = true
/// the view that represents the marker
public var marker: ChartMarker?
private var _interceptTouchEvents = false
// MARK: - Initializers
public override init(frame: CGRect)
{
super.init(frame: frame);
self.backgroundColor = UIColor.clearColor();
initialize();
}
public required init(coder aDecoder: NSCoder)
{
super.init(coder: aDecoder);
initialize();
}
deinit
{
self.removeObserver(self, forKeyPath: "bounds");
self.removeObserver(self, forKeyPath: "frame");
}
internal func initialize()
{
_animator = ChartAnimator();
_animator.delegate = self;
_viewPortHandler = ChartViewPortHandler();
_viewPortHandler.setChartDimens(width: bounds.size.width, height: bounds.size.height);
_legend = ChartLegend();
_legendRenderer = ChartLegendRenderer(viewPortHandler: _viewPortHandler, legend: _legend);
_defaultValueFormatter.maximumFractionDigits = 1;
_defaultValueFormatter.minimumFractionDigits = 1;
_defaultValueFormatter.usesGroupingSeparator = true;
_valueFormatter = _defaultValueFormatter.copy() as! NSNumberFormatter;
self.addObserver(self, forKeyPath: "bounds", options: .New, context: nil);
self.addObserver(self, forKeyPath: "frame", options: .New, context: nil);
}
// MARK: - ChartViewBase
/// The data for the chart
public var data: ChartData?
{
get
{
return _data;
}
set
{
if (newValue == nil || newValue?.yValCount == 0)
{
println("Charts: data argument is nil on setData()");
return;
}
_dataNotSet = false;
_offsetsCalculated = false;
_data = newValue;
// calculate how many digits are needed
calculateFormatter(min: _data.getYMin(), max: _data.getYMax());
notifyDataSetChanged();
}
}
/// Clears the chart from all data (sets it to null) and refreshes it (by calling setNeedsDisplay()).
public func clear()
{
_data = nil;
_dataNotSet = true;
setNeedsDisplay();
}
/// Removes all DataSets (and thereby Entries) from the chart. Does not remove the x-values. Also refreshes the chart by calling setNeedsDisplay().
public func clearValues()
{
if (_data !== nil)
{
_data.clearValues();
}
setNeedsDisplay();
}
/// Returns true if the chart is empty (meaning it's data object is either null or contains no entries).
public func isEmpty() -> Bool
{
if (_data == nil)
{
return true;
}
else
{
if (_data.yValCount <= 0)
{
return true;
}
else
{
return false;
}
}
}
/// Lets the chart know its underlying data has changed and should perform all necessary recalculations.
public func notifyDataSetChanged()
{
fatalError("notifyDataSetChanged() cannot be called on ChartViewBase");
}
/// calculates the offsets of the chart to the border depending on the position of an eventual legend or depending on the length of the y-axis and x-axis labels and their position
internal func calculateOffsets()
{
fatalError("calculateOffsets() cannot be called on ChartViewBase");
}
/// calcualtes the y-min and y-max value and the y-delta and x-delta value
internal func calcMinMax()
{
fatalError("calcMinMax() cannot be called on ChartViewBase");
}
/// calculates the required number of digits for the values that might be drawn in the chart (if enabled), and creates the default value formatter
internal func calculateFormatter(#min: Float, max: Float)
{
// check if a custom formatter is set or not
var reference = Float(0.0);
if (_data == nil || _data.xValCount < 2)
{
var absMin = fabs(min);
var absMax = fabs(max);
reference = absMin > absMax ? absMin : absMax;
}
else
{
reference = fabs(max - min);
}
var digits = ChartUtils.decimals(reference);
_defaultValueFormatter.maximumFractionDigits = digits;
_defaultValueFormatter.minimumFractionDigits = digits;
}
public override func drawRect(rect: CGRect)
{
let context = UIGraphicsGetCurrentContext();
let frame = self.bounds;
if (_dataNotSet || _data === nil || _data.yValCount == 0)
{ // check if there is data
CGContextSaveGState(context);
// if no data, inform the user
ChartUtils.drawText(context: context, text: noDataText, point: CGPoint(x: frame.width / 2.0, y: frame.height / 2.0), align: .Center, attributes: [NSFontAttributeName: _infoFont, NSForegroundColorAttributeName: _infoTextColor]);
if (noDataTextDescription?.lengthOfBytesUsingEncoding(NSUTF16StringEncoding) > 0)
{
var textOffset = -_infoFont.lineHeight / 2.0;
ChartUtils.drawText(context: context, text: noDataTextDescription!, point: CGPoint(x: frame.width / 2.0, y: frame.height / 2.0 + textOffset), align: .Center, attributes: [NSFontAttributeName: _infoFont, NSForegroundColorAttributeName: _infoTextColor]);
}
return;
}
if (!_offsetsCalculated)
{
calculateOffsets();
_offsetsCalculated = true;
}
}
/// draws the description text in the bottom right corner of the chart
internal func drawDescription(#context: CGContext)
{
if (descriptionText.lengthOfBytesUsingEncoding(NSUTF16StringEncoding) == 0)
{
return;
}
let frame = self.bounds;
var attrs = [NSObject: AnyObject]();
var font = descriptionFont;
if (font == nil)
{
font = UIFont.systemFontOfSize(UIFont.systemFontSize());
}
attrs[NSFontAttributeName] = font;
attrs[NSForegroundColorAttributeName] = UIColor.blackColor();
ChartUtils.drawText(context: context, text: descriptionText, point: CGPoint(x: frame.width - _viewPortHandler.offsetRight - 10.0, y: frame.height - _viewPortHandler.offsetBottom - 10.0 - font!.lineHeight), align: .Right, attributes: attrs);
}
/// enables/disables defauilt touch events to be handled. When disable, touches are not passed to parent views so scrolling inside a UIScrollView won't work.
public var defaultTouchEventsEnabled: Bool
{
get { return _interceptTouchEvents; }
set { _interceptTouchEvents = true; }
}
// MARK: - Highlighting
/// Returns the array of currently highlighted values. This might be null or empty if nothing is highlighted.
public var highlighted: [ChartHighlight]
{
return _indicesToHightlight;
}
/// Returns true if there are values to highlight,
/// false if there are no values to highlight.
/// Checks if the highlight array is null, has a length of zero or if the first object is null.
public func valuesToHighlight() -> Bool
{
return _indicesToHightlight.count > 0;
}
/// Highlights the values at the given indices in the given DataSets. Provide
/// null or an empty array to undo all highlighting.
/// This should be used to programmatically highlight values.
/// This DOES NOT generate a callback to the delegate.
public func highlightValues(highs: [ChartHighlight]?)
{
// set the indices to highlight
_indicesToHightlight = highs ?? [ChartHighlight]();
// redraw the chart
setNeedsDisplay();
}
/// Highlights the value at the given x-index in the given DataSet.
/// Provide -1 as the x-index to undo all highlighting.
public func highlightValue(#xIndex: Int, dataSetIndex: Int, callDelegate: Bool)
{
if (xIndex < 0 || dataSetIndex < 0 || xIndex >= _data.xValCount || dataSetIndex >= _data.dataSetCount)
{
highlightValue(highlight: nil, callDelegate: callDelegate);
}
else
{
highlightValue(highlight: ChartHighlight(xIndex: xIndex, dataSetIndex: dataSetIndex), callDelegate: callDelegate);
}
}
/// Highlights the value selected by touch gesture.
public func highlightValue(#highlight: ChartHighlight?, callDelegate: Bool)
{
if (highlight == nil)
{
_indicesToHightlight.removeAll(keepCapacity: false);
}
else
{
// set the indices to highlight
_indicesToHightlight = [highlight!];
}
// redraw the chart
setNeedsDisplay();
if (callDelegate && delegate != nil)
{
if (highlight == nil)
{
delegate!.chartValueNothingSelected!(self);
}
else
{
var e = _data.getEntryForHighlight(highlight!);
// notify the listener
delegate!.chartValueSelected!(self, entry: e, dataSetIndex: highlight!.dataSetIndex, highlight: highlight!);
}
}
}
// MARK: - Markers
/// draws all MarkerViews on the highlighted positions
internal func drawMarkers(#context: CGContext)
{
// if there is no marker view or drawing marker is disabled
if (marker === nil || !drawMarkers || !valuesToHighlight())
{
return;
}
for (var i = 0, count = _indicesToHightlight.count; i < count; i++)
{
let highlight = _indicesToHightlight[i];
let xIndex = highlight.xIndex;
let dataSetIndex = highlight.dataSetIndex;
if (xIndex <= Int(_deltaX) && xIndex <= Int(_deltaX * _animator.phaseX))
{
let e = _data.getEntryForHighlight(highlight);
var pos = getMarkerPosition(entry: e, dataSetIndex: dataSetIndex);
// check bounds
if (!_viewPortHandler.isInBounds(x: pos.x, y: pos.y))
{
continue;
}
// callbacks to update the content
marker!.refreshContent(entry: e, dataSetIndex: dataSetIndex);
let markerSize = marker!.size;
if (pos.y - markerSize.height <= 0.0)
{
let y = markerSize.height - pos.y;
marker!.draw(context: context, point: CGPoint(x: pos.x, y: pos.y + y));
}
else
{
marker!.draw(context: context, point: pos);
}
}
}
}
/// Returns the actual position in pixels of the MarkerView for the given Entry in the given DataSet.
public func getMarkerPosition(#entry: ChartDataEntry, dataSetIndex: Int) -> CGPoint
{
fatalError("getMarkerPosition() cannot be called on ChartViewBase");
}
// MARK: - Animation
/// Returns the animator responsible for animating chart values.
public var animator: ChartAnimator!
{
return _animator;
}
/// Animates the drawing / rendering of the chart on both x- and y-axis with the specified animation time.
/// If animate(...) is called, no further calling of invalidate() is necessary to refresh the chart.
/// :param: xAxisDuration duration for animating the x axis
/// :param: yAxisDuration duration for animating the y axis
/// :param: easingX an easing function for the animation on the x axis
/// :param: easingY an easing function for the animation on the y axis
public func animate(#xAxisDuration: NSTimeInterval, yAxisDuration: NSTimeInterval, easingX: ChartEasingFunctionBlock?, easingY: ChartEasingFunctionBlock?)
{
_animator.animate(xAxisDuration: xAxisDuration, yAxisDuration: yAxisDuration, easingX: easingX, easingY: easingY);
}
/// Animates the drawing / rendering of the chart on both x- and y-axis with the specified animation time.
/// If animate(...) is called, no further calling of invalidate() is necessary to refresh the chart.
/// :param: xAxisDuration duration for animating the x axis
/// :param: yAxisDuration duration for animating the y axis
/// :param: easingOptionX the easing function for the animation on the x axis
/// :param: easingOptionY the easing function for the animation on the y axis
public func animate(#xAxisDuration: NSTimeInterval, yAxisDuration: NSTimeInterval, easingOptionX: ChartEasingOption, easingOptionY: ChartEasingOption)
{
_animator.animate(xAxisDuration: xAxisDuration, yAxisDuration: yAxisDuration, easingOptionX: easingOptionX, easingOptionY: easingOptionY);
}
/// Animates the drawing / rendering of the chart on both x- and y-axis with the specified animation time.
/// If animate(...) is called, no further calling of invalidate() is necessary to refresh the chart.
/// :param: xAxisDuration duration for animating the x axis
/// :param: yAxisDuration duration for animating the y axis
/// :param: easing an easing function for the animation
public func animate(#xAxisDuration: NSTimeInterval, yAxisDuration: NSTimeInterval, easing: ChartEasingFunctionBlock?)
{
_animator.animate(xAxisDuration: xAxisDuration, yAxisDuration: yAxisDuration, easing: easing);
}
/// Animates the drawing / rendering of the chart on both x- and y-axis with the specified animation time.
/// If animate(...) is called, no further calling of invalidate() is necessary to refresh the chart.
/// :param: xAxisDuration duration for animating the x axis
/// :param: yAxisDuration duration for animating the y axis
/// :param: easingOption the easing function for the animation
public func animate(#xAxisDuration: NSTimeInterval, yAxisDuration: NSTimeInterval, easingOption: ChartEasingOption)
{
_animator.animate(xAxisDuration: xAxisDuration, yAxisDuration: yAxisDuration, easingOption: easingOption);
}
/// Animates the drawing / rendering of the chart on both x- and y-axis with the specified animation time.
/// If animate(...) is called, no further calling of invalidate() is necessary to refresh the chart.
/// :param: xAxisDuration duration for animating the x axis
/// :param: yAxisDuration duration for animating the y axis
public func animate(#xAxisDuration: NSTimeInterval, yAxisDuration: NSTimeInterval)
{
_animator.animate(xAxisDuration: xAxisDuration, yAxisDuration: yAxisDuration);
}
/// Animates the drawing / rendering of the chart the x-axis with the specified animation time.
/// If animate(...) is called, no further calling of invalidate() is necessary to refresh the chart.
/// :param: xAxisDuration duration for animating the x axis
/// :param: easing an easing function for the animation
public func animate(#xAxisDuration: NSTimeInterval, easing: ChartEasingFunctionBlock?)
{
_animator.animate(xAxisDuration: xAxisDuration, easing: easing);
}
/// Animates the drawing / rendering of the chart the x-axis with the specified animation time.
/// If animate(...) is called, no further calling of invalidate() is necessary to refresh the chart.
/// :param: xAxisDuration duration for animating the x axis
/// :param: easingOption the easing function for the animation
public func animate(#xAxisDuration: NSTimeInterval, easingOption: ChartEasingOption)
{
_animator.animate(xAxisDuration: xAxisDuration, easingOption: easingOption);
}
/// Animates the drawing / rendering of the chart the x-axis with the specified animation time.
/// If animate(...) is called, no further calling of invalidate() is necessary to refresh the chart.
/// :param: xAxisDuration duration for animating the x axis
public func animate(#xAxisDuration: NSTimeInterval)
{
_animator.animate(xAxisDuration: xAxisDuration);
}
/// Animates the drawing / rendering of the chart the y-axis with the specified animation time.
/// If animate(...) is called, no further calling of invalidate() is necessary to refresh the chart.
/// :param: yAxisDuration duration for animating the y axis
/// :param: easing an easing function for the animation
public func animate(#yAxisDuration: NSTimeInterval, easing: ChartEasingFunctionBlock?)
{
_animator.animate(yAxisDuration: yAxisDuration, easing: easing);
}
/// Animates the drawing / rendering of the chart the y-axis with the specified animation time.
/// If animate(...) is called, no further calling of invalidate() is necessary to refresh the chart.
/// :param: yAxisDuration duration for animating the y axis
/// :param: easingOption the easing function for the animation
public func animate(#yAxisDuration: NSTimeInterval, easingOption: ChartEasingOption)
{
_animator.animate(yAxisDuration: yAxisDuration, easingOption: easingOption);
}
/// Animates the drawing / rendering of the chart the y-axis with the specified animation time.
/// If animate(...) is called, no further calling of invalidate() is necessary to refresh the chart.
/// :param: yAxisDuration duration for animating the y axis
public func animate(#yAxisDuration: NSTimeInterval)
{
_animator.animate(yAxisDuration: yAxisDuration);
}
// MARK: - Accessors
/// returns the total value (sum) of all y-values across all DataSets
public var yValueSum: Float
{
return _data.yValueSum;
}
/// returns the current y-max value across all DataSets
public var chartYMax: Float
{
return _data.yMax;
}
/// returns the current y-min value across all DataSets
public var chartYMin: Float
{
return _data.yMin;
}
public var chartXMax: Float
{
return _chartXMax;
}
public var chartXMin: Float
{
return _chartXMin;
}
/// returns the average value of all values the chart holds
public func getAverage() -> Float
{
return yValueSum / Float(_data.yValCount);
}
/// returns the average value for a specific DataSet (with a specific label) in the chart
public func getAverage(#dataSetLabel: String) -> Float
{
var ds = _data.getDataSetByLabel(dataSetLabel, ignorecase: true);
if (ds == nil)
{
return 0.0;
}
return ds!.yValueSum / Float(ds!.entryCount);
}
/// returns the total number of values the chart holds (across all DataSets)
public var getValueCount: Int
{
return _data.yValCount;
}
/// Returns the center of the chart taking offsets under consideration. (returns the center of the content rectangle)
public var centerOffsets: CGPoint
{
return _viewPortHandler.contentCenter;
}
/// Returns the Legend object of the chart. This method can be used to get an instance of the legend in order to customize the automatically generated Legend.
public var legend: ChartLegend
{
return _legend;
}
/// Returns the renderer object responsible for rendering / drawing the Legend.
public var legendRenderer: ChartLegendRenderer!
{
return _legendRenderer;
}
/// Returns the rectangle that defines the borders of the chart-value surface (into which the actual values are drawn).
public var contentRect: CGRect
{
return _viewPortHandler.contentRect;
}
/// Sets the formatter to be used for drawing the values inside the chart.
/// If no formatter is set, the chart will automatically determine a reasonable
/// formatting (concerning decimals) for all the values that are drawn inside
/// the chart. Set this to nil to re-enable auto formatting.
public var valueFormatter: NSNumberFormatter!
{
get
{
return _valueFormatter;
}
set
{
if (newValue === nil)
{
_valueFormatter = _defaultValueFormatter.copy() as! NSNumberFormatter;
}
else
{
_valueFormatter = newValue;
}
}
}
/// returns the x-value at the given index
public func getXValue(index: Int) -> String!
{
if (_data == nil || _data.xValCount <= index)
{
return nil;
}
else
{
return _data.xVals[index];
}
}
/// Get all Entry objects at the given index across all DataSets.
public func getEntriesAtIndex(xIndex: Int) -> [ChartDataEntry]
{
var vals = [ChartDataEntry]();
for (var i = 0, count = _data.dataSetCount; i < count; i++)
{
var set = _data.getDataSetByIndex(i);
var e = set!.entryForXIndex(xIndex);
if (e !== nil)
{
vals.append(e);
}
}
return vals;
}
/// returns the percentage the given value has of the total y-value sum
public func percentOfTotal(val: Float) -> Float
{
return val / _data.yValueSum * 100.0;
}
/// Returns the ViewPortHandler of the chart that is responsible for the
/// content area of the chart and its offsets and dimensions.
public var viewPortHandler: ChartViewPortHandler!
{
return _viewPortHandler;
}
/// Returns the bitmap that represents the chart.
public func getChartImage(#transparent: Bool) -> UIImage
{
UIGraphicsBeginImageContextWithOptions(bounds.size, opaque || !transparent, UIScreen.mainScreen().scale);
var context = UIGraphicsGetCurrentContext();
var rect = CGRect(origin: CGPoint(x: 0, y: 0), size: bounds.size);
if (opaque || !transparent)
{
// Background color may be partially transparent, we must fill with white if we want to output an opaque image
CGContextSetFillColorWithColor(context, UIColor.whiteColor().CGColor);
CGContextFillRect(context, rect);
if (self.backgroundColor !== nil)
{
CGContextSetFillColorWithColor(context, self.backgroundColor?.CGColor);
CGContextFillRect(context, rect);
}
}
layer.renderInContext(UIGraphicsGetCurrentContext());
var image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
public enum ImageFormat
{
case JPEG;
case PNG;
}
/// Saves the current chart state with the given name to the given path on
/// the sdcard leaving the path empty "" will put the saved file directly on
/// the SD card chart is saved as a PNG image, example:
/// saveToPath("myfilename", "foldername1/foldername2");
///
/// :filePath: path to the image to save
/// :format: the format to save
/// :compressionQuality: compression quality for lossless formats (JPEG)
///
/// :returns: true if the image was saved successfully
public func saveToPath(path: String, format: ImageFormat, compressionQuality: Float) -> Bool
{
var image = getChartImage(transparent: format != .JPEG);
var imageData: NSData!;
switch (format)
{
case .PNG:
imageData = UIImagePNGRepresentation(image);
break;
case .JPEG:
imageData = UIImageJPEGRepresentation(image, CGFloat(compressionQuality));
break;
}
return imageData.writeToFile(path, atomically: true);
}
/// Saves the current state of the chart to the camera roll
public func saveToCameraRoll()
{
UIImageWriteToSavedPhotosAlbum(getChartImage(transparent: false), nil, nil, nil);
}
internal typealias VoidClosureType = () -> ()
internal var _sizeChangeEventActions = [VoidClosureType]()
override public func observeValueForKeyPath(keyPath: String, ofObject object: AnyObject, change: [NSObject: AnyObject], context: UnsafeMutablePointer<Void>)
{
if (keyPath == "bounds" || keyPath == "frame")
{
var bounds = self.bounds;
if (_viewPortHandler !== nil &&
(bounds.size.width != _viewPortHandler.chartWidth ||
bounds.size.height != _viewPortHandler.chartHeight))
{
_viewPortHandler.setChartDimens(width: bounds.size.width, height: bounds.size.height);
// Finish any pending viewport changes
while (!_sizeChangeEventActions.isEmpty)
{
_sizeChangeEventActions.removeAtIndex(0)();
}
notifyDataSetChanged();
}
}
}
public func clearPendingViewPortChanges()
{
_sizeChangeEventActions.removeAll(keepCapacity: false);
}
/// if true, value highlightning is enabled
public var isHighlightEnabled: Bool { return highlightEnabled; }
/// :returns: true if chart continues to scroll after touch up, false if not.
/// :default: true
public var isDragDecelerationEnabled: Bool
{
return dragDecelerationEnabled;
}
/// Deceleration friction coefficient in [0 ; 1] interval, higher values indicate that speed will decrease slowly, for example if it set to 0, it will stop immediately.
/// 1 is an invalid value, and will be converted to 0.999 automatically.
/// :default: true
public var dragDecelerationFrictionCoef: CGFloat
{
get
{
return _dragDecelerationFrictionCoef;
}
set
{
var val = newValue;
if (val < 0.0)
{
val = 0.0;
}
if (val >= 1.0)
{
val = 0.999;
}
_dragDecelerationFrictionCoef = val;
}
}
// MARK: - ChartAnimatorDelegate
public func chartAnimatorUpdated(chartAnimator: ChartAnimator)
{
setNeedsDisplay();
}
public func chartAnimatorStopped(chartAnimator: ChartAnimator)
{
}
// MARK: - Touches
public override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent)
{
if (!_interceptTouchEvents)
{
super.touchesBegan(touches, withEvent: event);
}
}
public override func touchesMoved(touches: Set<NSObject>, withEvent event: UIEvent)
{
if (!_interceptTouchEvents)
{
super.touchesMoved(touches, withEvent: event);
}
}
public override func touchesEnded(touches: Set<NSObject>, withEvent event: UIEvent)
{
if (!_interceptTouchEvents)
{
super.touchesEnded(touches, withEvent: event);
}
}
public override func touchesCancelled(touches: Set<NSObject>, withEvent event: UIEvent)
{
if (!_interceptTouchEvents)
{
super.touchesCancelled(touches, withEvent: event);
}
}
} | mit | 8cc37da182f184e810841e6e1131d67d | 35.30157 | 268 | 0.623657 | 5.326534 | false | false | false | false |
MarcusSmith/ipaHelperSwift | ipaHelper/ipaHelper/ProfileManager.swift | 1 | 3317 | //
// ProfileManager.swift
// ipaHelper
//
// Created by Marcus Smith on 6/3/15.
// Copyright (c) 2015 ipaHelper. All rights reserved.
//
import Foundation
public class ProfileManager {
//==========================================================================
// MARK: Library
//==========================================================================
public static let library = ProfileManager(directoryPath: "~/Library/MobileDevice/Provisioning Profiles/".stringByExpandingTildeInPath)
//==========================================================================
// MARK: General
//==========================================================================
public var directoryPath: String
init(directoryPath: String) {
self.directoryPath = directoryPath
}
//==========================================================================
// MARK: Profile Caching
//==========================================================================
public var profiles: [Profile] {
if _profiles == nil {
updateProfiles()
}
if let profiles = _profiles {
return profiles
}
return []
}
private var _profiles: [Profile]?
//==========================================================================
// MARK: Filtered Profiles
//==========================================================================
public var expiredProfiles: [Profile] {
return profiles.filter({ $0.isExpired})
}
public func profilesMatching(bundleID: String, profileType: ProfileType? = nil, acceptWildcardMatches: Bool = false) -> [Profile] {
var matches = profiles.filter({ $0.matches(bundleID) })
if !acceptWildcardMatches {
matches = matches.filter({ !$0.isWildcard })
}
if let type = profileType {
matches = matches.filter({ $0.type == type })
}
return matches
}
//==========================================================================
// MARK: Profile Updating
//==========================================================================
public func updateProfiles() {
_profiles = getProfiles()
}
private func getProfiles() -> [Profile] {
var profiles: [Profile] = []
if let libraryFiles = NSFileManager.defaultManager().contentsOfDirectoryAtPath(directoryPath, error: nil) as? [String] {
let profileFiles = libraryFiles.filter({(filePath: String) -> (Bool) in
if filePath.lastPathComponent.pathExtension == "mobileprovision" {
return true
}
return false
})
for profileFile: AnyObject in profileFiles {
if let profilePathComponent = profileFile as? String {
let fullPath = directoryPath + "/" + profilePathComponent
if let profile = Profile(filePath: fullPath) {
profiles.append(profile)
}
}
}
}
return profiles
}
}
| mit | 3a86538e3f02a3d522289139cbb8578c | 30.590476 | 139 | 0.409708 | 6.867495 | false | false | false | false |
ryanipete/AmericanChronicle | AmericanChronicle/Code/Modules/Page/View/PageViewController.swift | 1 | 7431 | import PDFKit
// MARK: -
// MARK: PageUserInterfaceDelegate protocol
protocol PageUserInterfaceDelegate: AnyObject {
func userDidTapDone()
func userDidTapCancel()
func userDidTapShare(with pdf: PDFPage)
}
// MARK: -
// MARK: PageUserInterface protocol
protocol PageUserInterface: AnyObject {
var thumbnailImage: UIImage? { get set }
var document: PDFDocument? { get set }
var highlights: OCRCoordinates? { get set }
var delegate: PageUserInterfaceDelegate? { get set }
var modalPresentationStyle: UIModalPresentationStyle { get set }
var transitioningDelegate: UIViewControllerTransitioningDelegate? { get set }
func showLoadingIndicator()
func hideLoadingIndicator()
func showErrorWithTitle(_ title: String?, message: String?)
func present(_ uiVC: UIViewController, animated: Bool, completion: (() -> Void)?)
}
// MARK: -
// MARK: PageViewController class
final class PageViewController: UIViewController, PageUserInterface {
// MARK: Properties
weak var delegate: PageUserInterfaceDelegate?
var thumbnailImage: UIImage? {
didSet {
thumbnailImageView?.image = thumbnailImage
}
}
@IBOutlet private weak var thumbnailImageView: UIImageView! {
didSet {
thumbnailImageView.image = thumbnailImage
}
}
@IBOutlet private var tapGesture: UITapGestureRecognizer!
@IBOutlet private weak var doneButton: UIButton!
@IBOutlet private weak var shareButton: UIButton!
@IBOutlet private weak var bottomBarBG: UIView!
@IBOutlet private weak var placeholderView: UIView!
@IBOutlet private weak var activityIndicator: UIActivityIndicatorView!
@IBOutlet private weak var loadingView: UIView!
@IBOutlet private weak var progressView: UIProgressView!
@IBOutlet private weak var errorView: UIView!
@IBOutlet private weak var errorTitleLabel: UILabel!
@IBOutlet private weak var errorMessageLabel: UILabel!
@IBOutlet private weak var pageView: PDFPageView!
private let toastButton = UIButton()
// MARK: Internal methods
var document: PDFDocument? {
get {
pageView.document
}
set {
self.pageView.document = newValue
self.refreshAnnotationsIfPageLoaded()
}
}
var highlights: OCRCoordinates? {
didSet {
refreshAnnotationsIfPageLoaded()
}
}
func showLoadingIndicator() {
if isViewLoaded {
loadingView.isHidden = false
activityIndicator.startAnimating()
bottomBarBG.alpha = 0
}
}
func hideLoadingIndicator() {
activityIndicator.stopAnimating()
loadingView.isHidden = true
hidePlaceholderIfVisibleAndLoaded()
}
func hidePlaceholderIfVisibleAndLoaded() {
guard loadingView.isHidden else {
return
}
guard viewIfLoaded?.window != nil else {
return
}
UIView.animate(withDuration: 0.3) {
self.placeholderView.alpha = 0
self.bottomBarBG.alpha = 1.0
}
}
func showErrorWithTitle(_ title: String?, message: String?) {
errorTitleLabel.text = title
errorMessageLabel.text = message
errorView.isHidden = false
}
// MARK: UIViewController overrides
override func viewDidLoad() {
super.viewDidLoad()
doneButton.setBackgroundImage(nil, for: .normal)
doneButton.setTitleColor(.lightText, for: .normal)
doneButton.setTitle(nil, for: .normal)
doneButton.tintColor = .white
let doneImage = UIImage(named: "UIAccessoryButtonX")
doneButton.setImage(doneImage?.withRenderingMode(.alwaysTemplate), for: .normal)
shareButton.setBackgroundImage(nil, for: .normal)
shareButton.setTitleColor(.lightText, for: .normal)
shareButton.setTitle(nil, for: .normal)
shareButton.tintColor = .white
let actionImage = UIImage(named: "UIButtonBarAction")
shareButton.setImage(actionImage?.withRenderingMode(.alwaysTemplate),
for: .normal)
toastButton.backgroundColor = UIColor(white: 1.0, alpha: 0.8)
toastButton.setTitleColor(.darkGray, for: .normal)
toastButton.layer.shadowColor = UIColor.black.cgColor
toastButton.layer.shadowOffset = .zero
toastButton.layer.shadowRadius = 1.0
toastButton.layer.shadowOpacity = 1.0
view.addSubview(toastButton)
errorView.isHidden = true
showLoadingIndicator()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationController?.isNavigationBarHidden = true
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
hidePlaceholderIfVisibleAndLoaded()
}
override var prefersStatusBarHidden: Bool {
true
}
// MARK: Private methods
@IBAction private func shareButtonTapped() {
guard (pageView.document?.pageCount ?? 0) > 0 else {
assertionFailure()
return
}
if let page = pageView.document?.page(at: 0) {
delegate?.userDidTapShare(with: page)
}
}
@IBAction private func doneButtonTapped() {
delegate?.userDidTapDone()
}
@IBAction private func didTapCancelButton() {
delegate?.userDidTapCancel()
}
@IBAction private func didRecognizeTap() {
bottomBarBG.isHidden.toggle()
}
@IBAction private func errorOKButtonTapped() {
delegate?.userDidTapDone()
}
private func refreshAnnotationsIfPageLoaded() {
guard let currentPage = pageView.currentPage else {
return
}
currentPage.removeAllAnnotations()
currentPage.addAnnotations(annotations(for: highlights, inPage: currentPage))
}
private func annotations(for highlights: OCRCoordinates?, inPage page: PDFPage) -> [PDFAnnotation] {
guard let wordCoordinates = highlights?.wordCoordinates else {
return []
}
let pdfSize = page.bounds(for: .mediaBox).size
let widthRatio = pdfSize.width / (highlights?.width ?? 1)
let heightRatio = pdfSize.height / (highlights?.height ?? 1)
return wordCoordinates.flatMap { _, rects in
rects.map { rect in
// Scale rect from website's content size to PDF size
var scaled = rect
scaled.origin.x = rect.origin.x * widthRatio
scaled.origin.y = rect.origin.y * heightRatio
scaled.size.width = rect.size.width * widthRatio
scaled.size.height = rect.size.height * heightRatio
// Convert the scaled rect to PDF's upside-down coordinates
// (Not using PDFView's convert... methods because these aren't
// the view's coordinates, they're the page's coordinates with
// the y-coordinates flipped.
let transform = CGAffineTransform(a: 1, b: 0, c: 0, d: -1, tx: 0, ty: pdfSize.height)
let converted = scaled.applying(transform)
return PDFAnnotation(bounds: converted,
forType: .highlight,
withProperties: nil)
}
}
}
}
| mit | 1ea64bbf5724c8fd689ff1f1b773497e | 31.592105 | 104 | 0.638541 | 5.270213 | false | false | false | false |
hilen/TSWeChat | TSWeChat/Classes/Chat/ChatHelper/UITableView+ChatAdditions.swift | 1 | 2440 | //
// UITableView+ChatAdditions.swift
// TSWeChat
//
// Created by Hilen on 1/29/16.
// Copyright © 2016 Hilen. All rights reserved.
//
import Foundation
extension UITableView {
func reloadData(_ completion: @escaping ()->()) {
UIView.animate(withDuration: 0, animations: {
self.reloadData()
}, completion:{ _ in
completion()
})
}
func insertRowsAtBottom(_ rows: [IndexPath]) {
//保证 insert row 不闪屏
UIView.setAnimationsEnabled(false)
CATransaction.begin()
CATransaction.setDisableActions(true)
self.beginUpdates()
self.insertRows(at: rows, with: .none)
self.endUpdates()
self.scrollToRow(at: rows[0], at: .bottom, animated: false)
CATransaction.commit()
UIView.setAnimationsEnabled(true)
}
func totalRows() -> Int {
var i = 0
var rowCount = 0
while i < self.numberOfSections {
rowCount += self.numberOfRows(inSection: i)
i += 1
}
return rowCount
}
var lastIndexPath: IndexPath? {
if (self.totalRows()-1) > 0{
return IndexPath(row: self.totalRows()-1, section: 0)
} else {
return nil
}
}
//插入数据后调用
func scrollBottomWithoutFlashing() {
guard let indexPath = self.lastIndexPath else {
return
}
UIView.setAnimationsEnabled(false)
CATransaction.begin()
CATransaction.setDisableActions(true)
self.scrollToRow(at: indexPath, at: .bottom, animated: false)
CATransaction.commit()
UIView.setAnimationsEnabled(true)
}
//键盘动画结束后调用
func scrollBottomToLastRow() {
guard let indexPath = self.lastIndexPath else {
return
}
self.scrollToRow(at: indexPath, at: .bottom, animated: false)
}
func scrollToBottom(animated: Bool) {
let bottomOffset = CGPoint(x: 0, y:self.contentSize.height - self.bounds.size.height)
self.setContentOffset(bottomOffset, animated: animated)
}
var isContentInsetBottomZero: Bool {
get { return self.contentInset.bottom == 0 }
}
func resetContentInsetAndScrollIndicatorInsets() {
self.contentInset = UIEdgeInsets.zero
self.scrollIndicatorInsets = UIEdgeInsets.zero
}
}
| mit | 2de2a4312488c10e2f7a5eeb8e97b811 | 26.238636 | 93 | 0.596579 | 4.672515 | false | false | false | false |
ioveracker/oscon-swift | ImageDownloading/ImageDownloading/ViewController.swift | 1 | 1582 | //
// ViewController.swift
// ImageDownloading
//
// Created by Isaac Overacker on 7/21/15.
// Copyright (c) 2015 Isaac Overacker. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var activityIndicator: UIActivityIndicatorView!
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.
}
@IBAction func downloadImage(sender: AnyObject) {
self.activityIndicator.startAnimating()
let URLString = "http://placekitten.com/g/500/500"
let URL = NSURL(string: URLString)
let session = NSURLSession.sharedSession()
if let theURL = URL {
let task = session.dataTaskWithURL(theURL, completionHandler: { (data, response, error) -> Void in
if data == nil {
println("no data, response: \(response)")
return
}
if let theImage = UIImage(data: data!) {
NSOperationQueue.mainQueue().addOperationWithBlock() {
self.imageView.image = theImage
self.activityIndicator.stopAnimating()
}
}
})
task.resume()
}
}
}
| unlicense | 89fd05e7a483a942b566b5275875a36e | 28.296296 | 110 | 0.564475 | 5.436426 | false | false | false | false |
Antondomashnev/ADArrowButton | Source/ADArrowButton.swift | 1 | 13841 | //
// ADArrowButton.swift
// ADArrowButton
//
// Created by Anton Domashnev on 11/29/14.
// Copyright (c) 2014 adomashnev. All rights reserved.
//
import UIKit
import QuartzCore;
enum ArrowDirection: String {
case Left = "Left"
case Right = "Right"
case Top = "Top"
case Bottom = "Bottom"
static var allValues: [String] {
return [ArrowDirection.Left.rawValue, ArrowDirection.Right.rawValue, ArrowDirection.Bottom.rawValue, ArrowDirection.Top.rawValue]
}
static func arrowDirectionFromString(string: String) -> ArrowDirection
{
switch(string){
case "Left":
return .Left
case "Right":
return .Right
case "Top":
return .Top
case "Bottom":
return .Bottom
default:
return .Left
}
}
}
@IBDesignable public class ADArrowButton: UIControl {
private var topLineLayer: CAShapeLayer?
private var bottomLineLayer: CAShapeLayer?
private var startLineLayerPoint: CGPoint! = CGPointZero
private var endTopLineLayerPoint: CGPoint! = CGPointZero
private var endBottomLineLayerPoint: CGPoint! = CGPointZero
private var arrowDirectionEnumValue: ArrowDirection = ArrowDirection.Left
@IBInspectable var ADArrowDirection: String = "Left" {
willSet(newValue) {
assert(newValue == ArrowDirection.Left.rawValue || newValue == ArrowDirection.Right.rawValue || newValue == ArrowDirection.Bottom.rawValue || newValue == ArrowDirection.Top.rawValue, "Invalid arrow direction. Possible values: \(ArrowDirection.allValues)")
self.arrowDirectionEnumValue = ArrowDirection.arrowDirectionFromString(newValue)
}
didSet {
self.recalculateLineLayersPoints()
self.render()
}
}
@IBInspectable var lineColor: UIColor = UIColor.blackColor() {
didSet {
self.render()
}
}
@IBInspectable var highlightedBackgroundColor: UIColor = UIColor.blackColor() {
didSet {
self.render()
}
}
@IBInspectable var normalBackgroundColor: UIColor = UIColor.blackColor() {
didSet {
self.render()
}
}
@IBInspectable var highlightedLineColor: UIColor = UIColor.blackColor() {
didSet {
self.render()
}
}
@IBInspectable var lineWidth: CGFloat = 2 {
didSet {
self.render()
}
}
@IBInspectable var insetTop: CGFloat = 2 {
didSet {
self.recalculateLineLayersPoints()
self.render()
}
}
@IBInspectable var insetLeft: CGFloat = 2 {
didSet {
self.recalculateLineLayersPoints()
self.render()
}
}
@IBInspectable var insetBottom: CGFloat = 2 {
didSet {
self.recalculateLineLayersPoints()
self.render()
}
}
@IBInspectable var insetRight: CGFloat = 2 {
didSet {
self.recalculateLineLayersPoints()
self.render()
}
}
@IBInspectable override public var enabled: Bool {
didSet {
self.recalculateLineLayersPoints()
self.render()
}
}
required public override init(frame: CGRect)
{
super.init(frame: frame)
self.setUp()
}
//MARK: - Interface
public func setEnabled(enabled: Bool, animated: Bool)
{
if(animated){
super.enabled = enabled
self.startLineLayerPoint = self.lineLayersStartPointForCurrentState()
self.animateEnableChange()
}
else{
self.enabled = enabled
}
}
//MARK: - NSCoding
required public init(coder aDecoder: NSCoder)
{
super.init(coder: aDecoder)
self.setUp()
}
//MARK: - UI
private func addTopLineLayer()
{
let topLine = CAShapeLayer()
self.layer.addSublayer(topLine)
self.topLineLayer = topLine
}
private func addBottomLineLayer()
{
let bottomLine = CAShapeLayer()
self.layer.addSublayer(bottomLine)
self.bottomLineLayer = bottomLine
}
//MARK: - Helpers
private func setUp()
{
self.addTopLineLayer()
self.addBottomLineLayer()
}
private func recalculateLineLayersPoints()
{
self.startLineLayerPoint = self.lineLayersStartPointForCurrentState()
self.endTopLineLayerPoint = self.topLineLayersEndPointForCurrentState()
self.endBottomLineLayerPoint = self.bottomLineLayersEndPointForCurrentState()
}
private func lineLayersStartPointForCurrentState() -> CGPoint
{
switch(self.arrowDirectionEnumValue){
case .Left:
return CGPoint(x: self.insetLeft, y: self.bounds.height / 2)
case .Right:
return CGPoint(x: self.bounds.width - self.insetRight, y: self.bounds.height / 2)
case .Top:
return CGPoint(x: self.bounds.width / 2, y: self.insetTop)
case .Bottom:
return CGPoint(x: self.bounds.width / 2, y: self.bounds.height - self.insetBottom)
}
}
private func topLineLayersEndPointForCurrentState() -> CGPoint
{
if(self.enabled){
switch(self.arrowDirectionEnumValue){
case .Left:
let pointY = self.insetTop
let pointX = self.bounds.size.width - self.insetRight
return CGPoint(x: pointX, y: pointY)
case .Right:
let pointY = self.insetTop
let pointX = self.insetLeft
return CGPoint(x: pointX, y: pointY)
case .Top:
let pointY = self.bounds.height - self.insetBottom
let pointX = self.insetLeft
return CGPoint(x: pointX, y: pointY)
case .Bottom:
let pointY = self.insetTop
let pointX = self.insetLeft
return CGPoint(x: pointX, y: pointY)
}
}
else{
switch(self.arrowDirectionEnumValue){
case .Left:
let pointY = self.bounds.size.height / 2
let pointX = self.bounds.size.width - self.insetRight
return CGPoint(x: pointX, y: pointY)
case .Right:
let pointY = self.bounds.size.height / 2
let pointX = self.insetLeft
return CGPoint(x: pointX, y: pointY)
case .Top:
let pointY = self.bounds.height - self.insetBottom
let pointX = self.bounds.size.width / 2
return CGPoint(x: pointX, y: pointY)
case .Bottom:
let pointY = self.insetTop
let pointX = self.bounds.size.width / 2
return CGPoint(x: pointX, y: pointY)
}
}
}
private func bottomLineLayersEndPointForCurrentState() -> CGPoint
{
if(self.enabled){
switch(self.arrowDirectionEnumValue){
case .Left:
let pointY = self.bounds.height - self.insetBottom
let pointX = self.bounds.size.width - self.insetRight
return CGPoint(x: pointX, y: pointY)
case .Right:
let pointY = self.bounds.height - self.insetBottom
let pointX = self.insetLeft
return CGPoint(x: pointX, y: pointY)
case .Top:
let pointY = self.bounds.height - self.insetBottom
let pointX = self.bounds.size.width - self.insetRight
return CGPoint(x: pointX, y: pointY)
case .Bottom:
let pointY = self.insetTop
let pointX = self.bounds.size.width - self.insetRight
return CGPoint(x: pointX, y: pointY)
}
}
else{
switch(self.arrowDirectionEnumValue){
case .Left:
let pointY = self.bounds.size.height / 2
let pointX = self.bounds.size.width - self.insetRight
return CGPoint(x: pointX, y: pointY)
case .Right:
let pointY = self.bounds.size.height / 2
let pointX = self.insetLeft
return CGPoint(x: pointX, y: pointY)
case .Top:
let pointY = self.bounds.height - self.insetBottom
let pointX = self.bounds.size.width / 2
return CGPoint(x: pointX, y: pointY)
case .Bottom:
let pointY = self.insetTop
let pointX = self.bounds.size.width / 2
return CGPoint(x: pointX, y: pointY)
}
}
}
private func lineLayerPath(startPoint: CGPoint, endPoint: CGPoint) -> UIBezierPath
{
let path: UIBezierPath = UIBezierPath()
path.moveToPoint(startPoint)
path.addLineToPoint(endPoint)
return path
}
private func render()
{
self.backgroundColor = self.highlighted ? self.highlightedBackgroundColor : self.normalBackgroundColor
self.topLineLayer?.strokeColor = self.highlighted ? self.highlightedLineColor.CGColor : self.lineColor.CGColor
self.bottomLineLayer?.strokeColor = self.highlighted ? self.highlightedLineColor.CGColor : self.lineColor.CGColor
self.topLineLayer?.lineWidth = self.lineWidth
self.bottomLineLayer?.lineWidth = self.lineWidth
self.topLineLayer?.path = self.lineLayerPath(self.startLineLayerPoint, endPoint: self.endTopLineLayerPoint).CGPath
self.bottomLineLayer?.path = self.lineLayerPath(self.startLineLayerPoint, endPoint: self.endBottomLineLayerPoint).CGPath
}
private func animateEnableChange()
{
var topLineLayerAnimation: POPSpringAnimation = POPSpringAnimation()
topLineLayerAnimation.toValue = NSValue(CGPoint: self.topLineLayersEndPointForCurrentState())
topLineLayerAnimation.property = self.topLayerLinePathAnimationProperty()
topLineLayerAnimation.springBounciness = self.enabled ? 12 : 0
self.pop_addAnimation(topLineLayerAnimation, forKey: "topLineLayerAnimation")
var bottomLineLayerAnimation: POPSpringAnimation = POPSpringAnimation()
bottomLineLayerAnimation.toValue = NSValue(CGPoint: self.bottomLineLayersEndPointForCurrentState())
bottomLineLayerAnimation.property = self.bottomLayerLinePathAnimationProperty()
bottomLineLayerAnimation.springBounciness = self.enabled ? 12 : 0
self.pop_addAnimation(bottomLineLayerAnimation, forKey: "bottomLineLayerAnimation")
}
private func topLayerLinePathAnimationProperty() -> POPAnimatableProperty
{
let animatableProperty: POPAnimatableProperty = POPAnimatableProperty.propertyWithName("topLayerLinePathAnimationProperty", initializer: { (prop :POPMutableAnimatableProperty!) -> Void in
prop.readBlock = {(button: AnyObject!, values: UnsafeMutablePointer<CGFloat>) -> Void in
let arrowButton: ADArrowButton = button as ADArrowButton!
values[0] = arrowButton.endTopLineLayerPoint.x
values[1] = arrowButton.endTopLineLayerPoint.y
}
prop.writeBlock = {(button: AnyObject!, values: UnsafePointer<CGFloat>) -> Void in
let arrowButton: ADArrowButton = button as ADArrowButton!
arrowButton.endTopLineLayerPoint = CGPoint(x: values[0], y: values[1])
arrowButton.topLineLayer?.path = arrowButton.lineLayerPath(arrowButton.startLineLayerPoint, endPoint: arrowButton.endTopLineLayerPoint).CGPath
}
}) as POPAnimatableProperty
return animatableProperty
}
private func bottomLayerLinePathAnimationProperty() -> POPAnimatableProperty
{
let animatableProperty: POPAnimatableProperty = POPAnimatableProperty.propertyWithName("bottomLayerLinePathAnimationProperty", initializer: { (prop :POPMutableAnimatableProperty!) -> Void in
prop.readBlock = {(button: AnyObject!, values: UnsafeMutablePointer<CGFloat>) -> Void in
let arrowButton: ADArrowButton = button as ADArrowButton!
values[0] = arrowButton.endBottomLineLayerPoint.x
values[1] = arrowButton.endBottomLineLayerPoint.y
}
prop.writeBlock = {(button: AnyObject!, values: UnsafePointer<CGFloat>) -> Void in
let arrowButton: ADArrowButton = button as ADArrowButton!
arrowButton.endBottomLineLayerPoint = CGPoint(x: values[0], y: values[1])
arrowButton.bottomLineLayer?.path = arrowButton.lineLayerPath(arrowButton.startLineLayerPoint, endPoint: arrowButton.endBottomLineLayerPoint).CGPath
}
}) as POPAnimatableProperty
return animatableProperty
}
//MARK: - UIControl
public override func beginTrackingWithTouch(touch: UITouch, withEvent event: UIEvent) -> Bool {
self.highlighted = true
self.sendActionsForControlEvents(UIControlEvents.TouchDown)
return true
}
public override func continueTrackingWithTouch(touch: UITouch, withEvent event: UIEvent) -> Bool {
return true
}
public override func endTrackingWithTouch(touch: UITouch, withEvent event: UIEvent) {
self.sendActionsForControlEvents(UIControlEvents.TouchUpInside)
self.highlighted = false
}
public override func cancelTrackingWithEvent(event: UIEvent?) {
self.sendActionsForControlEvents(UIControlEvents.TouchUpOutside)
self.highlighted = false
}
}
| mit | 3e30b8cb91306a197dced83d62536640 | 35.909333 | 267 | 0.614912 | 5.408753 | false | false | false | false |
turekj/ReactiveTODO | ReactiveTODOTests/Classes/Logic/Messages/Impl/MessageFactorySpec.swift | 1 | 2974 | @testable import ReactiveTODOFramework
import Foundation
import Messages
import Nimble
import Quick
@available(iOS 10.0, *)
class MessageFactorySpec: QuickSpec {
override func spec() {
describe("MessageFactory") {
let todoNoteDAO = TODONoteDataAccessObjectMock()
let note = TODONote()
note.priority = .High
note.note = "Something to do"
todoNoteDAO.resolvedNote = note
let dateFormatter = DateFormatterMock()
dateFormatter.formatReturnValue = "formatted_D@73"
let bundle = NSBundle(forClass: MessageFactorySpec.self)
let imageFactory = MessageImageFactoryMock()
imageFactory.returnedImage = UIImage(named: "white_pixel",
inBundle: bundle,
compatibleWithTraitCollection: nil)
let sut = MessageFactory(todoNoteDAO: todoNoteDAO,
dateFormatter: dateFormatter,
messageImageFactory: imageFactory)
it("Should resolve correct note") {
sut.createMessage("correct_note_guid")
expect(todoNoteDAO.resolvedNoteGuid).to(equal("correct_note_guid"))
}
it("Should create message layout") {
let message = sut.createMessage("selfie_guid")
expect(message.layout).toNot(beNil())
expect(message.layout).to(beAKindOf(MSMessageTemplateLayout.self))
}
it("Should set message image") {
let expectedImage = UIImage(named: "white_pixel",
inBundle: bundle,
compatibleWithTraitCollection: nil)!
let expectedImageData = UIImagePNGRepresentation(expectedImage)
let message = sut.createMessage("asdf")
expect((message.layout as? MSMessageTemplateLayout)?.image).toNot(beNil())
expect(UIImagePNGRepresentation(
((message.layout as? MSMessageTemplateLayout)?.image)!)).to(
equal(expectedImageData))
}
it("Should set title with note") {
let message = sut.createMessage("123")
expect((message.layout as? MSMessageTemplateLayout)?.caption).to(
equal("Something to do"))
}
it("Should set subtitle with date") {
let message = sut.createMessage("890")
expect((message.layout as? MSMessageTemplateLayout)?.subcaption).to(
equal("formatted_D@73"))
}
}
}
}
| mit | ca888d7cf0918a6b587c66f935f8e982 | 39.189189 | 90 | 0.507734 | 6.354701 | false | false | false | false |
cjcaufield/SecretKit | SecretKit/ios/SGColorView.swift | 1 | 1251 | //
// SGColorView.swift
// SecretKit
//
// Created by Colin Caufield on 2016-01-14.
// Copyright © 2016 Secret Geometry. All rights reserved.
//
import UIKit
public class SGColorView: UIView {
public var color = UIColor.black {
didSet {
self.setNeedsDisplay()
}
}
public override init(frame: CGRect) {
super.init(frame: frame)
self.initCommon()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.initCommon()
}
public func initCommon() {
self.isOpaque = false
}
public override func draw(_ rect: CGRect) {
let inner = rect.insetBy(dx: 1.0, dy: 1.0)
var fill = getRGBA(forColor: self.color)
let light = fill[0] > 0.9 && fill[1] > 0.9 && fill[2] > 0.9
var stroke = fill
if light {
stroke = [ 0.8, 0.8, 0.8, 1.0 ]
}
let context = UIGraphicsGetCurrentContext()
context!.addEllipse(in: inner)
context!.setStrokeColor(stroke)
context!.setFillColor(fill)
context!.setLineWidth(1.5)
context!.drawPath(using: CGPathDrawingMode.fillStroke)
}
}
| mit | 26888f8a9221e150cd2abf2d6fb0939a | 23.038462 | 67 | 0.5568 | 4.058442 | false | false | false | false |
cjcaufield/SecretKit | SecretKit/ios/SGCellData.swift | 1 | 3159 | //
// SGRowData.swift
// TermKit
//
// Created by Colin Caufield on 2016-01-13.
// Copyright © 2016 Secret Geometry. All rights reserved.
//
import Foundation
public let BASIC_CELL_ID = "BasicCell"
public let LABEL_CELL_ID = "LabelCell"
public let TEXT_FIELD_CELL_ID = "TextFieldCell"
public let SWITCH_CELL_ID = "SwitchCell"
public let SLIDER_CELL_ID = "SliderCell"
public let TIME_LABEL_CELL_ID = "TimeLabelCell"
public let TIME_PICKER_CELL_ID = "TimePickerCell"
public let PICKER_LABEL_CELL_ID = "PickerLabelCell"
public let PICKER_CELL_ID = "PickerCell"
public let DATE_LABEL_CELL_ID = "DateLabelCell"
public let DATE_PICKER_CELL_ID = "DatePickerCell"
public let SEGMENTED_CELL_ID = "SegmentedCell"
public let TEXT_VIEW_CELL_ID = "TextViewCell"
public let COLOR_CELL_ID = "ColorCell"
public let OTHER_CELL_ID = "OtherCell"
public enum SGRowDataTargetType {
case ViewController
case Object
}
public class SGRowData: Equatable {
public var cellIdentifier: String
public var title: String
public var modelPath: String?
public var targetType: SGRowDataTargetType
public var action: Selector?
public var segueName: String?
public var checked: Bool?
public var range: NSRange
public var expandable = false
public var hidden = false
public init(cellIdentifier: String = OTHER_CELL_ID,
title: String = "",
modelPath: String? = nil,
targetType: SGRowDataTargetType = .Object,
action: Selector? = nil,
segueName: String? = nil,
checked: Bool? = nil,
range: NSRange = NSMakeRange(0, 1),
expandable: Bool = false,
hidden: Bool = false) {
self.cellIdentifier = cellIdentifier
self.title = title
self.modelPath = modelPath
self.targetType = targetType
self.action = action
self.segueName = segueName
self.checked = checked
self.range = range
self.expandable = expandable
self.hidden = hidden
}
}
public func ==(a: SGRowData, b: SGRowData) -> Bool {
return ObjectIdentifier(a) == ObjectIdentifier(b)
}
public class SGSliderRowData : SGRowData {
/*
public init(title: String = "",
targetType: SGRowDataTargetType = .Object,
modelPath: String? = nil,
range: NSRange = NSMakeRange(0, 1)) {
super.init(cellIdentifier: SLIDER_CELL_ID,
title: title,
targetType: targetType,
modelPath: modelPath)
self.range = range
}
*/
}
public class SGSectionData {
public var rows = [SGRowData]()
public var title = ""
public init(_ rows: SGRowData..., title: String = "") {
self.rows = rows
}
}
public class SGTableData {
public var sections = [SGSectionData]()
public init() {
// nothing
}
public init(_ sections: SGSectionData...) {
self.sections = sections
}
}
| mit | 7a729dedaba0cf88725eb70e179a02af | 27.196429 | 59 | 0.60133 | 4.349862 | false | false | false | false |
banxi1988/Staff | Pods/BXForm/Pod/Classes/View/OvalImageView.swift | 1 | 505 | //
// OvalImageView.swift
// Pods
//
// Created by Haizhen Lee on 16/1/15.
//
//
import UIKit
public class OvalImageView: UIImageView {
public lazy var maskLayer : CAShapeLayer = { [unowned self] in
let maskLayer = CAShapeLayer()
maskLayer.frame = self.frame
self.layer.mask = maskLayer
return maskLayer
}()
public override func layoutSubviews() {
super.layoutSubviews()
maskLayer.frame = bounds
maskLayer.path = UIBezierPath(ovalInRect:bounds).CGPath
}
} | mit | db762d9c9c86d79130bbfd4d8e5ff72a | 18.461538 | 64 | 0.679208 | 4.173554 | false | false | false | false |
rnystrom/GitHawk | Classes/History/PathHistoryViewController.swift | 1 | 2259 | //
// PathHistoryViewController.swift
// Freetime
//
// Created by Ryan Nystrom on 10/20/18.
// Copyright © 2018 Ryan Nystrom. All rights reserved.
//
import UIKit
import IGListKit
import Squawk
import DropdownTitleView
final class PathHistoryViewController: BaseListViewController<String>,
BaseListViewControllerDataSource {
private let viewModel: PathHistoryViewModel
private var models = [PathCommitModel]()
init(viewModel: PathHistoryViewModel) {
self.viewModel = viewModel
super.init(emptyErrorMessage: NSLocalizedString("Cannot load history.", comment: ""))
dataSource = self
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
let titleView = DropdownTitleView()
titleView.configure(
title: NSLocalizedString("History", comment: ""),
subtitle: viewModel.path?.path,
chevronEnabled: false
)
titleView.addTouchEffect()
navigationItem.titleView = titleView
}
override func fetch(page: String?) {
viewModel.client.client.fetchHistory(
owner: viewModel.owner,
repo: viewModel.repo,
branch: viewModel.branch,
path: viewModel.path?.path,
cursor: page,
width: view.safeContentWidth(with: feed.collectionView),
contentSizeCategory: UIApplication.shared.preferredContentSizeCategory
) { [weak self] result in
switch result {
case .error(let error):
Squawk.show(error: error)
case .success(let commits, let nextPage):
if page == nil {
self?.models = commits
} else {
self?.models += commits
}
self?.update(page: nextPage, animated: trueUnlessReduceMotionEnabled)
}
}
}
// MARK: BaseListViewControllerDataSource
func models(adapter: ListSwiftAdapter) -> [ListSwiftPair] {
return models.map { ListSwiftPair.pair($0, { PathCommitSectionController() }) }
}
}
| mit | d3ab6470f03555a7d189bc00a9f2cbb3 | 29.931507 | 93 | 0.605846 | 5.263403 | false | false | false | false |
MounikaAnkam/Learn-The-Anthem | project/Piano1.swift | 1 | 14739 | //
// Piano1.swift
// project
//
// Created by Ankam,Mounika on 3/30/15.
// Copyright (c) 2015 Mounika. All rights reserved.
//
import UIKit
import AVFoundation
class Piano1: UIViewController {
@IBOutlet weak var cName: UILabel!
var name:String!
var playing:Bool = false
var audioPlayer:AVAudioPlayer!
var highlighted:Bool = true
@IBOutlet var playBTN:UIButton!
@IBOutlet weak var C3: UIButton!
@IBOutlet weak var D3: UIButton!
@IBOutlet weak var E3: UIButton!
@IBOutlet weak var F3: UIButton!
@IBOutlet weak var G3: UIButton!
@IBOutlet weak var A3: UIButton!
@IBOutlet weak var B3: UIButton!
@IBOutlet weak var C4: UIButton!
@IBOutlet weak var D4: UIButton!
@IBOutlet weak var E4: UIButton!
@IBOutlet weak var F4: UIButton!
@IBOutlet weak var G4: UIButton!
@IBOutlet weak var A4: UIButton!
@IBOutlet weak var B4: UIButton!
@IBOutlet weak var C5: UIButton!
var pianoSoundC3 = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("C3", ofType: "mp3")!)
var audioplayerC3 = AVAudioPlayer()
var pianoSoundCS = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("C#", ofType: "mp3")!)
var audioPlayerCS = AVAudioPlayer()
var pianoSoundD = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("D", ofType: "mp3")!)
var audioPlayerD = AVAudioPlayer()
var pianoSoundDS = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("D#", ofType: "mp3")!)
var audioPlayerDS = AVAudioPlayer()
var pianoSoundE = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("E", ofType: "mp3")!)
var audioPlayerE = AVAudioPlayer()
var pianoSoundF = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("F", ofType: "mp3")!)
var audioPlayerF = AVAudioPlayer()
var pianoSoundFS = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("F#", ofType: "mp3")!)
var audioPlayerFS = AVAudioPlayer()
var pianoSoundG = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("G", ofType: "mp3")!)
var audioPlayerG = AVAudioPlayer()
var pianoSoundGS = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("G#", ofType: "mp3")!)
var audioPlayerGS = AVAudioPlayer()
var pianoSoundA = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("A", ofType: "mp3")!)
var audioPlayerA = AVAudioPlayer()
var pianoSoundAS = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("A#", ofType: "mp3")!)
var audioPlayerAS = AVAudioPlayer()
var pianoSoundB = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("B", ofType: "mp3")!)
var audioPlayerB = AVAudioPlayer()
var pianoSoundC4 = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("C4", ofType: "mp3")!)
var audioPlayerC4 = AVAudioPlayer()
var pianoSoundC4S = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("C#4", ofType: "mp3")!)
var audioPlayerC4S = AVAudioPlayer()
var pianoSoundD4 = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("D4", ofType: "mp3")!)
var audioPlayerD4 = AVAudioPlayer()
var pianoSoundD4S = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("D#4", ofType: "mp3")!)
var audioPlayerD4S = AVAudioPlayer()
var pianoSoundE4 = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("E4", ofType: "mp3")!)
var audioPlayerE4 = AVAudioPlayer()
var pianoSoundF4 = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("F4", ofType: "mp3")!)
var audioPlayerF4 = AVAudioPlayer()
var pianoSoundF4S = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("F#4", ofType: "mp3")!)
var audioPlayerF4S = AVAudioPlayer()
var pianoSoundG4 = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("G4", ofType: "mp3")!)
var audioPlayerG4 = AVAudioPlayer()
var pianoSoundG4S = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("G#4", ofType: "mp3")!)
var audioPlayerG4S = AVAudioPlayer()
var pianoSoundA4 = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("A4", ofType: "mp3")!)
var audioPlayerA4 = AVAudioPlayer()
var pianoSoundA4S = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("A#4", ofType: "mp3")!)
var audioPlayerA4S = AVAudioPlayer()
var pianoSoundB4 = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("B4", ofType: "mp3")!)
var audioPlayerB4 = AVAudioPlayer()
var pianoSoundC5 = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("C5", ofType: "mp3")!)
var audioPlayerC5 = AVAudioPlayer()
override func shouldAutorotate() -> Bool {
return true
}
override func supportedInterfaceOrientations() -> Int {
return Int(UIInterfaceOrientationMask.Landscape.rawValue)
}
override func viewDidLoad() {
super.viewDidLoad()
cName.text = name
self.view.backgroundColor = UIColor(patternImage: UIImage(named: "bg3.png")!)
C3.backgroundColor = UIColor.whiteColor()
D3.backgroundColor = UIColor.whiteColor()
E3.backgroundColor = UIColor.whiteColor()
F3.backgroundColor = UIColor.whiteColor()
G3.backgroundColor = UIColor.whiteColor()
A3.backgroundColor = UIColor.whiteColor()
B3.backgroundColor = UIColor.whiteColor()
C4.backgroundColor = UIColor.whiteColor()
D4.backgroundColor = UIColor.whiteColor()
E4.backgroundColor = UIColor.whiteColor()
F4.backgroundColor = UIColor.whiteColor()
G4.backgroundColor = UIColor.whiteColor()
A4.backgroundColor = UIColor.whiteColor()
B4.backgroundColor = UIColor.whiteColor()
C5.backgroundColor = UIColor.whiteColor()
var playAudio = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource(name, ofType: "mp3")!)
audioPlayer = AVAudioPlayer()
audioPlayer = AVAudioPlayer(contentsOfURL: playAudio, error: nil)
audioPlayer.prepareToPlay()
audioplayerC3 = AVAudioPlayer(contentsOfURL: pianoSoundC3, error: nil)
audioplayerC3.prepareToPlay()
audioPlayerCS = AVAudioPlayer(contentsOfURL: pianoSoundCS, error: nil)
audioPlayerCS.prepareToPlay()
audioPlayerD = AVAudioPlayer(contentsOfURL: pianoSoundD, error: nil)
audioPlayerD.prepareToPlay()
audioPlayerDS = AVAudioPlayer(contentsOfURL: pianoSoundDS, error: nil)
audioPlayerDS.prepareToPlay()
audioPlayerE = AVAudioPlayer(contentsOfURL: pianoSoundE, error: nil)
audioPlayerE.prepareToPlay()
audioPlayerF = AVAudioPlayer(contentsOfURL: pianoSoundF, error: nil)
audioPlayerF.prepareToPlay()
audioPlayerFS = AVAudioPlayer(contentsOfURL: pianoSoundFS, error: nil)
audioPlayerFS.prepareToPlay()
audioPlayerG = AVAudioPlayer(contentsOfURL: pianoSoundG, error: nil)
audioPlayerG.prepareToPlay()
audioPlayerGS = AVAudioPlayer(contentsOfURL: pianoSoundGS, error: nil)
audioPlayerGS.prepareToPlay()
audioPlayerA = AVAudioPlayer(contentsOfURL: pianoSoundA, error: nil)
audioPlayerA.prepareToPlay()
audioPlayerAS = AVAudioPlayer(contentsOfURL: pianoSoundAS, error: nil)
audioPlayerAS.prepareToPlay()
audioPlayerB = AVAudioPlayer(contentsOfURL: pianoSoundB, error: nil)
audioPlayerB.prepareToPlay()
audioPlayerC4 = AVAudioPlayer(contentsOfURL: pianoSoundC4, error: nil)
audioPlayerC4.prepareToPlay()
audioPlayerC4S = AVAudioPlayer(contentsOfURL: pianoSoundC4S, error: nil)
audioPlayerC4S.prepareToPlay()
audioPlayerD4 = AVAudioPlayer(contentsOfURL: pianoSoundD4, error: nil)
audioPlayerD4 .prepareToPlay()
audioPlayerD4S = AVAudioPlayer(contentsOfURL: pianoSoundD4S, error: nil)
audioPlayerD4S.prepareToPlay()
audioPlayerE4 = AVAudioPlayer(contentsOfURL: pianoSoundE4, error: nil)
audioPlayerE4.prepareToPlay()
audioPlayerF4 = AVAudioPlayer(contentsOfURL: pianoSoundF4, error: nil)
audioPlayerF4.prepareToPlay()
audioPlayerF4S = AVAudioPlayer(contentsOfURL: pianoSoundF4S, error: nil)
audioPlayerF4S.prepareToPlay()
audioPlayerG4 = AVAudioPlayer(contentsOfURL: pianoSoundG4, error: nil)
audioPlayerG4.prepareToPlay()
audioPlayerG4S = AVAudioPlayer(contentsOfURL: pianoSoundG4S, error: nil)
audioPlayerG4S.prepareToPlay()
audioPlayerA4 = AVAudioPlayer(contentsOfURL: pianoSoundA4, error: nil)
audioPlayerA4.prepareToPlay()
audioPlayerA4S = AVAudioPlayer(contentsOfURL: pianoSoundA4S, error: nil)
audioPlayerA4S.prepareToPlay()
audioPlayerB4 = AVAudioPlayer(contentsOfURL: pianoSoundB4, error: nil)
audioPlayerB4.prepareToPlay()
audioPlayerC5 = AVAudioPlayer(contentsOfURL: pianoSoundC5, error: nil)
audioPlayerC5.prepareToPlay()
// Do any additional setup after loading the view.
}
@IBAction func C3(sender: UIButton) {
audioplayerC3.currentTime = 0
audioplayerC3.play()
}
@IBAction func CS(sender: UIButton) {
audioPlayerCS.currentTime = 0
audioPlayerCS.play()
}
@IBAction func D(sender: UIButton) {
audioPlayerD.currentTime = 0
audioPlayerD.play()
}
@IBAction func DS(sender: UIButton) {
audioPlayerDS.currentTime = 0
audioPlayerDS.play()
}
@IBAction func E(sender: UIButton) {
audioPlayerE.currentTime = 0
audioPlayerE.play()
}
@IBAction func F(sender: UIButton) {
audioPlayerF.currentTime = 0
audioPlayerF.play()
}
@IBAction func FS(sender: UIButton) {
audioPlayerFS.currentTime = 0
audioPlayerFS.play()
}
@IBAction func G(sender: UIButton) {
audioPlayerG.currentTime = 0
audioPlayerG.play()
}
@IBAction func GS(sender: UIButton) {
audioPlayerGS.currentTime = 0
audioPlayerGS.play()
}
@IBAction func A(sender: UIButton) {
audioPlayerA.currentTime = 0
audioPlayerA.play()
}
@IBAction func AS(sender: UIButton) {
audioPlayerAS.currentTime = 0
audioPlayerAS.play()
}
@IBAction func B(sender: UIButton) {
audioPlayerB.currentTime = 0
audioPlayerB.play()
}
@IBAction func C4(sender: UIButton) {
audioPlayerC4.currentTime = 0
audioPlayerC4.play()
}
@IBAction func C4S(sender: UIButton) {
audioPlayerC4S.currentTime = 0
audioPlayerC4S.play()
}
@IBAction func D4(sender: UIButton) {
audioPlayerD4.currentTime = 0
audioPlayerD4.play()
}
@IBAction func D4S(sender: UIButton) {
audioPlayerD4S.currentTime = 0
audioPlayerD4S.play()
}
@IBAction func E4(sender: UIButton) {
audioPlayerE4.currentTime = 0
audioPlayerE4.play()
}
@IBAction func F4(sender: UIButton) {
audioPlayerF4.currentTime = 0
audioPlayerF4.play()
}
@IBAction func F4S(sender: UIButton) {
audioPlayerF4S.currentTime = 0
audioPlayerF4S.play()
}
@IBAction func G4(sender: UIButton) {
audioPlayerG4.currentTime = 0
audioPlayerG4.play()
}
@IBAction func G4S(sender: UIButton) {
audioPlayerG4S.currentTime = 0
audioPlayerG4S.play()
}
@IBAction func A4(sender: UIButton) {
audioPlayerA4.currentTime = 0
audioPlayerA4.play()
}
@IBAction func A4S(sender: UIButton) {
audioPlayerA4S.currentTime = 0
audioPlayerA4S.play()
}
@IBAction func B4(sender: UIButton) {
audioPlayerB4.currentTime = 0
audioPlayerB4.play()
}
@IBAction func C5(sender: UIButton) {
audioPlayerC5.currentTime = 0
audioPlayerC5.play()
}
@IBAction func playAction(sender: AnyObject) {
if(playing == false) {
audioPlayer.play()
playBTN.setBackgroundImage(UIImage(named: "pause.png"), forState: UIControlState.Normal)
playing = true
}
else if playing == true {
audioPlayer.pause()
playBTN.setBackgroundImage(UIImage(named: "play.png"), forState: UIControlState.Normal)
playing = false
}
}
@IBAction func stopAction(sender: AnyObject) {
audioPlayer.stop()
playBTN.setBackgroundImage(UIImage(named: "play.png"), forState: UIControlState.Normal)
playing = false
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func Done(sender: AnyObject) {
self.dismissViewControllerAnimated(true , completion: nil)
}
/*
// 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 | 8e716a5149525a932dd5955043cbf59b | 31.251641 | 112 | 0.612864 | 5.351852 | false | false | false | false |
iOS-mamu/SS | P/Potatso/Base/RequestEventRow.swift | 1 | 2856 | //
// RequestStageCell.swift
// Potatso
//
// Created by LEI on 7/17/16.
// Copyright © 2016 TouchingApp. All rights reserved.
//
import Foundation
import PotatsoModel
import Eureka
import Cartography
final class RequestEventRow: Row<RequestEvent, RequestEventRowCell>, RowType {
required init(tag: String?) {
super.init(tag: tag)
displayValueFor = nil
}
}
class RequestEventRowCell: Cell<RequestEvent>, CellType {
static let dateformatter: DateFormatter = {
let f = DateFormatter()
f.dateFormat = "MM-dd hh:mm:ss.SSS"
return f
}()
var copyContent: String? {
return contentLabel.text
}
required init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func setup() {
super.setup()
selectionStyle = .none
preservesSuperviewLayoutMargins = false
layoutMargins = UIEdgeInsets.zero
separatorInset = UIEdgeInsets.zero
contentView.addSubview(titleLabel)
contentView.addSubview(contentLabel)
contentView.addSubview(timeLabel)
constrain(titleLabel, timeLabel, contentLabel, contentView) { titleLabel, timeLabel, contentLabel, contentView in
titleLabel.leading == contentView.leading + 15
titleLabel.top == contentView.top + 14
timeLabel.leading == titleLabel.trailing + 10
timeLabel.centerY == titleLabel.centerY
timeLabel.trailing == contentView.trailing - 15
contentLabel.top == titleLabel.bottom + 8
contentLabel.leading == titleLabel.leading
contentLabel.trailing == contentView.trailing - 15
contentLabel.bottom == contentView.bottom - 14
}
}
override func update() {
super.update()
guard let event = row.value else {
return
}
titleLabel.text = event.stage.description
timeLabel.text = RequestEventRowCell.dateformatter.string(from: Date(timeIntervalSince1970: event.timestamp))
contentLabel.text = event.contentDescription
}
lazy var titleLabel: UILabel = {
let v = UILabel()
v.font = UIFont.systemFont(ofSize: 13)
v.textColor = Color.Gray
return v
}()
lazy var timeLabel: UILabel = {
let v = UILabel()
v.font = UIFont.systemFont(ofSize: 13)
v.textColor = Color.Gray
v.textAlignment = .right
return v
}()
lazy var contentLabel: UILabel = {
let v = UILabel()
v.font = UIFont.systemFont(ofSize: 16)
v.textColor = Color.Black
v.numberOfLines = 0
return v
}()
}
| mit | 9f54ad3ad58d92e95f8433856b6e8745 | 27.838384 | 121 | 0.632224 | 4.855442 | false | false | false | false |
richardbuckle/Laurine | LaurineGenerator.swift | 1 | 72196 | #!/usr/bin/env xcrun -sdk macosx swift
//
// Laurine - Storyboard Generator Script
//
// Generate swift localization file based on localizables.string
//
// Usage:
// laurine.swift Main.storyboard > Output.swift
//
// Licence: MIT
// Author: Jiří Třečák http://www.jiritrecak.com @jiritrecak
//
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
// MARK: - CommandLine Tool
/* NOTE *
* I am using command line tool for parsing of the input / output arguments. Since static frameworks are not yet
* supported, I just hardcoded entire project to keep it.
* For whoever is interested in the project, please check their repository. It rocks!
* I'm not an author of the code that follows. Licence kept intact.
*
* https://github.com/jatoben/CommandLine
*
*/
/*
* CommandLine.swift, Option.swift, StringExtensions.swift
* Copyright (c) 2014 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.
*/
/* Required for setlocale(3) */
#if os(OSX)
import Darwin
#elseif os(Linux)
import Glibc
#endif
let ShortOptionPrefix = "-"
let LongOptionPrefix = "--"
/* Stop parsing arguments when an ArgumentStopper (--) is detected. This is a GNU getopt
* convention; cf. https://www.gnu.org/prep/standards/html_node/Command_002dLine-Interfaces.html
*/
let ArgumentStopper = "--"
/* Allow arguments to be attached to flags when separated by this character.
* --flag=argument is equivalent to --flag argument
*/
let ArgumentAttacher: Character = "="
/* An output stream to stderr; used by CommandLine.printUsage(). */
private struct StderrOutputStream: OutputStreamType {
static let stream = StderrOutputStream()
func write(s: String) {
fputs(s, stderr)
}
}
/**
* The CommandLine class implements a command-line interface for your app.
*
* To use it, define one or more Options (see Option.swift) and add them to your
* CommandLine object, then invoke `parse()`. Each Option object will be populated with
* the value given by the user.
*
* If any required options are missing or if an invalid value is found, `parse()` will throw
* a `ParseError`. You can then call `printUsage()` to output an automatically-generated usage
* message.
*/
public class CommandLine {
private var _arguments: [String]
private var _options: [Option] = [Option]()
private var _maxFlagDescriptionWidth: Int = 0
private var _usedFlags: Set<String> {
var usedFlags = Set<String>(minimumCapacity: _options.count * 2)
for option in _options {
for case let flag? in [option.shortFlag, option.longFlag] {
usedFlags.insert(flag)
}
}
return usedFlags
}
/**
* After calling `parse()`, this property will contain any values that weren't captured
* by an Option. For example:
*
* ```
* let cli = CommandLine()
* let fileType = StringOption(shortFlag: "t", longFlag: "type", required: true, helpMessage: "Type of file")
*
* do {
* try cli.parse()
* print("File type is \(type), files are \(cli.strayValues)")
* catch {
* cli.printUsage(error)
* exit(EX_USAGE)
* }
*
* ---
*
* $ ./readfiles --type=pdf ~/file1.pdf ~/file2.pdf
* File type is pdf, files are ["~/file1.pdf", "~/file2.pdf"]
* ```
*/
public private(set) var strayValues: [String] = [String]()
/**
* If supplied, this function will be called when printing usage messages.
*
* You can use the `defaultFormat` function to get the normally-formatted
* output, either before or after modifying the provided string. For example:
*
* ```
* let cli = CommandLine()
* cli.formatOutput = { str, type in
* switch(type) {
* case .Error:
* // Make errors shouty
* return defaultFormat(str.uppercaseString, type: type)
* case .OptionHelp:
* // Don't use the default indenting
* return ">> \(s)\n"
* default:
* return defaultFormat(str, type: type)
* }
* }
* ```
*
* - note: Newlines are not appended to the result of this function. If you don't use
* `defaultFormat()`, be sure to add them before returning.
*/
public var formatOutput: ((String, OutputType) -> String)?
/**
* The maximum width of all options' `flagDescription` properties; provided for use by
* output formatters.
*
* - seealso: `defaultFormat`, `formatOutput`
*/
public var maxFlagDescriptionWidth: Int {
if _maxFlagDescriptionWidth == 0 {
_maxFlagDescriptionWidth = _options.map { $0.flagDescription.characters.count }.sort().first ?? 0
}
return _maxFlagDescriptionWidth
}
/**
* The type of output being supplied to an output formatter.
*
* - seealso: `formatOutput`
*/
public enum OutputType {
/** About text: `Usage: command-example [options]` and the like */
case About
/** An error message: `Missing required option --extract` */
case Error
/** An Option's `flagDescription`: `-h, --help:` */
case OptionFlag
/** An Option's help message */
case OptionHelp
}
/** A ParseError is thrown if the `parse()` method fails. */
public enum ParseError: ErrorType, CustomStringConvertible {
/** Thrown if an unrecognized argument is passed to `parse()` in strict mode */
case InvalidArgument(String)
/** Thrown if the value for an Option is invalid (e.g. a string is passed to an IntOption) */
case InvalidValueForOption(Option, [String])
/** Thrown if an Option with required: true is missing */
case MissingRequiredOptions([Option])
public var description: String {
switch self {
case let .InvalidArgument(arg):
return "Invalid argument: \(arg)"
case let .InvalidValueForOption(opt, vals):
let vs = vals.joinWithSeparator(", ")
return "Invalid value(s) for option \(opt.flagDescription): \(vs)"
case let .MissingRequiredOptions(opts):
return "Missing required options: \(opts.map { return $0.flagDescription })"
}
}
}
/**
* Initializes a CommandLine object.
*
* - parameter arguments: Arguments to parse. If omitted, the arguments passed to the app
* on the command line will automatically be used.
*
* - returns: An initalized CommandLine object.
*/
public init(arguments: [String] = Process.arguments) {
self._arguments = arguments
/* Initialize locale settings from the environment */
setlocale(LC_ALL, "")
}
/* Returns all argument values from flagIndex to the next flag or the end of the argument array. */
private func _getFlagValues(flagIndex: Int, _ attachedArg: String? = nil) -> [String] {
var args: [String] = [String]()
var skipFlagChecks = false
if let a = attachedArg {
args.append(a)
}
for i in (flagIndex + 1).stride(to: _arguments.count, by: 1) {
if !skipFlagChecks {
if _arguments[i] == ArgumentStopper {
skipFlagChecks = true
continue
}
if _arguments[i].hasPrefix(ShortOptionPrefix) && Int(_arguments[i]) == nil &&
_arguments[i].toDouble() == nil {
break
}
}
args.append(_arguments[i])
}
return args
}
/**
* Adds an Option to the command line.
*
* - parameter option: The option to add.
*/
public func addOption(option: Option) {
let uf = _usedFlags
for case let flag? in [option.shortFlag, option.longFlag] {
assert(!uf.contains(flag), "Flag '\(flag)' already in use")
}
_options.append(option)
_maxFlagDescriptionWidth = 0
}
/**
* Adds one or more Options to the command line.
*
* - parameter options: An array containing the options to add.
*/
public func addOptions(options: [Option]) {
for o in options {
addOption(o)
}
}
/**
* Adds one or more Options to the command line.
*
* - parameter options: The options to add.
*/
public func addOptions(options: Option...) {
for o in options {
addOption(o)
}
}
/**
* Sets the command line Options. Any existing options will be overwritten.
*
* - parameter options: An array containing the options to set.
*/
public func setOptions(options: [Option]) {
_options = [Option]()
addOptions(options)
}
/**
* Sets the command line Options. Any existing options will be overwritten.
*
* - parameter options: The options to set.
*/
public func setOptions(options: Option...) {
_options = [Option]()
addOptions(options)
}
/**
* Parses command-line arguments into their matching Option values.
*
* - parameter strict: Fail if any unrecognized flags are present (default: false).
*
* - throws: A `ParseError` if argument parsing fails:
* - `.InvalidArgument` if an unrecognized flag is present and `strict` is true
* - `.InvalidValueForOption` if the value supplied to an option is not valid (for
* example, a string is supplied for an IntOption)
* - `.MissingRequiredOptions` if a required option isn't present
*/
public func parse(strict: Bool = false) throws {
/* Kind of an ugly cast here */
var strays = _arguments.map { $0 as String? }
/* Nuke executable name */
strays[0] = nil
for (idx, arg) in _arguments.enumerate() {
if arg == ArgumentStopper {
break
}
if !arg.hasPrefix(ShortOptionPrefix) {
continue
}
let skipChars = arg.hasPrefix(LongOptionPrefix) ?
LongOptionPrefix.characters.count : ShortOptionPrefix.characters.count
let flagWithArg = arg[arg.startIndex.advancedBy(skipChars)..<arg.endIndex]
/* The argument contained nothing but ShortOptionPrefix or LongOptionPrefix */
if flagWithArg.isEmpty {
continue
}
/* Remove attached argument from flag */
let splitFlag = flagWithArg.splitByCharacter(ArgumentAttacher, maxSplits: 1)
let flag = splitFlag[0]
let attachedArg: String? = splitFlag.count == 2 ? splitFlag[1] : nil
var flagMatched = false
for option in _options where option.flagMatch(flag) {
let vals = self._getFlagValues(idx, attachedArg)
guard option.setValue(vals) else {
throw ParseError.InvalidValueForOption(option, vals)
}
var claimedIdx = idx + option.claimedValues
if attachedArg != nil { claimedIdx -= 1 }
for i in idx.stride(through: claimedIdx, by: 1) {
strays[i] = nil
}
flagMatched = true
break
}
/* Flags that do not take any arguments can be concatenated */
let flagLength = flag.characters.count
if !flagMatched && !arg.hasPrefix(LongOptionPrefix) {
for (i, c) in flag.characters.enumerate() {
for option in _options where option.flagMatch(String(c)) {
/* Values are allowed at the end of the concatenated flags, e.g.
* -xvf <file1> <file2>
*/
let vals = (i == flagLength - 1) ? self._getFlagValues(idx, attachedArg) : [String]()
guard option.setValue(vals) else {
throw ParseError.InvalidValueForOption(option, vals)
}
var claimedIdx = idx + option.claimedValues
if attachedArg != nil { claimedIdx -= 1 }
for i in idx.stride(through: claimedIdx, by: 1) {
strays[i] = nil
}
flagMatched = true
break
}
}
}
/* Invalid flag */
guard !strict || flagMatched else {
throw ParseError.InvalidArgument(arg)
}
}
/* Check to see if any required options were not matched */
let missingOptions = _options.filter { $0.required && !$0.wasSet }
guard missingOptions.count == 0 else {
throw ParseError.MissingRequiredOptions(missingOptions)
}
strayValues = strays.flatMap { $0 }
}
/**
* Provides the default formatting of `printUsage()` output.
*
* - parameter s: The string to format.
* - parameter type: Type of output.
*
* - returns: The formatted string.
* - seealso: `formatOutput`
*/
public func defaultFormat(s: String, type: OutputType) -> String {
switch type {
case .About:
return "\(s)\n"
case .Error:
return "\(s)\n\n"
case .OptionFlag:
return " \(s.paddedToWidth(maxFlagDescriptionWidth)):\n"
case .OptionHelp:
return " \(s)\n"
}
}
/* printUsage() is generic for OutputStreamType because the Swift compiler crashes
* on inout protocol function parameters in Xcode 7 beta 1 (rdar://21372694).
*/
/**
* Prints a usage message.
*
* - parameter to: An OutputStreamType to write the error message to.
*/
public func printUsage<TargetStream: OutputStreamType>(inout to: TargetStream) {
/* Nil coalescing operator (??) doesn't work on closures :( */
let format = formatOutput != nil ? formatOutput! : defaultFormat
let name = _arguments[0]
print(format("Usage: \(name) [options]", .About), terminator: "", toStream: &to)
for opt in _options {
print(format(opt.flagDescription, .OptionFlag), terminator: "", toStream: &to)
print(format(opt.helpMessage, .OptionHelp), terminator: "", toStream: &to)
}
}
/**
* Prints a usage message.
*
* - parameter error: An error thrown from `parse()`. A description of the error
* (e.g. "Missing required option --extract") will be printed before the usage message.
* - parameter to: An OutputStreamType to write the error message to.
*/
public func printUsage<TargetStream: OutputStreamType>(error: ErrorType, inout to: TargetStream) {
let format = formatOutput != nil ? formatOutput! : defaultFormat
print(format("\(error)", .Error), terminator: "", toStream: &to)
printUsage(&to)
}
/**
* Prints a usage message.
*
* - parameter error: An error thrown from `parse()`. A description of the error
* (e.g. "Missing required option --extract") will be printed before the usage message.
*/
public func printUsage(error: ErrorType) {
var out = StderrOutputStream.stream
printUsage(error, to: &out)
}
/**
* Prints a usage message.
*/
public func printUsage() {
var out = StderrOutputStream.stream
printUsage(&out)
}
}
/**
* The base class for a command-line option.
*/
public class Option {
public let shortFlag: String?
public let longFlag: String?
public let required: Bool
public let helpMessage: String
/** True if the option was set when parsing command-line arguments */
public var wasSet: Bool {
return false
}
public var claimedValues: Int { return 0 }
public var flagDescription: String {
switch (shortFlag, longFlag) {
case let (.Some(sf), .Some(lf)):
return "\(ShortOptionPrefix)\(sf), \(LongOptionPrefix)\(lf)"
case (.None, let .Some(lf)):
return "\(LongOptionPrefix)\(lf)"
case (let .Some(sf), .None):
return "\(ShortOptionPrefix)\(sf)"
default:
return ""
}
}
private init(_ shortFlag: String?, _ longFlag: String?, _ required: Bool, _ helpMessage: String) {
if let sf = shortFlag {
assert(sf.characters.count == 1, "Short flag must be a single character")
assert(Int(sf) == nil && sf.toDouble() == nil, "Short flag cannot be a numeric value")
}
if let lf = longFlag {
assert(Int(lf) == nil && lf.toDouble() == nil, "Long flag cannot be a numeric value")
}
self.shortFlag = shortFlag
self.longFlag = longFlag
self.helpMessage = helpMessage
self.required = required
}
/* The optional casts in these initalizers force them to call the private initializer. Without
* the casts, they recursively call themselves.
*/
/** Initializes a new Option that has both long and short flags. */
public convenience init(shortFlag: String, longFlag: String, required: Bool = false, helpMessage: String) {
self.init(shortFlag as String?, longFlag, required, helpMessage)
}
/** Initializes a new Option that has only a short flag. */
public convenience init(shortFlag: String, required: Bool = false, helpMessage: String) {
self.init(shortFlag as String?, nil, required, helpMessage)
}
/** Initializes a new Option that has only a long flag. */
public convenience init(longFlag: String, required: Bool = false, helpMessage: String) {
self.init(nil, longFlag as String?, required, helpMessage)
}
func flagMatch(flag: String) -> Bool {
return flag == shortFlag || flag == longFlag
}
func setValue(values: [String]) -> Bool {
return false
}
}
/**
* A boolean option. The presence of either the short or long flag will set the value to true;
* absence of the flag(s) is equivalent to false.
*/
public class BoolOption: Option {
private var _value: Bool = false
public var value: Bool {
return _value
}
override public var wasSet: Bool {
return _value
}
override func setValue(values: [String]) -> Bool {
_value = true
return true
}
}
/** An option that accepts a positive or negative integer value. */
public class IntOption: Option {
private var _value: Int?
public var value: Int? {
return _value
}
override public var wasSet: Bool {
return _value != nil
}
override public var claimedValues: Int {
return _value != nil ? 1 : 0
}
override func setValue(values: [String]) -> Bool {
if values.count == 0 {
return false
}
if let val = Int(values[0]) {
_value = val
return true
}
return false
}
}
/**
* An option that represents an integer counter. Each time the short or long flag is found
* on the command-line, the counter will be incremented.
*/
public class CounterOption: Option {
private var _value: Int = 0
public var value: Int {
return _value
}
override public var wasSet: Bool {
return _value > 0
}
public func reset() {
_value = 0
}
override func setValue(values: [String]) -> Bool {
_value += 1
return true
}
}
/** An option that accepts a positive or negative floating-point value. */
public class DoubleOption: Option {
private var _value: Double?
public var value: Double? {
return _value
}
override public var wasSet: Bool {
return _value != nil
}
override public var claimedValues: Int {
return _value != nil ? 1 : 0
}
override func setValue(values: [String]) -> Bool {
if values.count == 0 {
return false
}
if let val = values[0].toDouble() {
_value = val
return true
}
return false
}
}
/** An option that accepts a string value. */
public class StringOption: Option {
private var _value: String? = nil
public var value: String? {
return _value
}
override public var wasSet: Bool {
return _value != nil
}
override public var claimedValues: Int {
return _value != nil ? 1 : 0
}
override func setValue(values: [String]) -> Bool {
if values.count == 0 {
return false
}
_value = values[0]
return true
}
}
/** An option that accepts one or more string values. */
public class MultiStringOption: Option {
private var _value: [String]?
public var value: [String]? {
return _value
}
override public var wasSet: Bool {
return _value != nil
}
override public var claimedValues: Int {
if let v = _value {
return v.count
}
return 0
}
override func setValue(values: [String]) -> Bool {
if values.count == 0 {
return false
}
_value = values
return true
}
}
/** An option that represents an enum value. */
public class EnumOption<T:RawRepresentable where T.RawValue == String>: Option {
private var _value: T?
public var value: T? {
return _value
}
override public var wasSet: Bool {
return _value != nil
}
override public var claimedValues: Int {
return _value != nil ? 1 : 0
}
/* Re-defining the intializers is necessary to make the Swift 2 compiler happy, as
* of Xcode 7 beta 2.
*/
private override init(_ shortFlag: String?, _ longFlag: String?, _ required: Bool, _ helpMessage: String) {
super.init(shortFlag, longFlag, required, helpMessage)
}
/** Initializes a new Option that has both long and short flags. */
public convenience init(shortFlag: String, longFlag: String, required: Bool = false, helpMessage: String) {
self.init(shortFlag as String?, longFlag, required, helpMessage)
}
/** Initializes a new Option that has only a short flag. */
public convenience init(shortFlag: String, required: Bool = false, helpMessage: String) {
self.init(shortFlag as String?, nil, required, helpMessage)
}
/** Initializes a new Option that has only a long flag. */
public convenience init(longFlag: String, required: Bool = false, helpMessage: String) {
self.init(nil, longFlag as String?, required, helpMessage)
}
override func setValue(values: [String]) -> Bool {
if values.count == 0 {
return false
}
if let v = T(rawValue: values[0]) {
_value = v
return true
}
return false
}
}
internal extension String {
/* Retrieves locale-specified decimal separator from the environment
* using localeconv(3).
*/
private func _localDecimalPoint() -> Character {
let locale = localeconv()
if locale != nil {
let decimalPoint = locale.memory.decimal_point
if decimalPoint != nil {
return Character(UnicodeScalar(UInt32(decimalPoint.memory)))
}
}
return "."
}
/**
* Attempts to parse the string value into a Double.
*
* - returns: A Double if the string can be parsed, nil otherwise.
*/
func toDouble() -> Double? {
var characteristic: String = "0"
var mantissa: String = "0"
var inMantissa: Bool = false
var isNegative: Bool = false
let decimalPoint = self._localDecimalPoint()
for (i, c) in self.characters.enumerate() {
if i == 0 && c == "-" {
isNegative = true
continue
}
if c == decimalPoint {
inMantissa = true
continue
}
if Int(String(c)) != nil {
if !inMantissa {
characteristic.append(c)
} else {
mantissa.append(c)
}
} else {
/* Non-numeric character found, bail */
return nil
}
}
return (Double(Int(characteristic)!) +
Double(Int(mantissa)!) / pow(Double(10), Double(mantissa.characters.count - 1))) *
(isNegative ? -1 : 1)
}
/**
* Splits a string into an array of string components.
*
* - parameter splitBy: The character to split on.
* - parameter maxSplit: The maximum number of splits to perform. If 0, all possible splits are made.
*
* - returns: An array of string components.
*/
func splitByCharacter(splitBy: Character, maxSplits: Int = 0) -> [String] {
var s = [String]()
var numSplits = 0
var curIdx = self.startIndex
for i in self.characters.indices {
let c = self[i]
if c == splitBy && (maxSplits == 0 || numSplits < maxSplits) {
s.append(self[curIdx..<i])
curIdx = i.successor()
numSplits += 1
}
}
if curIdx != self.endIndex {
s.append(self[curIdx..<self.endIndex])
}
return s
}
/**
* Pads a string to the specified width.
*
* - parameter width: The width to pad the string to.
* - parameter padBy: The character to use for padding.
*
* - returns: A new string, padded to the given width.
*/
func paddedToWidth(width: Int, padBy: Character = " ") -> String {
var s = self
var currentLength = self.characters.count
while currentLength < width {
s.append(padBy)
currentLength += 1
}
return s
}
/**
* Wraps a string to the specified width.
*
* This just does simple greedy word-packing, it doesn't go full Knuth-Plass.
* If a single word is longer than the line width, it will be placed (unsplit)
* on a line by itself.
*
* - parameter width: The maximum length of a line.
* - parameter wrapBy: The line break character to use.
* - parameter splitBy: The character to use when splitting the string into words.
*
* - returns: A new string, wrapped at the given width.
*/
func wrappedAtWidth(width: Int, wrapBy: Character = "\n", splitBy: Character = " ") -> String {
var s = ""
var currentLineWidth = 0
for word in self.splitByCharacter(splitBy) {
let wordLength = word.characters.count
if currentLineWidth + wordLength + 1 > width {
/* Word length is greater than line length, can't wrap */
if wordLength >= width {
s += word
}
s.append(wrapBy)
currentLineWidth = 0
}
currentLineWidth += wordLength + 1
s += word
s.append(splitBy)
}
return s
}
}
#if os(Linux)
/**
* Returns `true` iff `self` begins with `prefix`.
*
* A basic implementation of `hasPrefix` for Linux.
* Should be removed once a proper `hasPrefix` patch makes it to the Swift 2.2 development branch.
*/
extension String {
func hasPrefix(prefix: String) -> Bool {
if prefix.isEmpty {
return false
}
let c = self.characters
let p = prefix.characters
if p.count > c.count {
return false
}
for (c, p) in zip(c.prefix(p.count), p) {
guard c == p else {
return false
}
}
return true
}
/**
* Returns `true` iff `self` ends with `suffix`.
*
* A basic implementation of `hasSuffix` for Linux.
* Should be removed once a proper `hasSuffix` patch makes it to the Swift 2.2 development branch.
*/
func hasSuffix(suffix: String) -> Bool {
if suffix.isEmpty {
return false
}
let c = self.characters
let s = suffix.characters
if s.count > c.count {
return false
}
for (c, s) in zip(c.suffix(s.count), s) {
guard c == s else {
return false
}
}
return true
}
}
#endif
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
//MARK: - Import
import Foundation
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
//MARK: - Definitions
private let BASE_CLASS_NAME : String = "Localizations"
private let OBJC_CLASS_PREFIX : String = "_"
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
// MARK: - Extensions
private extension String {
func alphanumericString(exceptionCharactersFromString: String = "") -> String {
// removes diacritic marks
var copy = self.stringByFoldingWithOptions(.DiacriticInsensitiveSearch, locale: NSLocale.currentLocale())
// removes all non alphanumeric characters
let characterSet = NSCharacterSet.alphanumericCharacterSet().invertedSet.mutableCopy() as! NSMutableCharacterSet
// don't remove the characters that are given
characterSet.removeCharactersInString(exceptionCharactersFromString)
copy = copy.componentsSeparatedByCharactersInSet(characterSet).reduce("") { $0 + $1 }
return copy
}
func replacedNonAlphaNumericCharacters(replacement: Character) -> String {
return String( self.characters.map { NSCharacterSet.alphanumericCharacterSet().containsCharacter($0) ? $0 : replacement } )
}
}
private extension NSCharacterSet {
// thanks to http://stackoverflow.com/a/27698155/354018
func containsCharacter(c: Character) -> Bool {
let s = String(c)
let ix = s.startIndex
let ix2 = s.endIndex
let result = s.rangeOfCharacterFromSet(self, options: [], range: ix..<ix2)
return result != nil
}
}
private extension NSMutableDictionary {
func setObject(object : AnyObject!, forKeyPath : String, delimiter : String = ".") {
self.setObject(object, onObject : self, forKeyPath: forKeyPath, createIntermediates: true, replaceIntermediates: true, delimiter: delimiter)
}
func setObject(object : AnyObject, onObject : AnyObject, forKeyPath keyPath : String, createIntermediates: Bool, replaceIntermediates: Bool, delimiter: String) {
// Make keypath mutable
var primaryKeypath = keyPath
// Replace delimiter with dot delimiter - otherwise key value observing does not work properly
let baseDelimiter = "."
primaryKeypath = primaryKeypath.stringByReplacingOccurrencesOfString(delimiter, withString: baseDelimiter, options: .LiteralSearch, range: nil)
// Create path components separated by delimiter (. by default) and get key for root object
// filter empty path components, these can be caused by delimiter at beginning/end, or multiple consecutive delimiters in the middle
let pathComponents : Array<String> = primaryKeypath.componentsSeparatedByString(baseDelimiter).filter({ $0.characters.count > 0 })
primaryKeypath = pathComponents.joinWithSeparator(baseDelimiter)
let rootKey : String = pathComponents[0]
if pathComponents.count == 1 {
onObject.setObject(object, forKey: rootKey)
}
let replacementDictionary : NSMutableDictionary = NSMutableDictionary();
// Store current state for further replacement
var previousObject : AnyObject? = onObject;
var previousReplacement : NSMutableDictionary = replacementDictionary;
var reachedDictionaryLeaf : Bool = false;
// Traverse through path from root to deepest level
for path : String in pathComponents {
let currentObject : AnyObject? = reachedDictionaryLeaf ? nil : previousObject?.objectForKey(path);
// Check if object already exists. If not, create new level, if allowed, or end
if currentObject == nil {
reachedDictionaryLeaf = true;
if createIntermediates {
let newNode : NSMutableDictionary = NSMutableDictionary();
previousReplacement.setObject(newNode, forKey: path);
previousReplacement = newNode;
} else {
return;
}
// If it does and it is dictionary, create mutable copy and assign new node there
} else if currentObject is NSDictionary {
let newNode : NSMutableDictionary = NSMutableDictionary(dictionary: currentObject as! [NSObject : AnyObject]);
previousReplacement.setObject(newNode, forKey: path);
previousReplacement = newNode;
// It exists but it is not NSDictionary, so we replace it, if allowed, or end
} else {
reachedDictionaryLeaf = true;
if replaceIntermediates {
let newNode : NSMutableDictionary = NSMutableDictionary();
previousReplacement.setObject(newNode, forKey: path);
previousReplacement = newNode;
} else {
return;
}
}
// Replace previous object with the new one
previousObject = currentObject;
}
// Replace root object with newly created n-level dictionary
replacementDictionary.setValue(object, forKeyPath: primaryKeypath);
onObject.setObject(replacementDictionary.objectForKey(rootKey), forKey: rootKey);
}
}
private extension NSFileManager {
func isDirectoryAtPath(path : String) -> Bool {
let manager = NSFileManager.defaultManager()
do {
let attribs: NSDictionary? = try manager.attributesOfItemAtPath(path)
if let attributes = attribs {
let type = attributes["NSFileType"] as? String
return type == NSFileTypeDirectory
}
} catch _ {
return false
}
}
}
private extension String {
var camelCasedString: String {
let inputArray = self.componentsSeparatedByCharactersInSet(NSCharacterSet.alphanumericCharacterSet().invertedSet)
return inputArray.reduce("", combine:{$0 + $1.capitalizedString})
}
var nolineString: String {
return self.componentsSeparatedByCharactersInSet(NSCharacterSet.newlineCharacterSet())
.filter { !$0.isEmpty }
.joinWithSeparator(" ")
}
func isFirstLetterDigit() -> Bool {
guard let c : Character = self.characters.first else {
return false
}
let s = String(c).unicodeScalars
let uni = s[s.startIndex]
let digits = NSCharacterSet.decimalDigitCharacterSet()
return digits.longCharacterIsMember(uni.value)
}
func isReservedKeyword(lang : Runtime.ExportLanguage) -> Bool {
// Define keywords for each language
var keywords : [String] = []
if lang == .ObjC {
keywords = ["auto", "break", "case", "char", "const", "continue", "default", "do", "double", "else", "enum", "extern", "float", "for", "goto", "if", "inline", "int", "long",
"register", "restrict", "return", "short", "signed", "sizeof", "static", "struct", "swift", "typedef", "union", "unsigned", "void", "volatile", "while",
"BOOL", "Class", "bycopy", "byref", "id", "IMP", "in", "inout", "nil", "NO", "NULL", "oneway", "out", "Protocol", "SEL", "self", "super", "YES"]
} else if lang == .Swift {
keywords = ["class", "deinit", "enum", "extension", "func", "import", "init", "inout", "internal", "let", "operator", "private", "protocol", "public", "static", "struct", "subscript", "typealias", "var", "break", "case", "continue", "default", "defer", "do", "else", "fallthrough", "for", "guard", "if", "in", "repeat", "return", "switch", "where", "while", "as", "catch", "dynamicType", "false", "is", "nil", "rethrows", "super", "self", "Self", "throw", "throws", "true", "try", "__COLUMN__", "__FILE__", "__FUNCTION__", "__LINE__"]
}
// Check if it contains that keyword
return keywords.indexOf(self) != nil
}
}
private enum SpecialCharacter {
case String
case Double
case Int
case Int64
case UInt
}
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
// MARK: - Localization Class implementation
class Localization {
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
// MARK: - Properties
var flatStructure = NSDictionary()
var objectStructure = NSMutableDictionary()
var autocapitalize : Bool = true
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
// MARK: - Setup
convenience init(inputFile : NSURL, delimiter : String, autocapitalize : Bool) {
self.init()
// Load localization file
self.processInputFromFile(inputFile, delimiter: delimiter, autocapitalize: autocapitalize)
}
func processInputFromFile(file : NSURL, delimiter : String, autocapitalize : Bool) {
guard let path = file.path, let dictionary = NSDictionary(contentsOfFile: path) else {
// TODO: Better error handling
print("Bad format of input file")
exit(EX_IOERR)
}
self.flatStructure = dictionary
self.autocapitalize = autocapitalize
self.expandFlatStructure(dictionary, delimiter: delimiter)
}
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
// MARK: - Public
func writerWithSwiftImplementation() -> StreamWriter {
let writer = StreamWriter()
// Generate header
writer.writeHeader()
// Imports
writer.writeMarkWithName("Imports")
writer.writeSwiftImports()
// Extensions
writer.writeMarkWithName("Extensions")
writer.writeRequiredExtensions()
// Generate actual localization structures
writer.writeMarkWithName("Localizations")
writer.writeCodeStructure(self.swiftStructWithContent(self.codifySwift(self.objectStructure), structName: BASE_CLASS_NAME, contentLevel: 0))
return writer
}
func writerWithObjCImplementationWithFilename(filename : String) -> StreamWriter {
let writer = StreamWriter()
// Generate header
writer.writeHeader()
// Imports
writer.writeMarkWithName("Imports")
writer.writeObjCImportsWithFileName(filename)
// Generate actual localization structures
writer.writeMarkWithName("Header")
writer.writeCodeStructure(self.codifyObjC(self.objectStructure, baseClass: BASE_CLASS_NAME, header: false))
return writer
}
func writerWithObjCHeader() -> StreamWriter {
let writer = StreamWriter()
// Generate header
writer.writeHeader()
// Imports
writer.writeMarkWithName("Imports")
writer.writeObjCHeaderImports()
// Generate actual localization structures
writer.writeMarkWithName("Header")
writer.writeCodeStructure(self.codifyObjC(self.objectStructure, baseClass: BASE_CLASS_NAME, header: true))
// Generate macros
writer.writeMarkWithName("Macros")
writer.writeObjCHeaderMacros()
return writer
}
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
// MARK: - Private
private func expandFlatStructure(flatStructure : NSDictionary, delimiter: String) {
// Writes values to dictionary and also
for (key, _) in flatStructure {
guard let key = key as? String else { continue }
objectStructure.setObject(key, forKeyPath: key, delimiter: delimiter)
}
}
private func codifySwift(expandedStructure : NSDictionary, contentLevel : Int = 0) -> String {
// Increase content level
let contentLevel = contentLevel + 1
// Prepare output structure
var outputStructure : [String] = []
// First iterate through properties
for (key, value) in expandedStructure {
if let value = value as? String {
let comment = (self.flatStructure.objectForKey(value) as! String).nolineString
let methodParams = self.methodParamsForString(comment)
let staticString: String
if methodParams.count > 0 {
staticString = self.swiftLocalizationFuncFromLocalizationKey(value, methodName: key as! String, baseTranslation: comment, methodSpecification: methodParams, contentLevel: contentLevel)
} else {
staticString = self.swiftLocalizationStaticVarFromLocalizationKey(value, variableName: key as! String, baseTranslation: comment, contentLevel: contentLevel)
}
outputStructure.append(staticString)
}
}
// Then iterate through nested structures
for (key, value) in expandedStructure {
if let value = value as? NSDictionary {
outputStructure.append(self.swiftStructWithContent(self.codifySwift(value, contentLevel: contentLevel), structName: key as! String, contentLevel: contentLevel))
}
}
// At the end, return everything merged together
return outputStructure.joinWithSeparator("\n")
}
private func codifyObjC(expandedStructure : NSDictionary, baseClass : String, header : Bool) -> String {
// Prepare output structure
var outputStructure : [String] = []
var contentStructure : [String] = []
// First iterate through properties
for (key, value) in expandedStructure {
if let value = value as? String {
let comment = (self.flatStructure.objectForKey(value) as! String).nolineString
let methodParams = self.methodParamsForString(comment)
let staticString : String
if methodParams.count > 0 {
staticString = self.objcLocalizationFuncFromLocalizationKey(value, methodName: self.variableName(key as! String, lang: .ObjC), baseTranslation: comment, methodSpecification: methodParams, header: header)
} else {
staticString = self.objcLocalizationStaticVarFromLocalizationKey(value, variableName: self.variableName(key as! String, lang: .ObjC), baseTranslation: comment, header: header)
}
contentStructure.append(staticString)
}
}
// Then iterate through nested structures
for (key, value) in expandedStructure {
if let value = value as? NSDictionary {
outputStructure.append(self.codifyObjC(value, baseClass : baseClass + self.variableName(key as! String, lang: .ObjC), header: header))
contentStructure.insert(self.objcClassVarWithName(self.variableName(key as! String, lang: .ObjC), className: baseClass + self.variableName(key as! String, lang: .ObjC), header: header), atIndex: 0)
}
}
if baseClass == BASE_CLASS_NAME {
if header {
contentStructure.append(TemplateFactory.templateForObjCBaseClassHeader(OBJC_CLASS_PREFIX + BASE_CLASS_NAME))
} else {
contentStructure.append(TemplateFactory.templateForObjCBaseClassImplementation(OBJC_CLASS_PREFIX + BASE_CLASS_NAME))
}
}
// Generate class code for current class
outputStructure.append(self.objcClassWithContent(contentStructure.joinWithSeparator("\n"), className: OBJC_CLASS_PREFIX + baseClass, header: header))
// At the end, return everything merged together
return outputStructure.joinWithSeparator("\n")
}
private func methodParamsForString(string : String) -> [SpecialCharacter] {
// Split the string into pieces by %
let matches = self.matchesForRegexInText("%([0-9]*.[0-9]*(d|i|u|f|ld)|(\\d\\$)?@|d|i|u|f|ld)", text: string)
var characters : [SpecialCharacter] = []
// If there is just one component, no special characters are found
if matches.count == 0 {
return []
} else {
for match in matches {
characters.append(self.propertyTypeForMatch(match))
}
return characters
}
}
private func propertyTypeForMatch(string : String) -> SpecialCharacter {
if string.containsString("ld") {
return .Int64
} else if string.containsString("d") || string.containsString("i") {
return .Int
} else if string.containsString("u") {
return .UInt
} else if string.containsString("f") {
return .Double
} else {
return .String
}
}
private func variableName(string : String, lang : Runtime.ExportLanguage) -> String {
// . is not allowed, nested structure expanding must take place before calling this function
let legalCharacterString = string.replacedNonAlphaNumericCharacters("_")
if self.autocapitalize {
return (legalCharacterString.isFirstLetterDigit() || legalCharacterString.isReservedKeyword(lang) ? "_" + legalCharacterString.camelCasedString : legalCharacterString.camelCasedString)
} else {
return (legalCharacterString.isFirstLetterDigit() || legalCharacterString.isReservedKeyword(lang) ? "_" + string : legalCharacterString)
}
}
private func matchesForRegexInText(regex: String!, text: String!) -> [String] {
do {
let regex = try NSRegularExpression(pattern: regex, options: [])
let nsString = text as NSString
let results = regex.matchesInString(text,
options: [], range: NSMakeRange(0, nsString.length))
return results.map { nsString.substringWithRange($0.range)}
} catch let error as NSError {
print("invalid regex: \(error.localizedDescription)")
return []
}
}
private func dataTypeFromSpecialCharacter(char : SpecialCharacter, language : Runtime.ExportLanguage) -> String {
switch char {
case .String: return language == .Swift ? "String" : "NSString *"
case .Double: return language == .Swift ? "Double" : "double"
case .Int: return language == .Swift ? "Int" : "int"
case .Int64: return language == .Swift ? "Int64" : "long"
case .UInt: return language == .Swift ? "UInt" : "unsigned int"
}
}
private func swiftStructWithContent(content : String, structName : String, contentLevel : Int = 0) -> String {
return TemplateFactory.templateForSwiftStructWithName(self.variableName(structName, lang: .Swift), content: content, contentLevel: contentLevel)
}
private func swiftLocalizationStaticVarFromLocalizationKey(key : String, variableName : String, baseTranslation : String, contentLevel : Int = 0) -> String {
return TemplateFactory.templateForSwiftStaticVarWithName(self.variableName(variableName, lang: .Swift), key: key, baseTranslation : baseTranslation, contentLevel: contentLevel)
}
private func swiftLocalizationFuncFromLocalizationKey(key : String, methodName : String, baseTranslation : String, methodSpecification : [SpecialCharacter], contentLevel : Int = 0) -> String {
var counter = 0
var methodHeaderParams = methodSpecification.reduce("") { (string, character) -> String in
counter += 1
return "\(string), _ value\(counter) : \(self.dataTypeFromSpecialCharacter(character, language: .Swift))"
}
var methodParams : [String] = []
for (index, _) in methodSpecification.enumerate() {
methodParams.append("value\(index + 1)")
}
let methodParamsString = methodParams.joinWithSeparator(", ")
methodHeaderParams = methodHeaderParams.stringByTrimmingCharactersInSet(NSCharacterSet(charactersInString: ", _"))
return TemplateFactory.templateForSwiftFuncWithName(self.variableName(methodName, lang: .Swift), key: key, baseTranslation : baseTranslation, methodHeader: methodHeaderParams, params: methodParamsString, contentLevel: contentLevel)
}
private func objcClassWithContent(content : String, className : String, header : Bool, contentLevel : Int = 0) -> String {
if header {
return TemplateFactory.templateForObjCClassHeaderWithName(className, content: content, contentLevel: contentLevel)
} else {
return TemplateFactory.templateForObjCClassImplementationWithName(className, content: content, contentLevel: contentLevel)
}
}
private func objcClassVarWithName(name : String, className : String, header : Bool, contentLevel : Int = 0) -> String {
if header {
return TemplateFactory.templateForObjCClassVarHeaderWithName(name, className: className, contentLevel: contentLevel)
} else {
return TemplateFactory.templateForObjCClassVarImplementationWithName(name, className: className, contentLevel: contentLevel)
}
}
private func objcLocalizationStaticVarFromLocalizationKey(key : String, variableName : String, baseTranslation : String, header : Bool, contentLevel : Int = 0) -> String {
if header {
return TemplateFactory.templateForObjCStaticVarHeaderWithName(variableName, key: key, baseTranslation : baseTranslation, contentLevel: contentLevel)
} else {
return TemplateFactory.templateForObjCStaticVarImplementationWithName(variableName, key: key, baseTranslation : baseTranslation, contentLevel: contentLevel)
}
}
private func objcLocalizationFuncFromLocalizationKey(key : String, methodName : String, baseTranslation : String, methodSpecification : [SpecialCharacter], header : Bool, contentLevel : Int = 0) -> String {
var counter = 0
var methodHeader = methodSpecification.reduce("") { (string, character) -> String in
counter += 1
return "\(string), \(self.dataTypeFromSpecialCharacter(character, language: .ObjC))"
}
counter = 0
var blockHeader = methodSpecification.reduce("") { (string, character) -> String in
counter += 1
return "\(string), \(self.dataTypeFromSpecialCharacter(character, language: .ObjC)) value\(counter) "
}
var blockParamComponent : [String] = []
for (index, _) in methodSpecification.enumerate() {
blockParamComponent.append("value\(index + 1)")
}
let blockParams = blockParamComponent.joinWithSeparator(", ")
methodHeader = methodHeader.stringByTrimmingCharactersInSet(NSCharacterSet(charactersInString: ", "))
blockHeader = blockHeader.stringByTrimmingCharactersInSet(NSCharacterSet(charactersInString: ", "))
if header {
return TemplateFactory.templateForObjCMethodHeaderWithName(methodName, key: key, baseTranslation: baseTranslation, methodHeader: methodHeader, contentLevel: contentLevel)
} else {
return TemplateFactory.templateForObjCMethodImplementationWithName(methodName, key: key, baseTranslation: baseTranslation, methodHeader: methodHeader, blockHeader: blockHeader, blockParams: blockParams, contentLevel: contentLevel)
}
}
}
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
// MARK: - Runtime Class implementation
class Runtime {
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
// MARK: - Properties
enum ExportLanguage : String {
case Swift = "swift"
case ObjC = "objc"
}
enum ExportStream : String {
case Standard = "stdout"
case File = "file"
}
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
// MARK: - Properties
var localizationFilePathToRead : NSURL!
var localizationFilePathToWriteTo : NSURL!
var localizationFileHeaderPathToWriteTo : NSURL?
var localizationDelimiter = "."
var localizationDebug = false
var localizationCore : Localization!
var localizationExportLanguage : ExportLanguage = .Swift
var localizationExportStream : ExportStream = .File
var localizationAutocapitalize = false
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
// MARK: - Public
func run() {
// Initialize command line tool
if self.checkCLI() {
// Process files
if self.checkIO() {
// Generate input -> output based on user configuration
self.processOutput()
}
}
}
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
// MARK: - Private
private func checkCLI() -> Bool {
// Define CLI options
let inputFilePath = StringOption(shortFlag: "i", longFlag: "input", required: true,
helpMessage: "Required | String | Path to the localization file")
let outputFilePath = StringOption(shortFlag: "o", longFlag: "output", required: false,
helpMessage: "Optional | String | Path to output file (.swift or .m, depending on your configuration. If you are using ObjC, header will be created on that location. If ommited, output will be sent to stdout instead.")
let outputLanguage = StringOption(shortFlag: "l", longFlag: "language", required: false,
helpMessage: "Optional | String | [swift | objc] | Specifies language of generated output files | Defaults to [swift]")
let delimiter = StringOption(shortFlag: "d", longFlag: "delimiter", required: false,
helpMessage: "Optional | String | String delimiter to separate segments of each string | Defaults to [.]")
let autocapitalize = BoolOption(shortFlag: "c", longFlag: "capitalize", required: false,
helpMessage: "Optional | Bool | When enabled, name of all structures / methods / properties are automatically CamelCased | Defaults to false")
let cli = CommandLine()
cli.addOptions(inputFilePath, outputFilePath, outputLanguage, delimiter, autocapitalize)
// TODO: make output file path NOT optional when print output stream is selected
do {
// Parse user input
try cli.parse()
// It passed, now process input
self.localizationFilePathToRead = NSURL(fileURLWithPath: inputFilePath.value!)
if let value = delimiter.value { self.localizationDelimiter = value }
self.localizationAutocapitalize = autocapitalize.wasSet ? true : false
if let value = outputLanguage.value, type = ExportLanguage(rawValue: value) { self.localizationExportLanguage = type }
if let value = outputFilePath.value {
self.localizationFilePathToWriteTo = NSURL(fileURLWithPath: value)
self.localizationExportStream = .File
} else {
self.localizationExportStream = .Standard
}
return true
} catch {
cli.printUsage(error)
exit(EX_USAGE)
}
return false
}
private func checkIO() -> Bool {
// Check if we have input file
if !NSFileManager.defaultManager().fileExistsAtPath(self.localizationFilePathToRead.path!) {
// TODO: Better error handling
exit(EX_IOERR)
}
// Handle output file checks only if we are writing to file
if self.localizationExportStream == .File {
// Remove output file first
_ = try? NSFileManager.defaultManager().removeItemAtPath(self.localizationFilePathToWriteTo.path!)
if !NSFileManager.defaultManager().createFileAtPath(self.localizationFilePathToWriteTo.path!, contents: NSData(), attributes: nil) {
// TODO: Better error handling
exit(EX_IOERR)
}
// ObjC - we also need header file for ObjC code
if self.localizationExportLanguage == .ObjC {
// Create header file name
self.localizationFileHeaderPathToWriteTo = self.localizationFilePathToWriteTo.URLByDeletingPathExtension!.URLByAppendingPathExtension("h")
// Remove file at path and replace it with new one
_ = try? NSFileManager.defaultManager().removeItemAtPath(self.localizationFileHeaderPathToWriteTo!.path!)
if !NSFileManager.defaultManager().createFileAtPath(self.localizationFileHeaderPathToWriteTo!.path!, contents: NSData(), attributes: nil) {
// TODO: Better error handling
exit(EX_IOERR)
}
}
}
return true
}
private func processOutput() {
// Create translation core which will process all required data
self.localizationCore = Localization(inputFile: self.localizationFilePathToRead, delimiter: self.localizationDelimiter, autocapitalize: self.localizationAutocapitalize)
// Write output for swift
if self.localizationExportLanguage == .Swift {
let implementation = self.localizationCore.writerWithSwiftImplementation()
// Write swift file
if self.localizationExportStream == .Standard {
implementation.writeToSTD(true)
} else if self.localizationExportStream == .File {
implementation.writeToOutputFileAtPath(self.localizationFilePathToWriteTo)
}
// or write output for objc, based on user configuration
} else if self.localizationExportLanguage == .ObjC {
let implementation = self.localizationCore.writerWithObjCImplementationWithFilename(self.localizationFilePathToWriteTo.URLByDeletingPathExtension!.lastPathComponent!)
let header = self.localizationCore.writerWithObjCHeader()
// Write .h and .m file
if self.localizationExportStream == .Standard {
header.writeToSTD(true)
implementation.writeToSTD(true)
} else if self.localizationExportStream == .File {
implementation.writeToOutputFileAtPath(self.localizationFilePathToWriteTo)
header.writeToOutputFileAtPath(self.localizationFileHeaderPathToWriteTo!)
}
}
}
}
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
// MARK: - LocalizationPrinter Class implementation
class StreamWriter {
var outputBuffer : String = ""
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
// MARK: - Public
func writeHeader() {
// let formatter = NSDateFormatter()
// formatter.dateFormat = "yyyy-MM-dd 'at' h:mm a"
self.store("//\n")
self.store("// Autogenerated by Laurine - by Jiri Trecak ( http://jiritrecak.com, @jiritrecak )\n")
self.store("// Do not change this file manually!\n")
self.store("//\n")
// self.store("// \(formatter.stringFromDate(NSDate()))\n")
// self.store("//\n")
}
func writeRequiredExtensions() {
self.store("private extension String {\n")
self.store("\n")
self.store(" var localized: String {\n")
self.store("\n")
self.store(" return NSLocalizedString(self, tableName: nil, bundle: NSBundle.mainBundle(), value: \"\", comment: \"\")\n")
self.store(" }\n")
self.store("\n")
self.store(" func localizedWithComment(comment:String) -> String {\n")
self.store("\n")
self.store(" return NSLocalizedString(self, tableName: nil, bundle: NSBundle.mainBundle(), value: \"\", comment: comment)\n")
self.store(" }\n")
self.store("}\n")
}
func writeMarkWithName(name : String, contentLevel : Int = 0) {
self.store(TemplateFactory.contentIndentForLevel(contentLevel) + "\n")
self.store(TemplateFactory.contentIndentForLevel(contentLevel) + "\n")
self.store(TemplateFactory.contentIndentForLevel(contentLevel) + "// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---\n")
self.store(TemplateFactory.contentIndentForLevel(contentLevel) + "// MARK: - \(name)\n")
self.store(TemplateFactory.contentIndentForLevel(contentLevel) + "\n")
}
func writeSwiftImports() {
self.store("import Foundation\n")
}
func writeObjCImportsWithFileName(name : String) {
self.store("#import \"\(name).h\"\n")
}
func writeObjCHeaderImports() {
self.store("@import Foundation;\n")
self.store("@import UIKit;\n")
}
func writeObjCHeaderMacros() {
self.store("// Make localization to be easily accessible\n")
self.store("#define Localizations [\(OBJC_CLASS_PREFIX)\(BASE_CLASS_NAME) sharedInstance]\n")
}
func writeCodeStructure(structure : String) {
self.store(structure)
}
func writeToOutputFileAtPath(path : NSURL, clearBuffer : Bool = true) {
_ = try? self.outputBuffer.writeToFile(path.path!, atomically: true, encoding: NSUTF8StringEncoding)
if clearBuffer {
self.outputBuffer = ""
}
}
func writeToSTD(clearBuffer : Bool = true) {
print(self.outputBuffer)
if clearBuffer {
self.outputBuffer = ""
}
}
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
// MARK: - Private
private func store(string : String) {
self.outputBuffer += string
}
}
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
// MARK: - TemplateFactory Class implementation
class TemplateFactory {
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
// MARK: - Public - Swift Templates
class func templateForSwiftStructWithName(name : String, content : String, contentLevel : Int) -> String {
return "\n"
+ TemplateFactory.contentIndentForLevel(contentLevel) + "public struct \(name) {\n"
+ "\n"
+ TemplateFactory.contentIndentForLevel(contentLevel) + "\(content)\n"
+ TemplateFactory.contentIndentForLevel(contentLevel) + "}"
}
class func templateForSwiftStaticVarWithName(name : String, key : String, baseTranslation : String, contentLevel : Int) -> String {
return TemplateFactory.contentIndentForLevel(contentLevel) + "/// Base translation: \(baseTranslation)\n"
+ TemplateFactory.contentIndentForLevel(contentLevel) + "public static var \(name) : String = \"\(key)\".localized\n"
}
class func templateForSwiftFuncWithName(name : String, key : String, baseTranslation : String, methodHeader : String, params : String, contentLevel : Int) -> String {
return TemplateFactory.contentIndentForLevel(contentLevel) + "/// Base translation: \(baseTranslation)\n"
+ TemplateFactory.contentIndentForLevel(contentLevel) + "public static func \(name)(\(methodHeader)) -> String {\n"
+ TemplateFactory.contentIndentForLevel(contentLevel + 1) + "return String(format: NSLocalizedString(\"\(key)\", tableName: nil, bundle: NSBundle.mainBundle(), value: \"\", comment: \"\"), \(params))\n"
+ TemplateFactory.contentIndentForLevel(contentLevel) + "}\n"
}
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
// MARK: - Public - ObjC templates
class func templateForObjCClassImplementationWithName(name : String, content : String, contentLevel : Int) -> String {
return "@implementation \(name)\n\n"
+ "\(content)\n"
+ "@end\n\n"
}
class func templateForObjCStaticVarImplementationWithName(name : String, key : String, baseTranslation : String, contentLevel : Int) -> String {
return "- (NSString *)\(name) {\n"
+ TemplateFactory.contentIndentForLevel(1) + "return NSLocalizedString(@\"\(key)\", nil);\n"
+ "}\n"
}
class func templateForObjCClassVarImplementationWithName(name : String, className : String, contentLevel : Int) -> String {
return "- (_\(className) *)\(name) {\n"
+ TemplateFactory.contentIndentForLevel(1) + "return [\(OBJC_CLASS_PREFIX)\(className) new];\n"
+ "}\n"
}
class func templateForObjCMethodImplementationWithName(name : String, key : String, baseTranslation : String, methodHeader : String, blockHeader : String, blockParams : String, contentLevel : Int) -> String {
return "- (NSString *(^)(\(methodHeader)))\(name) {\n"
+ TemplateFactory.contentIndentForLevel(1) + "return ^(\(blockHeader)) {\n"
+ TemplateFactory.contentIndentForLevel(2) + "return [NSString stringWithFormat: NSLocalizedString(@\"\(key)\", nil), \(blockParams)];\n"
+ TemplateFactory.contentIndentForLevel(1) + "};\n"
+ "}\n"
}
class func templateForObjCClassHeaderWithName(name : String, content : String, contentLevel : Int) -> String {
return "@interface \(name) : NSObject\n\n"
+ "\(content)\n"
+ "@end\n"
}
class func templateForObjCStaticVarHeaderWithName(name : String, key : String, baseTranslation : String, contentLevel : Int) -> String {
return "/// Base translation: \(baseTranslation)\n"
+ "- (NSString *)\(name);\n"
}
class func templateForObjCClassVarHeaderWithName(name : String, className : String, contentLevel : Int) -> String {
return "- (_\(className) *)\(name);\n"
}
class func templateForObjCMethodHeaderWithName(name : String, key : String, baseTranslation : String, methodHeader : String, contentLevel : Int) -> String {
return "/// Base translation: \(baseTranslation)\n"
+ "- (NSString *(^)(\(methodHeader)))\(name);"
}
class func templateForObjCBaseClassHeader(name: String) -> String {
return "+ (\(name) *)sharedInstance;\n"
}
class func templateForObjCBaseClassImplementation(name : String) -> String {
return "+ (\(name) *)sharedInstance {\n"
+ "\n"
+ TemplateFactory.contentIndentForLevel(1) + "static dispatch_once_t once;\n"
+ TemplateFactory.contentIndentForLevel(1) + "static \(name) *instance;\n"
+ TemplateFactory.contentIndentForLevel(1) + "dispatch_once(&once, ^{\n"
+ TemplateFactory.contentIndentForLevel(2) + "instance = [[\(name) alloc] init];\n"
+ TemplateFactory.contentIndentForLevel(1) + "});\n"
+ TemplateFactory.contentIndentForLevel(1) + "return instance;\n"
+ "}"
}
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
// MARK: - Public - Helpers
class func contentIndentForLevel(contentLevel : Int) -> String {
var outputString = ""
for _ in 0 ..< contentLevel {
outputString += " "
}
return outputString
}
}
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
// MARK: - Actual processing
let runtime = Runtime()
runtime.run()
| mit | 027a90e0311420c3e479bd58ad9c597a | 35.204112 | 546 | 0.567065 | 5.040919 | false | false | false | false |
iZhang/travel-architect | main/ViewController.swift | 1 | 6663 | /*
See LICENSE folder for this sample’s licensing information.
Abstract:
Main view controller for the AR experience.
*/
import ARKit
import SceneKit
import UIKit
class ViewController: UIViewController {
// MARK: IBOutlets
@IBOutlet var sceneView: VirtualObjectARView!
@IBOutlet weak var addObjectButton: UIButton!
@IBOutlet weak var blurView: UIVisualEffectView!
@IBOutlet weak var spinner: UIActivityIndicatorView!
// MARK: - UI Elements
var focusSquare = FocusSquare()
/// The view controller that displays the status and "restart experience" UI.
lazy var statusViewController: StatusViewController = {
return childViewControllers.lazy.flatMap({ $0 as? StatusViewController }).first!
}()
/// The view controller that displays the virtual object selection menu.
var objectsViewController: VirtualObjectSelectionViewController?
// MARK: - ARKit Configuration Properties
/// A type which manages gesture manipulation of virtual content in the scene.
lazy var virtualObjectInteraction = VirtualObjectInteraction(sceneView: sceneView)
/// Coordinates the loading and unloading of reference nodes for virtual objects.
let virtualObjectLoader = VirtualObjectLoader()
/// Marks if the AR experience is available for restart.
var isRestartAvailable = true
/// A serial queue used to coordinate adding or removing nodes from the scene.
let updateQueue = DispatchQueue(label: "com.architect.arkit")
var screenCenter: CGPoint {
let bounds = sceneView.bounds
return CGPoint(x: bounds.midX, y: bounds.midY)
}
/// Convenience accessor for the session owned by ARSCNView.
var session: ARSession {
return sceneView.session
}
// MARK: - View Controller Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
sceneView.delegate = self
sceneView.session.delegate = self
// Set up scene content.
setupCamera()
sceneView.scene.rootNode.addChildNode(focusSquare)
/*
The `sceneView.automaticallyUpdatesLighting` option creates an
ambient light source and modulates its intensity. This sample app
instead modulates a global lighting environment map for use with
physically based materials, so disable automatic lighting.
*/
sceneView.automaticallyUpdatesLighting = false
if let environmentMap = UIImage(named: "Models.scnassets/sharedImages/environment_blur.exr") {
sceneView.scene.lightingEnvironment.contents = environmentMap
}
// Hook up status view controller callback(s).
statusViewController.restartExperienceHandler = { [unowned self] in
self.restartExperience()
}
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(showVirtualObjectSelectionViewController))
// Set the delegate to ensure this gesture is only used when there are no virtual objects in the scene.
tapGesture.delegate = self
sceneView.addGestureRecognizer(tapGesture)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
// Prevent the screen from being dimmed to avoid interuppting the AR experience.
UIApplication.shared.isIdleTimerDisabled = true
// Start the `ARSession`.
resetTracking()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
session.pause()
}
// MARK: - Scene content setup
func setupCamera() {
guard let camera = sceneView.pointOfView?.camera else {
fatalError("Expected a valid `pointOfView` from the scene.")
}
/*
Enable HDR camera settings for the most realistic appearance
with environmental lighting and physically based materials.
*/
camera.wantsHDR = true
camera.exposureOffset = -1
camera.minimumExposure = -1
camera.maximumExposure = 3
}
// MARK: - Session management
/// Creates a new AR configuration to run on the `session`.
func resetTracking() {
virtualObjectInteraction.selectedObject = nil
let configuration = ARWorldTrackingConfiguration()
configuration.planeDetection = [.horizontal, .vertical]
session.run(configuration, options: [.resetTracking, .removeExistingAnchors])
statusViewController.scheduleMessage("FIND A SURFACE TO PLACE AN OBJECT", inSeconds: 7.5, messageType: .planeEstimation)
}
// MARK: - Focus Square
func updateFocusSquare() {
let isObjectVisible = virtualObjectLoader.loadedObjects.contains { object in
return sceneView.isNode(object, insideFrustumOf: sceneView.pointOfView!)
}
if isObjectVisible {
focusSquare.hide()
} else {
focusSquare.unhide()
statusViewController.scheduleMessage("TRY MOVING LEFT OR RIGHT", inSeconds: 5.0, messageType: .focusSquare)
}
// Perform hit testing only when ARKit tracking is in a good state.
if let camera = session.currentFrame?.camera, case .normal = camera.trackingState,
let result = self.sceneView.smartHitTest(screenCenter) {
updateQueue.async {
self.sceneView.scene.rootNode.addChildNode(self.focusSquare)
self.focusSquare.state = .detecting(hitTestResult: result, camera: camera)
}
addObjectButton.isHidden = false
statusViewController.cancelScheduledMessage(for: .focusSquare)
} else {
updateQueue.async {
self.focusSquare.state = .initializing
self.sceneView.pointOfView?.addChildNode(self.focusSquare)
}
addObjectButton.isHidden = true
}
}
// MARK: - Error handling
func displayErrorMessage(title: String, message: String) {
// Blur the background.
blurView.isHidden = false
// Present an alert informing about the error that has occurred.
let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
let restartAction = UIAlertAction(title: "Restart Session", style: .default) { _ in
alertController.dismiss(animated: true, completion: nil)
self.blurView.isHidden = true
self.resetTracking()
}
alertController.addAction(restartAction)
present(alertController, animated: true, completion: nil)
}
}
| mit | 44a19e5c10fb4394982b74c1453bf9d3 | 34.243386 | 128 | 0.67092 | 5.32454 | false | false | false | false |
tensorflow/swift-models | Models/Text/BERT/Attention.swift | 1 | 11459 | // Copyright 2019 The TensorFlow Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import TensorFlow
/// Input to an attention layer.
public struct AttentionInput<Scalar: TensorFlowFloatingPoint>: Differentiable {
/// Source tensor that we are attending from, with shape
/// `[batchSize, sourceSequenceLength, sourceDepth]` or
/// `[batchSize, sourceSequenceLength * sourceDepth]`.
public var source: Tensor<Scalar>
/// Target tensor that we are attending to, with shape
/// `[batchSize, targetSequenceLength, targetDepth]` or
/// `[batchSize, targetSequenceLength * targetDepth]`.
public var target: Tensor<Scalar>
/// Mask to apply on the attention scores. This is a tensor with shape
/// `[batchSize, sourceSequenceLength, targetSequenceLength]` or
/// `[batchSize, sourceSequenceLength * targetSequenceLength]`. The values should be `1` or `0`.
/// The attention scores will effectively be set to negative infinity for any positions in the
/// mask that are set to `0`, and will be unchanged for positions that are set to `1`.
public var mask: Tensor<Scalar>
/// The batch size of this input. This is optional because it is only needed if the input
/// sequences have been reshaped to matrices.
@noDerivative let batchSize: Int?
@differentiable
public init(
source: Tensor<Scalar>,
target: Tensor<Scalar>,
mask: Tensor<Scalar>,
batchSize: Int? = nil
) {
precondition(
source.rank == target.rank,
"The rank of the attention source and target tensors must match.")
self.source = source
self.target = target
self.mask = mask
self.batchSize = batchSize
}
}
/// Multi-head attention layer.
///
/// This implementation is based on the
/// ["Attention Is All You Need"](https://arxiv.org/abs/1706.03762) paper. If the source and target
/// tensors are the same, then this layer behaves as a self-attention layer. Each sequence step in
/// the source tensor attends to the corresponding sequence in the target tensor and returns a
/// fixed-size vector.
///
/// This function first projects the source tensor into a "query" tensor and the target tensor into
/// "key" and "value" tensors. These are (effectively) a list of tensors of length `headCount`,
/// where each tensor has shape `[batchSize, sequenceLength, headSize]`. It then performs a dot
/// product between the query and they key tensors and scales them. Finally, they are passed
/// through the softmax function to obtain attention probabilities. The value tensors are then
/// interpolated by these probabilities, and then concatenated back to a single result tensor.
///
/// In practice, the multi-head attention is implemented using transpose and reshape operations,
/// rather than using separate tensors.
///
/// - Source: ["Attention Is All You Need"](https://arxiv.org/abs/1706.03762).
public struct MultiHeadAttention: Layer, Regularizable {
// TODO: Convert to a generic constraint once TF-427 is resolved.
public typealias Scalar = Float
@noDerivative public let sourceSize: Int
@noDerivative public let targetSize: Int
@noDerivative public let headCount: Int
@noDerivative public let headSize: Int
@noDerivative public let queryActivation: Activation<Scalar>
@noDerivative public let keyActivation: Activation<Scalar>
@noDerivative public let valueActivation: Activation<Scalar>
@noDerivative public let matrixResult: Bool
public var queryWeight: Tensor<Scalar>
public var queryBias: Tensor<Scalar>
public var keyWeight: Tensor<Scalar>
public var keyBias: Tensor<Scalar>
public var valueWeight: Tensor<Scalar>
public var valueBias: Tensor<Scalar>
@noDerivative public var attentionDropout: Dropout<Scalar>
public var regularizationValue: TangentVector {
TangentVector(
queryWeight: queryWeight,
queryBias: Tensor(Scalar(0), on: queryBias.device),
keyWeight: keyWeight,
keyBias: Tensor(Scalar(0), on: keyBias.device),
valueWeight: valueWeight,
valueBias: Tensor(Scalar(0), on: valueBias.device))
}
/// Creates a multi-head attention layer.
///
/// - Parameters:
/// - sourceSize: Size/depth of the source tensor this layer is attending from.
/// - targetSize: Size/depth of the target tensor this layer is attending to.
/// - headCount: Number of attention heads.
/// - headSize: Size/depth of each attention head.
/// - queryActivation: Activation function applied to the attention query tensor.
/// - keyActivation: Activation function applied to the attention key tensor.
/// - valueActivation: Activation function applied to the attention value tensor.
/// - attentionDropoutProbability: Dropout probability for the attention scores.
/// - matrixResult: If `true`, the resulting tensor will have shape
/// `[batchSize * sourceSequenceLength, headCount * headSize]`. Otherwise, it will have shape
/// `[batchSize, sourceSequenceLength, headCount * headSize]`.
/// - queryWeightInitializer: Initializer for the query transformation weight.
/// - queryBiasInitializer: Initializer for the query transformation bias.
/// - keyWeightInitializer: Initializer for the key transformation weight.
/// - keyBiasInitializer: Initializer for the key transformation bias.
/// - valueWeightInitializer: Initializer for the value transformation weight.
/// - valueBiasInitializer: Initializer for the value transformation bias.
public init(
sourceSize: Int,
targetSize: Int,
headCount: Int = 1,
headSize: Int = 512,
queryActivation: @escaping Activation<Scalar> = identity,
keyActivation: @escaping Activation<Scalar> = identity,
valueActivation: @escaping Activation<Scalar> = identity,
attentionDropoutProbability: Scalar = 0,
matrixResult: Bool = false,
queryWeightInitializer: ParameterInitializer<Scalar> = defaultWeightInitializer,
queryBiasInitializer: ParameterInitializer<Scalar> = defaultBiasInitializer,
keyWeightInitializer: ParameterInitializer<Scalar> = defaultWeightInitializer,
keyBiasInitializer: ParameterInitializer<Scalar> = defaultBiasInitializer,
valueWeightInitializer: ParameterInitializer<Scalar> = defaultWeightInitializer,
valueBiasInitializer: ParameterInitializer<Scalar> = defaultBiasInitializer
) {
self.sourceSize = sourceSize
self.targetSize = targetSize
self.headCount = headCount
self.headSize = headSize
self.queryActivation = queryActivation
self.keyActivation = keyActivation
self.valueActivation = valueActivation
self.matrixResult = matrixResult
self.queryWeight = queryWeightInitializer([sourceSize, headCount * headSize])
self.queryBias = queryBiasInitializer([headCount * headSize])
self.keyWeight = keyWeightInitializer([targetSize, headCount * headSize])
self.keyBias = keyBiasInitializer([headCount * headSize])
self.valueWeight = valueWeightInitializer([targetSize, headCount * headSize])
self.valueBias = valueBiasInitializer([headCount * headSize])
// TODO: Make dropout generic over the probability type.
self.attentionDropout = Dropout(probability: Double(attentionDropoutProbability))
}
@differentiable
public func callAsFunction(_ input: AttentionInput<Scalar>) -> Tensor<Scalar> {
precondition(
input.source.rank == 3 || input.batchSize != nil,
"Whenever the input is provided in matrix form, the batch size must also be provided.")
// Scalar dimensions referenced here:
// - B = batch size (number of sequences)
// - F = `input.source` sequence length
// - T = `input.target` sequence length
// - N = number of attention heads
// - H = size per attention head
let matrixInput = input.source.rank < 3
let B = matrixInput ? input.batchSize! : input.source.shape[0]
let F = matrixInput ? input.source.shape[0] / B : input.source.shape[1]
let T = matrixInput ? input.target.shape[0] / B : input.target.shape[1]
let N = headCount
let H = headSize
let source = input.source.reshapedToMatrix()
let target = input.target.reshapedToMatrix()
var q = queryActivation(matmul(source, queryWeight) + queryBias) // [B * F, N * H]
var k = keyActivation(matmul(target, keyWeight) + keyBias) // [B * T, N * H]
var v = valueActivation(matmul(target, valueWeight) + valueBias) // [B * T, N * H]
q = q.reshaped(to: [B, F, N, H]).transposed(permutation: 0, 2, 1, 3) // [B, N, F, H]
k = k.reshaped(to: [B, T, N, H]).transposed(permutation: 0, 2, 1, 3) // [B, N, T, H]
v = v.reshaped(to: [B, T, N, H]).transposed(permutation: 0, 2, 1, 3) // [B, N, T, H]
// Take the dot product between the query and the key to get the raw attention scores.
var attentionScores = matmul(q, transposed: false, k, transposed: true) // [B, N, F, T]
attentionScores = attentionScores / sqrtf(Scalar(headSize))
// Since the attention mask is set to 1.0 for positions we want to attend to and 0.0 for
// masked positions, we create a tensor which is 0.0 for positions we want to attend to and
// -10000.0 for masked positions. Since we are adding this tensor to the raw scores before
// the softmax, this is effectively the same as removing the masked entries entirely.
let attentionMask = input.mask.expandingShape(at: 1) // [B, 1, F, T]
attentionScores = attentionScores - 10000 * (1 - attentionMask)
// Normalize the attention scores to convert them to probabilities. We are also dropping
// out entire tokens to attend to, which might seem a bit unusual, but it is taken from the
// original Transformer paper.
let attentionProbabilities = attentionDropout(softmax(attentionScores)) // [B, N, F, T]
let result = matmul(attentionProbabilities, v) // [B, N, F, H]
.transposed(permutation: 0, 2, 1, 3) // [B, F, N, H]
return matrixResult
? result.reshaped(to: [B * F, N * H]) : result.reshaped(to: [B, F, N * H])
}
}
extension MultiHeadAttention {
/// Default initializer to use for the linear transform weights.
public static var defaultWeightInitializer: ParameterInitializer<Scalar> {
truncatedNormalInitializer(standardDeviation: Tensor<Scalar>(0.02))
}
/// Default initializer to use for the linear transform biases.
public static var defaultBiasInitializer: ParameterInitializer<Scalar> {
zeros()
}
}
| apache-2.0 | ffffead8a23838f1d204e2d7e7ddf557 | 50.15625 | 101 | 0.686535 | 4.585434 | false | false | false | false |
EyreFree/EFQRCode | Examples/iOS/watchOS Example Extension/NumberPadInterfaceController.swift | 1 | 2965 | //
// NumberPadInterfaceController.swift
// watchOS Example Extension
//
// Created by Apollo Zhu on 12/27/17.
//
// Copyright (c) 2017 EyreFree <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import WatchKit
typealias NumberInputHandler = (Int) -> Void
extension WKInterfaceController {
func presentNumberInputController(withDefault default: Int, completion handler: @escaping NumberInputHandler) {
presentController(withName: "NumberPad", context: (abs(`default`), handler))
}
}
class NumberPadInterfaceController: WKInterfaceController {
@IBOutlet var display: WKInterfaceLabel!
private var value: Int = 0 {
didSet {
display.setText("\(value)")
}
}
private var completion: NumberInputHandler?
override func awake(withContext context: Any?) {
super.awake(withContext: context)
if let (preferred, handler) = context as? (Int, NumberInputHandler) {
value = preferred
completion = handler
}
}
@IBAction func didFinishInput() {
completion?(value)
dismiss()
}
@IBAction func tapped0() {
if value != 0 {
tapped(0)
}
}
@IBAction func tapped1() {
tapped(1)
}
@IBAction func tapped2() {
tapped(2)
}
@IBAction func tapped3() {
tapped(3)
}
@IBAction func tapped4() {
tapped(4)
}
@IBAction func tapped5() {
tapped(5)
}
@IBAction func tapped6() {
tapped(6)
}
@IBAction func tapped7() {
tapped(7)
}
@IBAction func tapped8() {
tapped(8)
}
@IBAction func tapped9() {
tapped(9)
}
@IBAction func removeLast() {
value /= 10
}
private func tapped(_ number: Int) {
if let newValue = Int("\(value)\(number)") {
value = newValue
}
}
}
| mit | 850754747008dd73bab5ff10c598db49 | 29.56701 | 115 | 0.644182 | 4.405646 | false | false | false | false |
KoCMoHaBTa/MHLocalizationKit | MHLocalizationKit/Language/Language.swift | 1 | 4431 | //
// Language.swift
// MHLocalizationKit
//
// Created by Milen Halachev on 3/7/16.
// Copyright © 2016 Milen Halachev. All rights reserved.
//
import Foundation
///Represents a langauge formed by code, script and region
//https://developer.apple.com/library/archive/documentation/MacOSX/Conceptual/BPInternational/LanguageandLocaleIDs/LanguageandLocaleIDs.html
public struct Language {
public let id: String //code-script-region; code-region; code-script; code
//designators
public let code: String //2-3 chars: en, bg, fr
public let script: String? //4-5 chars: Cyrl, Latn, Arab, POSIX
public let region: String? //2 chars: US, GB
fileprivate init(id: String, code: String, script: String?, region: String?) {
self.id = id
self.code = code
self.script = script
self.region = region
}
}
extension Language {
/**
Creates an instance of the receiver by parsing a language id into designators.
- parameter id: The language id in one of the following forms - `code-script-region`, `code-region`, `code-script`, `code`.
- warning: Do not use for custom languages, or have in mind that region is restricted to 2 chars for `code-region`, `code-script` cases.
- note: For custom languages - use `init(code:region:script)`
*/
public init(id: String) {
let id = id.replacingOccurrences(of: "_", with: "-")
//create designators
let code: String
var script: String?
var region: String?
let components = id.components(separatedBy: "-")
switch components.count {
//the 3rd components is always region
case 3:
region = components[2]
fallthrough
//the second components could be either 2 chars region or a script
case 2:
if region == nil && components[1].utf8.count == 2 {
region = components[1]
}
else {
script = components[1]
}
fallthrough
//the first component is always the code
default:
code = components[0]
}
self.init(id: id, code: code, script: script, region: region)
}
}
extension Language {
///Creates an instance of the receiver for with a code, script and region
public init(code: String, script: String? = nil, region: String? = nil) {
//create id
var id = code
if let script = script {
id += "-\(script)"
}
if let region = region {
id += "-\(region)"
}
self.init(id: id, code: code, script: script, region: region)
}
}
//MARK: - CustomDebugStringConvertible
extension Language: CustomDebugStringConvertible {
public var debugDescription: String {
var designators = ["code": self.code]
designators["script"] = self.script
designators["region"] = self.region
return "\(self.id) <=> \(designators.debugDescription)"
}
}
//MARK: - CustomStringConvertible
//extension Language: CustomStringConvertible {
//
// public var description: String {
//
// return self.id
// }
//}
//MARK: - RawRepresentable
extension Language: RawRepresentable {
public init?(rawValue: String) {
self.init(id: rawValue)
}
public var rawValue: String {
return self.id
}
}
//MARK: - StringLiteralConvertible
extension Language: ExpressibleByStringLiteral {
public init(stringLiteral value: String) {
self.init(id: value)
}
public init(extendedGraphemeClusterLiteral value: String) {
self.init(id: value)
}
public init(unicodeScalarLiteral value: String) {
self.init(id: value)
}
}
//MARK: - Hashable
extension Language: Hashable {
public var hashValue: Int {
return self.id.hashValue
}
}
public func ==(lhs: Language, rhs: Language) -> Bool {
return lhs.id == rhs.id
}
| mit | e8fa589795e6b1b118790c519e57aa2f | 23.88764 | 141 | 0.552596 | 4.697773 | false | false | false | false |
davidkuchar/codepath-03-twitter | Twitter/User.swift | 1 | 2055 | //
// User.swift
// Twitter
//
// Created by David Kuchar on 5/24/15.
// Copyright (c) 2015 David Kuchar. All rights reserved.
//
import UIKit
var _currentUser: User? = nil
let currentUserKey = "kCurrentUserKey"
let userDidLoginNotification = "userDidLoginNotification"
let userDidLogoutNotification = "userDidLogoutNotification"
class User: NSObject {
var name: String?
var screenname: String?
var profileImageUrl: String?
var tagline: String?
var dictionary: NSDictionary
init(dictionary: NSDictionary) {
self.dictionary = dictionary
name = dictionary["name"] as? String
screenname = dictionary["screen_name"] as? String
profileImageUrl = dictionary["profile_image_url"] as? String
tagline = dictionary["description"] as? String
}
func logout() {
User.currentUser = nil
TwitterClient.sharedInstance().requestSerializer.removeAccessToken()
NSNotificationCenter.defaultCenter().postNotificationName(userDidLogoutNotification, object: nil)
}
class var currentUser: User? {
get {
if _currentUser == nil {
if var data = NSUserDefaults.standardUserDefaults().objectForKey(currentUserKey) as? NSData {
var dictionary = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: nil) as! NSDictionary
_currentUser = User(dictionary: dictionary)
}
}
return _currentUser
}
set(user) {
_currentUser = user
if _currentUser != nil {
var data = NSJSONSerialization.dataWithJSONObject(user!.dictionary, options: nil, error: nil)
NSUserDefaults.standardUserDefaults().setObject(data, forKey: currentUserKey)
} else {
NSUserDefaults.standardUserDefaults().setObject(nil, forKey: currentUserKey)
}
NSUserDefaults.standardUserDefaults().synchronize()
}
}
} | mit | 4f10a1407a5ccaba49236efb24285901 | 32.704918 | 124 | 0.629684 | 5.407895 | false | false | false | false |
apple/swift-algorithms | Sources/Algorithms/Product.swift | 1 | 15837 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Algorithms open source project
//
// Copyright (c) 2020 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
//
//===----------------------------------------------------------------------===//
/// A sequence that represents the product of two sequences' elements.
public struct Product2Sequence<Base1: Sequence, Base2: Collection> {
/// The outer sequence in the product.
@usableFromInline
internal let base1: Base1
/// The inner sequence in the product.
@usableFromInline
internal let base2: Base2
@inlinable
internal init(_ base1: Base1, _ base2: Base2) {
self.base1 = base1
self.base2 = base2
}
}
extension Product2Sequence: Sequence {
public typealias Element = (Base1.Element, Base2.Element)
/// The iterator for a `Product2Sequence` sequence.
public struct Iterator: IteratorProtocol {
@usableFromInline
internal var i1: Base1.Iterator
@usableFromInline
internal var i2: Base2.Iterator
@usableFromInline
internal var element1: Base1.Element?
@usableFromInline
internal let base2: Base2
@inlinable
internal init(_ c: Product2Sequence) {
self.base2 = c.base2
self.i1 = c.base1.makeIterator()
self.i2 = c.base2.makeIterator()
self.element1 = nil
}
@inlinable
public mutating func next() -> (Base1.Element,
Base2.Element)? {
// This is the initial state, where i1.next() has never
// been called, or the final state, where i1.next() has
// already returned nil.
if element1 == nil {
element1 = i1.next()
// once Base1 is exhausted, return `nil` forever
if element1 == nil { return nil }
}
// Get the next element from the second sequence, if not
// at end.
if let element2 = i2.next() {
return (element1!, element2)
}
// We've reached the end of the second sequence, so:
// 1) Get the next element of the first sequence, if exists
// 2) Restart iteration of the second sequence
// 3) Get the first element of the second sequence, if exists
element1 = i1.next()
guard let element1 = element1
else { return nil }
i2 = base2.makeIterator()
if let element2 = i2.next() {
return (element1, element2)
} else {
return nil
}
}
}
@inlinable
public func makeIterator() -> Iterator {
Iterator(self)
}
}
extension Product2Sequence: Collection where Base1: Collection {
/// The index type for a `Product2Sequence` collection.
public struct Index: Comparable {
@usableFromInline
internal var i1: Base1.Index
@usableFromInline
internal var i2: Base2.Index
@inlinable
internal init(i1: Base1.Index, i2: Base2.Index) {
self.i1 = i1
self.i2 = i2
}
@inlinable
public static func < (lhs: Index, rhs: Index) -> Bool {
(lhs.i1, lhs.i2) < (rhs.i1, rhs.i2)
}
}
@inlinable
public var count: Int {
base1.count * base2.count
}
@inlinable
public var startIndex: Index {
Index(
i1: base2.isEmpty ? base1.endIndex : base1.startIndex,
i2: base2.startIndex)
}
@inlinable
public var endIndex: Index {
// `base2.startIndex` simplifies index calculations.
Index(i1: base1.endIndex, i2: base2.startIndex)
}
@inlinable
public subscript(position: Index) -> (Base1.Element,
Base2.Element) {
(base1[position.i1], base2[position.i2])
}
/// Forms an index from a pair of base indices, normalizing
/// `(i, base2.endIndex)` to `(base1.index(after: i), base2.startIndex)` if
/// necessary.
@inlinable
internal func normalizeIndex(_ i1: Base1.Index, _ i2: Base2.Index) -> Index {
i2 == base2.endIndex
? Index(i1: base1.index(after: i1), i2: base2.startIndex)
: Index(i1: i1, i2: i2)
}
@inlinable
public func index(after i: Index) -> Index {
precondition(i.i1 != base1.endIndex, "Can't advance past endIndex")
return normalizeIndex(i.i1, base2.index(after: i.i2))
}
@inlinable
public func distance(from start: Index, to end: Index) -> Int {
guard start.i1 <= end.i1
else { return -distance(from: end, to: start) }
guard start.i1 != end.i1
else { return base2.distance(from: start.i2, to: end.i2) }
// The number of full cycles through `base2` between `start` and `end`,
// excluding the cycles that `start` and `end` are on.
let fullBase2Cycles = base1[start.i1..<end.i1].count - 1
if start.i2 <= end.i2 {
// start.i2
// v
// start.i1 > [l l l|c c c c c c r r r]
// [l l l c c c c c c r r r] >
// ... > `fullBase2Cycles` times
// [l l l c c c c c c r r r] >
// end.i1 > [l l l c c c c c c|r r r]
// ^
// end.i2
let left = base2[..<start.i2].count
let center = base2[start.i2..<end.i2].count
let right = base2[end.i2...].count
return center + right
+ fullBase2Cycles * (left + center + right)
+ left + center
} else {
// start.i2
// v
// start.i1 > [l l l c c c c c c|r r r]
// [l l l c c c c c c r r r] >
// ... > `fullBase2Cycles` times
// [l l l c c c c c c r r r] >
// end.i1 > [l l l|c c c c c c r r r]
// ^
// end.i2
let left = base2[..<end.i2].count
let right = base2[start.i2...].count
// We can avoid traversing `base2[end.i2..<start.i2]` if `start` and `end`
// are on consecutive cycles.
guard fullBase2Cycles > 0 else { return right + left }
let center = base2[end.i2..<start.i2].count
return right
+ fullBase2Cycles * (left + center + right)
+ left
}
}
@inlinable
public func index(_ i: Index, offsetBy distance: Int) -> Index {
guard distance != 0 else { return i }
return distance > 0
? offsetForward(i, by: distance)
: offsetBackward(i, by: -distance)
}
@inlinable
public func index(
_ i: Index,
offsetBy distance: Int,
limitedBy limit: Index
) -> Index? {
if distance >= 0 {
return limit >= i
? offsetForward(i, by: distance, limitedBy: limit)
: offsetForward(i, by: distance)
} else {
return limit <= i
? offsetBackward(i, by: -distance, limitedBy: limit)
: offsetBackward(i, by: -distance)
}
}
@inlinable
internal func offsetForward(_ i: Index, by distance: Int) -> Index {
guard let index = offsetForward(i, by: distance, limitedBy: endIndex)
else { fatalError("Index is out of bounds") }
return index
}
@inlinable
internal func offsetBackward(_ i: Index, by distance: Int) -> Index {
guard let index = offsetBackward(i, by: distance, limitedBy: startIndex)
else { fatalError("Index is out of bounds") }
return index
}
@inlinable
internal func offsetForward(
_ i: Index, by distance: Int, limitedBy limit: Index
) -> Index? {
assert(distance >= 0)
assert(limit >= i)
if limit.i1 == i.i1 {
// Delegate to `base2` if the offset is limited to `i.i1`.
//
// i.i2 limit.i2
// v v
// i.i1 > [x x x|x x x x x x|x x x]
return base2.index(i.i2, offsetBy: distance, limitedBy: limit.i2)
.map { i2 in Index(i1: i.i1, i2: i2) }
}
if let i2 = base2.index(i.i2, offsetBy: distance, limitedBy: base2.endIndex) {
// `distance` does not overflow `base2[i.i2...]`.
//
// i.i2 i2
// v v
// i.i1 > [x x x|x x x x x x|x x x]
// [ |> > > > > >| ] (`distance`)
return normalizeIndex(i.i1, i2)
}
let suffixCount = base2[i.i2...].count
let remaining = distance - suffixCount
let nextI1 = base1.index(after: i.i1)
if limit.i1 == nextI1 {
// Delegate to `base2` if the offset is limited to `nextI1`.
//
// i.i2
// v
// i.i1 > [x x x|x x x x x x x x x]
// nextI1 > [x x x x x x x x x|x x x]
// ^
// limit.i2
return base2.index(base2.startIndex, offsetBy: remaining, limitedBy: limit.i2)
.map { i2 in Index(i1: nextI1, i2: i2) }
}
if let i2 = base2.index(base2.startIndex, offsetBy: remaining, limitedBy: i.i2) {
// `remaining` does not overflow `base2[..<i.i2]`.
//
// i.i2
// v
// i.i1 > [x x x x x x x x x|x x x]
// [ |> > >] (`suffixCount`)
// [> > >| ] (`remaining`)
// nextI1 > [x x x|x x x x x x x x x]
// ^
// i2
return Index(i1: nextI1, i2: i2)
}
let prefixCount = base2[..<i.i2].count
let base2Count = prefixCount + suffixCount
let base1Distance = remaining / base2Count
guard let i1 = base1.index(nextI1, offsetBy: base1Distance, limitedBy: limit.i1)
else { return nil }
// The distance from `base2.startIndex` to the target.
let base2Distance = remaining % base2Count
let base2Limit = limit.i1 == i1 ? limit.i2 : base2.endIndex
return base2.index(base2.startIndex, offsetBy: base2Distance, limitedBy: base2Limit)
.map { i2 in Index(i1: i1, i2: i2) }
}
@inlinable
internal func offsetBackward(
_ i: Index, by distance: Int, limitedBy limit: Index
) -> Index? {
assert(distance >= 0)
assert(limit <= i)
if limit.i1 == i.i1 {
// Delegate to `base2` if the offset is limited to `i.i1`.
//
// limit.i2 i.i2
// v v
// i.i1 > [x x x|x x x x x x|x x x]
return base2.index(i.i2, offsetBy: -distance, limitedBy: limit.i2)
.map { i2 in Index(i1: i.i1, i2: i2) }
}
if let i2 = base2.index(i.i2, offsetBy: -distance, limitedBy: base2.startIndex) {
// `distance` does not underflow `base2[..<i.i2]`.
//
// i2 i.i2
// v v
// i.i1 > [x x x|x x x x x x|x x x]
// [ |< < < < < <| ] (`distance`)
return Index(i1: i.i1, i2: i2)
}
let prefixCount = base2[..<i.i2].count
let remaining = distance - prefixCount
let previousI1 = base1.index(i.i1, offsetBy: -1)
if limit.i1 == previousI1 {
// Delegate to `base2` if the offset is limited to `previousI1`.
//
// limit.i2
// v
// previousI1 > [x x x|x x x x x x x x x]
// i.i1 > [x x x x x x x x x|x x x]
// ^
// i.i2
return base2.index(base2.endIndex, offsetBy: -remaining, limitedBy: limit.i2)
.map { i2 in Index(i1: previousI1, i2: i2) }
}
if let i2 = base2.index(base2.endIndex, offsetBy: -remaining, limitedBy: i.i2) {
// `remaining` does not underflow `base2[i.i2...]`.
//
// i2
// v
// previousI1 > [x x x x x x x x x|x x x]
// [ |< < <] (`remaining`)
// [< < <| ] (`prefixCount`)
// i.i1 > [x x x|x x x x x x x x x]
// ^
// i.i2
return Index(i1: previousI1, i2: i2)
}
let suffixCount = base2[i.i2...].count
let base2Count = prefixCount + suffixCount
let base1Distance = remaining / base2Count
// The distance from `base2.endIndex` to the target.
let base2Distance = remaining % base2Count
if base2Distance == 0 {
// We end up exactly between two cycles, so `base1Distance` would
// overshoot the target by 1.
//
// base2.startIndex
// v
// i1 > |x x x x x x x x x x x x] >
// ... > `base1Distance` times
// previousI1 > [x x x x x x x x x x x x] >
// i.i1 > [x x x|x x x x x x x x x]
// ^
// i.i2
if let i1 = base1.index(previousI1, offsetBy: -(base1Distance - 1), limitedBy: limit.i1) {
let index = Index(i1: i1, i2: base2.startIndex)
return index < limit ? nil : index
} else {
return nil
}
}
guard let i1 = base1.index(previousI1, offsetBy: -base1Distance, limitedBy: limit.i1)
else { return nil }
let base2Limit = limit.i1 == i1 ? limit.i2 : base2.startIndex
return base2.index(base2.endIndex, offsetBy: -base2Distance, limitedBy: base2Limit)
.map { i2 in Index(i1: i1, i2: i2) }
}
}
extension Product2Sequence: BidirectionalCollection
where Base1: BidirectionalCollection, Base2: BidirectionalCollection
{
@inlinable
public func index(before i: Index) -> Index {
precondition(i != startIndex,
"Can't move before startIndex")
if i.i2 == base2.startIndex {
return Index(
i1: base1.index(before: i.i1),
i2: base2.index(before: base2.endIndex))
} else {
return Index(i1: i.i1, i2: base2.index(before: i.i2))
}
}
}
extension Product2Sequence: RandomAccessCollection
where Base1: RandomAccessCollection, Base2: RandomAccessCollection {}
extension Product2Sequence.Index: Hashable
where Base1.Index: Hashable, Base2.Index: Hashable {}
//===----------------------------------------------------------------------===//
// product(_:_:)
//===----------------------------------------------------------------------===//
/// Creates a sequence of each pair of elements of two underlying sequences.
///
/// Use this function to iterate over every pair of elements in two different
/// collections. The returned sequence yields 2-element tuples, where the first
/// element of the tuple is from the first collection and the second element is
/// from the second collection.
///
///
/// let numbers = 1...3
/// let colors = ["cerise", "puce", "heliotrope"]
/// for (number, color) in product(numbers, colors) {
/// print("\(number): \(color)")
/// }
/// // 1: cerise
/// // 1: puce
/// // 1: heliotrope
/// // 2: cerise
/// // 2: puce
/// // 2: heliotrope
/// // 3: cerise
/// // 3: puce
/// // 3: heliotrope
///
/// The order of tuples in the returned sequence is consistent. The first
/// element of the first collection is paired with each element of the second
/// collection, then the second element of the first collection is paired with
/// each element of the second collection, and so on.
///
/// - Parameters:
/// - s1: The first sequence to iterate over.
/// - s2: The second sequence to iterate over.
///
/// - Complexity: O(1)
@inlinable
public func product<Base1: Sequence, Base2: Collection>(
_ s1: Base1, _ s2: Base2
) -> Product2Sequence<Base1, Base2> {
Product2Sequence(s1, s2)
}
| apache-2.0 | 53890a6ec130f56bccea9f744380b92e | 31.452869 | 96 | 0.529456 | 3.66852 | false | false | false | false |
proversity-org/edx-app-ios | Source/OEXCheckBox.swift | 1 | 1450 | //
// OEXCheckBox.swift
// edX
//
// Created by Michael Katz on 8/27/15.
// Copyright (c) 2015 edX. All rights reserved.
//
import UIKit
public class OEXCheckBox: UIButton {
@IBInspectable public var checked: Bool = false {
didSet {
updateState()
}
}
private func _setup() {
imageView?.contentMode = .scaleAspectFit
addTarget(self, action: #selector(OEXCheckBox.tapped), for: .touchUpInside)
updateState()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
_setup()
}
override init(frame: CGRect) {
super.init(frame: frame)
_setup()
}
public override func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
updateState()
}
private func updateState() {
let newIcon = checked ? Icon.CheckCircleO : Icon.CircleO
let size = min(bounds.width, bounds.height)
let image = newIcon.imageWithFontSize(size: size)
setImage(image, for: .normal)
accessibilityLabel = checked ? Strings.accessibilityCheckboxChecked : Strings.accessibilityCheckboxUnchecked
accessibilityHint = checked ? Strings.accessibilityCheckboxHintChecked : Strings.accessibilityCheckboxHintUnchecked
}
@objc func tapped() {
checked = !checked
sendActions(for: .valueChanged)
}
}
| apache-2.0 | 1d5f864d57a3e10514867405bb8f18dc | 25.851852 | 123 | 0.628276 | 4.785479 | false | true | false | false |
oisinlavery/HackingWithSwift | project8-oisin/project8-oisin/ViewController.swift | 1 | 3923 | //
// ViewController.swift
// project8-oisin
//
// Created by Oisín Lavery on 10/11/15.
// Copyright © 2015 Oisín Lavery. All rights reserved.
//
import UIKit
import GameKit
class ViewController: UIViewController {
@IBOutlet weak var letterButtonsStackView: UIStackView!
@IBOutlet weak var cluesLabel: UILabel!
@IBOutlet weak var answersLabel: UILabel!
@IBOutlet weak var currentAnswer: UITextField!
@IBOutlet weak var scoreLabel: UILabel!
var letterButtons = [UIButton]()
var activatedButtons = [UIButton]()
var solutions = [String]()
var level = 1
var score: Int = 0 {
didSet {
scoreLabel.text = "Score: \(score)"
}
}
override func viewDidLoad() {
super.viewDidLoad()
for subview in letterButtonsStackView.subviews {
for subview in subview.subviews where subview.tag == 1001 {
let btn = subview as! UIButton
letterButtons.append(btn)
btn.addTarget(self, action: "letterTapped:", forControlEvents: .TouchUpInside)
}
}
loadLevel()
}
func letterTapped(btn: UIButton) {
currentAnswer.text = currentAnswer.text! + btn.titleLabel!.text!
activatedButtons.append(btn)
btn.hidden = true
}
func loadLevel() {
var clueString = ""
var solutionString = ""
var letterBits = [String]()
if let levelFilePath = NSBundle.mainBundle().pathForResource("level\(level)", ofType: "txt") {
if let levelContents = try? String(contentsOfFile: levelFilePath, usedEncoding: nil) {
var lines = levelContents.componentsSeparatedByString("\n")
lines = GKRandomSource.sharedRandom().arrayByShufflingObjectsInArray(lines) as! [String]
for (index, line) in lines.enumerate() {
let parts = line.componentsSeparatedByString(": ")
let answer = parts[0]
let clue = parts[1]
clueString += "\(index + 1). \(clue)\n"
let solutionWord = answer.stringByReplacingOccurrencesOfString("|", withString: "")
solutionString += "\(solutionWord.characters.count) letters\n"
solutions.append(solutionWord)
let bits = answer.componentsSeparatedByString("|")
letterBits += bits
}
}
}
cluesLabel.text = clueString.stringByTrimmingCharactersInSet(.whitespaceAndNewlineCharacterSet())
answersLabel.text = solutionString.stringByTrimmingCharactersInSet(.whitespaceAndNewlineCharacterSet())
letterBits = GKRandomSource.sharedRandom().arrayByShufflingObjectsInArray(letterBits) as! [String]
letterButtons = GKRandomSource.sharedRandom().arrayByShufflingObjectsInArray(letterButtons) as! [UIButton]
if letterBits.count == letterButtons.count {
for i in 0 ..< letterBits.count {
letterButtons[i].setTitle(letterBits[i], forState: .Normal)
}
}
}
@IBAction func submitTapped(sender: AnyObject) {
if let solutionPosition = solutions.indexOf(currentAnswer.text!) {
activatedButtons.removeAll()
var splitClues = answersLabel.text!.componentsSeparatedByString("\n")
splitClues[solutionPosition] = currentAnswer.text!
answersLabel.text = splitClues.joinWithSeparator("\n")
currentAnswer.text = ""
++score
if score % 7 == 0 {
let ac = UIAlertController(title: "Well done!", message: "Are you ready for the next level?", preferredStyle: .Alert)
ac.addAction(UIAlertAction(title: "Let's go!", style: .Default, handler: levelUp))
presentViewController(ac, animated: true, completion: nil)
}
}
}
func levelUp(action: UIAlertAction!) {
++level
solutions.removeAll(keepCapacity: true)
loadLevel()
for btn in letterButtons {
btn.hidden = false
}
}
@IBAction func clearTapped(sender: AnyObject) {
currentAnswer.text = ""
for btn in activatedButtons {
btn.hidden = false
}
activatedButtons.removeAll()
}
}
| unlicense | cc61d42968256f39a767538f1e2766da | 27.613139 | 125 | 0.67398 | 4.9 | false | false | false | false |
grantkemp/CloudKit-Demo-OSX | CloudKit Demo OSX/AppDelegate.swift | 1 | 2501 | //
// AppDelegate.swift
// CloudKit Demo OSX
//
// Created by Grant Kemp on 15/08/2016.
// Copyright © 2016 Grant Kemp. All rights reserved.
//
import Cocoa
import NotificationCenter
import CloudKit
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
var cloudKitDelegate:CloudKitable?
// The appdelegate handles the methods to receive Cloudkit Subscribe Requests and to let the main View Controller know it needs to get to work to process the the change pretty sharpish..
func applicationDidFinishLaunching(notification: NSNotification) {
//Remote Notification Info
// NSDictionary * remoteNotifiInfo = [launchOptions objectForKey: UIApplicationLaunchOptionsRemoteNotificationKey];
//
// //Accept push notification when app is not open
// if (remoteNotifiInfo) {
// [self application:application didReceiveRemoteNotification: remoteNotifiInfo];
// }
//
// return YES;
}
func applicationWillTerminate(aNotification: NSNotification) {
// Insert code here to tear down your application
}
func application(application: NSApplication, didReceiveRemoteNotification userInfo: [String : AnyObject]) {
let cknNotification = CKNotification(fromRemoteNotificationDictionary: userInfo as! [String:NSObject])
let alertBody = cknNotification.alertBody
if cknNotification.notificationType == .Query,
let queryNotification = cknNotification as? CKQueryNotification {
let recordId = queryNotification.recordID
print(recordId)
CloudKitManager.appCloudDataBase().fetchRecordWithID(recordId!, completionHandler: { (recordfetched, error) in
let cityRecord = recordfetched
let cityRecordType = recordfetched?.recordType
let cityObject = City(record: cityRecord!)
print("we added \(cityObject.name) via another device)")
self.cloudKitDelegate?.prot_newCityAdded([cityObject])
})
}
}
func application(application: NSApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) {
print(error)
}
func application(application: NSApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
print(deviceToken)
}
} | mit | 81799fd21ceac4d0aa76fb0068f92e98 | 34.728571 | 186 | 0.6668 | 5.747126 | false | false | false | false |
mzrimsek/school | CS49995/mzrimsek/KaleidoView/KaleidoView/KaleidoView.swift | 1 | 4524 | //
// KaleidoView.swift
// KaleidoView
//
// Created by Mike Zrimsek on 3/1/17.
// Copyright © 2017 Mike Zrimsek. All rights reserved.
//
import UIKit
class KaleidoView : UIView {
var colorMin : CGFloat = 0.0
var colorMax : CGFloat = 1.0
var alphaMin : CGFloat = 0.0
var alphaMax : CGFloat = 1.0
var rectMinDimension : CGFloat = 20
var rectMaxDimension : CGFloat = 150
var useAlpha = false
var delay : TimeInterval = 0.25
var timer : Timer?
var views : [UIView] = Array()
var currentView = 0
var viewCount = 200
func move() {
if views.count < viewCount {
addNewViews()
currentView = views.count - 4
}
let newFrames = getFrame()
let backgroundColor = getRandomColor()
drawFrame(frame: newFrames.topLeft, color: backgroundColor)
drawFrame(frame: newFrames.topRight, color: backgroundColor)
drawFrame(frame: newFrames.bottomLeft, color: backgroundColor)
drawFrame(frame: newFrames.bottomRight, color: backgroundColor)
if currentView >= views.count {
currentView = 0
}
}
func drawFrame(frame: CGRect, color: UIColor) {
views[currentView].frame = frame
views[currentView].backgroundColor = color
currentView += 1
}
func startDrawing()
{
timer = Timer(timeInterval: delay,
target : self,
selector : #selector(KaleidoView.move),
userInfo : nil,
repeats : true)
let runLoop = RunLoop.current
runLoop.add(timer!, forMode:RunLoopMode(rawValue:"NSDefaultRunLoopMode"))
}
func addNewViews() {
for _ in 0...4 {
let kaleidoSubview = UIView()
views.append(kaleidoSubview)
self.addSubview(kaleidoSubview)
}
}
func getFrame() -> (topLeft: CGRect, topRight: CGRect, bottomLeft: CGRect, bottomRight: CGRect) {
let rectAttrs = getRectAttributes()
let topLeft = CGRect(x: rectAttrs.leftX, y: rectAttrs.topY, width: rectAttrs.width, height: rectAttrs.height)
let topRight = CGRect(x: rectAttrs.rightX, y: rectAttrs.topY, width: rectAttrs.width, height: rectAttrs.height)
let bottomLeft = CGRect(x: rectAttrs.leftX, y: rectAttrs.bottomY, width: rectAttrs.width, height: rectAttrs.height)
let bottomRight = CGRect(x: rectAttrs.rightX, y: rectAttrs.bottomY, width: rectAttrs.width, height: rectAttrs.height)
return (topLeft, topRight, bottomLeft, bottomRight)
}
func getRectAttributes() -> (leftX: CGFloat, rightX: CGFloat, topY: CGFloat, bottomY: CGFloat, width: CGFloat, height: CGFloat) {
let centerX = frame.size.width/2
let centerY = frame.size.height/2
let leftX = getRandomFrom(min:0.0, thruMax:centerX)
let topY = getRandomFrom(min:0.0, thruMax:centerY)
let rectWidth = getRandomFrom(min: rectMinDimension, thruMax: rectMaxDimension)
let rectHeight = getRandomFrom(min: rectMinDimension, thruMax: rectMaxDimension)
let rightX = 2*centerX - leftX - rectWidth
let bottomY = 2*centerY - topY - rectHeight
return (leftX: leftX, rightX: rightX, topY: topY, bottomY: bottomY, width: rectWidth, height: rectHeight)
}
func getRandomColor() -> UIColor
{
let randRed = getRandomFrom(min:colorMin, thruMax:colorMax)
let randGreen = getRandomFrom(min:colorMin, thruMax:colorMax)
let randBlue = getRandomFrom(min:colorMin, thruMax:colorMax)
var alpha : CGFloat = 1.0
if useAlpha{
alpha = getRandomFrom(min:alphaMin, thruMax:alphaMax)
}
return UIColor(red:randRed, green:randGreen, blue:randBlue, alpha:alpha)
}
func getRandomFrom(min:CGFloat, thruMax max:CGFloat)-> CGFloat
{
guard max > min else {
return min
}
let randomNum = Int(arc4random() / 2)
let accuracy : CGFloat = 1000.0
let scaledMin : CGFloat = min * accuracy
let scaledMax : CGFloat = max * accuracy
let randomInRange = CGFloat(randomNum % Int(scaledMax - scaledMin))
let randomResult = randomInRange / accuracy + min
return randomResult
}
}
| mit | e66382d15f506833c8e87a6dc8ec6939 | 32.503704 | 133 | 0.602034 | 4.564077 | false | false | false | false |
samodom/TestSwagger | TestSwaggerTests/Tools/Spying/Spies/SwiftSpies.swift | 1 | 5251 | //
// SampleDirectInvocationClassSpies.swift
// TestSwagger
//
// Created by Sam Odom on 12/22/16.
// Copyright © 2016 Swagger Soft. All rights reserved.
//
import TestSwagger
import SampleTypes
import FoundationSwagger
extension SwiftRootSpyable: SampleObjectSpyable, SampleClassSpyable {}
public extension SwiftRootSpyable { // MARK: Spy controllers
public enum DirectClassSpyController: SpyController {
public static let rootSpyableClass: AnyClass = SwiftRootSpyable.self
public static let vector = SpyVector.direct
public static let coselectors: Set<SpyCoselectors> = [SampleSpyCoselectors.directClassSpy]
public static let evidence: Set<SpyEvidenceReference> = SampleReferences
public static var forwardsInvocations = false
}
public enum DirectObjectSpyController: SpyController {
public static let rootSpyableClass: AnyClass = SwiftRootSpyable.self
public static let vector = SpyVector.direct
public static let coselectors: Set<SpyCoselectors> = [SampleSpyCoselectors.directObjectSpy]
public static let evidence: Set<SpyEvidenceReference> = SampleReferences
public static var forwardsInvocations = false
}
public enum IndirectClassSpyController: SpyController {
public static let rootSpyableClass: AnyClass = SwiftRootSpyable.self
public static let vector = SpyVector.indirect
public static let coselectors: Set<SpyCoselectors> = [SampleSpyCoselectors.indirectClassSpy]
public static let evidence: Set<SpyEvidenceReference> = SampleReferences
public static var forwardsInvocations = false
}
public enum IndirectObjectSpyController: SpyController {
public static let rootSpyableClass: AnyClass = SwiftRootSpyable.self
public static let vector = SpyVector.indirect
public static let coselectors: Set<SpyCoselectors> = [SampleSpyCoselectors.indirectObjectSpy]
public static let evidence: Set<SpyEvidenceReference> = SampleReferences
public static var forwardsInvocations = false
}
}
fileprivate extension SwiftRootSpyable { // MARK: Selectors
enum SampleMethodSelectors {
static let originalClassMethod = #selector(SwiftRootSpyable.sampleClassMethod(_:))
static let directSpyClassMethod = #selector(SwiftRootSpyable.directSpy_sampleClassMethod(_:))
static let indirectSpyClassMethod = #selector(SwiftRootSpyable.indirectSpy_sampleClassMethod(_:))
static let originalInstanceMethod = #selector(SwiftRootSpyable.sampleInstanceMethod(_:))
static let directSpyInstanceMethod = #selector(SwiftRootSpyable.directSpy_sampleInstanceMethod(_:))
static let indirectSpyInstanceMethod = #selector(SwiftRootSpyable.indirectSpy_sampleInstanceMethod(_:))
}
fileprivate enum SampleSpyCoselectors {
static let directClassSpy = SpyCoselectors(
methodType: .class,
original: SampleMethodSelectors.originalClassMethod,
spy: SampleMethodSelectors.directSpyClassMethod
)
static let directObjectSpy = SpyCoselectors(
methodType: .instance,
original: SampleMethodSelectors.originalInstanceMethod,
spy: SampleMethodSelectors.directSpyInstanceMethod
)
static let indirectClassSpy = SpyCoselectors(
methodType: .class,
original: SampleMethodSelectors.originalClassMethod,
spy: SampleMethodSelectors.indirectSpyClassMethod
)
static let indirectObjectSpy = SpyCoselectors(
methodType: .instance,
original: SampleMethodSelectors.originalInstanceMethod,
spy: SampleMethodSelectors.indirectSpyInstanceMethod
)
}
}
extension SwiftRootSpyable { // MARK: Spy methods
dynamic class func directSpy_sampleClassMethod(_ input: String) -> Int {
sampleClassMethodCalledAssociated = true
sampleClassMethodCalledSerialized = true
return DirectClassSpyController.forwardsInvocations ?
directSpy_sampleClassMethod(input) : WellKnownMethodReturnValues.commonSpyValue.rawValue
}
dynamic func directSpy_sampleInstanceMethod(_ input: String) -> Int {
sampleInstanceMethodCalledAssociated = true
sampleInstanceMethodCalledSerialized = true
return DirectObjectSpyController.forwardsInvocations ?
directSpy_sampleInstanceMethod(input) : WellKnownMethodReturnValues.commonSpyValue.rawValue
}
dynamic class func indirectSpy_sampleClassMethod(_ input: String) -> Int {
sampleClassMethodCalledAssociated = true
sampleClassMethodCalledSerialized = true
return IndirectClassSpyController.forwardsInvocations ?
indirectSpy_sampleClassMethod(input) : WellKnownMethodReturnValues.commonSpyValue.rawValue
}
dynamic func indirectSpy_sampleInstanceMethod(_ input: String) -> Int {
sampleInstanceMethodCalledAssociated = true
sampleInstanceMethodCalledSerialized = true
return IndirectObjectSpyController.forwardsInvocations ?
indirectSpy_sampleInstanceMethod(input) : WellKnownMethodReturnValues.commonSpyValue.rawValue
}
}
| mit | 862d4776fdbe6cad4dfad21f113fdcc6 | 39.384615 | 111 | 0.737714 | 6.302521 | false | false | false | false |
realm/SwiftLint | Tests/SwiftLintFrameworkTests/ModifierOrderTests.swift | 1 | 13264 | @testable import SwiftLintFramework
import XCTest
class ModifierOrderTests: XCTestCase {
func testAttributeTypeMethod() {
let descriptionOverride = ModifierOrderRule.description
.with(nonTriggeringExamples: [
Example("""
public class SomeClass {
class public func someFunc() {}
}
"""),
Example("""
public class SomeClass {
static public func someFunc() {}
}
""")
])
.with(triggeringExamples: [
Example("""
public class SomeClass {
public class func someFunc() {}
}
"""),
Example("""
public class SomeClass {
public static func someFunc() {}
}
""")
])
.with(corrections: [:])
verifyRule(descriptionOverride,
ruleConfiguration: ["preferred_modifier_order": ["typeMethods", "acl"]])
}
func testRightOrderedModifierGroups() {
let descriptionOverride = ModifierOrderRule.description
.with(nonTriggeringExamples: [
Example("public protocol Foo: class {}\n" +
"public weak internal(set) var bar: Foo? \n"),
Example("open final class Foo {" +
" fileprivate static func bar() {} \n" +
" open class func barFoo() {} }"),
Example("public struct Foo {" +
" private mutating func bar() {} }")
])
.with(triggeringExamples: [
Example("public protocol Foo: class {} \n" +
"public internal(set) weak var bar: Foo? \n"),
Example("final public class Foo {" +
" static fileprivate func bar() {} \n" +
" class open func barFoo() {} }"),
Example("public struct Foo {" +
" mutating private func bar() {} }")
])
.with(corrections: [:])
verifyRule(descriptionOverride,
ruleConfiguration: ["preferred_modifier_order": ["acl",
"typeMethods",
"owned",
"setterACL",
"final",
"mutators",
"override"]])
}
// swiftlint:disable:next function_body_length
func testAtPrefixedGroup() {
let descriptionOverride = ModifierOrderRule.description
.with(nonTriggeringExamples: [
Example(#"""
class Foo {
@objc
internal var bar: String {
return "foo"
}
}
class Bar: Foo {
@objc
override internal var bar: String {
return "bar"
}
}
"""#),
Example("""
@objcMembers
public final class Bar {}
"""),
Example("""
class Foo {
@IBOutlet internal weak var bar: UIView!
}
"""),
Example("""
class Foo {
@IBAction internal func bar() {}
}
"""),
Example("""
class Bar: Foo {
@IBAction override internal func bar() {}
}
"""),
Example(#"""
public class Foo {
@NSCopying public final var foo:NSString = "s"
}
"""#),
Example(#"""
public class Foo {
@NSCopying public final var foo: NSString
}
"""#)
])
.with(triggeringExamples: [
Example(#"""
class Foo {
@objc
internal var bar: String {
return "foo"
}
}
class Bar: Foo {
@objc
internal override var bar: String {
return "bar"
}
}
"""#),
Example("""
@objcMembers
final public class Bar {}
"""),
Example("""
class Foo {
@IBOutlet weak internal var bar: UIView!
}
"""),
Example("""
class Foo {
@IBAction internal func bar() {}
}
class Bar: Foo {
@IBAction internal override func bar() {}
}
"""),
Example(#"""
public class Foo {
@NSCopying final public var foo:NSString = "s"
}
"""#),
Example("""
public class Foo {
@NSManaged final public var foo: NSString
}
""")
])
.with(corrections: [:])
verifyRule(descriptionOverride,
ruleConfiguration: ["preferred_modifier_order": ["override", "acl", "owned", "final"]])
}
func testNonSpecifiedModifiersDontInterfere() {
let descriptionOverride = ModifierOrderRule.description
.with(nonTriggeringExamples: [
Example("""
class Foo {
weak final override private var bar: UIView?
}
"""),
Example("""
class Foo {
final weak override private var bar: UIView?
}
"""),
Example("""
class Foo {
final override weak private var bar: UIView?
}
"""),
Example("""
class Foo {
final override private weak var bar: UIView?
}
""")
])
.with(triggeringExamples: [
Example("""
class Foo {
weak override final private var bar: UIView?
}
"""),
Example("""
class Foo {
override weak final private var bar: UIView?
}
"""),
Example("""
class Foo {
override final weak private var bar: UIView?
}
"""),
Example("""
class Foo {
override final private weak var bar: UIView?
}
""")
])
.with(corrections: [:])
verifyRule(descriptionOverride,
ruleConfiguration: ["preferred_modifier_order": ["final", "override", "acl"]])
}
// swiftlint:disable:next function_body_length
func testCorrectionsAreAppliedCorrectly() {
let descriptionOverride = ModifierOrderRule.description
.with(nonTriggeringExamples: [], triggeringExamples: [])
.with(corrections: [
Example("""
class Foo {
private final override var bar: UIView?
}
"""):
Example("""
class Foo {
final override private var bar: UIView?
}
"""),
Example("""
class Foo {
private final var bar: UIView?
}
"""):
Example("""
class Foo {
final private var bar: UIView?
}
"""),
Example("""
class Foo {
class private final var bar: UIView?
}
"""):
Example("""
class Foo {
final private class var bar: UIView?
}
"""),
Example("""
class Foo {
@objc
private
class
final
override
var bar: UIView?
}
"""):
Example("""
class Foo {
@objc
final
override
private
class
var bar: UIView?
}
"""),
Example("""
private final class Foo {}
"""):
Example("""
final private class Foo {}
""")
])
verifyRule(descriptionOverride,
ruleConfiguration: ["preferred_modifier_order": ["final", "override", "acl", "typeMethods"]])
}
// swiftlint:disable:next function_body_length
func testCorrectionsAreNotAppliedToIrrelevantModifier() {
let descriptionOverride = ModifierOrderRule.description
.with(nonTriggeringExamples: [], triggeringExamples: [])
.with(corrections: [
Example("""
class Foo {
weak class final var bar: UIView?
}
"""):
Example("""
class Foo {
weak final class var bar: UIView?
}
"""),
Example("""
class Foo {
static weak final var bar: UIView?
}
"""):
Example("""
class Foo {
final weak static var bar: UIView?
}
"""),
Example("""
class Foo {
class final weak var bar: UIView?
}
"""):
Example("""
class Foo {
final class weak var bar: UIView?
}
"""),
Example("""
class Foo {
@objc
private
private(set)
class
final
var bar: UIView?
}
"""):
Example("""
class Foo {
@objc
final
private(set)
private
class
var bar: UIView?
}
"""),
Example("""
class Foo {
var bar: UIView?
}
"""):
Example("""
class Foo {
var bar: UIView?
}
""")
])
verifyRule(descriptionOverride,
ruleConfiguration: ["preferred_modifier_order": ["final", "override", "acl", "typeMethods"]])
}
func testTypeMethodClassCorrection() {
let descriptionOverride = ModifierOrderRule.description
.with(nonTriggeringExamples: [], triggeringExamples: [])
.with(corrections: [
Example("""
private final class Foo {}
"""):
Example("""
final private class Foo {}
"""),
Example("""
public protocol Foo: class {}\n
"""):
Example("""
public protocol Foo: class {}\n
""")
])
verifyRule(descriptionOverride,
ruleConfiguration: ["preferred_modifier_order": ["final", "typeMethods", "acl"]])
}
func testViolationMessage() {
let ruleID = ModifierOrderRule.description.identifier
guard let config = makeConfig(["preferred_modifier_order": ["acl", "final"]], ruleID) else {
XCTFail("Failed to create configuration")
return
}
let allViolations = violations(Example("final public var foo: String"), config: config)
let modifierOrderRuleViolation = allViolations.first { $0.ruleIdentifier == ruleID }
if let violation = modifierOrderRuleViolation {
XCTAssertEqual(violation.reason, "public modifier should be before final.")
} else {
XCTFail("A modifier order violation should have been triggered!")
}
}
}
| mit | d074ad5016f35dcdda0090067d342478 | 32.664975 | 112 | 0.377262 | 7.044079 | false | false | false | false |
zhugejunwei/Algorithms-in-Java-Swift-CPP | Dijkstra & Floyd/Carthage/Checkouts/Charts/Charts/Classes/Data/ChartDataSet.swift | 3 | 13372 | //
// ChartDataSet.swift
// Charts
//
// Created by Daniel Cohen Gindi on 23/2/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
//
import Foundation
import UIKit
public class ChartDataSet: NSObject
{
public var colors = [UIColor]()
internal var _yVals: [ChartDataEntry]!
internal var _yMax = Double(0.0)
internal var _yMin = Double(0.0)
internal var _yValueSum = Double(0.0)
/// the last start value used for calcMinMax
internal var _lastStart: Int = 0
/// the last end value used for calcMinMax
internal var _lastEnd: Int = 0
public var label: String? = "DataSet"
public var visible = true
public var drawValuesEnabled = true
/// the color used for the value-text
public var valueTextColor: UIColor = UIColor.blackColor()
/// the font for the value-text labels
public var valueFont: UIFont = UIFont.systemFontOfSize(7.0)
/// the formatter used to customly format the values
public var valueFormatter: NSNumberFormatter?
/// the axis this DataSet should be plotted against.
public var axisDependency = ChartYAxis.AxisDependency.Left
public var yVals: [ChartDataEntry] { return _yVals }
public var yValueSum: Double { return _yValueSum }
public var yMin: Double { return _yMin }
public var yMax: Double { return _yMax }
/// if true, value highlighting is enabled
public var highlightEnabled = true
/// - returns: true if value highlighting is enabled for this dataset
public var isHighlightEnabled: Bool { return highlightEnabled }
public override required init()
{
super.init()
}
public init(yVals: [ChartDataEntry]?, label: String?)
{
super.init()
self.label = label
_yVals = yVals == nil ? [ChartDataEntry]() : yVals
// default color
colors.append(UIColor(red: 140.0/255.0, green: 234.0/255.0, blue: 255.0/255.0, alpha: 1.0))
self.calcMinMax(start: _lastStart, end: _lastEnd)
self.calcYValueSum()
}
public convenience init(yVals: [ChartDataEntry]?)
{
self.init(yVals: yVals, label: "DataSet")
}
/// Use this method to tell the data set that the underlying data has changed
public func notifyDataSetChanged()
{
calcMinMax(start: _lastStart, end: _lastEnd)
calcYValueSum()
}
internal func calcMinMax(start start : Int, end: Int)
{
let yValCount = _yVals.count
if yValCount == 0
{
return
}
var endValue : Int
if end == 0 || end >= yValCount
{
endValue = yValCount - 1
}
else
{
endValue = end
}
_lastStart = start
_lastEnd = endValue
_yMin = DBL_MAX
_yMax = -DBL_MAX
for (var i = start; i <= endValue; i++)
{
let e = _yVals[i]
if (!e.value.isNaN)
{
if (e.value < _yMin)
{
_yMin = e.value
}
if (e.value > _yMax)
{
_yMax = e.value
}
}
}
if (_yMin == DBL_MAX)
{
_yMin = 0.0
_yMax = 0.0
}
}
private func calcYValueSum()
{
_yValueSum = 0
for var i = 0; i < _yVals.count; i++
{
_yValueSum += fabs(_yVals[i].value)
}
}
/// - returns: the average value across all entries in this DataSet.
public var average: Double
{
return yValueSum / Double(valueCount)
}
public var entryCount: Int { return _yVals!.count; }
public func yValForXIndex(x: Int) -> Double
{
let e = self.entryForXIndex(x)
if (e !== nil && e!.xIndex == x) { return e!.value }
else { return Double.NaN }
}
/// - returns: the first Entry object found at the given xIndex with binary search.
/// If the no Entry at the specifed x-index is found, this method returns the Entry at the closest x-index.
/// nil if no Entry object at that index.
public func entryForXIndex(x: Int) -> ChartDataEntry?
{
let index = self.entryIndex(xIndex: x)
if (index > -1)
{
return _yVals[index]
}
return nil
}
public func entriesForXIndex(x: Int) -> [ChartDataEntry]
{
var entries = [ChartDataEntry]()
var low = 0
var high = _yVals.count - 1
while (low <= high)
{
var m = Int((high + low) / 2)
var entry = _yVals[m]
if (x == entry.xIndex)
{
while (m > 0 && _yVals[m - 1].xIndex == x)
{
m--
}
high = _yVals.count
for (; m < high; m++)
{
entry = _yVals[m]
if (entry.xIndex == x)
{
entries.append(entry)
}
else
{
break
}
}
}
if (x > _yVals[m].xIndex)
{
low = m + 1
}
else
{
high = m - 1
}
}
return entries
}
public func entryIndex(xIndex x: Int) -> Int
{
var low = 0
var high = _yVals.count - 1
var closest = -1
while (low <= high)
{
var m = (high + low) / 2
let entry = _yVals[m]
if (x == entry.xIndex)
{
while (m > 0 && _yVals[m - 1].xIndex == x)
{
m--
}
return m
}
if (x > entry.xIndex)
{
low = m + 1
}
else
{
high = m - 1
}
closest = m
}
return closest
}
public func entryIndex(entry e: ChartDataEntry, isEqual: Bool) -> Int
{
if (isEqual)
{
for (var i = 0; i < _yVals.count; i++)
{
if (_yVals[i].isEqual(e))
{
return i
}
}
}
else
{
for (var i = 0; i < _yVals.count; i++)
{
if (_yVals[i] === e)
{
return i
}
}
}
return -1
}
/// - returns: the number of entries this DataSet holds.
public var valueCount: Int { return _yVals.count; }
/// Adds an Entry to the DataSet dynamically.
/// Entries are added to the end of the list.
/// This will also recalculate the current minimum and maximum values of the DataSet and the value-sum.
/// - parameter e: the entry to add
public func addEntry(e: ChartDataEntry)
{
let val = e.value
if (_yVals == nil)
{
_yVals = [ChartDataEntry]()
}
if (_yVals.count == 0)
{
_yMax = val
_yMin = val
}
else
{
if (_yMax < val)
{
_yMax = val
}
if (_yMin > val)
{
_yMin = val
}
}
_yValueSum += val
_yVals.append(e)
}
/// Adds an Entry to the DataSet dynamically.
/// Entries are added to their appropriate index respective to it's x-index.
/// This will also recalculate the current minimum and maximum values of the DataSet and the value-sum.
/// - parameter e: the entry to add
public func addEntryOrdered(e: ChartDataEntry)
{
let val = e.value
if (_yVals == nil)
{
_yVals = [ChartDataEntry]()
}
if (_yVals.count == 0)
{
_yMax = val
_yMin = val
}
else
{
if (_yMax < val)
{
_yMax = val
}
if (_yMin > val)
{
_yMin = val
}
}
_yValueSum += val
if _yVals.last?.xIndex > e.xIndex
{
var closestIndex = entryIndex(xIndex: e.xIndex)
if _yVals[closestIndex].xIndex < e.xIndex
{
closestIndex++
}
_yVals.insert(e, atIndex: closestIndex)
return;
}
_yVals.append(e)
}
public func removeEntry(entry: ChartDataEntry) -> Bool
{
var removed = false
for (var i = 0; i < _yVals.count; i++)
{
if (_yVals[i] === entry)
{
_yVals.removeAtIndex(i)
removed = true
break
}
}
if (removed)
{
_yValueSum -= entry.value
calcMinMax(start: _lastStart, end: _lastEnd)
}
return removed
}
public func removeEntry(xIndex xIndex: Int) -> Bool
{
let index = self.entryIndex(xIndex: xIndex)
if (index > -1)
{
let e = _yVals.removeAtIndex(index)
_yValueSum -= e.value
calcMinMax(start: _lastStart, end: _lastEnd)
return true
}
return false
}
/// Removes the first Entry (at index 0) of this DataSet from the entries array.
///
/// - returns: true if successful, false if not.
public func removeFirst() -> Bool
{
let entry: ChartDataEntry? = _yVals.isEmpty ? nil : _yVals.removeFirst()
let removed = entry != nil
if (removed)
{
let val = entry!.value
_yValueSum -= val
calcMinMax(start: _lastStart, end: _lastEnd)
}
return removed;
}
/// Removes the last Entry (at index size-1) of this DataSet from the entries array.
///
/// - returns: true if successful, false if not.
public func removeLast() -> Bool
{
let entry: ChartDataEntry? = _yVals.isEmpty ? nil : _yVals.removeLast()
let removed = entry != nil
if (removed)
{
let val = entry!.value
_yValueSum -= val
calcMinMax(start: _lastStart, end: _lastEnd)
}
return removed;
}
public func resetColors()
{
colors.removeAll(keepCapacity: false)
}
public func addColor(color: UIColor)
{
colors.append(color)
}
public func setColor(color: UIColor)
{
colors.removeAll(keepCapacity: false)
colors.append(color)
}
public func colorAt(var index: Int) -> UIColor
{
if (index < 0)
{
index = 0
}
return colors[index % colors.count]
}
public var isVisible: Bool
{
return visible
}
public var isDrawValuesEnabled: Bool
{
return drawValuesEnabled
}
/// Checks if this DataSet contains the specified Entry.
/// - returns: true if contains the entry, false if not.
public func contains(e: ChartDataEntry) -> Bool
{
for entry in _yVals
{
if (entry.isEqual(e))
{
return true
}
}
return false
}
/// Removes all values from this DataSet and recalculates min and max value.
public func clear()
{
_yVals.removeAll(keepCapacity: true)
_lastStart = 0
_lastEnd = 0
notifyDataSetChanged()
}
// MARK: NSObject
public override var description: String
{
return String(format: "ChartDataSet, label: %@, %i entries", arguments: [self.label ?? "", _yVals.count])
}
public override var debugDescription: String
{
var desc = description + ":"
for (var i = 0; i < _yVals.count; i++)
{
desc += "\n" + _yVals[i].description
}
return desc
}
// MARK: NSCopying
public func copyWithZone(zone: NSZone) -> AnyObject
{
let copy = self.dynamicType.init()
copy.colors = colors
copy._yVals = _yVals
copy._yMax = _yMax
copy._yMin = _yMin
copy._yValueSum = _yValueSum
copy._lastStart = _lastStart
copy._lastEnd = _lastEnd
copy.label = label
return copy
}
}
| mit | 2766b846ccb0fbe634197d7725a3cf77 | 23.312727 | 113 | 0.459991 | 4.811803 | false | false | false | false |
TonnyTao/HowSwift | Funny Swift.playground/Pages/subscript_dic.xcplaygroundpage/Contents.swift | 1 | 674 | import Foundation
extension Dictionary {
subscript(input: [Key]) -> [Value] {
get {
var result = [Value]()
result.reserveCapacity(input.count)
for key in input {
if let value = self[key] {
result.append(value)
}
}
return result
}
set {
assert(input.count == newValue.count, "not supported")
for (index, key) in input.enumerated() {
self[key] = newValue[index]
}
}
}
}
var dic = ["a": "1", "b":"2", "c": "3"]
dic[["a", "c"]]
dic[["a", "c"]] = ["0", "2"]
print(dic)
| mit | 0ae10fad1dc85da182b69cb643fa45fd | 20.741935 | 66 | 0.4273 | 3.895954 | false | false | false | false |
volatilegg/QuarkSwift | QuarkSwift/Extensions/UIExtensions/UIViewExtensions.swift | 1 | 5432 | //
// UIViewExtensions.swift
// QuarkSwift
//
// Created by Do Duc on 18/10/2016.
// Copyright © 2016 Do Duc. All rights reserved.
//
import UIKit
// MARK: Animation
extension UIView {
/// Fade in animation with default duration 0.2s, can be use for one or more views at once
class func fadeIn(_ views: [UIView], duration: TimeInterval = 0.2, delay: TimeInterval = 0.0, completion: @escaping ((Bool) -> Void) = {(finished: Bool) -> Void in}) {
UIView.animate(withDuration: duration, delay: delay, options: UIViewAnimationOptions.curveEaseIn, animations: {
for view in views {
view.alpha = 1.0
}
}, completion: completion)
}
/// Fade out animation with default duration 0.2s, can be use for one or more views at once
class func fadeOut(_ views: [UIView], duration: TimeInterval = 0.2, delay: TimeInterval = 0.0, completion: @escaping ((Bool) -> Void) = {(finished: Bool) -> Void in}) {
UIView.animate(withDuration: duration, delay: delay, options: UIViewAnimationOptions.curveEaseIn, animations: {
for view in views {
view.alpha = 0.0
}
}, completion: completion)
}
/// Fade in animation with default duration 0.2s
public func fadeIn(duration: TimeInterval = 0.2, delay: TimeInterval = 0.0, completion: @escaping ((Bool) -> Void) = {(finished: Bool) -> Void in}) {
UIView.animate(withDuration: duration, delay: delay, options: UIViewAnimationOptions.curveEaseIn, animations: {
self.alpha = 1
}, completion: completion)
}
/// Fade out animation with default duration 0.2s
public func fadeOut(duration: TimeInterval = 0.2, delay: TimeInterval = 0.0, completion: @escaping ((Bool) -> Void) = {(finished: Bool) -> Void in}) {
UIView.animate(withDuration: duration, delay: delay, options: UIViewAnimationOptions.curveEaseIn, animations: {
self.alpha = 0.0
}, completion: completion)
}
}
// MARK: Frame extensions
extension UIView {
/// Make frame become circle if width = height, or oval if width != height
func roundFrame(_ isWidthPrior: Bool = true) {
self.cornerRadius = isWidthPrior ? self.width/2 : self.height/2
}
/// Shortcut for frame x
public var x: CGFloat {
get {
return self.frame.origin.x
}
set {
self.frame = CGRect(x: newValue, y: self.y, width: self.width, height: self.height)
}
}
/// Shortcut for frame y
public var y: CGFloat {
get {
return self.frame.origin.y
}
set {
self.frame = CGRect(x: self.x, y: newValue, width: self.width, height: self.height)
}
}
/// Shortcut for frame width
public var width: CGFloat {
get {
return self.frame.size.width
}
set {
self.frame = CGRect(x: self.x, y: self.y, width: newValue, height: self.height)
}
}
/// Shortcut for frame height
public var height: CGFloat {
get {
return self.frame.size.height
}
set {
self.frame = CGRect(x: newValue, y: self.y, width: self.width, height: newValue)
}
}
/// Shortcut for frame left
public var left: CGFloat {
get {
return self.x
}
set {
self.x = newValue
}
}
/// Shortcut for frame right
public var right: CGFloat {
get {
return self.x + self.width
}
set {
self.x = newValue - self.width
}
}
/// Shortcut for frame top
public var top: CGFloat {
get {
return self.y
}
set {
self.y = newValue
}
}
/// Shortcut for frame bottom
public var bottom: CGFloat {
get {
return self.y + self.height
}
set {
self.y = newValue - self.height
}
}
/// Shortcut for frame size
public var size: CGSize {
get {
return self.frame.size
}
set {
self.frame = CGRect(x: self.x, y: self.y, width: newValue.width, height: newValue.height)
}
}
/// Shortcut for frame origin
public var origin: CGPoint {
get {
return self.frame.origin
}
set {
self.frame = CGRect(x: newValue.x, y: newValue.y, width: self.width, height: self.height)
}
}
/// Shortcut for center X
public var centerX: CGFloat {
get {
return self.center.x
}
set {
self.center.x = newValue
}
}
/// Shortcut for center Y
public var centerY: CGFloat {
get {
return self.center.y
}
set {
self.center.y = newValue
}
}
/// Shortcut for corner radius
public var cornerRadius: CGFloat {
get {
return self.layer.cornerRadius
}
set {
self.layer.cornerRadius = newValue
}
}
/// Detect if view is include point
public func isIncludePoint(_ point: CGPoint) -> Bool {
if self.left <= point.x && self.right >= point.x && self.top < point.y && self.bottom > point.y {
return true
}
return false
}
}
| mit | 992b1404c272e66fcad44bc688ebae08 | 25.364078 | 172 | 0.548334 | 4.306899 | false | false | false | false |
Shopify/unity-buy-sdk | PluginDependencies/iOSPlugin/UnityBuySDKPlugin/PKShippingMethod+Deserializable.swift | 1 | 3030 | //
// PKShippingMethod+Deserializable.swift
// UnityBuySDK
//
// Created by Shopify.
// Copyright © 2017 Shopify Inc. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
import PassKit
extension PKShippingMethod {
public class func deserializeShippingMethod(_ json: JSON) -> Self? {
guard
let label = json[Field.label.rawValue] as? String,
let amount = json[Field.amount.rawValue] as? String
else {
return nil
}
let shippingMethod = self.init(label: label, amount: NSDecimalNumber(string: amount))
if let typeString = json[Field.type.rawValue] as? String,
let type = PKPaymentSummaryItemType(rawStringValue: typeString) {
shippingMethod.type = type
}
shippingMethod.detail = json[Field.detail.rawValue] as? String
shippingMethod.identifier = json[Field.identifier.rawValue] as? String
return shippingMethod
}
public class func deserializeShippingMethod(_ jsonCollection: [JSON]) -> [PKShippingMethod]? {
let items = jsonCollection.compactMap {
PKShippingMethod.deserializeShippingMethod($0)
}
if items.count < jsonCollection.count {
return nil
} else {
return items
}
}
public static func deserializeShippingMethod(_ string: String) -> PKShippingMethod? {
guard
let data = string.data(using: .utf8),
let jsonObject = (try? JSONSerialization.jsonObject(with: data)) as? JSON
else {
return nil
}
return PKShippingMethod.deserializeShippingMethod(jsonObject)
}
}
extension PKShippingMethod {
fileprivate enum Field: String {
case amount = "Amount"
case label = "Label"
case type = "Type"
case detail = "Detail"
case identifier = "Identifier"
}
}
| mit | d49780b72c243fdd4eac21ddd282d6ef | 35.493976 | 98 | 0.664246 | 4.740219 | false | false | false | false |
omondigeno/ActionablePushMessages | Pods/MK/Sources/RobotoFont.swift | 1 | 3390 | /*
* Copyright (C) 2015 - 2016, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.io>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * 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.
*
* * Neither the name of MaterialKit nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* 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 HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import UIKit
public struct RobotoFont : MaterialFontType {
/**
:name: pointSize
*/
public static var pointSize: CGFloat {
return MaterialFont.pointSize
}
/**
:name: thin
*/
public static var thin: UIFont {
return thinWithSize(MaterialFont.pointSize)
}
/**
:name: thinWithSize
*/
public static func thinWithSize(size: CGFloat) -> UIFont {
if let f = UIFont(name: "Roboto-Thin", size: size) {
return f
}
return MaterialFont.systemFontWithSize(size)
}
/**
:name: light
*/
public static var light: UIFont {
return lightWithSize(MaterialFont.pointSize)
}
/**
:name: lightWithSize
*/
public static func lightWithSize(size: CGFloat) -> UIFont {
if let f = UIFont(name: "Roboto-Light", size: size) {
return f
}
return MaterialFont.systemFontWithSize(size)
}
/**
:name: regular
*/
public static var regular: UIFont {
return regularWithSize(MaterialFont.pointSize)
}
/**
:name: regularWithSize
*/
public static func regularWithSize(size: CGFloat) -> UIFont {
if let f = UIFont(name: "Roboto-Regular", size: size) {
return f
}
return MaterialFont.systemFontWithSize(size)
}
/**
:name: mediumWithSize
*/
public static func mediumWithSize(size: CGFloat) -> UIFont {
if let f = UIFont(name: "Roboto-Medium", size: size) {
return f
}
return MaterialFont.boldSystemFontWithSize(size)
}
/**
:name: medium
*/
public static var medium: UIFont {
return mediumWithSize(MaterialFont.pointSize)
}
/**
:name: bold
*/
public static var bold: UIFont {
return boldWithSize(MaterialFont.pointSize)
}
/**
:name: boldWithSize
*/
public static func boldWithSize(size: CGFloat) -> UIFont {
if let f = UIFont(name: "Roboto-Bold", size: size) {
return f
}
return MaterialFont.boldSystemFontWithSize(size)
}
} | apache-2.0 | 308f27fc6b04223880a19494780968de | 26.128 | 86 | 0.729204 | 3.700873 | false | false | false | false |
montionugera/yellow | yellow-ios/yellow/CustomUITabBarController.swift | 1 | 1098 | //
// CustomUITabBarController.swift
// yellow
//
// Created by ekachai limpisoot on 9/6/17.
// Copyright © 2017 23. All rights reserved.
//
import UIKit
class CustomUITabBarController: UITabBarController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.tabBar.tintColor = UIColor.black
}
override func viewWillLayoutSubviews() {
var newTabBarFrame = tabBar.frame
let newTabBarHeight: CGFloat = 69
newTabBarFrame.size.height = newTabBarHeight
newTabBarFrame.origin.y = self.view.frame.size.height - newTabBarHeight
tabBar.frame = newTabBarFrame
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit | 0c06def83941d46ac0fb4b0cca03c03c | 26.425 | 106 | 0.663628 | 4.769565 | false | false | false | false |
tomomura/TimeSheet | Classes/Controllers/Intros/FTIntrosModelViewController.swift | 1 | 2934 | //
// FTIntrosModelViewController.swift
// TimeSheet
//
// Created by TomomuraRyota on 2015/04/19.
// Copyright (c) 2015年 TomomuraRyota. All rights reserved.
//
import UIKit
class FTIntrosModelViewController: NSObject, UIPageViewControllerDataSource, UIPageViewControllerDelegate {
// MARK: - Variables
/// 表示するページのストーリーボードID
let pageIdentifiers : Array<String> = [
"FTIntrosWelcomeViewController",
"FTIntrosInputInitialDataViewController",
"FTIntrosCompleteViewController"
]
var _user : User? = nil
/// データモデルを返すクラスを返す
var user : User {
if _user == nil {
_user = User.MR_createEntity() as! User?
}
return _user!
}
// MARK: - Page View Controller Data Source
func pageViewController(pageViewController: UIPageViewController, viewControllerBeforeViewController viewController: UIViewController) -> UIViewController? {
var index = self.indexOfViewController(viewController as! FTIntrosPageDataViewController)
if (index == 0) || (index == NSNotFound) {
return nil
}
index--
return self.viewControllerAtIndex(index, storyboard: viewController.storyboard!)
}
func pageViewController(pageViewController: UIPageViewController, viewControllerAfterViewController viewController: UIViewController) -> UIViewController? {
var index = self.indexOfViewController(viewController as! FTIntrosPageDataViewController)
if index == NSNotFound {
return nil
}
index++
if index == self.pageIdentifiers.count {
return nil
}
return self.viewControllerAtIndex(index, storyboard: viewController.storyboard!)
}
// MARK: - Helper Methods
/**
指定されたView Controllerのインデックスを返す
:param: viewController ページのインデックスを求めるView Controller
:returns: ページのインデックス
*/
func indexOfViewController(viewController: FTIntrosPageDataViewController) -> Int {
return viewController.pageIndex
}
/**
指定されたインデックスからView Controllerを返す
:param: index インデックス
:param: storyboard ストーリーボード
:returns: View Controller
*/
func viewControllerAtIndex(index: Int, storyboard: UIStoryboard) -> FTIntrosPageDataViewController? {
if (self.pageIdentifiers.count == 0) || (index >= self.pageIdentifiers.count) {
return nil
}
let dataViewController = storyboard.instantiateViewControllerWithIdentifier(self.pageIdentifiers[index]) as! FTIntrosPageDataViewController
dataViewController.user = self.user
return dataViewController
}
}
| mit | b41d516cfaf87677cc242ba29f2841c1 | 30.045455 | 161 | 0.665813 | 5.154717 | false | false | false | false |
slxl/ReactKit | Carthage/Checkouts/SwiftTask/Carthage/Checkouts/Alamofire/Source/Stream.swift | 2 | 6572 | //
// Stream.swift
//
// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
//
// 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
#if !os(watchOS)
@available(iOS 9.0, OSX 10.11, tvOS 9.0, *)
extension Manager {
private enum Streamable {
case stream(String, Int)
case netService(Foundation.NetService)
}
private func stream(_ streamable: Streamable) -> Request {
var streamTask: URLSessionStreamTask!
switch streamable {
case .stream(let hostName, let port):
queue.sync {
streamTask = self.session.streamTask(withHostName: hostName, port: port)
}
case .netService(let netService):
queue.sync {
streamTask = self.session.streamTask(with: netService)
}
}
let request = Request(session: session, task: streamTask)
delegate[request.delegate.task] = request.delegate
if startRequestsImmediately {
request.resume()
}
return request
}
/**
Creates a request for bidirectional streaming with the given hostname and port.
- parameter hostName: The hostname of the server to connect to.
- parameter port: The port of the server to connect to.
:returns: The created stream request.
*/
public func stream(hostName: String, port: Int) -> Request {
return stream(.stream(hostName, port))
}
/**
Creates a request for bidirectional streaming with the given `NSNetService`.
- parameter netService: The net service used to identify the endpoint.
- returns: The created stream request.
*/
public func stream(netService: NetService) -> Request {
return stream(.netService(netService))
}
}
// MARK: -
@available(iOS 9.0, OSX 10.11, tvOS 9.0, *)
extension Manager.SessionDelegate: URLSessionStreamDelegate {
// MARK: Override Closures
/// Overrides default behavior for NSURLSessionStreamDelegate method `URLSession:readClosedForStreamTask:`.
public var streamTaskReadClosed: ((Foundation.URLSession, URLSessionStreamTask) -> Void)? {
get {
return _streamTaskReadClosed as? (Foundation.URLSession, URLSessionStreamTask) -> Void
}
set {
_streamTaskReadClosed = newValue
}
}
/// Overrides default behavior for NSURLSessionStreamDelegate method `URLSession:writeClosedForStreamTask:`.
public var streamTaskWriteClosed: ((Foundation.URLSession, URLSessionStreamTask) -> Void)? {
get {
return _streamTaskWriteClosed as? (Foundation.URLSession, URLSessionStreamTask) -> Void
}
set {
_streamTaskWriteClosed = newValue
}
}
/// Overrides default behavior for NSURLSessionStreamDelegate method `URLSession:betterRouteDiscoveredForStreamTask:`.
public var streamTaskBetterRouteDiscovered: ((Foundation.URLSession, URLSessionStreamTask) -> Void)? {
get {
return _streamTaskBetterRouteDiscovered as? (Foundation.URLSession, URLSessionStreamTask) -> Void
}
set {
_streamTaskBetterRouteDiscovered = newValue
}
}
/// Overrides default behavior for NSURLSessionStreamDelegate method `URLSession:streamTask:didBecomeInputStream:outputStream:`.
public var streamTaskDidBecomeInputStream: ((Foundation.URLSession, URLSessionStreamTask, InputStream, NSOutputStream) -> Void)? {
get {
return _streamTaskDidBecomeInputStream as? (Foundation.URLSession, URLSessionStreamTask, InputStream, NSOutputStream) -> Void
}
set {
_streamTaskDidBecomeInputStream = newValue
}
}
// MARK: Delegate Methods
/**
Tells the delegate that the read side of the connection has been closed.
- parameter session: The session.
- parameter streamTask: The stream task.
*/
public func urlSession(_ session: URLSession, readClosedFor streamTask: URLSessionStreamTask) {
streamTaskReadClosed?(session, streamTask)
}
/**
Tells the delegate that the write side of the connection has been closed.
- parameter session: The session.
- parameter streamTask: The stream task.
*/
public func urlSession(_ session: URLSession, writeClosedFor streamTask: URLSessionStreamTask) {
streamTaskWriteClosed?(session, streamTask)
}
/**
Tells the delegate that the system has determined that a better route to the host is available.
- parameter session: The session.
- parameter streamTask: The stream task.
*/
public func urlSession(_ session: URLSession, betterRouteDiscoveredFor streamTask: URLSessionStreamTask) {
streamTaskBetterRouteDiscovered?(session, streamTask)
}
/**
Tells the delegate that the stream task has been completed and provides the unopened stream objects.
- parameter session: The session.
- parameter streamTask: The stream task.
- parameter inputStream: The new input stream.
- parameter outputStream: The new output stream.
*/
public func urlSession(
_ session: URLSession,
streamTask: URLSessionStreamTask,
didBecome inputStream: InputStream,
outputStream: NSOutputStream)
{
streamTaskDidBecomeInputStream?(session, streamTask, inputStream, outputStream)
}
}
#endif
| mit | d6154212093163af9bb10ff67006aa60 | 35.10989 | 137 | 0.678484 | 5.378069 | false | false | false | false |
apple/swift-driver | Sources/SwiftDriver/Jobs/ModuleWrapJob.swift | 1 | 1423 | //===--------------- ModuleWrapJob.swift - Swift Module Wrapping ----------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2020 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
//
//===----------------------------------------------------------------------===//
extension Driver {
mutating func moduleWrapJob(moduleInput: TypedVirtualPath) throws -> Job {
var commandLine: [Job.ArgTemplate] = swiftCompilerPrefixArgs.map { Job.ArgTemplate.flag($0) }
commandLine.appendFlags("-modulewrap")
// Add the input.
commandLine.append(.path(moduleInput.file))
assert(compilerOutputType == .object, "-modulewrap mode only produces object files")
commandLine.appendFlags("-target", targetTriple.triple)
let outputPath = try moduleInput.file.replacingExtension(with: .object)
commandLine.appendFlag("-o")
commandLine.appendPath(outputPath)
return Job(
moduleName: moduleOutputInfo.name,
kind: .moduleWrap,
tool: try toolchain.resolvedTool(.swiftCompiler),
commandLine: commandLine,
inputs: [moduleInput],
primaryInputs: [],
outputs: [.init(file: outputPath.intern(), type: .object)]
)
}
}
| apache-2.0 | 87b87faa0507e2112b78dd461e5638bb | 35.487179 | 97 | 0.659874 | 4.711921 | false | false | false | false |
Tj3n/TVNExtensions | UIKit/UIViewController.swift | 1 | 5951 | //
// UIViewControllerExtension.swift
// MerchantDashboard
//
// Created by Tien Nhat Vu on 3/17/16.
// Copyright © 2016 Tien Nhat Vu. All rights reserved.
//
import Foundation
import UIKit
import SafariServices
public extension UIViewController {
/// Create VC from storyboard name and Viewcontroller ID
///
/// - Parameters:
/// - storyboardName: storyboard name, default to "Main"
/// - controllerId: controller identifier, default to the same Class name
/// - Returns: view controller
class func instantiate(fromStoryboard storyboardName: String = "Main", controllerId: String = "") -> Self {
let sb = UIStoryboard(name: storyboardName, bundle: Bundle.main)
return instantiateFromStoryboardHelper(sb, controllerId: controllerId.isEmpty ? String(describing: self) : controllerId)
}
class func instantiate(fromStoryboard storyboard: UIStoryboard?, controllerId: String = "") -> Self {
return instantiateFromStoryboardHelper(storyboard ?? UIStoryboard(name: "Main", bundle: Bundle.main),
controllerId: controllerId.isEmpty ? String(describing: self) : controllerId)
}
fileprivate class func instantiateFromStoryboardHelper<T>(_ storyboard: UIStoryboard, controllerId: String) -> T {
let controller = storyboard.instantiateViewController(withIdentifier: controllerId) as! T
return controller
}
/// Get top view controller from window
///
/// - Parameter window: default UIApplication.shared.keyWindow
/// - Returns: top view controller, does not detect childViewController
class func getTopViewController(from window: UIWindow? = UIApplication.shared.keyWindow) -> UIViewController? {
return getTopViewController(from: window?.rootViewController)
}
class func getTopViewController(from rootVC: UIViewController?) -> UIViewController? {
if let nav = rootVC as? UINavigationController, let navFirst = nav.visibleViewController {
return getTopViewController(from: navFirst)
} else if let tab = rootVC as? UITabBarController, let selectedTab = tab.selectedViewController {
return getTopViewController(from: selectedTab)
} else if let split = rootVC as? UISplitViewController, let splitLast = split.viewControllers.last {
return getTopViewController(from: splitLast)
} else if let presented = rootVC?.presentedViewController {
return getTopViewController(from: presented)
}
return rootVC
}
/// Add child VC with present animation, should use animation with full-screen child VC only
///
/// - Parameters:
/// - controller: Child view controller
/// - toView: The view to contain the controller's view
/// - animated: Set to true to use custom present animation
func addChildViewController(_ childController: UIViewController, toView: UIView, animated: Bool, completion: (()->())?) {
self.addChild(childController)
let v = childController.view!
v.alpha = 0
v.addTo(toView)
v.edgesToSuperView()
guard animated else {
v.alpha = 1
childController.didMove(toParent: self)
completion?()
return
}
var transform = CATransform3DMakeScale(0.3, 0.3, 1.0)
transform = CATransform3DTranslate(transform, 0, UIScreen.main.bounds.maxY, 0)
v.layer.transform = transform
UIView.animate(withDuration: 0.3, delay: 0, options: [.curveEaseInOut], animations: {
v.layer.transform = CATransform3DIdentity
v.alpha = 1
}, completion: { (_) in
childController.didMove(toParent: self)
completion?()
})
}
/// Switch child view controller with animation
///
/// - Parameters:
/// - oldViewController: oldViewController
/// - newViewController: newViewController
/// - containerView: containerView to switch
/// - completion: completion handler
func switchChildViewController(_ oldViewController: UIViewController, to newViewController: UIViewController, in containerView: UIView, completion: (()->())?) {
self.addChild(newViewController)
newViewController.view.addTo(containerView)
newViewController.view.edgesToSuperView()
newViewController.view.alpha = 0
newViewController.view.layoutIfNeeded()
newViewController.view.layer.transform = CATransform3DMakeTranslation(0, UIScreen.main.bounds.maxY, 0)
UIView.animate(withDuration: 0.5, delay: 0, options: [.allowAnimatedContent, .curveEaseInOut], animations: {
newViewController.view.alpha = 1
newViewController.view.layer.transform = CATransform3DIdentity
oldViewController.view.alpha = 0
oldViewController.view.layer.transform = CATransform3DMakeScale(0.8, 0.8, 1.0)
}) { (_) in
oldViewController.willMove(toParent: nil)
oldViewController.view.removeFromSuperview()
oldViewController.removeFromParent()
newViewController.didMove(toParent: self)
completion?()
}
}
/// Open the URL string with SFSafariViewController, do nothing if url is invalid
/// - Parameters:
/// - urlString: urlString
/// - completion: view present completion
func openURL(_ urlString: String, completion: (()->Void)?) {
let urlString = urlString.trim()
var url = URL(string: urlString)
if url?.scheme == nil {
url = URL(string: "https://"+urlString)
}
guard let unwrappedURL = url else { return }
let svc = SFSafariViewController(url: unwrappedURL)
present(svc, animated: true, completion: completion)
}
}
| mit | 386920ec326ffea4ffd1db4c295bf540 | 42.430657 | 164 | 0.653277 | 5.370036 | false | false | false | false |
josve05a/wikipedia-ios | Wikipedia/Code/ReadingListsViewController.swift | 2 | 20911 | import Foundation
enum ReadingListsDisplayType {
case readingListsTab, addArticlesToReadingList
}
protocol ReadingListsViewControllerDelegate: NSObjectProtocol {
func readingListsViewController(_ readingListsViewController: ReadingListsViewController, didAddArticles articles: [WMFArticle], to readingList: ReadingList)
func readingListsViewControllerDidChangeEmptyState(_ readingListsViewController: ReadingListsViewController, isEmpty: Bool)
}
@objc(WMFReadingListsViewController)
class ReadingListsViewController: ColumnarCollectionViewController, EditableCollection, UpdatableCollection {
typealias T = ReadingList
let dataStore: MWKDataStore
let readingListsController: ReadingListsController
var fetchedResultsController: NSFetchedResultsController<ReadingList>?
var collectionViewUpdater: CollectionViewUpdater<ReadingList>?
var editController: CollectionViewEditController!
private var articles: [WMFArticle] = [] // the articles that will be added to a reading list
private var readingLists: [ReadingList]? // the displayed reading lists
private var displayType: ReadingListsDisplayType = .readingListsTab
public weak var delegate: ReadingListsViewControllerDelegate?
private var createReadingListViewController: CreateReadingListViewController?
func setupFetchedResultsController() {
let request: NSFetchRequest<ReadingList> = ReadingList.fetchRequest()
request.relationshipKeyPathsForPrefetching = ["previewArticles"]
let isDefaultListEnabled = readingListsController.isDefaultListEnabled
if let readingLists = readingLists, !readingLists.isEmpty {
request.predicate = NSCompoundPredicate(andPredicateWithSubpredicates: [basePredicate, NSPredicate(format:"self IN %@", readingLists)])
} else if displayType == .addArticlesToReadingList {
let commonReadingLists = articles.reduce(articles.first?.readingLists ?? []) { $0.intersection($1.readingLists ?? []) }
var subpredicates: [NSPredicate] = []
if !commonReadingLists.isEmpty {
subpredicates.append(NSPredicate(format:"NOT (self IN %@)", commonReadingLists))
}
if !isDefaultListEnabled {
subpredicates.append(NSPredicate(format: "isDefault != YES"))
}
subpredicates.append(basePredicate)
request.predicate = NSCompoundPredicate(andPredicateWithSubpredicates: subpredicates)
} else {
var predicate = basePredicate
if !isDefaultListEnabled {
predicate = NSCompoundPredicate(andPredicateWithSubpredicates: [NSPredicate(format: "isDefault != YES"), basePredicate])
}
request.predicate = predicate
}
var sortDescriptors = baseSortDescriptors
sortDescriptors.append(NSSortDescriptor(key: "canonicalName", ascending: true, selector: #selector(NSString.localizedCaseInsensitiveCompare)))
request.sortDescriptors = sortDescriptors
fetchedResultsController = NSFetchedResultsController(fetchRequest: request, managedObjectContext: dataStore.viewContext, sectionNameKeyPath: nil, cacheName: nil)
}
var isShowingDefaultReadingListOnly: Bool {
guard readingListsController.isDefaultListEnabled else {
return false
}
guard let readingList = readingList(at: IndexPath(item: 0, section: 0)), readingList.isDefault else {
return false
}
return collectionView.numberOfSections == 1 && collectionView(collectionView, numberOfItemsInSection: 0) == 1
}
var basePredicate: NSPredicate {
return NSPredicate(format: "isDeletedLocally == NO")
}
var baseSortDescriptors: [NSSortDescriptor] {
return [NSSortDescriptor(keyPath: \ReadingList.isDefault, ascending: false)]
}
init(with dataStore: MWKDataStore) {
self.dataStore = dataStore
self.readingListsController = dataStore.readingListsController
super.init()
}
convenience init(with dataStore: MWKDataStore, articles: [WMFArticle]) {
self.init(with: dataStore)
self.articles = articles
self.displayType = .addArticlesToReadingList
}
convenience init(with dataStore: MWKDataStore, readingLists: [ReadingList]?) {
self.init(with: dataStore)
self.readingLists = readingLists
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) not supported")
}
override func viewDidLoad() {
super.viewDidLoad()
layoutManager.register(ReadingListsCollectionViewCell.self, forCellWithReuseIdentifier: ReadingListsCollectionViewCell.identifier, addPlaceholder: true)
emptyViewType = .noReadingLists
emptyViewTarget = self
emptyViewAction = #selector(presentCreateReadingListViewController)
setupEditController()
// Remove peek & pop for now
unregisterForPreviewing()
isRefreshControlEnabled = true
}
override func refresh() {
dataStore.readingListsController.fullSync {
self.endRefreshing()
}
}
override func viewWillAppear(_ animated: Bool) {
// setup FRC before calling super so that the data is available before the superclass checks for the empty state
setupFetchedResultsController()
setupCollectionViewUpdater()
fetch()
editController.isShowingDefaultCellOnly = isShowingDefaultReadingListOnly
super.viewWillAppear(animated)
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
collectionViewUpdater = nil
fetchedResultsController = nil
editController.close()
}
func readingList(at indexPath: IndexPath) -> ReadingList? {
guard let fetchedResultsController = fetchedResultsController,fetchedResultsController.isValidIndexPath(indexPath) else {
return nil
}
return fetchedResultsController.object(at: indexPath)
}
// MARK: - Reading list creation
@objc func createReadingList(with articles: [WMFArticle] = [], moveFromReadingList: ReadingList? = nil) {
createReadingListViewController = CreateReadingListViewController(theme: self.theme, articles: articles, moveFromReadingList: moveFromReadingList)
guard let createReadingListViewController = createReadingListViewController else {
assertionFailure("createReadingListViewController is nil")
return
}
createReadingListViewController.delegate = self
let navigationController = WMFThemeableNavigationController(rootViewController: createReadingListViewController, theme: theme, style: .sheet)
createReadingListViewController.navigationItem.rightBarButtonItem = UIBarButtonItem.wmf_buttonType(WMFButtonType.X, target: self, action: #selector(dismissCreateReadingListViewController))
present(navigationController, animated: true, completion: nil)
}
@objc func presentCreateReadingListViewController() {
createReadingList(with: articles)
}
@objc func dismissCreateReadingListViewController() {
dismiss(animated: true, completion: nil)
}
private func handleReadingListError(_ error: Error) {
if let readingListsError = error as? ReadingListError {
WMFAlertManager.sharedInstance.showErrorAlertWithMessage(readingListsError.localizedDescription, sticky: true, dismissPreviousAlerts: true, tapCallBack: nil)
} else {
WMFAlertManager.sharedInstance.showErrorAlertWithMessage(
CommonStrings.unknownError, sticky: false, dismissPreviousAlerts: true, tapCallBack: nil)
}
}
public lazy var createNewReadingListButtonView: CreateNewReadingListButtonView = {
let createNewReadingListButtonView = CreateNewReadingListButtonView.wmf_viewFromClassNib()
createNewReadingListButtonView?.title = CommonStrings.createNewListTitle
createNewReadingListButtonView?.button.addTarget(self, action: #selector(presentCreateReadingListViewController), for: .touchUpInside)
createNewReadingListButtonView?.apply(theme: theme)
return createNewReadingListButtonView!
}()
// MARK: - Cell configuration
open func configure(cell: ReadingListsCollectionViewCell, forItemAt indexPath: IndexPath, layoutOnly: Bool) {
guard let readingList = readingList(at: indexPath) else {
return
}
let articleCount = readingList.countOfEntries
let lastFourArticlesWithLeadImages = Array(readingList.previewArticles ?? []) as? Array<WMFArticle> ?? []
cell.layoutMargins = layout.itemLayoutMargins
cell.configureAlert(for: readingList, listLimit: dataStore.viewContext.wmf_readingListsConfigMaxListsPerUser, entryLimit: dataStore.viewContext.wmf_readingListsConfigMaxEntriesPerList.intValue)
if readingList.isDefault {
cell.configure(with: CommonStrings.readingListsDefaultListTitle, description: CommonStrings.readingListsDefaultListDescription, isDefault: true, index: indexPath.item, shouldShowSeparators: true, theme: theme, for: displayType, articleCount: articleCount, lastFourArticlesWithLeadImages: lastFourArticlesWithLeadImages, layoutOnly: layoutOnly)
cell.isBatchEditing = false
cell.isBatchEditable = false
} else {
cell.isBatchEditable = true
cell.isBatchEditing = editController.isBatchEditing
editController.configureSwipeableCell(cell, forItemAt: indexPath, layoutOnly: layoutOnly)
cell.configure(readingList: readingList, index: indexPath.item, shouldShowSeparators: true, theme: theme, for: displayType, articleCount: articleCount, lastFourArticlesWithLeadImages: lastFourArticlesWithLeadImages, layoutOnly: layoutOnly)
}
}
// MARK: - ColumnarCollectionViewLayoutDelegate
override func collectionView(_ collectionView: UICollectionView, estimatedHeightForItemAt indexPath: IndexPath, forColumnWidth columnWidth: CGFloat) -> ColumnarCollectionViewLayoutHeightEstimate {
var estimate = ColumnarCollectionViewLayoutHeightEstimate(precalculated: false, height: 100)
guard let placeholderCell = layoutManager.placeholder(forCellWithReuseIdentifier: ReadingListsCollectionViewCell.identifier) as? ReadingListsCollectionViewCell else {
return estimate
}
configure(cell: placeholderCell, forItemAt: indexPath, layoutOnly: true)
estimate.height = placeholderCell.sizeThatFits(CGSize(width: columnWidth, height: UIView.noIntrinsicMetric), apply: false).height
estimate.precalculated = true
return estimate
}
override func metrics(with size: CGSize, readableWidth: CGFloat, layoutMargins: UIEdgeInsets) -> ColumnarCollectionViewLayoutMetrics {
return ColumnarCollectionViewLayoutMetrics.tableViewMetrics(with: size, readableWidth: readableWidth, layoutMargins: layoutMargins)
}
// MARK: - Empty state
override func isEmptyDidChange() {
editController.isCollectionViewEmpty = isEmpty
collectionView.isHidden = isEmpty
super.isEmptyDidChange()
delegate?.readingListsViewControllerDidChangeEmptyState(self, isEmpty: isEmpty)
}
func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool {
guard displayType != .addArticlesToReadingList else {
return true
}
guard !editController.isClosed else {
return true
}
guard let readingList = readingList(at: indexPath), !readingList.isDefault else {
return false
}
return true
}
// MARK: - Batch editing
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
guard editController.isClosed else {
return
}
guard let readingList = readingList(at: indexPath) else {
return
}
guard displayType == .readingListsTab else {
do {
try readingListsController.add(articles: articles, to: readingList)
delegate?.readingListsViewController(self, didAddArticles: articles, to: readingList)
} catch let error {
handleReadingListError(error)
}
return
}
let readingListDetailViewController = ReadingListDetailViewController(for: readingList, with: dataStore)
readingListDetailViewController.apply(theme: theme)
wmf_push(readingListDetailViewController, animated: true)
}
func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
let _ = editController.isClosed
}
lazy var availableBatchEditToolbarActions: [BatchEditToolbarAction] = {
//let updateItem = BatchEditToolbarActionType.update.action(with: self)
let deleteItem = BatchEditToolbarActionType.delete.action(with: self)
return [deleteItem]
}()
override func scrollViewDidScroll(_ scrollView: UIScrollView) {
super.scrollViewDidScroll(scrollView)
editController.transformBatchEditPaneOnScroll()
}
// MARK: Themeable
override func apply(theme: Theme) {
super.apply(theme: theme)
view.backgroundColor = theme.colors.paperBackground
createNewReadingListButtonView.apply(theme: theme)
}
}
// MARK: - CreateReadingListViewControllerDelegate
extension ReadingListsViewController: CreateReadingListDelegate {
func createReadingListViewController(_ createReadingListViewController: CreateReadingListViewController, didCreateReadingListWith name: String, description: String?, articles: [WMFArticle]) {
do {
let readingList = try readingListsController.createReadingList(named: name, description: description, with: articles)
if let moveFromReadingList = createReadingListViewController.moveFromReadingList {
try readingListsController.remove(articles: articles, readingList: moveFromReadingList)
}
delegate?.readingListsViewController(self, didAddArticles: articles, to: readingList)
createReadingListViewController.dismiss(animated: true, completion: nil)
if displayType == .addArticlesToReadingList {
ReadingListsFunnel.shared.logCreateInAddToReadingList()
} else {
ReadingListsFunnel.shared.logCreateInReadingLists()
}
} catch let error {
switch error {
case let readingListError as ReadingListError where readingListError == .listExistsWithTheSameName:
createReadingListViewController.handleReadingListNameError(readingListError)
default:
createReadingListViewController.dismiss(animated: true) {
self.handleReadingListError(error)
}
}
}
}
}
// MARK: - UICollectionViewDataSource
extension ReadingListsViewController {
override func numberOfSections(in collectionView: UICollectionView) -> Int {
guard let sectionsCount = self.fetchedResultsController?.sections?.count else {
return 0
}
return sectionsCount
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
guard let sections = self.fetchedResultsController?.sections, section < sections.count else {
return 0
}
return sections[section].numberOfObjects
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ReadingListsCollectionViewCell.identifier, for: indexPath)
guard let readingListCell = cell as? ReadingListsCollectionViewCell else {
return cell
}
configure(cell: readingListCell, forItemAt: indexPath, layoutOnly: false)
return cell
}
}
// MARK: - CollectionViewUpdaterDelegate
extension ReadingListsViewController: CollectionViewUpdaterDelegate {
func collectionViewUpdater<T>(_ updater: CollectionViewUpdater<T>, didUpdate collectionView: UICollectionView) {
for indexPath in collectionView.indexPathsForVisibleItems {
guard let cell = collectionView.cellForItem(at: indexPath) as? ReadingListsCollectionViewCell else {
continue
}
configure(cell: cell, forItemAt: indexPath, layoutOnly: false)
}
updateEmptyState()
editController.isShowingDefaultCellOnly = isShowingDefaultReadingListOnly
collectionView.setNeedsLayout()
}
func collectionViewUpdater<T: NSFetchRequestResult>(_ updater: CollectionViewUpdater<T>, updateItemAtIndexPath indexPath: IndexPath, in collectionView: UICollectionView) {
}
}
// MARK: - ActionDelegate
extension ReadingListsViewController: ActionDelegate {
func willPerformAction(_ action: Action) -> Bool {
guard let readingList = readingList(at: action.indexPath) else {
return false
}
guard action.type == .delete else {
return self.editController.didPerformAction(action)
}
let alertController = ReadingListsAlertController()
let cancel = ReadingListsAlertActionType.cancel.action()
let delete = ReadingListsAlertActionType.delete.action { let _ = self.editController.didPerformAction(action) }
alertController.showAlertIfNeeded(presenter: self, for: [readingList], with: [cancel, delete]) { showed in
if !showed {
let _ = self.editController.didPerformAction(action)
}
}
return true
}
private func deleteReadingLists(_ readingLists: [ReadingList]) {
do {
try self.readingListsController.delete(readingLists: readingLists)
self.editController.close()
let readingListsCount = readingLists.count
if displayType == .addArticlesToReadingList {
ReadingListsFunnel.shared.logDeleteInAddToReadingList(readingListsCount: readingListsCount)
} else {
ReadingListsFunnel.shared.logDeleteInReadingLists(readingListsCount: readingListsCount)
}
} catch let error {
handleReadingListError(error)
}
}
func didPerformBatchEditToolbarAction(_ action: BatchEditToolbarAction, completion: @escaping (Bool) -> Void) {
guard let selectedIndexPaths = collectionView.indexPathsForSelectedItems else {
completion(false)
return
}
let readingLists: [ReadingList] = selectedIndexPaths.compactMap({ readingList(at: $0) })
switch action.type {
case .delete:
let alertController = ReadingListsAlertController()
let deleteReadingLists = {
self.deleteReadingLists(readingLists)
completion(true)
}
let delete = ReadingListsAlertActionType.delete.action {
self.deleteReadingLists(readingLists)
completion(true)
}
let cancel = ReadingListsAlertActionType.cancel.action {
completion(false)
}
let actions = [cancel, delete]
alertController.showAlertIfNeeded(presenter: self, for: readingLists, with: actions) { showed in
if !showed {
deleteReadingLists()
}
}
default:
completion(false)
break
}
}
func didPerformAction(_ action: Action) -> Bool {
let indexPath = action.indexPath
guard let readingList = readingList(at: indexPath) else {
return false
}
switch action.type {
case .delete:
self.deleteReadingLists([readingList])
UIAccessibility.post(notification: UIAccessibility.Notification.announcement, argument: WMFLocalizedString("reading-list-deleted-accessibility-notification", value: "Reading list deleted", comment: "Notification spoken after user deletes a reading list from the list."))
return true
default:
return false
}
}
func availableActions(at indexPath: IndexPath) -> [Action] {
return [ActionType.delete.action(with: self, indexPath: indexPath)]
}
}
| mit | fb49c40b882db3daf9b7b5edfa37291d | 44.757112 | 355 | 0.694754 | 6.285242 | false | false | false | false |
IBM-MIL/IBM-Ready-App-for-Venue | iOS/Venue/Controllers/HomeViewController.swift | 1 | 14724 | /*
Licensed Materials - Property of IBM
© Copyright IBM Corporation 2015. All Rights Reserved.
*/
import UIKit
import AVFoundation
/// Controller to serve as a starting point, showing the user's list of POIs and all POIs near them
class HomeViewController: VenueUIViewController {
@IBOutlet weak var fillerTableViewHeader: UIView!
@IBOutlet weak var myListButton: UIButton!
@IBOutlet weak var nearMeButton: UIButton!
@IBOutlet weak var leadingIndicatorViewConstraint: NSLayoutConstraint!
@IBOutlet weak var overlayView: UIView!
@IBOutlet weak var shadowImageView: UIImageView!
@IBOutlet weak var emptyButtonTableViewHeader: UIView!
@IBOutlet var buttonView: UIView!
@IBOutlet weak var homeTableView: UITableView!
@IBOutlet weak var avPlayerView: UIView!
@IBOutlet var completedSectionHeader: UIView!
@IBOutlet var invitationSectionHeader: UIView!
@IBOutlet var favoritesSectionHeader: UIView!
@IBOutlet weak var favoritesHeaderLabel: UILabel!
/// Helper setter to be used when we want to keep overlayView and buttonView colors in sync
var overlayColor: UIColor {
get {
return overlayView.backgroundColor!
}
set(color) {
overlayView.backgroundColor = color
buttonView.backgroundColor = color
}
}
var avPlayer: AVPlayer!
var avPlayerLayer: AVPlayerLayer!
var viewModel = HomeViewModel()
// Local constants
let headerVideoHeight: CGFloat = 234.0
let customNavBarHeight: CGFloat = 66.0
let yOffset: CGFloat = -20.0
override func viewDidLoad() {
super.viewDidLoad()
overlayColor = UIColor.venueLightBlue().colorWithAlphaComponent(0.0)
setupBindings()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
navigationController?.setNavigationBarHidden(true, animated: true)
}
/**
Setup ReactiveCocoa bindings to UI and data
*/
func setupBindings() {
// Listener to ensure video playback loops to the beginning every time it ends
NSNotificationCenter.defaultCenter().rac_addObserverForName(AVPlayerItemDidPlayToEndTimeNotification, object: nil)
.deliverOnMainThread()
.subscribeNextAs { [unowned self] (notification: NSNotification) in
if let player = notification.object as? AVPlayerItem {
self.restartVideo(player)
self.avPlayer.play()
}
}
// Listener to restart player when coming from an inactive state
NSNotificationCenter.defaultCenter().rac_addObserverForName(UIApplicationWillEnterForegroundNotification, object: nil)
.deliverOnMainThread()
.subscribeNextAs { [weak self] (notification: NSNotification) in
MQALogger.log("App and Home screen have entered foreground", withLevel: MQALogLevelInfo)
guard let strongSelf = self else {
return
}
strongSelf.configureVideoPlayer()
}
myListButton.rac_signalForControlEvents(UIControlEvents.TouchUpInside).subscribeNext { [unowned self] _ in
self.toggleTableView(true)
}
nearMeButton.rac_signalForControlEvents(UIControlEvents.TouchUpInside).subscribeNext { [unowned self] _ in
self.toggleTableView(false)
}
/* Data based UI updates */
/**
Convenience method to add newly sent or accepted invites to home tableView
- parameter updatedInviteList: the updated invite list to work with
- parameter oppositeList: either the sent or accepted invitations, used to get an accurate count
*/
func addInvite(updatedInviteList: AnyObject!, oppositeList: [Invitation]) {
if let updatedInviteList = updatedInviteList as? [Invitation] {
if self.viewModel.userInvitations.count < updatedInviteList.count + oppositeList.count {
self.viewModel.userInvitations.append(updatedInviteList.last!)
self.homeTableView.reloadData()
}
}
}
// The following listeners help reload tableView with new data
RACObserve(UserDataManager.sharedInstance.currentUser, keyPath: "invitationsSent").subscribeNext({(invitationsSent: AnyObject!) in
addInvite(invitationsSent, oppositeList: UserDataManager.sharedInstance.currentUser.invitationsAccepted)
})
RACObserve(UserDataManager.sharedInstance.currentUser, keyPath: "invitationsAccepted").subscribeNext({ (invitationsAccepted: AnyObject!) in
addInvite(invitationsAccepted, oppositeList: UserDataManager.sharedInstance.currentUser.invitationsSent)
})
RACObserve(UserDataManager.sharedInstance.currentUser, keyPath: "favorites").subscribeNextAs({ [weak self] (favorites: [FavoritedPOI]) in
guard let strongSelf = self else {
return
}
strongSelf.homeTableView.reloadData()
})
}
/**
Helper method to switch between tableViews in a smooth way
- parameter showMyList: deteremines whether we are showing MyList or not
*/
func toggleTableView(showMyList: Bool) {
self.viewModel.showMyList = showMyList
self.leadingIndicatorViewConstraint.constant = showMyList ? 0 : self.view.frame.size.width/2
self.homeTableView.reloadData()
self.homeTableView.setContentOffset(CGPointZero, animated: true)
// Fixes issue with buttonView getting out of sync in y position
self.buttonView.setOriginY(fillerTableViewHeader.height)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
MQALogger.log("Memory warning in Home View", withLevel: MQALogLevelWarning)
}
// MARK: Video Player Management
/**
Helper metho to restart video from beginning
- parameter player: the player to restart
*/
func restartVideo(player: AVPlayerItem) {
player.seekToTime(kCMTimeZero)
MQALogger.log("Video Restarted", withLevel: MQALogLevelInfo)
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
if avPlayer == nil {
configureVideoPlayer()
}
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
avPlayer.play()
if buttonView.superview == nil {
buttonView.frame = emptyButtonTableViewHeader.frame
self.view.addSubview(buttonView)
}
}
override func viewDidDisappear(animated: Bool) {
super.viewDidDisappear(animated)
avPlayer.pause()
}
/**
Sets up AVPlayer and begins playing video
*/
func configureVideoPlayer() {
let fileURL = NSURL(fileURLWithPath: viewModel.videoPath)
avPlayer = AVPlayer(URL: fileURL)
avPlayerLayer = AVPlayerLayer(player: avPlayer)
avPlayer.actionAtItemEnd = AVPlayerActionAtItemEnd.None
avPlayerLayer.frame = avPlayerView.frame
avPlayerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
avPlayerView.layer.insertSublayer(avPlayerLayer, below: overlayView.layer)
avPlayer.play()
}
/**
Method to update video player frame based on offset passed in, moves frame up when offset is positive, increases height of video when scrolling down
we also move the light blue overlay and buttonView in this method to avoid UI issues
- parameter scrollViewContentOffset: y offset sent from scrollView
*/
func updateFrameWithScrollViewDidScroll(scrollViewContentOffset : CGFloat){
if (scrollViewContentOffset >= 0) {
let magicLine = headerVideoHeight - customNavBarHeight
if(scrollViewContentOffset >= magicLine){
// Prevents views from going futher than this
let updatedFrame = CGRectMake(0, -magicLine + yOffset, avPlayerLayer.frame.size.width, headerVideoHeight)
avPlayerLayer.resizeImmediatly(updatedFrame)
overlayView.frame = updatedFrame
buttonView.setOriginY(0)
}
else {
// Moves views up with scroll view
let updatedFrame = CGRectMake(0, -scrollViewContentOffset + yOffset, avPlayerLayer.frame.size.width, avPlayerLayer.frame.size.height)
avPlayerLayer.resizeImmediatly(updatedFrame)
// Notice: moving overlayView up so it isn't visible when a user scrolls down
overlayView.frame = updatedFrame
// If buttonView is at top of screen - status bar height, make it stick to top
if -scrollViewContentOffset + emptyButtonTableViewHeader.frame.origin.y <= 0 {
buttonView.setOriginY(0)
} else {
buttonView.setOriginY(-scrollViewContentOffset + emptyButtonTableViewHeader.frame.origin.y)
}
}
}
else {
// Increases size of video player
avPlayerLayer.resizeImmediatly(CGRectMake(0, yOffset, avPlayerLayer.frame.size.width, headerVideoHeight - scrollViewContentOffset))
buttonView.setOriginY( -scrollViewContentOffset + emptyButtonTableViewHeader.frame.origin.y)
}
}
/**
Method fades and reveals overlays as tableView is scrolled, by modifing the alpha color value
- parameter offset: scrollview offset
*/
func fadeOverlays(offset: CGFloat) {
if(offset >= 0){
let magicLine = headerVideoHeight - customNavBarHeight
if(offset >= (magicLine + yOffset)){
overlayColor = UIColor.venueLightBlue().colorWithAlphaComponent(1.0)
shadowImageView.alpha = 0.0
}
else {
// Max value we can hit, min is 0
let max = CGFloat(magicLine + yOffset)
// Calculation to get percentage from 0 to max, in decimals
let calculatedAlpha = offset / max
overlayView.backgroundColor = UIColor.venueLightBlue().colorWithAlphaComponent(calculatedAlpha)
buttonView.backgroundColor = UIColor.venueLightBlue().colorWithAlphaComponent(0.0)
// Instead of moving the shadows frame, we gradually fade it
shadowImageView.alpha = 1.0 - calculatedAlpha
}
} else {
// Ensures overlay is transparent when image is expanding
overlayColor = UIColor.venueLightBlue().colorWithAlphaComponent(0.0)
}
}
}
extension HomeViewController: UITableViewDelegate, UITableViewDataSource {
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return viewModel.showMyList ? 5 : 2
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return viewModel.rowsInSection(section)
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! POITableViewCell
viewModel.setupPOICell(cell, indexPath: indexPath)
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
// Check if selected cell was an Ad, if so, return
let tableCell = tableView.cellForRowAtIndexPath(indexPath) as! POITableViewCell
let selectedIndex = homeTableView.indexPathForCell(tableCell)
if viewModel.displaysAd(selectedIndex!) {
return
}
// Otherwise segue to PlaceDetailVC
let selectedPOI = viewModel.getDisplayedPOI(selectedIndex!)
let placeDetailViewController = Utils.vcWithNameFromStoryboardWithName("placeDetail", storyboardName: "Places") as! PlaceDetailViewController
placeDetailViewController.viewModel = PlacesDetailViewModel(poi: selectedPOI)
self.navigationController?.pushViewController(placeDetailViewController, animated: true)
}
func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
// Workaround: Odd gap appears when there are no section headers after the first 2
if !viewModel.dataPresent && section == 3 {
favoritesHeaderLabel.text = NSLocalizedString("No Items in List", comment: "")
return favoritesSectionHeader
} else if section == 3 {
favoritesHeaderLabel.text = NSLocalizedString("Favorited", comment: "")
}
switch(section) {
case 0:
return fillerTableViewHeader
case 1:
return emptyButtonTableViewHeader
case 2:
return viewModel.rowsInSection(section) == 0 ? nil : invitationSectionHeader
case 3:
return viewModel.rowsInSection(section) == 0 ? nil : favoritesSectionHeader
case 4:
return viewModel.rowsInSection(section) == 0 ? nil : completedSectionHeader
default:
return nil
}
}
func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
if !viewModel.dataPresent && section == 3 {
return favoritesSectionHeader.height
}
switch(section) {
case 0:
return fillerTableViewHeader.frame.size.height
case 1:
return emptyButtonTableViewHeader.frame.size.height
case 2:
return viewModel.rowsInSection(section) == 0 ? 0 : invitationSectionHeader.height
case 3:
return viewModel.rowsInSection(section) == 0 ? 0 : favoritesSectionHeader.height
case 4:
return viewModel.rowsInSection(section) == 0 ? 0 : completedSectionHeader.height
default:
return 0
}
}
}
extension HomeViewController : UIScrollViewDelegate {
func scrollViewDidScroll(scrollView: UIScrollView) {
updateFrameWithScrollViewDidScroll(scrollView.contentOffset.y)
fadeOverlays(scrollView.contentOffset.y)
}
}
| epl-1.0 | f55c59b114750f61fab5eb92ce08f9de | 39.117166 | 152 | 0.649664 | 5.84478 | false | false | false | false |
triassic-park/triassic-swift | Sources/LocationInformation/GeoRestriction.swift | 1 | 793 | //
// GeoRestriction.swift
// Pods
//
// Created by Kilian Költzsch on 17/11/2016.
//
//
import Foundation
/// Definiert einen geografischen Filter.
public struct GeoRestriction {
/// Der Filter wird durch einen Kreis definiert.
let circle: GeoCircle?
/// Der Filter wird durch ein Rechteck definiert.
let rectangle: GeoRectangle?
/// Der Filter wird durch ein Polygon definiert.
let area: GeoArea?
init(circle: GeoCircle) {
self.circle = circle
self.rectangle = nil
self.area = nil
}
init(rectangle: GeoRectangle) {
self.circle = nil
self.rectangle = rectangle
self.area = nil
}
init(area: GeoArea) {
self.circle = nil
self.rectangle = nil
self.area = area
}
}
| mit | 1f87838e2e34c50bef4b6cb8562e4900 | 19.307692 | 53 | 0.616162 | 3.700935 | false | false | false | false |
ppraveentr/MobileCore | Sources/CoreUtility/Extensions/UIColor+Extension.swift | 1 | 4870 | //
// Color+Extension.swift
// MobileCore-CoreUtility
//
// Created by Praveen Prabhakar on 01/08/17.
// Copyright © 2017 Praveen Prabhakar. All rights reserved.
//
import Foundation
import UIKit
/*
Here's a correct table of percentages to hex values. E.g. for 50% white you'd use #80FFFFFF.
100% — FF
95% — F2
90% — E6
85% — D9
80% — CC
75% — BF
70% — B3
65% — A6
60% — 99
55% — 8C
50% — 80
45% — 73
40% — 66
35% — 59
30% — 4D
25% — 40
20% — 33
15% — 26
10% — 1A
5% — 0D
0% — 00
Percentage to hex values:
https://stackoverflow.com/questions/15852122/hex-transparency-in-colors
*/
public extension UIColor {
convenience init(red: UInt64, green: UInt64, blue: UInt64, a: CGFloat = 1.0) {
self.init(red: CGFloat(red) / 255, green: CGFloat(green) / 255, blue: CGFloat(blue) / 255, alpha: a)
}
// MARK: rgb: UInt64, a: CGFloat
// UIColor(rgb: 13_158_600, a: 0.5) --> "#C8C8C87F"
convenience init(rgb: UInt64, a: CGFloat = 1.0) {
self.init(red: (rgb >> 16 & 0xFF), green: (rgb >> 8 & 0xFF), blue: (rgb >> 0 & 0xFF), a: a)
}
// UIColor(red: 200, green: 200, blue: 200, a: 0.5) --> "#C8C8C8"
func hexString() -> String {
var (r, g, b, a): (CGFloat, CGFloat, CGFloat, CGFloat) = (0.0, 0.0, 0.0, 0.0)
getRed(&r, green: &g, blue: &b, alpha: &a)
let rgb: Int = (Int)(r * 255) << 16 | (Int)(g * 255) << 8 | (Int)(b * 255) << 0
return String(format: "#%06x", rgb)
}
// MARK: rgba: UInt64
// UIColor(rgb: 13_158_600) --> "#C8C8C8FF"
convenience init(rgba: UInt64) {
let (r, g, b, a) = (rgba >> 24 & 0xFF, rgba >> 16 & 0xFF, rgba >> 8 & 0xFF, rgba >> 0 & 0xFF)
self.init(red: r, green: g, blue: b, a: CGFloat(a) / 255)
}
// UIColor(red: 200, green: 200, blue: 200, a: 1.0) --> "#C8C8C8FF"
// UIColor(red: 200, green: 200, blue: 200, a: 0.5) --> "#C8C8C87F"
func hexAlphaString() -> String {
var (r, g, b, a): (CGFloat, CGFloat, CGFloat, CGFloat) = (0.0, 0.0, 0.0, 0.0)
getRed(&r, green: &g, blue: &b, alpha: &a)
let rgba: UInt64 = (UInt64)(r * 255) << 24 | (UInt64)(g * 255) << 16 | (UInt64)(b * 255) << 8 | (UInt64)(a * 255)
return String(format: "#%08x", rgba)
}
// MARK: hexString: String: "#C8C8C87F"
// "#C8C8C87F" --> UIColor(red: 200, green: 200, blue: 200, a: 0.5)
static func hexColor(_ hexString: String) -> UIColor? {
// Check if its acutal hex coded string
guard hexString.hasPrefix("#") else { return nil }
// Strip non-alphanumerics, and Make it capitalized
let hex = hexString.trimmingCharacters(in: CharacterSet.alphanumerics.inverted).uppercased()
// Read hex string into Int64
var int = UInt64()
Scanner(string: hex).scanHexInt64(&int)
switch hex.count {
case 3: // RGB (12-bit)
let (r, g, b) = ((int >> 8 & 0xF) * 17, (int >> 4 & 0xF) * 17, (int & 0xF) * 17)
return UIColor(red: r, green: g, blue: b)
case 6: // RGB (24-bit)
return UIColor(rgb: int)
case 8: // ARGB (32-bit)
return UIColor(rgba: int)
default:
return nil
}
}
func generateImage(opacity: CGFloat = 1,
contextSize: CGSize = CGSize(width: 1, height: 1),
contentsScale: CGFloat = CGFloat.greatestFiniteMagnitude) -> UIImage? {
let rect = CGRect(origin: .zero, size: contextSize)
if contentsScale == CGFloat.greatestFiniteMagnitude {
UIGraphicsBeginImageContext(contextSize)
}
else {
UIGraphicsBeginImageContextWithOptions(contextSize, false, contentsScale)
}
if let context = UIGraphicsGetCurrentContext() {
context.setFillColor(self.cgColor)
context.setAlpha(opacity)
context.fill(rect)
}
let img = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return img
}
}
public extension UIImage {
convenience init?(color: UIColor) {
if let cgImage = color.generateImage()?.cgImage {
self.init(cgImage: cgImage)
}
return nil
}
func getColor(a: CGFloat = -10) -> UIColor? {
guard let pixelData = self.cgImage?.dataProvider?.data,
let data = CFDataGetBytePtr(pixelData) else { return nil }
// The image is png
let pixelInfo = Int(0) * 4
let red = data[pixelInfo]
let green = data[(pixelInfo + 1)]
let blue = data[pixelInfo + 2]
let alpha = data[pixelInfo + 3]
return UIColor(red: UInt64(red), green: UInt64(green), blue: UInt64(blue), a: (a > 0 ? a : CGFloat(alpha)) / 255.0)
}
}
| mit | c5a91ef100199f423620888b7b7acf9d | 33.234043 | 123 | 0.55666 | 3.387368 | false | false | false | false |
stripe/stripe-ios | StripeFinancialConnections/StripeFinancialConnections/Source/Web/FinancialConnectionsSessionFetcher.swift | 1 | 2444 | //
// FinancialConnectionsSessionFetcher.swift
// StripeFinancialConnections
//
// Created by Vardges Avetisyan on 1/20/22.
//
import Foundation
@_spi(STP) import StripeCore
protocol FinancialConnectionsSessionFetcher {
func fetchSession() -> Future<StripeAPI.FinancialConnectionsSession>
}
class FinancialConnectionsSessionAPIFetcher: FinancialConnectionsSessionFetcher {
// MARK: - Properties
private let api: FinancialConnectionsAPIClient
private let clientSecret: String
private let accountFetcher: FinancialConnectionsAccountFetcher
// MARK: - Init
init(api: FinancialConnectionsAPIClient,
clientSecret: String,
accountFetcher: FinancialConnectionsAccountFetcher) {
self.api = api
self.clientSecret = clientSecret
self.accountFetcher = accountFetcher
}
// MARK: - AccountFetcher
func fetchSession() -> Future<StripeAPI.FinancialConnectionsSession> {
api.fetchFinancialConnectionsSession(clientSecret: clientSecret).chained { [weak self] session in
guard session.accounts.hasMore, let self = self else {
return Promise(value: session)
}
return self.accountFetcher
.fetchAccounts(initial: session.accounts.data)
.chained { fullAccountList in
/**
Here we create a synthetic FinancialConnectionsSession object with full account list.
*/
let fullList = StripeAPI.FinancialConnectionsSession.AccountList(data: fullAccountList, hasMore: false)
let sessionWithFullAccountList = StripeAPI.FinancialConnectionsSession(clientSecret: session.clientSecret,
id: session.id,
accounts: fullList,
livemode: session.livemode,
paymentAccount: session.paymentAccount,
bankAccountToken: session.bankAccountToken)
return Promise(value: sessionWithFullAccountList)
}
}
}
}
| mit | f3893474cc96f871c69b31699a2c8a4c | 40.423729 | 134 | 0.561784 | 6.788889 | false | false | false | false |
CoderKingdom/swiftExtensions | SwiftExtensions/SwiftExtensions/NSDateComponents.swift | 1 | 1809 | //
// NSDateComponent.swift
// UICollectionInUITableViewCell
//
// Created by Douglas Barreto on 2/24/16.
// Copyright © 2016 CoderKingdom. All rights reserved.
//
import Foundation
extension NSDateComponents {
func zeroTime() {
self.hour -= self.hour
self.minute -= self.minute
self.second -= self.second
self.nanosecond -= self.nanosecond
}
func nextDay() {
self.day += 1
updateWeekDay()
}
func lastDay() {
self.day -= 1
updateWeekDay()
}
func lastWeek() {
self.backward(days: 7)
updateWeekDay()
}
func nextWeek() {
self.forward(days: 7)
updateWeekDay()
}
func forwardWeek( weeks:Int ) {
self.forward(days: weeks * 7)
}
func backwardWeek( weeks:Int ) {
self.backward(days: weeks * 7)
}
func forward( days days:Int ) {
self.day += days
updateWeekDay()
}
func backward( days days:Int ) {
self.day -= days
updateWeekDay()
}
func beginOfMonth() {
self.day -= self.day - 1
updateWeekDay()
}
func endOfWeek() {
self.forward(days: WeekDays.Saturday.rawValue - self.weekday)
updateWeekDay()
}
func beginOfWeek() {
print( WeekDays.Sunday.rawValue - self.weekday )
self.forward(days: WeekDays.Sunday.rawValue - self.weekday)
updateWeekDay()
}
func updateWeekDay() {
if let date = self.date {
self.weekday = NSCalendar.currentCalendar().components(NSCalendarUnit.Weekday, fromDate: date).weekday
}
}
func fixGMTTimeZone() {
self.timeZone = NSTimeZone(forSecondsFromGMT: 0)
}
}
| mit | 6b4f27ad1d41296e725d907a6c68e730 | 20.270588 | 114 | 0.553097 | 4.486352 | false | false | false | false |
r-mckay/montreal-iqa | montrealIqaCore/Carthage/Checkouts/realm-cocoa/examples/ios/swift-3.0/TableView/TableViewController.swift | 3 | 5023 | ////////////////////////////////////////////////////////////////////////////
//
// 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
class DemoObject: Object {
dynamic var title = ""
dynamic var date = NSDate()
}
class Cell: UITableViewCell {
override init(style: UITableViewCellStyle, reuseIdentifier: String!) {
super.init(style: .subtitle, reuseIdentifier: reuseIdentifier)
}
required init(coder: NSCoder) {
fatalError("NSCoding not supported")
}
}
class TableViewController: UITableViewController {
let realm = try! Realm()
let results = try! Realm().objects(DemoObject.self).sorted(byKeyPath: "date")
var notificationToken: NotificationToken?
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
// Set results notification block
self.notificationToken = results.addNotificationBlock { (changes: RealmCollectionChange) in
switch changes {
case .initial:
// Results are now populated and can be accessed without blocking the UI
self.tableView.reloadData()
break
case .update(_, let deletions, let insertions, let modifications):
// Query results have changed, so apply them to the TableView
self.tableView.beginUpdates()
self.tableView.insertRows(at: insertions.map { IndexPath(row: $0, section: 0) }, with: .automatic)
self.tableView.deleteRows(at: deletions.map { IndexPath(row: $0, section: 0) }, with: .automatic)
self.tableView.reloadRows(at: modifications.map { IndexPath(row: $0, section: 0) }, with: .automatic)
self.tableView.endUpdates()
break
case .error(let err):
// An error occurred while opening the Realm file on the background worker thread
fatalError("\(err)")
break
}
}
}
// UI
func setupUI() {
tableView.register(Cell.self, forCellReuseIdentifier: "cell")
self.title = "TableView"
self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "BG Add", style: .plain,
target: self, action: #selector(backgroundAdd))
self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add,
target: self, action: #selector(add))
}
// Table view data source
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return results.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! Cell
let object = results[indexPath.row]
cell.textLabel?.text = object.title
cell.detailTextLabel?.text = object.date.description
return cell
}
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
realm.beginWrite()
realm.delete(results[indexPath.row])
try! realm.commitWrite()
}
}
// Actions
func backgroundAdd() {
// Import many items in a background thread
DispatchQueue.global().async {
// Get new realm and table since we are in a new thread
let realm = try! Realm()
realm.beginWrite()
for _ in 0..<5 {
// Add row via dictionary. Order is ignored.
realm.create(DemoObject.self, value: ["title": TableViewController.randomString(), "date": TableViewController.randomDate()])
}
try! realm.commitWrite()
}
}
func add() {
realm.beginWrite()
realm.create(DemoObject.self, value: [TableViewController.randomString(), TableViewController.randomDate()])
try! realm.commitWrite()
}
// Helpers
class func randomString() -> String {
return "Title \(arc4random())"
}
class func randomDate() -> NSDate {
return NSDate(timeIntervalSince1970: TimeInterval(arc4random()))
}
}
| mit | c203379c288b36f4af7d39b573f9302f | 35.398551 | 141 | 0.60442 | 5.259686 | false | false | false | false |
ello/ello-ios | Sources/Networking/ImageRegionData.swift | 1 | 1072 | ////
/// ImageRegionData.swift
//
struct ImageRegionData {
let image: UIImage
let data: Data?
let contentType: String?
let buyButtonURL: URL?
var isAnimatedGif: Bool { return contentType == "image/gif" }
init(image: UIImage, buyButtonURL: URL? = nil) {
self.image = image
self.data = nil
self.contentType = nil
self.buyButtonURL = buyButtonURL
}
init(image: UIImage, data: Data, contentType: String, buyButtonURL: URL? = nil) {
self.image = image
self.data = data
self.contentType = contentType
self.buyButtonURL = buyButtonURL
}
static func == (lhs: ImageRegionData, rhs: ImageRegionData) -> Bool {
guard lhs.image == rhs.image else { return false }
if let lhData = lhs.data, let rhData = rhs.data, let lhContentType = lhs.contentType,
let rhContentType = rhs.contentType
{
return lhData == rhData && lhContentType == rhContentType
}
return true
}
}
extension ImageRegionData: Equatable {}
| mit | 97e20ac021da66b0e3d06e9e34b01bb4 | 25.8 | 93 | 0.616604 | 4.253968 | false | false | false | false |
ello/ello-ios | Specs/Views/CategoryCardListViewSpec.swift | 1 | 6347 | ////
/// CategoryCardListViewSpec.swift
//
@testable import Ello
import Quick
import Nimble
class CategoryCardListViewSpec: QuickSpec {
class MockCategoryCardListDelegate: CategoryCardListDelegate {
var selectedIndex: Int?
var allCategoriesTappedCount = 0
var editCategoriesTappedCount = 0
var subscribedCategoriesTappedCount = 0
func categoryCardSelected(_ index: Int) {
selectedIndex = index
}
func allCategoriesTapped() {
allCategoriesTappedCount += 1
}
func editCategoriesTapped() {
editCategoriesTappedCount += 1
}
func subscribedCategoryTapped() {
subscribedCategoriesTappedCount += 1
}
}
override func spec() {
var subject: CategoryCardListView!
var delegate: MockCategoryCardListDelegate!
beforeEach {
subject = CategoryCardListView(
frame: CGRect(
origin: .zero,
size: CGSize(width: 320, height: CategoryCardListView.Size.height)
)
)
delegate = MockCategoryCardListDelegate()
subject.delegate = delegate
}
describe("CategoryCardListView") {
context("should have valid snapshot") {
it("when showing only categories") {
let infoA = CategoryCardListView.CategoryInfo(
title: "Art",
kind: .category,
imageURL: URL(string: "https://example.com")
)
let infoB = CategoryCardListView.CategoryInfo(
title: "Lorem ipsum dolor sit amet",
kind: .category,
imageURL: URL(string: "https://example.com")
)
subject.categoriesInfo = [infoA, infoB]
expectValidSnapshot(subject, named: "CategoryCardListView-categories")
}
it("when showing only categories with all and subscribed") {
let infoA = CategoryCardListView.CategoryInfo(
title: "Art",
kind: .category,
imageURL: URL(string: "https://example.com")
)
let infoB = CategoryCardListView.CategoryInfo(
title: "Lorem ipsum dolor sit amet",
kind: .category,
imageURL: URL(string: "https://example.com")
)
subject.categoriesInfo = [.all, .subscribed, infoA, infoB]
expectValidSnapshot(subject, named: "CategoryCardListView-all")
}
it("when showing zero state") {
subject.categoriesInfo = [.zeroState]
expectValidSnapshot(subject, named: "CategoryCardListView-zeroState")
}
}
describe("CategoryCardListDelegate") {
it("informs delegates of all category selection") {
let infoA = CategoryCardListView.CategoryInfo(
title: "Art",
kind: .category,
imageURL: URL(string: "https://example.com")
)
let infoB = CategoryCardListView.CategoryInfo(
title: "Lorem ipsum dolor sit amet",
kind: .category,
imageURL: URL(string: "https://example.com")
)
subject.categoriesInfo = [.all, .subscribed, infoA, infoB]
let buttons: [UIButton] = subject.findAllSubviews()
let button: UIButton! = buttons[0]
button.sendActions(for: .touchUpInside)
expect(delegate.allCategoriesTappedCount) == 1
}
it("informs delegates of subscribed category selection") {
let infoA = CategoryCardListView.CategoryInfo(
title: "Art",
kind: .category,
imageURL: URL(string: "https://example.com")
)
let infoB = CategoryCardListView.CategoryInfo(
title: "Lorem ipsum dolor sit amet",
kind: .category,
imageURL: URL(string: "https://example.com")
)
subject.categoriesInfo = [.all, .subscribed, infoA, infoB]
let buttons: [UIButton] = subject.findAllSubviews()
let button: UIButton! = buttons[1]
button.sendActions(for: .touchUpInside)
expect(delegate.subscribedCategoriesTappedCount) == 1
}
it("informs delegates of edit selection") {
subject.categoriesInfo = [.zeroState]
let buttons: [UIButton] = subject.findAllSubviews()
let button: UIButton! = buttons.first
button.sendActions(for: .touchUpInside)
expect(delegate.editCategoriesTappedCount) == 1
}
it("informs delegates of category selection") {
let infoA = CategoryCardListView.CategoryInfo(
title: "Art",
kind: .category,
imageURL: URL(string: "https://example.com")
)
let infoB = CategoryCardListView.CategoryInfo(
title: "Lorem ipsum dolor sit amet",
kind: .category,
imageURL: URL(string: "https://example.com")
)
let categoriesInfo = [infoA, infoB]
subject.categoriesInfo = [.all, .subscribed] + categoriesInfo
let buttons: [UIButton] = subject.findAllSubviews()
let button: UIButton! = buttons.last
button.sendActions(for: .touchUpInside)
expect(delegate.selectedIndex) == categoriesInfo.count - 1
}
}
}
}
}
| mit | af51cb581ebdddc044a54a126c44a1d4 | 39.948387 | 90 | 0.495037 | 6.277943 | false | false | false | false |
noais/ios-charts | Charts/Classes/Charts/RadarChartView.swift | 3 | 9377 | //
// RadarChartView.swift
// Charts
//
// Created by Daniel Cohen Gindi on 4/3/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
//
import Foundation
import CoreGraphics
import UIKit
/// Implementation of the RadarChart, a "spidernet"-like chart. It works best
/// when displaying 5-10 entries per DataSet.
public class RadarChartView: PieRadarChartViewBase
{
/// width of the web lines that come from the center.
public var webLineWidth = CGFloat(1.5)
/// width of the web lines that are in between the lines coming from the center
public var innerWebLineWidth = CGFloat(0.75)
/// color for the web lines that come from the center
public var webColor = UIColor(red: 122/255.0, green: 122/255.0, blue: 122.0/255.0, alpha: 1.0)
/// color for the web lines in between the lines that come from the center.
public var innerWebColor = UIColor(red: 122/255.0, green: 122/255.0, blue: 122.0/255.0, alpha: 1.0)
/// transparency the grid is drawn with (0.0 - 1.0)
public var webAlpha: CGFloat = 150.0 / 255.0
/// flag indicating if the web lines should be drawn or not
public var drawWeb = true
/// modulus that determines how many labels and web-lines are skipped before the next is drawn
private var _skipWebLineCount = 0
/// the object reprsenting the y-axis labels
private var _yAxis: ChartYAxis!
/// the object representing the x-axis labels
private var _xAxis: ChartXAxis!
internal var _yAxisRenderer: ChartYAxisRendererRadarChart!
internal var _xAxisRenderer: ChartXAxisRendererRadarChart!
public override init(frame: CGRect)
{
super.init(frame: frame)
}
public required init?(coder aDecoder: NSCoder)
{
super.init(coder: aDecoder)
}
internal override func initialize()
{
super.initialize()
_yAxis = ChartYAxis(position: .Left)
_xAxis = ChartXAxis()
_xAxis.spaceBetweenLabels = 0
renderer = RadarChartRenderer(chart: self, animator: _animator, viewPortHandler: _viewPortHandler)
_yAxisRenderer = ChartYAxisRendererRadarChart(viewPortHandler: _viewPortHandler, yAxis: _yAxis, chart: self)
_xAxisRenderer = ChartXAxisRendererRadarChart(viewPortHandler: _viewPortHandler, xAxis: _xAxis, chart: self)
}
internal override func calcMinMax()
{
super.calcMinMax()
let minLeft = _data.getYMin(.Left)
let maxLeft = _data.getYMax(.Left)
_chartXMax = Double(_data.xVals.count) - 1.0
_deltaX = CGFloat(abs(_chartXMax - _chartXMin))
let leftRange = CGFloat(abs(maxLeft - (_yAxis.isStartAtZeroEnabled ? 0.0 : minLeft)))
let topSpaceLeft = Double(leftRange * _yAxis.spaceTop)
let bottomSpaceLeft = Double(leftRange * _yAxis.spaceBottom)
// Consider sticking one of the edges of the axis to zero (0.0)
if _yAxis.isStartAtZeroEnabled
{
if minLeft < 0.0 && maxLeft < 0.0
{
// If the values are all negative, let's stay in the negative zone
_yAxis.axisMinimum = min(0.0, !isnan(_yAxis.customAxisMin) ? _yAxis.customAxisMin : (minLeft - bottomSpaceLeft))
_yAxis.axisMaximum = 0.0
}
else if minLeft >= 0.0
{
// We have positive values only, stay in the positive zone
_yAxis.axisMinimum = 0.0
_yAxis.axisMaximum = max(0.0, !isnan(_yAxis.customAxisMax) ? _yAxis.customAxisMax : (maxLeft + topSpaceLeft))
}
else
{
// Stick the minimum to 0.0 or less, and maximum to 0.0 or more (startAtZero for negative/positive at the same time)
_yAxis.axisMinimum = min(0.0, !isnan(_yAxis.customAxisMin) ? _yAxis.customAxisMin : (minLeft - bottomSpaceLeft))
_yAxis.axisMaximum = max(0.0, !isnan(_yAxis.customAxisMax) ? _yAxis.customAxisMax : (maxLeft + topSpaceLeft))
}
}
else
{
// Use the values as they are
_yAxis.axisMinimum = !isnan(_yAxis.customAxisMin) ? _yAxis.customAxisMin : (minLeft - bottomSpaceLeft)
_yAxis.axisMaximum = !isnan(_yAxis.customAxisMax) ? _yAxis.customAxisMax : (maxLeft + topSpaceLeft)
}
_chartXMax = Double(_data.xVals.count) - 1.0
_deltaX = CGFloat(abs(_chartXMax - _chartXMin))
_yAxis.axisRange = abs(_yAxis.axisMaximum - _yAxis.axisMinimum)
}
public override func getMarkerPosition(entry entry: ChartDataEntry, highlight: ChartHighlight) -> CGPoint
{
let angle = self.sliceAngle * CGFloat(entry.xIndex) + self.rotationAngle
let val = CGFloat(entry.value) * self.factor
let c = self.centerOffsets
let p = CGPoint(x: c.x + val * cos(angle * ChartUtils.Math.FDEG2RAD),
y: c.y + val * sin(angle * ChartUtils.Math.FDEG2RAD))
return p
}
public override func notifyDataSetChanged()
{
if _data === nil
{
return
}
calcMinMax()
_yAxis?._defaultValueFormatter = _defaultValueFormatter
_yAxisRenderer?.computeAxis(yMin: _yAxis.axisMinimum, yMax: _yAxis.axisMaximum)
_xAxisRenderer?.computeAxis(xValAverageLength: _data.xValAverageLength, xValues: _data.xVals)
if (_legend !== nil && !_legend.isLegendCustom)
{
_legendRenderer?.computeLegend(_data)
}
calculateOffsets()
setNeedsDisplay()
}
public override func drawRect(rect: CGRect)
{
super.drawRect(rect)
if _data === nil
{
return
}
let optionalContext = UIGraphicsGetCurrentContext()
guard let context = optionalContext else { return }
_xAxisRenderer?.renderAxisLabels(context: context)
if (drawWeb)
{
renderer!.drawExtras(context: context)
}
_yAxisRenderer.renderLimitLines(context: context)
renderer!.drawData(context: context)
if (valuesToHighlight())
{
renderer!.drawHighlighted(context: context, indices: _indicesToHighlight)
}
_yAxisRenderer.renderAxisLabels(context: context)
renderer!.drawValues(context: context)
_legendRenderer.renderLegend(context: context)
drawDescription(context: context)
drawMarkers(context: context)
}
/// - returns: the factor that is needed to transform values into pixels.
public var factor: CGFloat
{
let content = _viewPortHandler.contentRect
return min(content.width / 2.0, content.height / 2.0)
/ CGFloat(_yAxis.axisRange)
}
/// - returns: the angle that each slice in the radar chart occupies.
public var sliceAngle: CGFloat
{
return 360.0 / CGFloat(_data.xValCount)
}
public override func indexForAngle(angle: CGFloat) -> Int
{
// take the current angle of the chart into consideration
let a = ChartUtils.normalizedAngleFromAngle(angle - self.rotationAngle)
let sliceAngle = self.sliceAngle
for (var i = 0; i < _data.xValCount; i++)
{
if (sliceAngle * CGFloat(i + 1) - sliceAngle / 2.0 > a)
{
return i
}
}
return 0
}
/// - returns: the object that represents all y-labels of the RadarChart.
public var yAxis: ChartYAxis
{
return _yAxis
}
/// - returns: the object that represents all x-labels that are placed around the RadarChart.
public var xAxis: ChartXAxis
{
return _xAxis
}
/// Sets the number of web-lines that should be skipped on chart web before the next one is drawn. This targets the lines that come from the center of the RadarChart.
/// if count = 1 -> 1 line is skipped in between
public var skipWebLineCount: Int
{
get
{
return _skipWebLineCount
}
set
{
_skipWebLineCount = max(0, newValue)
}
}
internal override var requiredLegendOffset: CGFloat
{
return _legend.font.pointSize * 4.0
}
internal override var requiredBaseOffset: CGFloat
{
return _xAxis.isEnabled && _xAxis.isDrawLabelsEnabled ? _xAxis.labelRotatedWidth : 10.0
}
public override var radius: CGFloat
{
let content = _viewPortHandler.contentRect
return min(content.width / 2.0, content.height / 2.0)
}
/// - returns: the maximum value this chart can display on it's y-axis.
public override var chartYMax: Double { return _yAxis.axisMaximum; }
/// - returns: the minimum value this chart can display on it's y-axis.
public override var chartYMin: Double { return _yAxis.axisMinimum; }
/// - returns: the range of y-values this chart can display.
public var yRange: Double { return _yAxis.axisRange}
} | apache-2.0 | 32e97804af0fc7e4cf0303aac8280c52 | 32.021127 | 170 | 0.610536 | 4.740647 | false | false | false | false |
RabbitMC/inbox-replica | Inbox-Fake/Inbox-Fake/ExpandingCellTransition.swift | 1 | 9110 | import UIKit
private let kExpandingCellTransitionDuration: TimeInterval = 0.6
class ExpandingCellTransition: NSObject,
UIViewControllerAnimatedTransitioning,
UIViewControllerTransitioningDelegate
{
enum TransitionType {
case none
case presenting
case dismissing
}
enum TransitionState {
case initial
case final
}
var type: TransitionType = .none
var presentingController: UIViewController!
var presentedController: UIViewController!
var targetSnapshot: UIView!
var targetContainer: UIView!
var topRegionSnapshot: UIView!
var bottomRegionSnapshot: UIView!
var navigationBarSnapshot: UIView!
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return kExpandingCellTransitionDuration
}
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
let duration = transitionDuration(using: transitionContext)
let fromViewController = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from)!
let toViewController = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to)!
let containerView = transitionContext.containerView
var foregroundViewController = toViewController
var backgroundViewController = fromViewController
if type == .dismissing {
foregroundViewController = fromViewController
backgroundViewController = toViewController
}
// get target view
var targetViewController = backgroundViewController
if let navController = targetViewController as? UINavigationController {
targetViewController = navController.topViewController!
}
let targetViewMaybe = (targetViewController as? ExpandingTransitionPresentingViewController)?.expandingTransitionTargetViewForTransition(self)
assert(targetViewMaybe != nil, "Cannot find target view in background view controller")
let targetView = targetViewMaybe!
// setup animation
let targetFrame = backgroundViewController.view.convert(targetView.frame, from: targetView.superview)
if type == .presenting {
sliceSnapshotsInBackgroundViewController(backgroundViewController, targetFrame: targetFrame, targetView: targetView)
(foregroundViewController as? ExpandingTransitionPresentedViewController)?.expandingTransition(self, navigationBarSnapshot: navigationBarSnapshot)
} else {
navigationBarSnapshot.frame = containerView.convert(navigationBarSnapshot.frame, from: navigationBarSnapshot.superview)
}
targetContainer.addSubview(foregroundViewController.view)
containerView.addSubview(targetContainer)
containerView.addSubview(topRegionSnapshot)
containerView.addSubview(bottomRegionSnapshot)
containerView.addSubview(navigationBarSnapshot)
let width = backgroundViewController.view.bounds.width
let height = backgroundViewController.view.bounds.height
let preTransition: TransitionState = (type == .presenting ? .initial : .final)
let postTransition: TransitionState = (type == .presenting ? .final : .initial)
configureViewsToState(preTransition, width: width, height: height, targetFrame: targetFrame, fullFrame: foregroundViewController.view.frame, foregroundView: foregroundViewController.view)
// perform animation
backgroundViewController.view.isHidden = true
UIView.animate(withDuration: duration,
delay: 0,
usingSpringWithDamping: 1,
initialSpringVelocity: 0,
options: UIViewAnimationOptions(),
animations: { () -> Void in
self.configureViewsToState(postTransition, width: width, height: height, targetFrame: targetFrame, fullFrame: foregroundViewController.view.frame, foregroundView: foregroundViewController.view)
if self.type == .presenting {
self.navigationBarSnapshot.frame.size.height = 0
}
}, completion: {
(finished) in
self.targetContainer.removeFromSuperview()
self.topRegionSnapshot.removeFromSuperview()
self.bottomRegionSnapshot.removeFromSuperview()
self.navigationBarSnapshot.removeFromSuperview()
containerView.addSubview(foregroundViewController.view)
backgroundViewController.view.isHidden = false
transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
})
}
func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
presentingController = presenting
if let navController = presentingController as? UINavigationController {
presentingController = navController.topViewController
}
if presentingController is ExpandingTransitionPresentingViewController {
type = .presenting
return self
} else {
type = .none
return nil
}
}
func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
if presentingController is ExpandingTransitionPresentingViewController {
type = .dismissing
return self
} else {
type = .none
return nil
}
}
func sliceSnapshotsInBackgroundViewController(_ backgroundViewController: UIViewController, targetFrame: CGRect, targetView: UIView) {
let view = backgroundViewController.view
let width = view?.bounds.width
let height = view?.bounds.height
// create top region snapshot
topRegionSnapshot = view?.resizableSnapshotView(from: CGRect(x: 0, y: 0, width: width!, height: targetFrame.minY), afterScreenUpdates: false, withCapInsets: UIEdgeInsets.zero)
// create bottom region snapshot
bottomRegionSnapshot = view?.resizableSnapshotView(from: CGRect(x: 0, y: targetFrame.maxY, width: width!, height: height!-targetFrame.maxY), afterScreenUpdates: false, withCapInsets: UIEdgeInsets.zero)
// create target view snapshot
targetSnapshot = targetView.snapshotView(afterScreenUpdates: false)
targetContainer = UIView(frame: targetFrame)
targetContainer.backgroundColor = UIColor.white
targetContainer.clipsToBounds = true
targetContainer.addSubview(targetSnapshot)
// create navigation bar snapshot
if let navController = backgroundViewController as? UINavigationController {
let barHeight = navController.navigationBar.frame.maxY
UIGraphicsBeginImageContext(CGSize(width: width!, height: barHeight))
view?.drawHierarchy(in: (view?.bounds)!, afterScreenUpdates: false)
let navigationBarImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
navigationBarSnapshot = UIImageView(image: navigationBarImage)
navigationBarSnapshot.backgroundColor = navController.navigationBar.barTintColor
navigationBarSnapshot.contentMode = .bottom
}
}
func configureViewsToState(_ state: TransitionState, width: CGFloat, height: CGFloat, targetFrame: CGRect, fullFrame: CGRect, foregroundView: UIView) {
switch state {
case .initial:
topRegionSnapshot.frame = CGRect(x: 0, y: 0, width: width, height: targetFrame.minY)
bottomRegionSnapshot.frame = CGRect(x: 0, y: targetFrame.maxY, width: width, height: height-targetFrame.maxY)
targetContainer.frame = targetFrame
targetSnapshot.alpha = 1
foregroundView.alpha = 0
navigationBarSnapshot.sizeToFit()
case .final:
topRegionSnapshot.frame = CGRect(x: 0, y: -targetFrame.minY, width: width, height: targetFrame.minY)
bottomRegionSnapshot.frame = CGRect(x: 0, y: height, width: width, height: height-targetFrame.maxY)
targetContainer.frame = fullFrame
targetSnapshot.alpha = 0
foregroundView.alpha = 1
}
}
}
@objc
protocol ExpandingTransitionPresentingViewController {
func expandingTransitionTargetViewForTransition(_ transition: ExpandingCellTransition) -> UIView!
}
@objc
protocol ExpandingTransitionPresentedViewController {
func expandingTransition(_ transition: ExpandingCellTransition, navigationBarSnapshot: UIView)
}
| mit | 9bec78deb2961be4ab6696d28d2f3abb | 44.55 | 217 | 0.681229 | 6.639942 | false | false | false | false |
oasisweng/DWActionsMenu | DWActionsMenu/DWAction.swift | 1 | 850 | //
// DWAction.swift
// DWActionsMenu
//
// Created by Dingzhong Weng on 27/12/2014.
// Copyright (c) 2014 Dingzhong Weng. All rights reserved.
//
import Foundation
import UIKit
class DWAction: NSObject{
var selString:String = ""
var title:String?
var imageNamed:String?
var highlightedImageNamed:String?
override init(){
self.title = "?"
}
init(selString:String,title:String?,imageNamed:String?,highlightedImageNamed:String?) {
super.init()
self.selString = selString
if (title != nil) {
self.title = title
}
if (imageNamed != nil) {
self.imageNamed = imageNamed
}
if (highlightedImageNamed != nil){
self.highlightedImageNamed = highlightedImageNamed
}
}
} | mit | 8190e2fa8b82f63ca3271bc0f76b7327 | 20.275 | 91 | 0.577647 | 4.427083 | false | false | false | false |
sunsidew/SlideMenuControllerSwift | Source/SlideMenuController.swift | 1 | 35192 | //
// SlideMenuController.swift
//
// Created by Yuji Hato on 12/3/14.
//
import Foundation
import UIKit
public struct SlideMenuOptions {
public static var leftViewWidth: CGFloat = 270.0
public static var leftBezelWidth: CGFloat = 16.0
public static var contentViewScale: CGFloat = 0.96
public static var contentViewOpacity: CGFloat = 0.5
public static var shadowOpacity: CGFloat = 0.0
public static var shadowRadius: CGFloat = 0.0
public static var shadowOffset: CGSize = CGSizeMake(0,0)
public static var panFromBezel: Bool = true
public static var animationDuration: CGFloat = 0.4
public static var rightViewWidth: CGFloat = 270.0
public static var rightBezelWidth: CGFloat = 16.0
public static var rightPanFromBezel: Bool = true
public static var hideStatusBar: Bool = true
public static var pointOfNoReturnWidth: CGFloat = 44.0
public static var opacityViewBackgroundColor: UIColor = UIColor.blackColor()
}
public class SlideMenuController: UIViewController, UIGestureRecognizerDelegate {
public enum SlideAction {
case Open
case Close
}
public enum TrackAction {
case TapOpen
case TapClose
case FlickOpen
case FlickClose
}
struct PanInfo {
var action: SlideAction
var shouldBounce: Bool
var velocity: CGFloat
}
public var opacityView = UIView()
public var mainContainerView = UIView()
public var leftContainerView = UIView()
public var rightContainerView = UIView()
public var mainViewController: UIViewController?
public var leftViewController: UIViewController?
public var leftPanGesture: UIPanGestureRecognizer?
public var leftTapGetsture: UITapGestureRecognizer?
public var rightViewController: UIViewController?
public var rightPanGesture: UIPanGestureRecognizer?
public var rightTapGesture: UITapGestureRecognizer?
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
public override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
public convenience init(mainViewController: UIViewController, leftMenuViewController: UIViewController) {
self.init()
self.mainViewController = mainViewController
leftViewController = leftMenuViewController
initView()
}
public convenience init(mainViewController: UIViewController, rightMenuViewController: UIViewController) {
self.init()
self.mainViewController = mainViewController
rightViewController = rightMenuViewController
initView()
}
public convenience init(mainViewController: UIViewController, leftMenuViewController: UIViewController, rightMenuViewController: UIViewController) {
self.init()
self.mainViewController = mainViewController
leftViewController = leftMenuViewController
rightViewController = rightMenuViewController
initView()
}
deinit { }
func initView() {
mainContainerView = UIView(frame: view.bounds)
mainContainerView.backgroundColor = UIColor.clearColor()
mainContainerView.autoresizingMask = [.FlexibleHeight, .FlexibleWidth]
view.insertSubview(mainContainerView, atIndex: 0)
var opacityframe: CGRect = view.bounds
let opacityOffset: CGFloat = 0
opacityframe.origin.y = opacityframe.origin.y + opacityOffset
opacityframe.size.height = opacityframe.size.height - opacityOffset
opacityView = UIView(frame: opacityframe)
opacityView.backgroundColor = SlideMenuOptions.opacityViewBackgroundColor
opacityView.autoresizingMask = [UIViewAutoresizing.FlexibleHeight, UIViewAutoresizing.FlexibleWidth]
opacityView.layer.opacity = 0.0
view.insertSubview(opacityView, atIndex: 1)
var leftFrame: CGRect = view.bounds
leftFrame.size.width = SlideMenuOptions.leftViewWidth
leftFrame.origin.x = leftMinOrigin();
let leftOffset: CGFloat = 0
leftFrame.origin.y = leftFrame.origin.y + leftOffset
leftFrame.size.height = leftFrame.size.height - leftOffset
leftContainerView = UIView(frame: leftFrame)
leftContainerView.backgroundColor = UIColor.clearColor()
leftContainerView.autoresizingMask = UIViewAutoresizing.FlexibleHeight
view.insertSubview(leftContainerView, atIndex: 2)
var rightFrame: CGRect = view.bounds
rightFrame.size.width = SlideMenuOptions.rightViewWidth
rightFrame.origin.x = rightMinOrigin()
let rightOffset: CGFloat = 0
rightFrame.origin.y = rightFrame.origin.y + rightOffset;
rightFrame.size.height = rightFrame.size.height - rightOffset
rightContainerView = UIView(frame: rightFrame)
rightContainerView.backgroundColor = UIColor.clearColor()
rightContainerView.autoresizingMask = UIViewAutoresizing.FlexibleHeight
view.insertSubview(rightContainerView, atIndex: 3)
addLeftGestures()
addRightGestures()
}
public override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator)
mainContainerView.transform = CGAffineTransformMakeScale(1.0, 1.0)
leftContainerView.hidden = true
rightContainerView.hidden = true
coordinator.animateAlongsideTransition(nil, completion: { (context: UIViewControllerTransitionCoordinatorContext!) -> Void in
self.closeLeftNonAnimation()
self.closeRightNonAnimation()
self.leftContainerView.hidden = false
self.rightContainerView.hidden = false
if self.leftPanGesture != nil && self.leftPanGesture != nil {
self.removeLeftGestures()
self.addLeftGestures()
}
if self.rightPanGesture != nil && self.rightPanGesture != nil {
self.removeRightGestures()
self.addRightGestures()
}
})
}
public override func viewDidLoad() {
super.viewDidLoad()
edgesForExtendedLayout = UIRectEdge.None
}
public override func viewWillLayoutSubviews() {
// topLayoutGuideの値が確定するこのタイミングで各種ViewControllerをセットする
setUpViewController(mainContainerView, targetViewController: mainViewController)
setUpViewController(leftContainerView, targetViewController: leftViewController)
setUpViewController(rightContainerView, targetViewController: rightViewController)
}
public override func openLeft() {
setOpenWindowLevel()
//leftViewControllerのviewWillAppearを呼ぶため
leftViewController?.beginAppearanceTransition(isLeftHidden(), animated: true)
openLeftWithVelocity(0.0)
track(.TapOpen)
}
public override func openRight() {
setOpenWindowLevel()
//menuViewControllerのviewWillAppearを呼ぶため
rightViewController?.beginAppearanceTransition(isRightHidden(), animated: true)
openRightWithVelocity(0.0)
}
public override func closeLeft() {
leftViewController?.beginAppearanceTransition(isLeftHidden(), animated: true)
closeLeftWithVelocity(0.0)
setCloseWindowLebel()
}
public override func closeRight() {
rightViewController?.beginAppearanceTransition(isRightHidden(), animated: true)
closeRightWithVelocity(0.0)
setCloseWindowLebel()
}
public func addLeftGestures() {
if (leftViewController != nil) {
if leftPanGesture == nil {
leftPanGesture = UIPanGestureRecognizer(target: self, action: "handleLeftPanGesture:")
leftPanGesture!.delegate = self
view.addGestureRecognizer(leftPanGesture!)
}
if leftTapGetsture == nil {
leftTapGetsture = UITapGestureRecognizer(target: self, action: "toggleLeft")
leftTapGetsture!.delegate = self
view.addGestureRecognizer(leftTapGetsture!)
}
}
}
public func addRightGestures() {
if (rightViewController != nil) {
if rightPanGesture == nil {
rightPanGesture = UIPanGestureRecognizer(target: self, action: "handleRightPanGesture:")
rightPanGesture!.delegate = self
view.addGestureRecognizer(rightPanGesture!)
}
if rightTapGesture == nil {
rightTapGesture = UITapGestureRecognizer(target: self, action: "toggleRight")
rightTapGesture!.delegate = self
view.addGestureRecognizer(rightTapGesture!)
}
}
}
public func removeLeftGestures() {
if leftPanGesture != nil {
view.removeGestureRecognizer(leftPanGesture!)
leftPanGesture = nil
}
if leftTapGetsture != nil {
view.removeGestureRecognizer(leftTapGetsture!)
leftTapGetsture = nil
}
}
public func removeRightGestures() {
if rightPanGesture != nil {
view.removeGestureRecognizer(rightPanGesture!)
rightPanGesture = nil
}
if rightTapGesture != nil {
view.removeGestureRecognizer(rightTapGesture!)
rightTapGesture = nil
}
}
public func isTagetViewController() -> Bool {
// Function to determine the target ViewController
// Please to override it if necessary
return true
}
public func track(trackAction: TrackAction) {
// function is for tracking
// Please to override it if necessary
}
struct LeftPanState {
static var frameAtStartOfPan: CGRect = CGRectZero
static var startPointOfPan: CGPoint = CGPointZero
static var wasOpenAtStartOfPan: Bool = false
static var wasHiddenAtStartOfPan: Bool = false
}
func handleLeftPanGesture(panGesture: UIPanGestureRecognizer) {
if !isTagetViewController() {
return
}
if isRightOpen() {
return
}
switch panGesture.state {
case UIGestureRecognizerState.Began:
LeftPanState.frameAtStartOfPan = leftContainerView.frame
LeftPanState.startPointOfPan = panGesture.locationInView(view)
LeftPanState.wasOpenAtStartOfPan = isLeftOpen()
LeftPanState.wasHiddenAtStartOfPan = isLeftHidden()
leftViewController?.beginAppearanceTransition(LeftPanState.wasHiddenAtStartOfPan, animated: true)
addShadowToView(leftContainerView)
setOpenWindowLevel()
case UIGestureRecognizerState.Changed:
let translation: CGPoint = panGesture.translationInView(panGesture.view!)
leftContainerView.frame = applyLeftTranslation(translation, toFrame: LeftPanState.frameAtStartOfPan)
applyLeftOpacity()
applyLeftContentViewScale()
case UIGestureRecognizerState.Ended:
let velocity:CGPoint = panGesture.velocityInView(panGesture.view)
let panInfo: PanInfo = panLeftResultInfoForVelocity(velocity)
if panInfo.action == .Open {
if !LeftPanState.wasHiddenAtStartOfPan {
leftViewController?.beginAppearanceTransition(true, animated: true)
}
openLeftWithVelocity(panInfo.velocity)
track(.FlickOpen)
} else {
if LeftPanState.wasHiddenAtStartOfPan {
leftViewController?.beginAppearanceTransition(false, animated: true)
}
closeLeftWithVelocity(panInfo.velocity)
setCloseWindowLebel()
track(.FlickClose)
}
default:
break
}
}
struct RightPanState {
static var frameAtStartOfPan: CGRect = CGRectZero
static var startPointOfPan: CGPoint = CGPointZero
static var wasOpenAtStartOfPan: Bool = false
static var wasHiddenAtStartOfPan: Bool = false
}
func handleRightPanGesture(panGesture: UIPanGestureRecognizer) {
if !isTagetViewController() {
return
}
if isLeftOpen() {
return
}
switch panGesture.state {
case UIGestureRecognizerState.Began:
RightPanState.frameAtStartOfPan = rightContainerView.frame
RightPanState.startPointOfPan = panGesture.locationInView(view)
RightPanState.wasOpenAtStartOfPan = isRightOpen()
RightPanState.wasHiddenAtStartOfPan = isRightHidden()
rightViewController?.beginAppearanceTransition(RightPanState.wasHiddenAtStartOfPan, animated: true)
addShadowToView(rightContainerView)
setOpenWindowLevel()
case UIGestureRecognizerState.Changed:
let translation: CGPoint = panGesture.translationInView(panGesture.view!)
rightContainerView.frame = applyRightTranslation(translation, toFrame: RightPanState.frameAtStartOfPan)
applyRightOpacity()
applyRightContentViewScale()
case UIGestureRecognizerState.Ended:
let velocity: CGPoint = panGesture.velocityInView(panGesture.view)
let panInfo: PanInfo = panRightResultInfoForVelocity(velocity)
if panInfo.action == .Open {
if !RightPanState.wasHiddenAtStartOfPan {
rightViewController?.beginAppearanceTransition(true, animated: true)
}
openRightWithVelocity(panInfo.velocity)
} else {
if RightPanState.wasHiddenAtStartOfPan {
rightViewController?.beginAppearanceTransition(false, animated: true)
}
closeRightWithVelocity(panInfo.velocity)
setCloseWindowLebel()
}
default:
break
}
}
public func openLeftWithVelocity(velocity: CGFloat) {
let xOrigin: CGFloat = leftContainerView.frame.origin.x
let finalXOrigin: CGFloat = 0.0
var frame = leftContainerView.frame;
frame.origin.x = finalXOrigin;
var duration: NSTimeInterval = Double(SlideMenuOptions.animationDuration)
if velocity != 0.0 {
duration = Double(fabs(xOrigin - finalXOrigin) / velocity)
duration = Double(fmax(0.1, fmin(1.0, duration)))
}
addShadowToView(leftContainerView)
UIView.animateWithDuration(duration, delay: 0.0, options: UIViewAnimationOptions.CurveEaseInOut, animations: { [weak self]() -> Void in
if let strongSelf = self {
strongSelf.leftContainerView.frame = frame
strongSelf.opacityView.layer.opacity = Float(SlideMenuOptions.contentViewOpacity)
strongSelf.mainContainerView.transform = CGAffineTransformMakeScale(SlideMenuOptions.contentViewScale, SlideMenuOptions.contentViewScale)
}
}) { [weak self](Bool) -> Void in
if let strongSelf = self {
strongSelf.disableContentInteraction()
strongSelf.leftViewController?.endAppearanceTransition()
}
}
}
public func openRightWithVelocity(velocity: CGFloat) {
let xOrigin: CGFloat = rightContainerView.frame.origin.x
// CGFloat finalXOrigin = SlideMenuOptions.rightViewOverlapWidth;
let finalXOrigin: CGFloat = CGRectGetWidth(view.bounds) - rightContainerView.frame.size.width
var frame = rightContainerView.frame
frame.origin.x = finalXOrigin
var duration: NSTimeInterval = Double(SlideMenuOptions.animationDuration)
if velocity != 0.0 {
duration = Double(fabs(xOrigin - CGRectGetWidth(view.bounds)) / velocity)
duration = Double(fmax(0.1, fmin(1.0, duration)))
}
addShadowToView(rightContainerView)
UIView.animateWithDuration(duration, delay: 0.0, options: UIViewAnimationOptions.CurveEaseInOut, animations: { [weak self]() -> Void in
if let strongSelf = self {
strongSelf.rightContainerView.frame = frame
strongSelf.opacityView.layer.opacity = Float(SlideMenuOptions.contentViewOpacity)
strongSelf.mainContainerView.transform = CGAffineTransformMakeScale(SlideMenuOptions.contentViewScale, SlideMenuOptions.contentViewScale)
}
}) { [weak self](Bool) -> Void in
if let strongSelf = self {
strongSelf.disableContentInteraction()
strongSelf.rightViewController?.endAppearanceTransition()
}
}
}
public func closeLeftWithVelocity(velocity: CGFloat) {
let xOrigin: CGFloat = leftContainerView.frame.origin.x
let finalXOrigin: CGFloat = leftMinOrigin()
var frame: CGRect = leftContainerView.frame;
frame.origin.x = finalXOrigin
var duration: NSTimeInterval = Double(SlideMenuOptions.animationDuration)
if velocity != 0.0 {
duration = Double(fabs(xOrigin - finalXOrigin) / velocity)
duration = Double(fmax(0.1, fmin(1.0, duration)))
}
UIView.animateWithDuration(duration, delay: 0.0, options: UIViewAnimationOptions.CurveEaseInOut, animations: { [weak self]() -> Void in
if let strongSelf = self {
strongSelf.leftContainerView.frame = frame
strongSelf.opacityView.layer.opacity = 0.0
strongSelf.mainContainerView.transform = CGAffineTransformMakeScale(1.0, 1.0)
}
}) { [weak self](Bool) -> Void in
if let strongSelf = self {
strongSelf.removeShadow(strongSelf.leftContainerView)
strongSelf.enableContentInteraction()
strongSelf.leftViewController?.endAppearanceTransition()
}
}
}
public func closeRightWithVelocity(velocity: CGFloat) {
let xOrigin: CGFloat = rightContainerView.frame.origin.x
let finalXOrigin: CGFloat = CGRectGetWidth(view.bounds)
var frame: CGRect = rightContainerView.frame
frame.origin.x = finalXOrigin
var duration: NSTimeInterval = Double(SlideMenuOptions.animationDuration)
if velocity != 0.0 {
duration = Double(fabs(xOrigin - CGRectGetWidth(view.bounds)) / velocity)
duration = Double(fmax(0.1, fmin(1.0, duration)))
}
UIView.animateWithDuration(duration, delay: 0.0, options: UIViewAnimationOptions.CurveEaseInOut, animations: { [weak self]() -> Void in
if let strongSelf = self {
strongSelf.rightContainerView.frame = frame
strongSelf.opacityView.layer.opacity = 0.0
strongSelf.mainContainerView.transform = CGAffineTransformMakeScale(1.0, 1.0)
}
}) { [weak self](Bool) -> Void in
if let strongSelf = self {
strongSelf.removeShadow(strongSelf.rightContainerView)
strongSelf.enableContentInteraction()
strongSelf.rightViewController?.endAppearanceTransition()
}
}
}
public override func toggleLeft() {
if isLeftOpen() {
closeLeft()
setCloseWindowLebel()
// closeMenuはメニュータップ時にも呼ばれるため、closeタップのトラッキングはここに入れる
track(.TapClose)
} else {
openLeft()
}
}
public func isLeftOpen() -> Bool {
return leftContainerView.frame.origin.x == 0.0
}
public func isLeftHidden() -> Bool {
return leftContainerView.frame.origin.x <= leftMinOrigin()
}
public override func toggleRight() {
if isRightOpen() {
closeRight()
setCloseWindowLebel()
} else {
openRight()
}
}
public func isRightOpen() -> Bool {
return rightContainerView.frame.origin.x == CGRectGetWidth(view.bounds) - rightContainerView.frame.size.width
}
public func isRightHidden() -> Bool {
return rightContainerView.frame.origin.x >= CGRectGetWidth(view.bounds)
}
public func changeMainViewController(mainViewController: UIViewController, close: Bool) {
removeViewController(self.mainViewController)
self.mainViewController = mainViewController
setUpViewController(mainContainerView, targetViewController: mainViewController)
if (close) {
closeLeft()
closeRight()
}
}
public func changeLeftViewController(leftViewController: UIViewController, closeLeft:Bool) {
removeViewController(self.leftViewController)
self.leftViewController = leftViewController
setUpViewController(leftContainerView, targetViewController: leftViewController)
if closeLeft {
self.closeLeft()
}
}
public func changeRightViewController(rightViewController: UIViewController, closeRight:Bool) {
removeViewController(self.rightViewController)
self.rightViewController = rightViewController;
setUpViewController(rightContainerView, targetViewController: rightViewController)
if closeRight {
self.closeRight()
}
}
private func leftMinOrigin() -> CGFloat {
return -SlideMenuOptions.leftViewWidth
}
private func rightMinOrigin() -> CGFloat {
return CGRectGetWidth(view.bounds)
}
private func panLeftResultInfoForVelocity(velocity: CGPoint) -> PanInfo {
let thresholdVelocity: CGFloat = 1000.0
let pointOfNoReturn: CGFloat = CGFloat(floor(leftMinOrigin())) + SlideMenuOptions.pointOfNoReturnWidth
let leftOrigin: CGFloat = leftContainerView.frame.origin.x
var panInfo: PanInfo = PanInfo(action: .Close, shouldBounce: false, velocity: 0.0)
panInfo.action = leftOrigin <= pointOfNoReturn ? .Close : .Open;
if velocity.x >= thresholdVelocity {
panInfo.action = .Open
panInfo.velocity = velocity.x
} else if velocity.x <= (-1.0 * thresholdVelocity) {
panInfo.action = .Close
panInfo.velocity = velocity.x
}
return panInfo
}
private func panRightResultInfoForVelocity(velocity: CGPoint) -> PanInfo {
let thresholdVelocity: CGFloat = -1000.0
let pointOfNoReturn: CGFloat = CGFloat(floor(CGRectGetWidth(view.bounds)) - SlideMenuOptions.pointOfNoReturnWidth)
let rightOrigin: CGFloat = rightContainerView.frame.origin.x
var panInfo: PanInfo = PanInfo(action: .Close, shouldBounce: false, velocity: 0.0)
panInfo.action = rightOrigin >= pointOfNoReturn ? .Close : .Open
if velocity.x <= thresholdVelocity {
panInfo.action = .Open
panInfo.velocity = velocity.x
} else if (velocity.x >= (-1.0 * thresholdVelocity)) {
panInfo.action = .Close
panInfo.velocity = velocity.x
}
return panInfo
}
private func applyLeftTranslation(translation: CGPoint, toFrame:CGRect) -> CGRect {
var newOrigin: CGFloat = toFrame.origin.x
newOrigin += translation.x
let minOrigin: CGFloat = leftMinOrigin()
let maxOrigin: CGFloat = 0.0
var newFrame: CGRect = toFrame
if newOrigin < minOrigin {
newOrigin = minOrigin
} else if newOrigin > maxOrigin {
newOrigin = maxOrigin
}
newFrame.origin.x = newOrigin
return newFrame
}
private func applyRightTranslation(translation: CGPoint, toFrame: CGRect) -> CGRect {
var newOrigin: CGFloat = toFrame.origin.x
newOrigin += translation.x
let minOrigin: CGFloat = rightMinOrigin()
let maxOrigin: CGFloat = rightMinOrigin() - rightContainerView.frame.size.width
var newFrame: CGRect = toFrame
if newOrigin > minOrigin {
newOrigin = minOrigin
} else if newOrigin < maxOrigin {
newOrigin = maxOrigin
}
newFrame.origin.x = newOrigin
return newFrame
}
private func getOpenedLeftRatio() -> CGFloat {
let width: CGFloat = leftContainerView.frame.size.width
let currentPosition: CGFloat = leftContainerView.frame.origin.x - leftMinOrigin()
return currentPosition / width
}
private func getOpenedRightRatio() -> CGFloat {
let width: CGFloat = rightContainerView.frame.size.width
let currentPosition: CGFloat = rightContainerView.frame.origin.x
return -(currentPosition - CGRectGetWidth(view.bounds)) / width
}
private func applyLeftOpacity() {
let openedLeftRatio: CGFloat = getOpenedLeftRatio()
let opacity: CGFloat = SlideMenuOptions.contentViewOpacity * openedLeftRatio
opacityView.layer.opacity = Float(opacity)
}
private func applyRightOpacity() {
let openedRightRatio: CGFloat = getOpenedRightRatio()
let opacity: CGFloat = SlideMenuOptions.contentViewOpacity * openedRightRatio
opacityView.layer.opacity = Float(opacity)
}
private func applyLeftContentViewScale() {
let openedLeftRatio: CGFloat = getOpenedLeftRatio()
let scale: CGFloat = 1.0 - ((1.0 - SlideMenuOptions.contentViewScale) * openedLeftRatio);
mainContainerView.transform = CGAffineTransformMakeScale(scale, scale)
}
private func applyRightContentViewScale() {
let openedRightRatio: CGFloat = getOpenedRightRatio()
let scale: CGFloat = 1.0 - ((1.0 - SlideMenuOptions.contentViewScale) * openedRightRatio)
mainContainerView.transform = CGAffineTransformMakeScale(scale, scale)
}
private func addShadowToView(targetContainerView: UIView) {
targetContainerView.layer.masksToBounds = false
targetContainerView.layer.shadowOffset = SlideMenuOptions.shadowOffset
targetContainerView.layer.shadowOpacity = Float(SlideMenuOptions.shadowOpacity)
targetContainerView.layer.shadowRadius = SlideMenuOptions.shadowRadius
targetContainerView.layer.shadowPath = UIBezierPath(rect: targetContainerView.bounds).CGPath
}
private func removeShadow(targetContainerView: UIView) {
targetContainerView.layer.masksToBounds = true
mainContainerView.layer.opacity = 1.0
}
private func removeContentOpacity() {
opacityView.layer.opacity = 0.0
}
private func addContentOpacity() {
opacityView.layer.opacity = Float(SlideMenuOptions.contentViewOpacity)
}
private func disableContentInteraction() {
mainContainerView.userInteractionEnabled = false
}
private func enableContentInteraction() {
mainContainerView.userInteractionEnabled = true
}
private func setOpenWindowLevel() {
if (SlideMenuOptions.hideStatusBar) {
dispatch_async(dispatch_get_main_queue(), {
if let window = UIApplication.sharedApplication().keyWindow {
window.windowLevel = UIWindowLevelStatusBar + 1
}
})
}
}
private func setCloseWindowLebel() {
if (SlideMenuOptions.hideStatusBar) {
dispatch_async(dispatch_get_main_queue(), {
if let window = UIApplication.sharedApplication().keyWindow {
window.windowLevel = UIWindowLevelNormal
}
})
}
}
private func setUpViewController(targetView: UIView, targetViewController: UIViewController?) {
if let viewController = targetViewController {
addChildViewController(viewController)
viewController.view.frame = targetView.bounds
targetView.addSubview(viewController.view)
viewController.didMoveToParentViewController(self)
}
}
private func removeViewController(viewController: UIViewController?) {
if let _viewController = viewController {
_viewController.willMoveToParentViewController(nil)
_viewController.view.removeFromSuperview()
_viewController.removeFromParentViewController()
}
}
public func closeLeftNonAnimation(){
setCloseWindowLebel()
let finalXOrigin: CGFloat = leftMinOrigin()
var frame: CGRect = leftContainerView.frame;
frame.origin.x = finalXOrigin
leftContainerView.frame = frame
opacityView.layer.opacity = 0.0
mainContainerView.transform = CGAffineTransformMakeScale(1.0, 1.0)
removeShadow(leftContainerView)
enableContentInteraction()
}
public func closeRightNonAnimation(){
setCloseWindowLebel()
let finalXOrigin: CGFloat = CGRectGetWidth(view.bounds)
var frame: CGRect = rightContainerView.frame
frame.origin.x = finalXOrigin
rightContainerView.frame = frame
opacityView.layer.opacity = 0.0
mainContainerView.transform = CGAffineTransformMakeScale(1.0, 1.0)
removeShadow(rightContainerView)
enableContentInteraction()
}
//pragma mark – UIGestureRecognizerDelegate
public func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldReceiveTouch touch: UITouch) -> Bool {
let point: CGPoint = touch.locationInView(view)
if gestureRecognizer == leftPanGesture {
return slideLeftForGestureRecognizer(gestureRecognizer, point: point)
} else if gestureRecognizer == rightPanGesture {
return slideRightViewForGestureRecognizer(gestureRecognizer, withTouchPoint: point)
} else if gestureRecognizer == leftTapGetsture {
return isLeftOpen() && !isPointContainedWithinLeftRect(point)
} else if gestureRecognizer == rightTapGesture {
return isRightOpen() && !isPointContainedWithinRightRect(point)
}
return true
}
private func slideLeftForGestureRecognizer( gesture: UIGestureRecognizer, point:CGPoint) -> Bool{
return isLeftOpen() || SlideMenuOptions.panFromBezel && isLeftPointContainedWithinBezelRect(point)
}
private func isLeftPointContainedWithinBezelRect(point: CGPoint) -> Bool{
var leftBezelRect: CGRect = CGRectZero
var tempRect: CGRect = CGRectZero
let bezelWidth: CGFloat = SlideMenuOptions.leftBezelWidth
CGRectDivide(view.bounds, &leftBezelRect, &tempRect, bezelWidth, CGRectEdge.MinXEdge)
return CGRectContainsPoint(leftBezelRect, point)
}
private func isPointContainedWithinLeftRect(point: CGPoint) -> Bool {
return CGRectContainsPoint(leftContainerView.frame, point)
}
private func slideRightViewForGestureRecognizer(gesture: UIGestureRecognizer, withTouchPoint point: CGPoint) -> Bool {
return isRightOpen() || SlideMenuOptions.rightPanFromBezel && isRightPointContainedWithinBezelRect(point)
}
private func isRightPointContainedWithinBezelRect(point: CGPoint) -> Bool {
var rightBezelRect: CGRect = CGRectZero
var tempRect: CGRect = CGRectZero
let bezelWidth: CGFloat = CGRectGetWidth(view.bounds) - SlideMenuOptions.rightBezelWidth
CGRectDivide(view.bounds, &tempRect, &rightBezelRect, bezelWidth, CGRectEdge.MinXEdge)
return CGRectContainsPoint(rightBezelRect, point)
}
private func isPointContainedWithinRightRect(point: CGPoint) -> Bool {
return CGRectContainsPoint(rightContainerView.frame, point)
}
}
extension UIViewController {
public func slideMenuController() -> SlideMenuController? {
var viewController: UIViewController? = self
while viewController != nil {
if viewController is SlideMenuController {
return viewController as? SlideMenuController
}
viewController = viewController?.parentViewController
}
return nil;
}
public func addLeftBarButtonWithImage(buttonImage: UIImage) {
let leftButton: UIBarButtonItem = UIBarButtonItem(image: buttonImage, style: UIBarButtonItemStyle.Plain, target: self, action: "toggleLeft")
navigationItem.leftBarButtonItem = leftButton;
}
public func addRightBarButtonWithImage(buttonImage: UIImage) {
let rightButton: UIBarButtonItem = UIBarButtonItem(image: buttonImage, style: UIBarButtonItemStyle.Plain, target: self, action: "toggleRight")
navigationItem.rightBarButtonItem = rightButton;
}
public func toggleLeft() {
slideMenuController()?.toggleLeft()
}
public func toggleRight() {
slideMenuController()?.toggleRight()
}
public func openLeft() {
slideMenuController()?.openLeft()
}
public func openRight() {
slideMenuController()?.openRight() }
public func closeLeft() {
slideMenuController()?.closeLeft()
}
public func closeRight() {
slideMenuController()?.closeRight()
}
// Please specify if you want menu gesuture give priority to than targetScrollView
public func addPriorityToMenuGesuture(targetScrollView: UIScrollView) {
guard let slideController = slideMenuController(), let recognizers = slideController.view.gestureRecognizers else {
return
}
for recognizer in recognizers where recognizer is UIPanGestureRecognizer {
targetScrollView.panGestureRecognizer.requireGestureRecognizerToFail(recognizer)
}
}
}
| mit | 96ccacb289db4162db8ad874bab10740 | 37.389923 | 153 | 0.644165 | 6.230004 | false | false | false | false |
rsmoz/swift-corelibs-foundation | TestFoundation/TestNSSet.swift | 1 | 5311 | // This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
#if DEPLOYMENT_RUNTIME_OBJC || os(Linux)
import Foundation
import XCTest
#else
import SwiftFoundation
import SwiftXCTest
#endif
class TestNSSet : XCTestCase {
var allTests : [(String, () throws -> Void)] {
return [
("test_BasicConstruction", test_BasicConstruction),
("testInitWithSet", testInitWithSet),
("test_enumeration", test_enumeration),
("test_sequenceType", test_sequenceType),
("test_setOperations", test_setOperations),
("test_equality", test_equality),
("test_copying", test_copying),
("test_mutableCopying", test_mutableCopying),
]
}
func test_BasicConstruction() {
let set = NSSet()
let set2 = NSSet(array: ["foo", "bar"].bridge().bridge())
XCTAssertEqual(set.count, 0)
XCTAssertEqual(set2.count, 2)
}
func testInitWithSet() {
let genres: Set<NSObject> = ["Rock".bridge(), "Classical".bridge(), "Hip hop".bridge()]
let set1 = NSSet(set: genres)
let set2 = NSSet(set: genres, copyItems: false)
XCTAssertEqual(set1.count, 3)
XCTAssertEqual(set2.count, 3)
XCTAssertEqual(set1, set2)
let set3 = NSSet(set: genres, copyItems: true)
XCTAssertEqual(set3.count, 3)
XCTAssertEqual(set3, set2)
}
func test_enumeration() {
let set = NSSet(array: ["foo", "bar", "baz"].bridge().bridge())
let e = set.objectEnumerator()
var result = Set<String>()
result.insert((e.nextObject()! as! NSString).bridge())
result.insert((e.nextObject()! as! NSString).bridge())
result.insert((e.nextObject()! as! NSString).bridge())
XCTAssertEqual(result, Set(["foo", "bar", "baz"]))
let empty = NSSet().objectEnumerator()
XCTAssertNil(empty.nextObject())
XCTAssertNil(empty.nextObject())
}
func test_sequenceType() {
let set = NSSet(array: ["foo", "bar", "baz"].bridge().bridge())
var res = Set<String>()
for obj in set {
res.insert((obj as! NSString).bridge())
}
XCTAssertEqual(res, Set(["foo", "bar", "baz"]))
}
func test_setOperations() {
// TODO: This fails because hashValue and == use NSObject's implementaitons, which don't have the right semantics
// let set = NSMutableSet(array: ["foo", "bar"])
// set.unionSet(["bar", "baz"])
// XCTAssertTrue(set.isEqualToSet(["foo", "bar", "baz"]))
}
func test_equality() {
let inputArray1 = ["this", "is", "a", "test", "of", "equality", "with", "strings"].bridge()
let inputArray2 = ["this", "is", "a", "test", "of", "equality", "with", "objects"].bridge()
let set1 = NSSet(array: inputArray1.bridge())
let set2 = NSSet(array: inputArray1.bridge())
let set3 = NSSet(array: inputArray2.bridge())
XCTAssertTrue(set1 == set2)
XCTAssertTrue(set1.isEqual(set2))
XCTAssertTrue(set1.isEqualToSet(set2.bridge()))
XCTAssertEqual(set1.hash, set2.hash)
XCTAssertEqual(set1.hashValue, set2.hashValue)
XCTAssertFalse(set1 == set3)
XCTAssertFalse(set1.isEqual(set3))
XCTAssertFalse(set1.isEqualToSet(set3.bridge()))
XCTAssertFalse(set1.isEqual(nil))
XCTAssertFalse(set1.isEqual(NSObject()))
}
func test_copying() {
let inputArray = ["this", "is", "a", "test", "of", "copy", "with", "strings"].bridge()
let set = NSSet(array: inputArray.bridge())
let setCopy1 = set.copy() as! NSSet
XCTAssertTrue(set === setCopy1)
let setMutableCopy = set.mutableCopy() as! NSMutableSet
let setCopy2 = setMutableCopy.copy() as! NSSet
XCTAssertTrue(setCopy2.dynamicType === NSSet.self)
XCTAssertFalse(setMutableCopy === setCopy2)
for entry in setCopy2 {
XCTAssertTrue(setMutableCopy.allObjects.bridge().indexOfObjectIdenticalTo(entry) != NSNotFound)
}
}
func test_mutableCopying() {
let inputArray = ["this", "is", "a", "test", "of", "mutableCopy", "with", "strings"].bridge()
let set = NSSet(array: inputArray.bridge())
let setMutableCopy1 = set.mutableCopy() as! NSMutableSet
XCTAssertTrue(setMutableCopy1.dynamicType === NSMutableSet.self)
XCTAssertFalse(set === setMutableCopy1)
for entry in setMutableCopy1 {
XCTAssertTrue(set.allObjects.bridge().indexOfObjectIdenticalTo(entry) != NSNotFound)
}
let setMutableCopy2 = setMutableCopy1.mutableCopy() as! NSMutableSet
XCTAssertTrue(setMutableCopy2.dynamicType === NSMutableSet.self)
XCTAssertFalse(setMutableCopy2 === setMutableCopy1)
for entry in setMutableCopy2 {
XCTAssertTrue(setMutableCopy1.allObjects.bridge().indexOfObjectIdenticalTo(entry) != NSNotFound)
}
}
}
| apache-2.0 | b40cf8e9789d130210f23231c600162a | 36.13986 | 121 | 0.616268 | 4.314379 | false | true | false | false |
liulichao123/fangkuaishou | 快手/SwiftyJSON-master/Example/Example/AppDelegate.swift | 70 | 1960 | // SwiftyJSON.h
//
// Copyright (c) 2014 Pinglin Tang
//
// 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 SwiftyJSON
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
let navigationController = self.window?.rootViewController as! UINavigationController
let viewController = navigationController.topViewController as! ViewController
if let file = NSBundle(forClass:AppDelegate.self).pathForResource("SwiftyJSONTests", ofType: "json") {
let data = NSData(contentsOfFile: file)!
let json = JSON(data:data)
viewController.json = json
} else {
viewController.json = JSON.null
}
return true
}
}
| apache-2.0 | 1e68b68bab64a7fd7a836cfcd160181c | 40.702128 | 127 | 0.719388 | 4.912281 | false | false | false | false |
ReiVerdugo/uikit-fundamentals | PresentModally/PresentModally/ViewController.swift | 1 | 1084 | //
// ViewController.swift
// PresentModally
//
// Created by Reinaldo Verdugo on 4/10/16.
// Copyright © 2016 Reinaldo Verdugo. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBAction func experiment(_ sender: AnyObject) {
let viewC = UIImagePickerController()
self.present(viewC, animated: true, completion: nil)
}
@IBAction func showActivityView(_ sender: AnyObject) {
let controller = UIActivityViewController(activityItems: [UIImage()], applicationActivities: nil)
self.present(controller, animated: true, completion: nil)
}
@IBAction func showAlertView(_ sender: AnyObject) {
let controller = UIAlertController()
controller.title = "Alert view"
controller.message = "This is a test"
let okAction = UIAlertAction(title: "Ok", style: .default, handler: {action in self.dismiss(animated: true, completion: nil)})
controller.addAction(okAction)
self.present(controller, animated: true, completion: nil)
}
}
| mit | bbe730782c973d1a626e3626d0bcd4f9 | 29.083333 | 134 | 0.66759 | 4.588983 | false | false | false | false |
cocoascientist/Luna | LunaTests/LocalURLProtocol.swift | 1 | 1907 | //
// LocalURLProtocol.swift
// Luna
//
// Created by Andrew Shepard on 4/13/15.
// Copyright (c) 2015 Andrew Shepard. All rights reserved.
//
import Foundation
class LocalURLProtocol: URLProtocol {
override class func canInit(with request: URLRequest) -> Bool {
return true
}
override class func canonicalRequest(for request: URLRequest) -> URLRequest {
return request
}
override func startLoading() {
guard let client = self.client else { fatalError("Client is missing") }
guard let url = request.url else { fatalError("URL is missing") }
let data = self.dataForRequest(request)
let headers = ["Content-Type": "application/json"]
guard let response = HTTPURLResponse(url: url, statusCode: 200, httpVersion: "HTTP/1.1", headerFields: headers) else {
fatalError("Response could not be created")
}
client.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed)
client.urlProtocol(self, didLoad: data)
client.urlProtocolDidFinishLoading(self)
}
override func stopLoading() {
// all data return at once, nothing to do
}
private func dataForRequest(_ request: URLRequest) -> Data {
if let path = request.url?.path {
var json: String?
if path.range(of: "/sunmoon/moonphases/") != nil {
json = Bundle(for: type(of: self)).path(forResource: "moonphases", ofType: "json")
}
else if path.range(of: "/sunmoon/") != nil {
json = Bundle(for: type(of: self)).path(forResource: "sunmoon", ofType: "json")
}
if json != nil {
let data = try? Data(contentsOf: URL(fileURLWithPath: json!))
return data!
}
}
return Data()
}
}
| mit | 93332bdd717a4227685710b8ff67693f | 31.87931 | 126 | 0.585737 | 4.573141 | false | false | false | false |
lorentey/swift | benchmark/single-source/FloatingPointParsing.swift | 11 | 15433 | //===--- FloatingPointParsing.swift -----------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2019 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// This test verifies the performance of parsing a floating point value
// from a String.
import TestsUtils
public let FloatingPointParsing = [
BenchmarkInfo(
name: "ParseFloat.Float.Exp",
runFunction: run_ParseFloatExp,
tags: [.validation, .api, .runtime, .String]),
BenchmarkInfo(
name: "ParseFloat.Double.Exp",
runFunction: run_ParseDoubleExp,
tags: [.validation, .api, .runtime, .String]),
BenchmarkInfo(
name: "ParseFloat.Float80.Exp",
runFunction: run_ParseFloat80Exp,
tags: [.validation, .api, .runtime, .String]),
BenchmarkInfo(
name: "ParseFloat.Float.Uniform",
runFunction: run_ParseFloatUniform,
tags: [.validation, .api, .runtime, .String]),
BenchmarkInfo(
name: "ParseFloat.Double.Uniform",
runFunction: run_ParseDoubleUniform,
tags: [.validation, .api, .runtime, .String]),
BenchmarkInfo(
name: "ParseFloat.Float80.Uniform",
runFunction: run_ParseFloat80Uniform,
tags: [.validation, .api, .runtime, .String]),
]
/// The 'Exp' test:
/// Generates values following a truncated exponential distribution on 0...1000,
/// each rounded to a number of significant digits uniformly selected from
/// 1...6 (Float), 1...15 (Double) and 1...18 (Float80).
/// This is a good representative sample of "well-scaled" values humans actually
/// write in programs; in particular, it includes good coverage for integer values
/// and values with short decimal parts.
// func genExpDistributedFloat(significantDigits: Int) -> String {
// let value = exp(Float80.random(in: 0...log(1000.0)))
// return String(format: "%.\(significantDigits)f", Double(value))
// }
/// Each workload contains 100 elements generated from the above function.
let floatExpWorkload = [
"840.23812", "15.9082", "319.784", "13.14857", "5.42759",
"901.771", "339.6", "7.27", "126.88", "326.08923", "18.2804",
"189.8467", "330.628", "8.272461", "19.337", "12.0082",
"29.6085", "27.4508", "5.14013", "725.388972", "124.102",
"13.315556", "21.288", "45.4670", "88.7246", "6.16",
"1.506155", "2.16918", "779.120", "22.89751", "15.33395",
"59.575817", "2.73305", "203.04", "321.08", "148.419",
"249.675", "579.453", "222.2", "153.62548", "305.501",
"96.3", "28.55095", "145.377249", "2.53048", "1.0",
"293.2052", "2.1", "814.091552", "157.45375", "15.0",
"1.304", "8.88", "799.458180", "11.3", "1.5645",
"25.69062", "569.28", "2.6464", "173.792970", "6.25",
"344.54", "2.09610", "3.547", "409.860",
"65.866038", "3.64", "2.7", "62.304", "67.7729",
"19.0638", "2.8", "8.89508", "20.04", "1.054648",
"3.5479", "5.203191", "52.11968", "326.39", "43.027",
"82.15620", "178.519010", "1.3", "5.40", "387.41",
"500.5", "5.96", "1.7740", "96.48818", "889.583",
"96.92098", "6.760", "199.441", "510.905", "307.726",
"87.9055", "11.7", "6.487537", "119.1", "5.8"
]
let doubleExpWorkload = [
"339.91", "662.95264138", "590.3312546", "44.58449489426322", "1.61025794592574",
"266.29744353690", "34.14542", "144.968532801343116", "1.790721486700", "609.0086620368",
"1.79655054299720", "138.906589772754131", "1.3663343399933", "3.018134440821", "14.7117491216652",
"97.0", "28.630149748915", "5.4", "29.7639", "4.520193",
"43.574150740143", "21.26131766279", "8.332799002305356", "70.267", "792.71364",
"987.54396679201125", "301.4300850", "707.7375522552", "3.350899864", "41.99",
"78.051", "2.5251720", "28.171984464058", "6.115905648", "31.7",
"2.90316715974825", "3.49235954808", "13.76", "3.2", "32.465845",
"460.84828154", "1.0268532933", "79.607954332859777", "173.25041830", "49.0888",
"23.2264", "130.018100263319411", "301.8", "1.707", "2.220651",
"11.9744168", "13.50610", "83.276270711070708", "1.207", "11.507359",
"887.81742700364475", "46.8051834077896", "174.367548608815781", "19.8671230", "5.0432",
"3.927758869", "1.6393532610", "232.5", "17.77417107", "94.1453702714822",
"746.2908548477199", "28.9832376533851", "1.7432454399", "96.15", "484.00318952955",
"14.90238658606421", "243.704906310113", "29.5307828313724", "19.200405681021813", "24.1717308",
"2.7453085963749", "2.856", "677.940804020", "221.57146165", "31.5891",
"350.74206", "3.06588790579", "171.404", "46.106851", "590.3917781324",
"829.052362588", "2.32566173", "7.0098461186", "306.11702882946065", "17.4345632593715",
"899.3720935006996", "108.31212", "3.703786329", "48.81100281168", "27.41503",
"169.15383", "1.978568", "3.68994208914", "29.4322212731893", "4.8719352"
]
let float80ExpWorkload = [
"6.77555058241", "147.74", "6.03", "507.6033533228630859", "100.7",
"11.46", "3.264282911002", "85.7858847516568", "34.4300032", "4.9957",
"198.3958760", "87.67549428326", "205.373035358974988", "27.93", "831.999235134615",
"46.886425395152", "5.77789", "89.564807063568139256", "3.85398054", "1.021",
"592.504", "1.802084399", "486.4972328197284", "5.22490700277", "29.917340694598",
"181.48302719", "75.74373681671689", "30.48161373580532", "1.24544077730", "1.2",
"10.426", "55.37308819", "1.87502584", "3.1486", "9.2794677633",
"24.59858334079387632", "20.2896643", "4.6", "9.017375215972097", "163.1",
"5.50921892286", "9.93079", "13.320762298", "3.194056167117689693", "211.6671712762052380",
"347.0356", "209.66", "13.170751077618", "34.568", "330.5",
"41.388619513", "625.5176", "7.3199072376", "2.40", "334.210711370",
"10.790469414612726240", "2.051865559526", "374.34104357856199", "1.444672057", "182.15138835680261",
"1.549898719", "2.2", "3.5960392119", "220.3919", "128.45273",
"955.052925", "441.738166", "21.365", "28.5534801613", "124.1",
"449.252220495138", "608.587461250119532", "107.88473705800", "2.085422", "2.5",
"121.0005042322", "5.4402224803576962", "90.46", "40.646406742621564945", "70.79133",
"4.59801271236", "1.893481804014", "17.52333", "1.3195086968", "46.70781",
"14.59891931096853", "402.75", "158.0343", "7.152603207", "7.3637945245",
"15.6", "545.740720800777012", "242.172569", "1.73940415531105", "151.14631658",
"26.5256384449273490", "135.236", "12.886101", "47.596174", "1.831407510"
]
/// The 'Uniform' test:
/// Generates values made up of uniform decimal significands with 9, 17 and 21
/// digits and exponents uniform on the valid range. This is a stress test
/// for rounding, and covers all the worst cases for tables generated by programs.
/// The exponent range is -45...38 for Floats, -324...308 for Doubles, and
/// -4951...4932 for Float80.
// func genUniformFloat(significandDigits: Int, exponentRange: ClosedRange<Int>) -> String {
// let afterDecimalPoint = (0..<significandDigits).map { _ in String(Int.random(in: 0...9)) }.joined()
// let sign = ["", "-", "+"].randomElement()!
// return "\(sign)\(Int.random(in: 1...9)).\(afterDecimalPoint)e\(exponentRange.randomElement()!)"
// }
/// Each workload contains 100 elements generated from the above function,
/// along with five inf/nan/invalid tests.
let floatUniformWorkload = [
"+1.253892113e-32", "+5.834995733e-41", "5.262096122e-17", "+4.917053817e-37", "8.535406338e-34",
"2.152837278e10", "-5.212739043e-16", "+9.799669278e-27", "+8.678995824e-6", "-5.965172043e26",
"-8.420371743e-10", "1.968856825e-8", "1.521071839e-19", "+1.048728457e-15", "-5.657219736e10",
"-7.664702071e-34", "+3.282753652e15", "-5.032906928e26", "-3.024685077e29", "+7.972511327e-22",
"-3.941547478e-19", "-2.424139629e4", "+1.222228289e2", "+9.872675983e4", "+8.505353502e-43",
"7.315998745e12", "-2.879924852e-38", "5.567658036e21", "5.751274848e-39", "-2.098314138e8",
"-2.295512125e-13", "-9.261977483e3", "-7.717209557e26", "+6.563403126e38", "-6.988491389e-45",
"3.318738022e21", "5.534799334e16", "7.236228752e0", "+6.134225015e-26", "-1.801539431e-3",
"-8.763001980e37", "-4.810306387e-30", "-8.902359860e5", "-4.654434339e17", "4.103749478e11",
"+1.624005001e0", "+6.810516979e-8", "+4.509584369e0", "7.115062319e15", "-3.275835669e24",
"-2.225975117e17", "+9.765601399e-27", "9.271660327e13", "-7.957489335e4", "+1.279815043e-30",
"-6.140235958e-3", "+2.925804509e-11", "-2.902478935e-36", "+2.870673595e-37", "+8.788759496e-20",
"+7.279719040e13", "-9.516217056e20", "2.306171183e21", "-2.655002939e22", "-8.678845371e32",
"6.086700440e20", "+6.768130785e12", "1.675300343e11", "+8.156722194e-16", "-6.040145895e35",
"-6.928961416e-26", "-5.119323586e27", "-4.566748978e-5", "-3.394147506e-7", "6.171944831e-19",
"+8.883811091e-11", "-3.390953266e-44", "-1.912771939e-7", "+8.506344503e-23", "-3.437927939e21",
"-3.515331652e1", "8.610555796e9", "2.340195107e-20", "+9.018470750e-42", "+8.321248518e27",
"-6.959418594e32", "-5.342372027e21", "+2.744186726e-24", "9.948785682e-37", "+6.310898794e-6",
"-2.477472268e16", "8.590689853e1", "+7.811554461e-24", "+1.508151084e17", "3.071428780e-7",
"4.545415458e-9", "7.075010280e11", "+8.616159616e-29", "4.613265893e-10", "7.770003218e-33",
"+inf", "Invalid", "nan", "NAN", "snan"
]
let doubleUniformWorkload = [
"-5.099347166e-78", "3.584151187e-255", "-7.555973282e17", "+6.217083912e-164", "-6.063585254e8",
"-5.374097872e-252", "2.688487062e208", "+1.030241589e-272", "2.120162986e-50", "-2.617585299e-69",
"8.560348373e282", "4.323584117e-168", "5.899559411e215", "+3.630548207e220", "-8.420738030e-73",
"-6.832994185e-129", "-9.751163985e90", "-3.923652856e222", "-5.337925604e-12", "+4.360166940e-75",
"+6.207675792e-164", "-8.275068142e-195", "+3.318047866e-71", "-9.162983038e197", "+9.330784575e-147",
"9.208831616e-322", "-5.688921689e270", "+2.871328480e-258", "-8.071161900e261", "-4.191368176e222",
"+5.792498976e-167", "5.835667380e235", "+9.402094050e6", "2.079961640e180", "+4.037655106e86",
"-1.267141442e106", "+2.361395667e138", "+2.101128051e142", "5.301258292e42", "-8.822348131e-280",
"-3.775817054e208", "-5.080405399e93", "+9.686534601e-77", "4.586641905e-175", "3.135576124e77",
"4.688137331e138", "+6.893752397e-189", "6.812711913e278", "3.812796443e115", "+3.744289703e7",
"+5.932500106e157", "+4.846313692e16", "-8.881077959e-290", "+1.535288334e-275", "7.250519901e-75",
"2.787321374e41", "+3.519991812e-183", "+7.589975072e79", "5.848655303e122", "-3.328972789e161",
"-2.190752323e104", "8.864042297e147", "+8.584292050e-239", "-7.972816817e219", "9.352363266e-99",
"+9.435082870e83", "+4.297178676e-122", "+8.699490866e-300", "+5.562137865e-57", "+9.063928579e-92",
"2.743744209e82", "+9.960619645e-39", "-1.962409303e90", "-4.371512402e-287", "4.790326011e-137",
"+1.295921853e-273", "9.137852847e-96", "2.934099551e35", "-8.176544555e-65", "-7.098452895e-220",
"+6.665950037e103", "+9.297850239e-254", "-8.529931750e-216", "-9.541329616e-324", "-4.761545594e148",
"3.507981964e-314", "-3.745430665e-89", "8.799599593e137", "8.736852803e181", "+8.328604940e291",
"-2.207530122e-202", "-4.259268955e-271", "+1.633874531e-225", "+6.167040542e211", "-2.632062534e-52",
"-2.296105107e69", "4.935681094e205", "+4.696549581e-117", "+5.032486364e-105", "6.718199716e48",
"-inf", "Invalid", "nan", "NAN", "snan"
]
let float80UniformWorkload = [
"-4.252484660e-718", "+7.789429046e-2371", "-2.914666745e-2986", "8.287524889e4854", "+4.792668657e-3693",
"-5.187192176e-756", "+2.452045856e-2309", "+7.133017664e-1055", "-6.749416450e-3803", "+6.808813002e-1771",
"+7.355881301e3600", "-9.209599679e4848", "+4.142753329e-3268", "3.950199398e-863", "-3.170838470e-4779",
"9.354087375e718", "2.769339314e-3567", "+1.889983496e3717", "+9.912545495e-2419", "-6.284830753e2041",
"+9.061812480e3682", "6.551587084e1912", "+6.485690673e-1591", "-3.522511676e-2344", "-6.846303741e-2830",
"-7.995042826e896", "6.268882688e937", "-3.776199447e-4134", "-2.353057456e801", "5.875638854e-3889",
"1.245553459e814", "4.593376472e-2139", "-8.277421726e1497", "+1.606488487e1221", "6.433878090e-2220",
"-2.515502287e2543", "-4.347251565e-1330", "1.101969004e-4525", "-7.602718782e-4037", "-7.289917475e-4547",
"+1.920523398e2160", "-8.279745071e4493", "+6.383586105e-3771", "-3.784311609e-1828", "-1.193395125e1296",
"-2.012225848e1954", "+2.238968379e-1455", "6.331805949e-2127", "-7.584066626e-717", "-9.040205012e1614",
"+1.953864302e4255", "+5.103307458e528", "9.491061048e531", "+2.165292603e54", "-6.471469370e654",
"-9.275772875e4856", "-4.070772582e1488", "+2.063335882e-2112", "+4.853853159e-3841", "-9.058842001e3955",
"2.897215261e3511", "1.389094534e-384", "-9.749518987e1602", "+3.103609399e-3559", "-7.156672429e3879",
"9.385923023e2310", "7.593508637e-2100", "-2.656332678e2833", "6.143253335e-340", "5.794793573e2972",
"3.869110366e2609", "+2.884288161e-1513", "-5.316488863e4336", "4.948197725e-3829", "3.755250612e-3011",
"+1.550352355e-767", "-1.625440305e-4354", "+3.086601758e-929", "6.042347288e-357", "-6.176954358e3288",
"1.594019881e480", "-8.613112966e4863", "+9.864076072e2498", "3.540199292e-821", "+3.770221960e4915",
"-4.115310178e-3958", "-8.343495037e-4238", "1.165941010e-317", "6.039736339e-693", "6.912425733e1200",
"-9.307038635e335", "-4.656175810e-637", "-6.342156592e-3848", "-1.221105578e1780", "+6.097066301e-2159",
"-5.823123345e1389", "+5.404800369e1379", "2.988649766e-736", "-3.733572715e2405", "-1.597565079e-377",
"+inf", "Invalid", "nan", "NAN", "snan"
]
@inline(__always)
public func parseFloatWorkload<T : LosslessStringConvertible>(_ N: Int, workload: [String], type: T.Type) {
for _ in 0..<N {
for element in workload {
let f = T(element)
blackHole(f)
}
}
}
@inline(never)
public func run_ParseFloatExp(_ N: Int) {
parseFloatWorkload(N, workload: floatExpWorkload, type: Float.self)
}
@inline(never)
public func run_ParseDoubleExp(_ N: Int) {
parseFloatWorkload(N, workload: doubleExpWorkload, type: Double.self)
}
@inline(never)
public func run_ParseFloat80Exp(_ N: Int) {
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) || os(Linux)
// On Darwin, long double is Float80 on x86, and Double otherwise.
// On Linux, Float80 is at aleast available on x86.
#if arch(x86_64) || arch(i386)
parseFloatWorkload(N, workload: float80ExpWorkload, type: Float80.self)
#endif // x86
#endif // Darwin/Linux
}
@inline(never)
public func run_ParseFloatUniform(_ N: Int) {
parseFloatWorkload(N, workload: floatUniformWorkload, type: Float.self)
}
@inline(never)
public func run_ParseDoubleUniform(_ N: Int) {
parseFloatWorkload(N, workload: doubleUniformWorkload, type: Double.self)
}
@inline(never)
public func run_ParseFloat80Uniform(_ N: Int) {
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) || os(Linux)
// On Darwin, long double is Float80 on x86, and Double otherwise.
// On Linux, Float80 is at aleast available on x86.
#if arch(x86_64) || arch(i386)
parseFloatWorkload(N, workload: float80UniformWorkload, type: Float80.self)
#endif // x86
#endif // Darwin/Linux
}
| apache-2.0 | 102b2445a167377c10e4aa81680d262e | 55.531136 | 111 | 0.657422 | 2.357623 | false | false | false | false |
alblue/swift | stdlib/public/core/NewtypeWrapper.swift | 2 | 5341 | //===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
/// An implementation detail used to implement support importing
/// (Objective-)C entities marked with the swift_newtype Clang
/// attribute.
public protocol _SwiftNewtypeWrapper
: RawRepresentable, _HasCustomAnyHashableRepresentation { }
extension _SwiftNewtypeWrapper where Self: Hashable, Self.RawValue: Hashable {
/// The hash value.
@inlinable
public var hashValue: Int {
return rawValue.hashValue
}
/// Hashes the essential components of this value by feeding them into the
/// given hasher.
///
/// - Parameter hasher: The hasher to use when combining the components
/// of this instance.
@inlinable
public func hash(into hasher: inout Hasher) {
hasher.combine(rawValue)
}
@inlinable // FIXME(sil-serialize-all)
public func _rawHashValue(seed: Int) -> Int {
return rawValue._rawHashValue(seed: seed)
}
}
extension _SwiftNewtypeWrapper {
public __consuming func _toCustomAnyHashable() -> AnyHashable? {
return nil
}
}
extension _SwiftNewtypeWrapper where Self: Hashable, Self.RawValue: Hashable {
public __consuming func _toCustomAnyHashable() -> AnyHashable? {
return AnyHashable(_box: _NewtypeWrapperAnyHashableBox(self))
}
}
internal struct _NewtypeWrapperAnyHashableBox<Base>: _AnyHashableBox
where Base: _SwiftNewtypeWrapper & Hashable, Base.RawValue: Hashable {
var _value: Base
init(_ value: Base) {
self._value = value
}
var _canonicalBox: _AnyHashableBox {
return (_value.rawValue as AnyHashable)._box._canonicalBox
}
func _isEqual(to other: _AnyHashableBox) -> Bool? {
_preconditionFailure("_isEqual called on non-canonical AnyHashable box")
}
var _hashValue: Int {
_preconditionFailure("_hashValue called on non-canonical AnyHashable box")
}
func _hash(into hasher: inout Hasher) {
_preconditionFailure("_hash(into:) called on non-canonical AnyHashable box")
}
func _rawHashValue(_seed: Int) -> Int {
_preconditionFailure("_rawHashValue(_seed:) called on non-canonical AnyHashable box")
}
var _base: Any { return _value }
func _unbox<T: Hashable>() -> T? {
return _value as? T ?? _value.rawValue as? T
}
func _downCastConditional<T>(into result: UnsafeMutablePointer<T>) -> Bool {
if let value = _value as? T {
result.initialize(to: value)
return true
}
if let value = _value.rawValue as? T {
result.initialize(to: value)
return true
}
return false
}
}
#if _runtime(_ObjC)
extension _SwiftNewtypeWrapper where Self.RawValue : _ObjectiveCBridgeable {
// Note: This is the only default typealias for _ObjectiveCType, because
// constrained extensions aren't allowed to define types in different ways.
// Fortunately the others don't need it.
public typealias _ObjectiveCType = Self.RawValue._ObjectiveCType
@inlinable // FIXME(sil-serialize-all)
public func _bridgeToObjectiveC() -> Self.RawValue._ObjectiveCType {
return rawValue._bridgeToObjectiveC()
}
@inlinable // FIXME(sil-serialize-all)
public static func _forceBridgeFromObjectiveC(
_ source: Self.RawValue._ObjectiveCType,
result: inout Self?
) {
var innerResult: Self.RawValue?
Self.RawValue._forceBridgeFromObjectiveC(source, result: &innerResult)
result = innerResult.flatMap { Self(rawValue: $0) }
}
@inlinable // FIXME(sil-serialize-all)
public static func _conditionallyBridgeFromObjectiveC(
_ source: Self.RawValue._ObjectiveCType,
result: inout Self?
) -> Bool {
var innerResult: Self.RawValue?
let success = Self.RawValue._conditionallyBridgeFromObjectiveC(
source,
result: &innerResult)
result = innerResult.flatMap { Self(rawValue: $0) }
return success
}
@inlinable // FIXME(sil-serialize-all)
@_effects(readonly)
public static func _unconditionallyBridgeFromObjectiveC(
_ source: Self.RawValue._ObjectiveCType?
) -> Self {
return Self(
rawValue: Self.RawValue._unconditionallyBridgeFromObjectiveC(source))!
}
}
extension _SwiftNewtypeWrapper where Self.RawValue: AnyObject {
@inlinable // FIXME(sil-serialize-all)
public func _bridgeToObjectiveC() -> Self.RawValue {
return rawValue
}
@inlinable // FIXME(sil-serialize-all)
public static func _forceBridgeFromObjectiveC(
_ source: Self.RawValue,
result: inout Self?
) {
result = Self(rawValue: source)
}
@inlinable // FIXME(sil-serialize-all)
public static func _conditionallyBridgeFromObjectiveC(
_ source: Self.RawValue,
result: inout Self?
) -> Bool {
result = Self(rawValue: source)
return result != nil
}
@inlinable // FIXME(sil-serialize-all)
@_effects(readonly)
public static func _unconditionallyBridgeFromObjectiveC(
_ source: Self.RawValue?
) -> Self {
return Self(rawValue: source!)!
}
}
#endif
| apache-2.0 | 1517ddfeb1cd05e40e5441a9ea51ea7c | 29.175141 | 89 | 0.686014 | 4.568862 | false | false | false | false |
ilyapuchka/SwiftFeatures | SwiftFeatures.playground/Contents.swift | 1 | 4540 | //: ## Swift interesting features
//:
//: or What Swift Language Guide do not tell you.
//:
//: This playground contains interesting features of Swift that I find while using it. The list is intended to be updated in future.
//:
//: ----
//:
//: ### **Var in for-in loop**
//: If you have an array of reference type objects you can mutate them in a loop just by adding var before loop variable. This will work only for reference types as value types are copied on assignment and so the items in array will be not modified. If you have value types though you will be able to modify loop variable inside the loop. It will work pretty much like mutable function arguments.
class Box {
var value: Int
init(_ value:Int) {
self.value = value
}
}
var objectsArray = [Box(1), Box(2), Box(3)]
for (var item) in objectsArray {
++item.value
}
objectsArray
var valuesArray = [1, 2, 3]
for (var valueItem) in valuesArray {
++valueItem
}
valuesArray
//: ### **Property observers for local variables**
//: This does not work in plyagrounds but give it a try in a real project and you will see "Will set 1" and "Did set 1":
func method() {
var some: Int = 0 {
willSet {
print("Will set \(newValue)")
}
didSet {
print("Did set \(some)")
}
}
some = 1
}
method()
//: ### **~= operator**
//: This is an expression matching operator. This is what switch statement uses for pattern matching. Outside switch you can use it i.e to find out if Range contains value.
let some = 1
if 0...5 ~= some {
print("\(some) is between 0 and 5")
}
//: You can even override this operator like any other to crate some crazy things. Here are the [docs](https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Patterns.html#//apple_ref/doc/uid/TP40014097-CH36-XID_909) for that operator.
typealias Age = UInt
enum Gender {
case Male
case Female
}
class Person {
var name: String
var age: Age
var gender: Gender
init(_ name: String, age: Age, gender: Gender) {
self.name = name
self.age = age
self.gender = gender
}
}
func ==(lhs: Person, rhs: Person) -> Bool {
return lhs.name == rhs.name && lhs.age == rhs.age && lhs.gender == rhs.gender
}
let Ilya = Person("Ilya", age: 28, gender: .Male)
let Marina = Person("Marina", age: 27, gender: .Female)
let me = Ilya
func ~=(pattern: Person, value: Person) -> Bool {
return pattern == value
}
switch me {
case Ilya:
print("Hi, man!")
case Marina:
print("Hi, gorgeous!")
default: break
}
func ~=(pattern:Range<Age>, value: Person) -> Bool {
return pattern ~= value.age
}
switch me {
case 0...18:
print("You are too young for that")
case 18..<UInt.max:
print("Do what ever you want")
default: break
}
//: Unfortunatelly complier will not let you to match your class against tuple or enum, which would be cool. But you can still use ~= directly if you define it with tuple or enum as a pattern to match. To make it better swap right and left hand statements. This can be fun but I don't see very good usecases for that.
func ~=(pattern: Person, value: Gender) -> Bool {
return pattern.gender == value
}
switch me {
case _ where me ~= .Male:
print("Hi, man!")
case _ where me ~= .Female:
print("Hi, gorgeous!")
default: break
}
//: ### **Curried functions**
//: Instance methods in Swift are actually curried functions. You can store it in variable and apply to different instances. Checkout [this post](http://oleb.net/blog/2014/07/swift-instance-methods-curried-functions/) by Ole Begemann for one of use cases for that feature.
extension Person {
func growOlder(years: Age) {
self.age += years
}
}
let growOlder = Person.growOlder
growOlder(Ilya)(5)
Ilya
growOlder(Marina)(5)
Marina
//: ### **Subscript with multiple parameters (by [AirspeedVelocity](https://twitter.com/AirspeedSwift/status/626701244455895044))**
//: Did you know that you can provide more that one paramtere to subscript? Also ++ will not just change returned value but will also write it back to that subscript. It's possible because subscript parameters are inout.
extension Dictionary {
subscript(key: Key, or or: Value) -> Value {
get {
return self[key] ?? or
}
set {
self[key] = newValue
}
}
}
var dict = ["a": 1]
dict["a"]?++
dict
dict["b"]?++
dict
dict["c", or: 3]++
dict
| mit | 3e541b480a1550ef33bb6f6444339b58 | 25.705882 | 396 | 0.65837 | 3.685065 | false | false | false | false |
alblue/swift | stdlib/public/SDK/Network/NWProtocolUDP.swift | 7 | 1639 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2018 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
@available(macOS 10.14, iOS 12.0, watchOS 5.0, tvOS 12.0, *)
public class NWProtocolUDP : NWProtocol {
public static let definition: NWProtocolDefinition = {
NWProtocolDefinition(nw_protocol_copy_udp_definition(), "udp")
}()
public class Options : NWProtocolOptions {
private var _preferNoChecksum: Bool = false
/// Configure UDP to skip computing checksums when sending.
/// This will only take effect when running over IPv4 (UDP_NOCKSUM).
public var preferNoChecksum: Bool {
set {
self._preferNoChecksum = newValue
nw_udp_options_set_prefer_no_checksum(self.nw, newValue)
}
get {
return self._preferNoChecksum
}
}
/// Create UDP options to set in an NWParameters.ProtocolStack
public init() {
super.init(nw_udp_create_options())
}
override internal init(_ nw: nw_protocol_options_t) {
super.init(nw)
}
}
public class Metadata: NWProtocolMetadata {
override internal init(_ nw: nw_protocol_metadata_t) {
super.init(nw)
}
/// Create an empty UDP metadata to send with ContentContext
public init() {
super.init(nw_udp_create_metadata())
}
}
}
| apache-2.0 | a86d596e89b2abbcbdfdc175aa0941c6 | 28.8 | 80 | 0.638194 | 3.829439 | false | false | false | false |
D8Ge/Jchat | Jchat/Pods/SwiftProtobuf/Sources/SwiftProtobuf/Google_Protobuf_FieldMask_Extensions.swift | 1 | 5106 | // ProtobufRuntime/Sources/Protobuf/Google_Protobuf_FieldMask_Extensions.swift - Fieldmask extensions
//
// 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
//
// -----------------------------------------------------------------------------
///
/// Extend the generated FieldMask message with customized JSON coding and
/// convenience methods.
///
// -----------------------------------------------------------------------------
import Swift
// TODO: We should have utilities to apply a fieldmask to an arbitrary
// message, intersect two fieldmasks, etc.
private func ProtoToJSON(name: String) -> String? {
var jsonPath = ""
var chars = name.characters.makeIterator()
while let c = chars.next() {
switch c {
case "_":
if let toupper = chars.next() {
switch toupper {
case "a"..."z":
jsonPath.append(String(toupper).uppercased())
default:
return nil
}
} else {
return nil
}
case "A"..."Z":
return nil
default:
jsonPath.append(c)
}
}
return jsonPath
}
private func JSONToProto(name: String) -> String? {
var path = ""
for c in name.characters {
switch c {
case "_":
return nil
case "A"..."Z":
path.append(Character("_"))
path.append(String(c).lowercased())
default:
path.append(c)
}
}
return path
}
private func parseJSONFieldNames(names: String) -> [String]? {
var fieldNameCount = 0
var fieldName = ""
var split = [String]()
for c: Character in names.characters {
switch c {
case ",":
if fieldNameCount == 0 {
return nil
}
if let pbName = JSONToProto(name: fieldName) {
split.append(pbName)
} else {
return nil
}
fieldName = ""
fieldNameCount = 0
default:
fieldName.append(c)
fieldNameCount += 1
}
}
if fieldNameCount == 0 { // Last field name can't be empty
return nil
}
if let pbName = JSONToProto(name: fieldName) {
split.append(pbName)
} else {
return nil
}
return split
}
public extension Google_Protobuf_FieldMask {
/// Initialize a FieldMask object with an array of paths.
/// The paths should match the names used in the proto file (which
/// will be different than the corresponding Swift property names).
public init(protoPaths: [String]) {
self.init()
paths = protoPaths
}
/// Initialize a FieldMask object with the provided paths.
/// The paths should match the names used in the proto file (which
/// will be different than the corresponding Swift property names).
public init(protoPaths: String...) {
self.init(protoPaths: protoPaths)
}
/// Initialize a FieldMask object with the provided paths.
/// The paths should match the names used in the JSON serialization
/// (which will be different than the field names in the proto file
/// or the corresponding Swift property names).
public init?(jsonPaths: String...) {
// TODO: This should fail if any of the conversions from JSON fails
self.init(protoPaths: jsonPaths.flatMap(JSONToProto))
}
// It would be nice if to have an initializer that accepted Swift property
// names, but translating between swift and protobuf/json property
// names is not entirely deterministic.
mutating public func decodeFromJSONToken(token: ProtobufJSONToken) throws {
switch token {
case .string(let s):
if let names = parseJSONFieldNames(names: s) {
paths = names
} else {
throw ProtobufDecodingError.fieldMaskConversion
}
default:
throw ProtobufDecodingError.schemaMismatch
}
}
// Custom hand-rolled JSON serializer
public func serializeJSON() throws -> String {
// Note: Proto requires alphanumeric field names, so there
// cannot be a ',' or '"' character to mess up this formatting.
var jsonPaths = [String]()
for p in paths {
if let jsonPath = ProtoToJSON(name: p) {
jsonPaths.append(jsonPath)
} else {
throw ProtobufEncodingError.fieldMaskConversion
}
}
return "\"" + jsonPaths.joined(separator: ",") + "\""
}
public func serializeAnyJSON() throws -> String {
let value = try serializeJSON()
return "{\"@type\":\"\(anyTypeURL)\",\"value\":\(value)}"
}
}
| mit | 3e39d6521e0dc4e30113583cce3fce4e | 31.316456 | 101 | 0.567568 | 5.025591 | false | false | false | false |
mozilla-mobile/firefox-ios | RustFxA/FxAWebViewModel.swift | 2 | 11787 | /* 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 WebKit
import Foundation
import Account
import MozillaAppServices
import Shared
enum FxAPageType {
case emailLoginFlow
case qrCode(url: String)
case settingsPage
}
// See https://mozilla.github.io/ecosystem-platform/docs/fxa-engineering/fxa-webchannel-protocol
// For details on message types.
private enum RemoteCommand: String {
// case canLinkAccount = "can_link_account"
// case loaded = "fxaccounts:loaded"
case status = "fxaccounts:fxa_status"
case login = "fxaccounts:oauth_login"
case changePassword = "fxaccounts:change_password"
case signOut = "fxaccounts:logout"
case deleteAccount = "fxaccounts:delete_account"
case profileChanged = "profile:change"
}
class FxAWebViewModel {
fileprivate let pageType: FxAPageType
fileprivate let profile: Profile
fileprivate var deepLinkParams: FxALaunchParams?
fileprivate(set) var baseURL: URL?
let fxAWebViewTelemetry = FxAWebViewTelemetry()
// This is not shown full-screen, use mobile UA
static let mobileUserAgent = UserAgent.mobileUserAgent()
func setupUserScript(for controller: WKUserContentController) {
guard let path = Bundle.main.path(forResource: "FxASignIn", ofType: "js"),
let source = try? String(contentsOfFile: path, encoding: .utf8)
else {
assert(false)
return
}
let userScript = WKUserScript(source: source, injectionTime: .atDocumentStart, forMainFrameOnly: true)
controller.addUserScript(userScript)
}
/**
init() FxAWebViewModel.
- parameter pageType: Specify login flow or settings page if already logged in.
- parameter profile: a Profile.
- parameter deepLinkParams: url parameters that originate from a deep link
*/
required init(pageType: FxAPageType, profile: Profile, deepLinkParams: FxALaunchParams?) {
self.pageType = pageType
self.profile = profile
self.deepLinkParams = deepLinkParams
// If accountMigrationFailed then the app menu has a caution icon,
// and at this point the user has taken sufficient action to clear the caution.
profile.rustFxA.accountMigrationFailed = false
}
var onDismissController: (() -> Void)?
func composeTitle(basedOn url: URL?, hasOnlySecureContent: Bool) -> String {
return (hasOnlySecureContent ? "🔒 " : "") + (url?.host ?? "")
}
func setupFirstPage(completion: @escaping (URLRequest, TelemetryWrapper.EventMethod?) -> Void) {
profile.rustFxA.accountManager.uponQueue(.main) { accountManager in
accountManager.getManageAccountURL(entrypoint: "ios_settings_manage") { [weak self] result in
guard let self = self else { return }
// Handle authentication with either the QR code login flow, email login flow, or settings page flow
switch self.pageType {
case .emailLoginFlow:
accountManager.beginAuthentication(entrypoint: "emailLoginFlow") { [weak self] result in
guard let self = self else { return }
if case .success(let url) = result {
self.baseURL = url
completion(self.makeRequest(url), .emailLogin)
}
}
case let .qrCode(url):
accountManager.beginPairingAuthentication(pairingUrl: url, entrypoint: "qrCode") { [weak self] result in
guard let self = self else { return }
if case .success(let url) = result {
self.baseURL = url
completion(self.makeRequest(url), .qrPairing)
}
}
case .settingsPage:
if case .success(let url) = result {
self.baseURL = url
completion(self.makeRequest(url), nil)
}
}
}
}
}
private func makeRequest(_ url: URL) -> URLRequest {
if let query = deepLinkParams?.query {
let args = query.filter { $0.key.starts(with: "utm_") }.map {
return URLQueryItem(name: $0.key, value: $0.value)
}
var comp = URLComponents(url: url, resolvingAgainstBaseURL: false)
comp?.queryItems?.append(contentsOf: args)
if let url = comp?.url {
return URLRequest(url: url)
}
}
return URLRequest(url: url)
}
}
// MARK: - Commands
extension FxAWebViewModel {
func handle(scriptMessage message: WKScriptMessage) {
guard let url = baseURL,
let webView = message.webView
else { return }
let origin = message.frameInfo.securityOrigin
guard origin.`protocol` == url.scheme && origin.host == url.host && origin.port == (url.port ?? 0) else {
print("Ignoring message - \(origin) does not match expected origin: \(url.origin ?? "nil")")
return
}
guard message.name == "accountsCommandHandler" else { return }
guard let body = message.body as? [String: Any],
let detail = body["detail"] as? [String: Any],
let msg = detail["message"] as? [String: Any],
let cmd = msg["command"] as? String
else { return }
let id = Int(msg["messageId"] as? String ?? "")
handleRemote(command: cmd, id: id, data: msg["data"], webView: webView)
}
// Handle a message coming from the content server.
private func handleRemote(command rawValue: String, id: Int?, data: Any?, webView: WKWebView) {
if let command = RemoteCommand(rawValue: rawValue) {
switch command {
case .login:
if let data = data {
onLogin(data: data, webView: webView)
}
case .changePassword:
if let data = data {
onPasswordChange(data: data, webView: webView)
}
case .status:
if let id = id {
onSessionStatus(id: id, webView: webView)
}
case .deleteAccount, .signOut:
profile.removeAccount()
onDismissController?()
case .profileChanged:
profile.rustFxA.accountManager.peek()?.refreshProfile(ignoreCache: true)
// dismiss keyboard after changing profile in order to see notification view
UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
}
}
}
/// Send a message to web content using the required message structure.
private func runJS(webView: WKWebView, typeId: String, messageId: Int, command: String, data: String = "{}") {
let msg = """
var msg = {
id: "\(typeId)",
message: {
messageId: \(messageId),
command: "\(command)",
data : \(data)
}
};
window.dispatchEvent(new CustomEvent('WebChannelMessageToContent', { detail: JSON.stringify(msg) }));
"""
webView.evaluateJavascriptInDefaultContentWorld(msg)
}
/// Respond to the webpage session status notification by either passing signed in
/// user info (for settings), or by passing CWTS setup info (in case the user is
/// signing up for an account). This latter case is also used for the sign-in state.
private func onSessionStatus(id: Int, webView: WKWebView) {
guard let fxa = profile.rustFxA.accountManager.peek() else { return }
let cmd = "fxaccounts:fxa_status"
let typeId = "account_updates"
let data: String
switch pageType {
case .settingsPage:
// Both email and uid are required at this time to properly link the FxA settings session
let email = fxa.accountProfile()?.email ?? ""
let uid = fxa.accountProfile()?.uid ?? ""
let token = (try? fxa.getSessionToken().get()) ?? ""
data = """
{
capabilities: {},
signedInUser: {
sessionToken: "\(token)",
email: "\(email)",
uid: "\(uid)",
verified: true,
}
}
"""
case .emailLoginFlow, .qrCode:
data = """
{ capabilities:
{ choose_what_to_sync: true, engines: ["bookmarks", "history", "tabs", "passwords"] },
}
"""
}
runJS(webView: webView, typeId: typeId, messageId: id, command: cmd, data: data)
}
private func onLogin(data: Any, webView: WKWebView) {
guard let data = data as? [String: Any],
let code = data["code"] as? String,
let state = data["state"] as? String
else { return }
if let declinedSyncEngines = data["declinedSyncEngines"] as? [String] {
// Stash the declined engines so on first sync we can disable them!
UserDefaults.standard.set(declinedSyncEngines, forKey: "fxa.cwts.declinedSyncEngines")
}
let auth = FxaAuthData(code: code, state: state, actionQueryParam: "signin")
profile.rustFxA.accountManager.peek()?.finishAuthentication(authData: auth) { _ in
self.profile.syncManager.onAddedAccount()
// ask for push notification
MZKeychainWrapper.sharedClientAppContainerKeychain.removeObject(forKey: KeychainKey.apnsToken, withAccessibility: MZKeychainItemAccessibility.afterFirstUnlock)
let center = UNUserNotificationCenter.current()
center.requestAuthorization(options: [.alert, .badge, .sound]) { (granted, error) in
guard error == nil else { return }
if granted {
NotificationCenter.default.post(name: .RegisterForPushNotifications, object: nil)
}
}
}
// Record login or registration completed telemetry
fxAWebViewTelemetry.recordTelemetry(for: .completed)
onDismissController?()
}
private func onPasswordChange(data: Any, webView: WKWebView) {
guard let data = data as? [String: Any],
let sessionToken = data["sessionToken"] as? String
else { return }
profile.rustFxA.accountManager.peek()?.handlePasswordChanged(newSessionToken: sessionToken) {
NotificationCenter.default.post(name: .RegisterForPushNotifications, object: nil)
}
}
func shouldAllowRedirectAfterLogIn(basedOn navigationURL: URL?) -> WKNavigationActionPolicy {
// Cancel navigation that happens after login to an account, which is when a redirect to `redirectURL` happens.
// The app handles this event fully in native UI.
let redirectUrl = RustFirefoxAccounts.redirectURL
if let navigationURL = navigationURL {
let expectedRedirectURL = URL(string: redirectUrl)!
if navigationURL.scheme == expectedRedirectURL.scheme && navigationURL.host == expectedRedirectURL.host && navigationURL.path == expectedRedirectURL.path {
return .cancel
}
}
return .allow
}
}
| mpl-2.0 | 15ff00e53dcd2aec0b544378229506ee | 40.787234 | 171 | 0.588001 | 5.040205 | false | false | false | false |
Swinject/SwinjectMVVMExample | Carthage/Checkouts/SwinjectStoryboard/Tests/iOS-tvOS/SwinjectStoryboardSpec.swift | 2 | 10234 | //
// SwinjectStoryboardSpec.swift
// Swinject
//
// Created by Yoichi Tagaya on 7/31/15.
// Copyright © 2015 Swinject Contributors. All rights reserved.
//
import Quick
import Nimble
import Swinject
@testable import SwinjectStoryboard
private var swinjectStoryboardSetupCount = 0
extension SwinjectStoryboard {
static func setup() {
swinjectStoryboardSetupCount += 1
}
}
class SwinjectStoryboardSpec: QuickSpec {
override func spec() {
let bundle = Bundle(for: SwinjectStoryboardSpec.self)
var container: Container!
beforeEach {
container = Container()
}
describe("Instantiation from storyboard") {
it("injects dependency definded by initCompleted handler.") {
container.registerForStoryboard(AnimalViewController.self) { r, c in
c.animal = r.resolve(AnimalType.self)
}
container.register(AnimalType.self) { _ in Cat(name: "Mimi") }
let storyboard = SwinjectStoryboard.create(name: "Animals", bundle: bundle, container: container)
let animalViewController = storyboard.instantiateViewController(withIdentifier: "AnimalAsCat") as! AnimalViewController
expect(animalViewController.hasAnimal(named: "Mimi")) == true
}
it("injects dependency to child view controllers.") {
container.registerForStoryboard(AnimalViewController.self) { r, c in
c.animal = r.resolve(AnimalType.self)
}
container.register(AnimalType.self) { _ in Cat() }
.inObjectScope(.container)
let storyboard = SwinjectStoryboard.create(name: "Tabs", bundle: bundle, container: container)
let tabBarController = storyboard.instantiateViewController(withIdentifier: "TabBarController")
let animalViewController1 = tabBarController.childViewControllers[0] as! AnimalViewController
let animalViewController2 = tabBarController.childViewControllers[1] as! AnimalViewController
let cat1 = animalViewController1.animal as! Cat
let cat2 = animalViewController2.animal as! Cat
expect(cat1 === cat2).to(beTrue()) // Workaround for crash in Nimble.
}
context("with a registration name set as a user defined runtime attribute on Interface Builder") {
it("injects dependency definded by initCompleted handler with the registration name.") {
// The registration name "hachi" is set in the storyboard.
container.registerForStoryboard(AnimalViewController.self, name: "hachi") { r, c in
c.animal = r.resolve(AnimalType.self)
}
container.register(AnimalType.self) { _ in Dog(name: "Hachi") }
// This registration should not be resolved.
container.registerForStoryboard(AnimalViewController.self) { _, c in
c.animal = Cat(name: "Mimi")
}
let storyboard = SwinjectStoryboard.create(name: "Animals", bundle: bundle, container: container)
let animalViewController = storyboard.instantiateViewController(withIdentifier: "AnimalAsDog") as! AnimalViewController
expect(animalViewController.hasAnimal(named: "Hachi")) == true
}
}
context("with container hierarchy") {
it("injects view controller dependency definded in the parent container.") {
container.registerForStoryboard(AnimalViewController.self) { r, c in
c.animal = r.resolve(AnimalType.self)
}
container.register(AnimalType.self) { _ in Cat(name: "Mimi") }
let childContainer = Container(parent: container)
let storyboard = SwinjectStoryboard.create(name: "Animals", bundle: bundle, container: childContainer)
let animalViewController = storyboard.instantiateViewController(withIdentifier: "AnimalAsCat") as! AnimalViewController
expect(animalViewController.hasAnimal(named: "Mimi")) == true
}
}
}
describe("Initial view controller") {
it("injects dependency definded by initCompleted handler.") {
container.registerForStoryboard(AnimalViewController.self) { r, c in
c.animal = r.resolve(AnimalType.self)
}
container.register(AnimalType.self) { _ in Cat(name: "Mimi") }
let storyboard = SwinjectStoryboard.create(name: "Animals", bundle: bundle, container: container)
let animalViewController = storyboard.instantiateInitialViewController() as! AnimalViewController
expect(animalViewController.hasAnimal(named: "Mimi")) == true
}
}
describe("AVPlayerViewController") { // Test for Issue #18
it("is able to inject a subclass of AVPlayerViewController") {
container.registerForStoryboard(AnimalPlayerViewController.self) { r, c in
c.animal = r.resolve(AnimalType.self)
}
container.register(AnimalType.self) { _ in Cat(name: "Mimi") }
let storyboard = SwinjectStoryboard.create(name: "AnimalPlayerViewController", bundle: bundle, container: container)
let animalPlayerViewController = storyboard.instantiateInitialViewController() as! AnimalPlayerViewController
expect(animalPlayerViewController.hasAnimal(named: "Mimi")) == true
}
}
describe("Factory method") {
it("uses the default shared container if no container is passed.") {
SwinjectStoryboard.defaultContainer.registerForStoryboard(AnimalViewController.self) { _, _ in }
let storyboard = SwinjectStoryboard.create(name: "Animals", bundle: bundle)
let animalViewController = storyboard.instantiateViewController(withIdentifier: "AnimalAsCat")
expect(animalViewController).notTo(beNil())
}
afterEach {
SwinjectStoryboard.defaultContainer.removeAll()
}
}
// We need to have test bundle deployment target on iOS 9.0 in order to compile storyboards with references.
// However, we need to disable these tests when running on iOS <9.0
// Using #available(iOS 9.0, *) produces complier warning for the reasons above
if ProcessInfo().isOperatingSystemAtLeast(OperatingSystemVersion(majorVersion: 9, minorVersion: 0, patchVersion: 0)) {
describe("Storyboard reference") {
it("inject dependency to the view controller in the referenced storyboard.") {
SwinjectStoryboard.defaultContainer.registerForStoryboard(AnimalViewController.self) { r, c in
c.animal = r.resolve(AnimalType.self)
}
SwinjectStoryboard.defaultContainer.register(AnimalType.self) { _ in Cat(name: "Mimi") }
let storyboard1 = SwinjectStoryboard.create(name: "Storyboard1", bundle: bundle)
let navigationController = storyboard1.instantiateInitialViewController() as! UINavigationController
navigationController.performSegue(withIdentifier: "ToStoryboard2", sender: navigationController)
let animalViewController = navigationController.topViewController as! AnimalViewController
expect(animalViewController.hasAnimal(named: "Mimi")) == true
}
context("referencing storyboard via relationship segue") {
it("should inject dependencies once") {
var injectedTimes = 0
SwinjectStoryboard.defaultContainer.registerForStoryboard(UIViewController.self) { r, c in
injectedTimes += 1
}
let storyboard = SwinjectStoryboard.create(name: "RelationshipReference1", bundle: bundle)
storyboard.instantiateInitialViewController()
expect(injectedTimes) == 1
}
context("not using defaultContainer") {
it("injects dependency to the view controller opened via segue") {
container.registerForStoryboard(AnimalViewController.self) { r, c in
c.animal = r.resolve(AnimalType.self)
}
container.register(AnimalType.self) { _ in Cat(name: "Mimi") }
let storyboard = SwinjectStoryboard.create(name: "RelationshipReference1", bundle: bundle, container: container)
let navigationController = storyboard.instantiateInitialViewController() as! UINavigationController
navigationController.topViewController!.performSegue(withIdentifier: "ToAnimalViewController", sender: nil)
let animalViewController = navigationController.topViewController as! AnimalViewController
expect(animalViewController.hasAnimal(named: "Mimi")) == true
}
}
}
afterEach {
SwinjectStoryboard.defaultContainer.removeAll()
}
}
}
describe("Setup") {
it("calls setup function only once.") {
_ = SwinjectStoryboard.create(name: "Animals", bundle: bundle)
_ = SwinjectStoryboard.create(name: "Animals", bundle: bundle)
expect(swinjectStoryboardSetupCount) == 1
}
}
}
}
| mit | 83873231213fb99e37c81dce5e60b0a8 | 54.918033 | 140 | 0.594547 | 6.160747 | false | false | false | false |
ithron/swift-atomics | Tests/CAtomicsTests/CAtomicsTests.swift | 1 | 21218 | //
// CAtomicsTests.swift
// AtomicsTests
//
// Copyright © 2016-2017 Guillaume Lessard. All rights reserved.
// This file is distributed under the BSD 3-clause license. See LICENSE for details.
//
import XCTest
import Dispatch
#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS)
import func Darwin.C.stdlib.arc4random
#else // assuming os(Linux)
import func Glibc.random
#endif
import CAtomics
#if swift(>=4.0)
extension FixedWidthInteger
{
// returns a positive random integer greater than 0 and less-than-or-equal to Self.max/2
// the least significant bit is always set.
static func randomPositive() -> Self
{
var t = Self()
for _ in 0...((t.bitWidth-1)/32)
{
#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS)
t = t<<32 &+ Self(truncatingIfNeeded: arc4random())
#else // probably Linux
t = t<<32 &+ Self(truncatingIfNeeded: random())
#endif
}
return (t|1) & (Self.max>>1)
}
}
#else
extension UInt
{
// returns a positive random integer greater than 0 and less-than-or-equal to UInt32.max/2
// the least significant bit is always set.
static func randomPositive() -> UInt
{
#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS)
return UInt(arc4random() & 0x3fff_fffe + 1)
#else
return UInt(random() & 0x3fff_fffe + 1)
#endif
}
}
#endif
public class CAtomicsTests: XCTestCase
{
public static var allTests = [
("testRawPointer", testRawPointer),
("testMutableRawPointer", testMutableRawPointer),
("testOpaquePointer", testOpaquePointer),
("testBool", testBool),
("testFence", testFence),
]
public func testInt()
{
var i = AtomicInt()
i.initialize(0)
XCTAssert(i.load(.relaxed) == 0)
#if swift(>=4.0)
let r1 = Int.randomPositive()
let r2 = Int.randomPositive()
let r3 = Int.randomPositive()
#else
let r1 = Int(UInt.randomPositive())
let r2 = Int(UInt.randomPositive())
let r3 = Int(UInt.randomPositive())
#endif
i.store(r1, .relaxed)
XCTAssert(r1 == i.load(.relaxed))
var j = i.swap(r2, .relaxed)
XCTAssertEqual(r1, j)
XCTAssertEqual(r2, i.load(.relaxed))
j = i.fetch_add(r1, .relaxed)
XCTAssertEqual(r2, j)
XCTAssertEqual(r1 &+ r2, i.load(.relaxed))
j = i.fetch_sub(r2, .relaxed)
XCTAssertEqual(r1 &+ r2, j)
XCTAssertEqual(r1, i.load(.relaxed))
i.store(r1, .relaxed)
j = i.fetch_or(r2, .relaxed)
XCTAssertEqual(r1, j)
XCTAssertEqual(r1 | r2, i.load(.relaxed))
i.store(r2, .relaxed)
j = i.fetch_xor(r1, .relaxed)
XCTAssertEqual(r2, j)
XCTAssertEqual(r1 ^ r2, i.load(.relaxed))
i.store(r1, .relaxed)
j = i.fetch_and(r2, .relaxed)
XCTAssertEqual(r1, j)
XCTAssertEqual(r1 & r2, i.load(.relaxed))
j = r1
i.store(r1, .relaxed)
XCTAssertTrue(i.loadCAS(&j, r2, .strong, .relaxed, .relaxed))
XCTAssertEqual(r2, i.load(.relaxed))
j = r2
i.store(r1, .relaxed)
while(!i.loadCAS(&j, r3, .weak, .relaxed, .relaxed)) {}
XCTAssertEqual(r1, j)
XCTAssertEqual(r3, i.load(.relaxed))
}
public func testUInt()
{
var i = AtomicUInt()
i.initialize(0)
XCTAssert(i.load(.relaxed) == 0)
#if swift(>=4.0)
let r1 = UInt.randomPositive()
let r2 = UInt.randomPositive()
let r3 = UInt.randomPositive()
#else
let r1 = UInt(UInt.randomPositive())
let r2 = UInt(UInt.randomPositive())
let r3 = UInt(UInt.randomPositive())
#endif
i.store(r1, .relaxed)
XCTAssert(r1 == i.load(.relaxed))
var j = i.swap(r2, .relaxed)
XCTAssertEqual(r1, j)
XCTAssertEqual(r2, i.load(.relaxed))
j = i.fetch_add(r1, .relaxed)
XCTAssertEqual(r2, j)
XCTAssertEqual(r1 &+ r2, i.load(.relaxed))
j = i.fetch_sub(r2, .relaxed)
XCTAssertEqual(r1 &+ r2, j)
XCTAssertEqual(r1, i.load(.relaxed))
i.store(r1, .relaxed)
j = i.fetch_or(r2, .relaxed)
XCTAssertEqual(r1, j)
XCTAssertEqual(r1 | r2, i.load(.relaxed))
i.store(r2, .relaxed)
j = i.fetch_xor(r1, .relaxed)
XCTAssertEqual(r2, j)
XCTAssertEqual(r1 ^ r2, i.load(.relaxed))
i.store(r1, .relaxed)
j = i.fetch_and(r2, .relaxed)
XCTAssertEqual(r1, j)
XCTAssertEqual(r1 & r2, i.load(.relaxed))
j = r1
i.store(r1, .relaxed)
XCTAssertTrue(i.loadCAS(&j, r2, .strong, .relaxed, .relaxed))
XCTAssertEqual(r2, i.load(.relaxed))
j = r2
i.store(r1, .relaxed)
while(!i.loadCAS(&j, r3, .weak, .relaxed, .relaxed)) {}
XCTAssertEqual(r1, j)
XCTAssertEqual(r3, i.load(.relaxed))
}
public func testInt8()
{
var i = AtomicInt8()
i.initialize(0)
XCTAssert(i.load(.relaxed) == 0)
#if swift(>=4.0)
let r1 = Int8.randomPositive()
let r2 = Int8.randomPositive()
let r3 = Int8.randomPositive()
#else
let r1 = Int8(truncatingBitPattern: UInt.randomPositive())
let r2 = Int8(truncatingBitPattern: UInt.randomPositive())
let r3 = Int8(truncatingBitPattern: UInt.randomPositive())
#endif
i.store(r1, .relaxed)
XCTAssert(r1 == i.load(.relaxed))
var j = i.swap(r2, .relaxed)
XCTAssertEqual(r1, j)
XCTAssertEqual(r2, i.load(.relaxed))
j = i.fetch_add(r1, .relaxed)
XCTAssertEqual(r2, j)
XCTAssertEqual(r1 &+ r2, i.load(.relaxed))
j = i.fetch_sub(r2, .relaxed)
XCTAssertEqual(r1 &+ r2, j)
XCTAssertEqual(r1, i.load(.relaxed))
i.store(r1, .relaxed)
j = i.fetch_or(r2, .relaxed)
XCTAssertEqual(r1, j)
XCTAssertEqual(r1 | r2, i.load(.relaxed))
i.store(r2, .relaxed)
j = i.fetch_xor(r1, .relaxed)
XCTAssertEqual(r2, j)
XCTAssertEqual(r1 ^ r2, i.load(.relaxed))
i.store(r1, .relaxed)
j = i.fetch_and(r2, .relaxed)
XCTAssertEqual(r1, j)
XCTAssertEqual(r1 & r2, i.load(.relaxed))
j = r1
i.store(r1, .relaxed)
XCTAssertTrue(i.loadCAS(&j, r2, .strong, .relaxed, .relaxed))
XCTAssertEqual(r2, i.load(.relaxed))
j = r2
i.store(r1, .relaxed)
while(!i.loadCAS(&j, r3, .weak, .relaxed, .relaxed)) {}
XCTAssertEqual(r1, j)
XCTAssertEqual(r3, i.load(.relaxed))
}
public func testUInt8()
{
var i = AtomicUInt8()
i.initialize(0)
XCTAssert(i.load(.relaxed) == 0)
#if swift(>=4.0)
let r1 = UInt8.randomPositive()
let r2 = UInt8.randomPositive()
let r3 = UInt8.randomPositive()
#else
let r1 = UInt8(truncatingBitPattern: UInt.randomPositive())
let r2 = UInt8(truncatingBitPattern: UInt.randomPositive())
let r3 = UInt8(truncatingBitPattern: UInt.randomPositive())
#endif
i.store(r1, .relaxed)
XCTAssert(r1 == i.load(.relaxed))
var j = i.swap(r2, .relaxed)
XCTAssertEqual(r1, j)
XCTAssertEqual(r2, i.load(.relaxed))
j = i.fetch_add(r1, .relaxed)
XCTAssertEqual(r2, j)
XCTAssertEqual(r1 &+ r2, i.load(.relaxed))
j = i.fetch_sub(r2, .relaxed)
XCTAssertEqual(r1 &+ r2, j)
XCTAssertEqual(r1, i.load(.relaxed))
i.store(r1, .relaxed)
j = i.fetch_or(r2, .relaxed)
XCTAssertEqual(r1, j)
XCTAssertEqual(r1 | r2, i.load(.relaxed))
i.store(r2, .relaxed)
j = i.fetch_xor(r1, .relaxed)
XCTAssertEqual(r2, j)
XCTAssertEqual(r1 ^ r2, i.load(.relaxed))
i.store(r1, .relaxed)
j = i.fetch_and(r2, .relaxed)
XCTAssertEqual(r1, j)
XCTAssertEqual(r1 & r2, i.load(.relaxed))
j = r1
i.store(r1, .relaxed)
XCTAssertTrue(i.loadCAS(&j, r2, .strong, .relaxed, .relaxed))
XCTAssertEqual(r2, i.load(.relaxed))
j = r2
i.store(r1, .relaxed)
while(!i.loadCAS(&j, r3, .weak, .relaxed, .relaxed)) {}
XCTAssertEqual(r1, j)
XCTAssertEqual(r3, i.load(.relaxed))
}
public func testInt16()
{
var i = AtomicInt16()
i.initialize(0)
XCTAssert(i.load(.relaxed) == 0)
#if swift(>=4.0)
let r1 = Int16.randomPositive()
let r2 = Int16.randomPositive()
let r3 = Int16.randomPositive()
#else
let r1 = Int16(truncatingBitPattern: UInt.randomPositive())
let r2 = Int16(truncatingBitPattern: UInt.randomPositive())
let r3 = Int16(truncatingBitPattern: UInt.randomPositive())
#endif
i.store(r1, .relaxed)
XCTAssert(r1 == i.load(.relaxed))
var j = i.swap(r2, .relaxed)
XCTAssertEqual(r1, j)
XCTAssertEqual(r2, i.load(.relaxed))
j = i.fetch_add(r1, .relaxed)
XCTAssertEqual(r2, j)
XCTAssertEqual(r1 &+ r2, i.load(.relaxed))
j = i.fetch_sub(r2, .relaxed)
XCTAssertEqual(r1 &+ r2, j)
XCTAssertEqual(r1, i.load(.relaxed))
i.store(r1, .relaxed)
j = i.fetch_or(r2, .relaxed)
XCTAssertEqual(r1, j)
XCTAssertEqual(r1 | r2, i.load(.relaxed))
i.store(r2, .relaxed)
j = i.fetch_xor(r1, .relaxed)
XCTAssertEqual(r2, j)
XCTAssertEqual(r1 ^ r2, i.load(.relaxed))
i.store(r1, .relaxed)
j = i.fetch_and(r2, .relaxed)
XCTAssertEqual(r1, j)
XCTAssertEqual(r1 & r2, i.load(.relaxed))
j = r1
i.store(r1, .relaxed)
XCTAssertTrue(i.loadCAS(&j, r2, .strong, .relaxed, .relaxed))
XCTAssertEqual(r2, i.load(.relaxed))
j = r2
i.store(r1, .relaxed)
while(!i.loadCAS(&j, r3, .weak, .relaxed, .relaxed)) {}
XCTAssertEqual(r1, j)
XCTAssertEqual(r3, i.load(.relaxed))
}
public func testUInt16()
{
var i = AtomicUInt16()
i.initialize(0)
XCTAssert(i.load(.relaxed) == 0)
#if swift(>=4.0)
let r1 = UInt16.randomPositive()
let r2 = UInt16.randomPositive()
let r3 = UInt16.randomPositive()
#else
let r1 = UInt16(truncatingBitPattern: UInt.randomPositive())
let r2 = UInt16(truncatingBitPattern: UInt.randomPositive())
let r3 = UInt16(truncatingBitPattern: UInt.randomPositive())
#endif
i.store(r1, .relaxed)
XCTAssert(r1 == i.load(.relaxed))
var j = i.swap(r2, .relaxed)
XCTAssertEqual(r1, j)
XCTAssertEqual(r2, i.load(.relaxed))
j = i.fetch_add(r1, .relaxed)
XCTAssertEqual(r2, j)
XCTAssertEqual(r1 &+ r2, i.load(.relaxed))
j = i.fetch_sub(r2, .relaxed)
XCTAssertEqual(r1 &+ r2, j)
XCTAssertEqual(r1, i.load(.relaxed))
i.store(r1, .relaxed)
j = i.fetch_or(r2, .relaxed)
XCTAssertEqual(r1, j)
XCTAssertEqual(r1 | r2, i.load(.relaxed))
i.store(r2, .relaxed)
j = i.fetch_xor(r1, .relaxed)
XCTAssertEqual(r2, j)
XCTAssertEqual(r1 ^ r2, i.load(.relaxed))
i.store(r1, .relaxed)
j = i.fetch_and(r2, .relaxed)
XCTAssertEqual(r1, j)
XCTAssertEqual(r1 & r2, i.load(.relaxed))
j = r1
i.store(r1, .relaxed)
XCTAssertTrue(i.loadCAS(&j, r2, .strong, .relaxed, .relaxed))
XCTAssertEqual(r2, i.load(.relaxed))
j = r2
i.store(r1, .relaxed)
while(!i.loadCAS(&j, r3, .weak, .relaxed, .relaxed)) {}
XCTAssertEqual(r1, j)
XCTAssertEqual(r3, i.load(.relaxed))
}
public func testInt32()
{
var i = AtomicInt32()
i.initialize(0)
XCTAssert(i.load(.relaxed) == 0)
#if swift(>=4.0)
let r1 = Int32.randomPositive()
let r2 = Int32.randomPositive()
let r3 = Int32.randomPositive()
#else
let r1 = Int32(truncatingBitPattern: UInt.randomPositive())
let r2 = Int32(truncatingBitPattern: UInt.randomPositive())
let r3 = Int32(truncatingBitPattern: UInt.randomPositive())
#endif
i.store(r1, .relaxed)
XCTAssert(r1 == i.load(.relaxed))
var j = i.swap(r2, .relaxed)
XCTAssertEqual(r1, j)
XCTAssertEqual(r2, i.load(.relaxed))
j = i.fetch_add(r1, .relaxed)
XCTAssertEqual(r2, j)
XCTAssertEqual(r1 &+ r2, i.load(.relaxed))
j = i.fetch_sub(r2, .relaxed)
XCTAssertEqual(r1 &+ r2, j)
XCTAssertEqual(r1, i.load(.relaxed))
i.store(r1, .relaxed)
j = i.fetch_or(r2, .relaxed)
XCTAssertEqual(r1, j)
XCTAssertEqual(r1 | r2, i.load(.relaxed))
i.store(r2, .relaxed)
j = i.fetch_xor(r1, .relaxed)
XCTAssertEqual(r2, j)
XCTAssertEqual(r1 ^ r2, i.load(.relaxed))
i.store(r1, .relaxed)
j = i.fetch_and(r2, .relaxed)
XCTAssertEqual(r1, j)
XCTAssertEqual(r1 & r2, i.load(.relaxed))
j = r1
i.store(r1, .relaxed)
XCTAssertTrue(i.loadCAS(&j, r2, .strong, .relaxed, .relaxed))
XCTAssertEqual(r2, i.load(.relaxed))
j = r2
i.store(r1, .relaxed)
while(!i.loadCAS(&j, r3, .weak, .relaxed, .relaxed)) {}
XCTAssertEqual(r1, j)
XCTAssertEqual(r3, i.load(.relaxed))
}
public func testUInt32()
{
var i = AtomicUInt32()
i.initialize(0)
XCTAssert(i.load(.relaxed) == 0)
#if swift(>=4.0)
let r1 = UInt32.randomPositive()
let r2 = UInt32.randomPositive()
let r3 = UInt32.randomPositive()
#else
let r1 = UInt32(truncatingBitPattern: UInt.randomPositive())
let r2 = UInt32(truncatingBitPattern: UInt.randomPositive())
let r3 = UInt32(truncatingBitPattern: UInt.randomPositive())
#endif
i.store(r1, .relaxed)
XCTAssert(r1 == i.load(.relaxed))
var j = i.swap(r2, .relaxed)
XCTAssertEqual(r1, j)
XCTAssertEqual(r2, i.load(.relaxed))
j = i.fetch_add(r1, .relaxed)
XCTAssertEqual(r2, j)
XCTAssertEqual(r1 &+ r2, i.load(.relaxed))
j = i.fetch_sub(r2, .relaxed)
XCTAssertEqual(r1 &+ r2, j)
XCTAssertEqual(r1, i.load(.relaxed))
i.store(r1, .relaxed)
j = i.fetch_or(r2, .relaxed)
XCTAssertEqual(r1, j)
XCTAssertEqual(r1 | r2, i.load(.relaxed))
i.store(r2, .relaxed)
j = i.fetch_xor(r1, .relaxed)
XCTAssertEqual(r2, j)
XCTAssertEqual(r1 ^ r2, i.load(.relaxed))
i.store(r1, .relaxed)
j = i.fetch_and(r2, .relaxed)
XCTAssertEqual(r1, j)
XCTAssertEqual(r1 & r2, i.load(.relaxed))
j = r1
i.store(r1, .relaxed)
XCTAssertTrue(i.loadCAS(&j, r2, .strong, .relaxed, .relaxed))
XCTAssertEqual(r2, i.load(.relaxed))
j = r2
i.store(r1, .relaxed)
while(!i.loadCAS(&j, r3, .weak, .relaxed, .relaxed)) {}
XCTAssertEqual(r1, j)
XCTAssertEqual(r3, i.load(.relaxed))
}
public func testInt64()
{
var i = AtomicInt64()
i.initialize(0)
XCTAssert(i.load(.relaxed) == 0)
#if swift(>=4.0)
let r1 = Int64.randomPositive()
let r2 = Int64.randomPositive()
let r3 = Int64.randomPositive()
#else
let r1 = Int64(UInt.randomPositive())
let r2 = Int64(UInt.randomPositive())
let r3 = Int64(UInt.randomPositive())
#endif
i.store(r1, .relaxed)
XCTAssert(r1 == i.load(.relaxed))
var j = i.swap(r2, .relaxed)
XCTAssertEqual(r1, j)
XCTAssertEqual(r2, i.load(.relaxed))
j = i.fetch_add(r1, .relaxed)
XCTAssertEqual(r2, j)
XCTAssertEqual(r1 &+ r2, i.load(.relaxed))
j = i.fetch_sub(r2, .relaxed)
XCTAssertEqual(r1 &+ r2, j)
XCTAssertEqual(r1, i.load(.relaxed))
i.store(r1, .relaxed)
j = i.fetch_or(r2, .relaxed)
XCTAssertEqual(r1, j)
XCTAssertEqual(r1 | r2, i.load(.relaxed))
i.store(r2, .relaxed)
j = i.fetch_xor(r1, .relaxed)
XCTAssertEqual(r2, j)
XCTAssertEqual(r1 ^ r2, i.load(.relaxed))
i.store(r1, .relaxed)
j = i.fetch_and(r2, .relaxed)
XCTAssertEqual(r1, j)
XCTAssertEqual(r1 & r2, i.load(.relaxed))
j = r1
i.store(r1, .relaxed)
XCTAssertTrue(i.loadCAS(&j, r2, .strong, .relaxed, .relaxed))
XCTAssertEqual(r2, i.load(.relaxed))
j = r2
i.store(r1, .relaxed)
while(!i.loadCAS(&j, r3, .weak, .relaxed, .relaxed)) {}
XCTAssertEqual(r1, j)
XCTAssertEqual(r3, i.load(.relaxed))
}
public func testUInt64()
{
var i = AtomicUInt64()
i.initialize(0)
XCTAssert(i.load(.relaxed) == 0)
#if swift(>=4.0)
let r1 = UInt64.randomPositive()
let r2 = UInt64.randomPositive()
let r3 = UInt64.randomPositive()
#else
let r1 = UInt64(UInt.randomPositive())
let r2 = UInt64(UInt.randomPositive())
let r3 = UInt64(UInt.randomPositive())
#endif
i.store(r1, .relaxed)
XCTAssert(r1 == i.load(.relaxed))
var j = i.swap(r2, .relaxed)
XCTAssertEqual(r1, j)
XCTAssertEqual(r2, i.load(.relaxed))
j = i.fetch_add(r1, .relaxed)
XCTAssertEqual(r2, j)
XCTAssertEqual(r1 &+ r2, i.load(.relaxed))
j = i.fetch_sub(r2, .relaxed)
XCTAssertEqual(r1 &+ r2, j)
XCTAssertEqual(r1, i.load(.relaxed))
i.store(r1, .relaxed)
j = i.fetch_or(r2, .relaxed)
XCTAssertEqual(r1, j)
XCTAssertEqual(r1 | r2, i.load(.relaxed))
i.store(r2, .relaxed)
j = i.fetch_xor(r1, .relaxed)
XCTAssertEqual(r2, j)
XCTAssertEqual(r1 ^ r2, i.load(.relaxed))
i.store(r1, .relaxed)
j = i.fetch_and(r2, .relaxed)
XCTAssertEqual(r1, j)
XCTAssertEqual(r1 & r2, i.load(.relaxed))
j = r1
i.store(r1, .relaxed)
XCTAssertTrue(i.loadCAS(&j, r2, .strong, .relaxed, .relaxed))
XCTAssertEqual(r2, i.load(.relaxed))
j = r2
i.store(r1, .relaxed)
while(!i.loadCAS(&j, r3, .weak, .relaxed, .relaxed)) {}
XCTAssertEqual(r1, j)
XCTAssertEqual(r3, i.load(.relaxed))
}
public func testRawPointer()
{
var p = AtomicRawPointer()
p.initialize(nil)
XCTAssert(p.load(.relaxed) == nil)
let r1 = UnsafeRawPointer(bitPattern: UInt.randomPositive())
let r2 = UnsafeRawPointer(bitPattern: UInt.randomPositive())
let r3 = UnsafeRawPointer(bitPattern: UInt.randomPositive())
p.store(r1, .relaxed)
XCTAssert(r1 == p.load(.relaxed))
var j = p.swap(r2, .relaxed)
XCTAssertEqual(r1, j)
XCTAssertEqual(r2, p.load(.relaxed))
XCTAssertTrue(p.CAS(r2, r3, .strong, .relaxed))
XCTAssertEqual(r3, p.load(.relaxed))
XCTAssertFalse(p.CAS(j, r2, .strong, .relaxed))
XCTAssertTrue(p.CAS(r3, r2, .strong, .relaxed))
j = p.load(.relaxed)
XCTAssertTrue(p.CAS(r2, r1, .strong, .relaxed))
while !p.loadCAS(&j, r3, .weak, .relaxed, .relaxed) {}
XCTAssertEqual(r1, j)
XCTAssertEqual(r3, p.load(.relaxed))
}
public func testMutableRawPointer()
{
var p = AtomicMutableRawPointer()
p.initialize(nil)
XCTAssert(p.load(.relaxed) == nil)
let r1 = UnsafeMutableRawPointer(bitPattern: UInt.randomPositive())
let r2 = UnsafeMutableRawPointer(bitPattern: UInt.randomPositive())
let r3 = UnsafeMutableRawPointer(bitPattern: UInt.randomPositive())
p.store(r1, .relaxed)
XCTAssert(r1 == p.load(.relaxed))
var j = p.swap(r2, .relaxed)
XCTAssertEqual(r1, j)
XCTAssertEqual(r2, p.load(.relaxed))
XCTAssertTrue(p.CAS(r2, r3, .strong, .relaxed))
XCTAssertEqual(r3, p.load(.relaxed))
XCTAssertFalse(p.CAS(j, r2, .strong, .relaxed))
XCTAssertTrue(p.CAS(r3, r2, .strong, .relaxed))
j = p.load(.relaxed)
XCTAssertTrue(p.CAS(r2, r1, .strong, .relaxed))
while !p.loadCAS(&j, r3, .weak, .relaxed, .relaxed) {}
XCTAssertEqual(r1, j)
XCTAssertEqual(r3, p.load(.relaxed))
}
public func testOpaquePointer()
{
var p = AtomicOpaquePointer()
p.initialize(nil)
XCTAssert(p.load(.relaxed) == nil)
let r1 = OpaquePointer(bitPattern: UInt.randomPositive())
let r2 = OpaquePointer(bitPattern: UInt.randomPositive())
let r3 = OpaquePointer(bitPattern: UInt.randomPositive())
p.store(r1, .relaxed)
XCTAssert(r1 == p.load(.relaxed))
var j = p.swap(r2, .relaxed)
XCTAssertEqual(r1, j)
XCTAssertEqual(r2, p.load(.relaxed))
XCTAssertTrue(p.CAS(r2, r3, .strong, .relaxed))
XCTAssertEqual(r3, p.load(.relaxed))
XCTAssertFalse(p.CAS(j, r2, .strong, .relaxed))
XCTAssertTrue(p.CAS(r3, r2, .strong, .relaxed))
j = p.load(.relaxed)
XCTAssertTrue(p.CAS(r2, r1, .strong, .relaxed))
while !p.loadCAS(&j, r3, .weak, .relaxed, .relaxed) {}
XCTAssertEqual(r1, j)
XCTAssertEqual(r3, p.load(.relaxed))
}
public func testBool()
{
var boolean = AtomicBool()
boolean.initialize(false)
XCTAssert(boolean.load(.relaxed) == false)
boolean.store(false, .relaxed)
XCTAssert(boolean.load(.relaxed) == false)
boolean.store(true, .relaxed)
XCTAssert(boolean.load(.relaxed) == true)
boolean.store(false, .relaxed)
boolean.fetch_or(true, .relaxed)
XCTAssert(boolean.load(.relaxed) == true)
boolean.fetch_or(false, .relaxed)
XCTAssert(boolean.load(.relaxed) == true)
boolean.store(false, .relaxed)
boolean.fetch_or(false, .relaxed)
XCTAssert(boolean.load(.relaxed) == false)
boolean.fetch_or(true, .relaxed)
XCTAssert(boolean.load(.relaxed) == true)
boolean.fetch_and(false, .relaxed)
XCTAssert(boolean.load(.relaxed) == false)
boolean.fetch_and(true, .relaxed)
XCTAssert(boolean.load(.relaxed) == false)
boolean.fetch_xor(false, .relaxed)
XCTAssert(boolean.load(.relaxed) == false)
boolean.fetch_xor(true, .relaxed)
XCTAssert(boolean.load(.relaxed) == true)
let old = boolean.swap(false, .relaxed)
XCTAssert(old == true)
XCTAssert(boolean.swap(true, .relaxed) == false)
var current = true
XCTAssert(boolean.load(.relaxed) == current)
boolean.loadCAS(¤t, false, .strong, .relaxed, .relaxed)
current = boolean.load(.relaxed)
XCTAssert(current == false)
if boolean.loadCAS(¤t, true, .strong, .relaxed, .relaxed)
{
current = !current
XCTAssert(boolean.loadCAS(¤t, false, .weak, .relaxed, .relaxed))
current = !current
XCTAssert(boolean.loadCAS(¤t, true, .weak, .relaxed, .relaxed))
}
}
public func testFence()
{
CAtomicsThreadFence(.release)
CAtomicsThreadFence(.acquire)
}
}
| bsd-3-clause | 7228761e88f65d9ea257d22d5dfd0f23 | 25.891001 | 92 | 0.632889 | 3.110085 | false | false | false | false |
jrmgx/swift | jrmgx/Classes/Helper/JrmgxKeyboard.swift | 1 | 4129 |
import UIKit
/**
* NAME
*
* - parameters
* - name: String
* - returns: nothing
* TODO rename jrmgxkeyboardprotocol => *delegate
*/
public protocol JrmgxKeyboardProtocol: class {
// TODO give the height already calculated or even pass hte constraint+time to animate
func keyboardWillShow(_ notification: Notification) /* example implementation {
let height = JrmgxKeyboard.GetKeyboardHeight(fromNotification: notification)
view.layoutIfNeeded()
textFieldContainerBottomConstraint.constant = height
UIView.animate(withDuration: 1) {
self.view.layoutIfNeeded()
self.chatSourceAndDelegate.scrollToBottom()
}
} */
func keyboardWillBeHidden(_ notification: Notification)
}
open class JrmgxKeyboard: NSObject {
//
fileprivate static let DefaultKeyboardHeight: CGFloat = 216 // good default value
/**
* NAME
*
* - parameters
* - name: String
* - returns: nothing
*/
open weak var delegate: JrmgxKeyboardProtocol?
/**
* NAME
*
* - parameters
* - name: String
* - returns: nothing
*/
public init(withDelegate: JrmgxKeyboardProtocol) {
super.init()
delegate = withDelegate
registerNotifications()
}
deinit {
unregisterNotifications()
}
/**
* NAME
*
* - parameters
* - name: String
* - returns: nothing
*/
open class func GetKeyboardHeight(fromNotification notification: Notification) -> CGFloat {
let dict = (notification as NSNotification).userInfo
let value = dict?[UIKeyboardFrameEndUserInfoKey] as? NSValue
let rect = value?.cgRectValue
if let h = rect?.height {
return h
}
printd("WARNING Got default value for Keyboard height")
return DefaultKeyboardHeight
}
/**
* NAME
*
* - parameters
* - name: String
* - returns: nothing
*/
open class func ShowKeyboard(forTextView textView: UITextView) {
textView.becomeFirstResponder()
}
/**
* NAME
*
* - parameters
* - name: String
* - returns: nothing
*/
open class func ShowKeyboard(forTextField textField: UITextField) {
textField.becomeFirstResponder()
}
/**
* NAME
*
* - parameters
* - name: String
* - returns: nothing
*/
open class func HideKeyboard(forTextView textView: UITextView) {
textView.resignFirstResponder()
}
/**
* NAME
*
* - parameters
* - name: String
* - returns: nothing
*/
open class func HideKeyboard(forTextField textField: UITextField) {
textField.resignFirstResponder()
}
/**
* NAME
*
* - parameters
* - name: String
* - returns: nothing
*/
open func delegateKeyboardWillShow(_ notification: Notification) {
if let delegate = delegate {
delegate.keyboardWillShow(notification)
}
}
/**
* NAME
*
* - parameters
* - name: String
* - returns: nothing
*/
open func delegateKeyboardWillBeHidden(_ notification: Notification) {
if let delegate = delegate {
delegate.keyboardWillBeHidden(notification)
}
}
/**
* NAME
*
* - parameters
* - name: String
* - returns: nothing
*/
open func registerNotifications() {
NotificationCenter.default.addObserver(self, selector: #selector(JrmgxKeyboard.delegateKeyboardWillShow(_:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(JrmgxKeyboard.delegateKeyboardWillBeHidden(_:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}
/**
* NAME
*
* - parameters
* - name: String
* - returns: nothing
*/
open func unregisterNotifications() {
if let d = delegate {
NotificationCenter.default.removeObserver(d)
}
}
}
| mit | 52e1151cb84e844157c69f77de299963 | 23.146199 | 180 | 0.597723 | 4.968712 | false | false | false | false |
joerocca/GitHawk | Classes/Notifications/NotificationViewModel.swift | 1 | 2454 | //
// NotificationViewModel.swift
// Freetime
//
// Created by Ryan Nystrom on 5/12/17.
// Copyright © 2017 Ryan Nystrom. All rights reserved.
//
import Foundation
import IGListKit
import FlatCache
final class NotificationViewModel: ListDiffable, Cachable {
enum Identifier {
case number(Int)
case hash(String)
}
let id: String
let title: NSAttributedStringSizing
let type: NotificationType
let date: Date
let read: Bool
let owner: String
let repo: String
let identifier: Identifier
init(
id: String,
title: NSAttributedStringSizing,
type: NotificationType,
date: Date,
read: Bool,
owner: String,
repo: String,
identifier: Identifier
) {
self.id = id
self.title = title
self.type = type
self.date = date
self.read = read
self.owner = owner
self.repo = repo
self.identifier = identifier
}
convenience init(
id: String,
title: String,
type: NotificationType,
date: Date,
read: Bool,
owner: String,
repo: String,
identifier: Identifier,
containerWidth: CGFloat
) {
let attributes = [
NSAttributedStringKey.font: Styles.Fonts.body,
NSAttributedStringKey.foregroundColor: Styles.Colors.Gray.dark.color
]
let title = NSAttributedStringSizing(
containerWidth: containerWidth,
attributedText: NSAttributedString(string: title, attributes: attributes),
inset: NotificationCell.labelInset
)
self.init(
id: id,
title: title,
type: type,
date: date,
read: read,
owner: owner,
repo: repo,
identifier: identifier
)
}
// MARK: ListDiffable
func diffIdentifier() -> NSObjectProtocol {
return id as NSObjectProtocol
}
func isEqual(toDiffableObject object: ListDiffable?) -> Bool {
if self === object { return true }
guard let object = object as? NotificationViewModel else { return false }
return read == object.read
&& type == object.type
&& date == object.date
&& repo == object.repo
&& owner == object.owner
&& title.attributedText.string == object.title.attributedText.string
}
}
| mit | 0c25378531f2c250c3a9e79e4d22d028 | 24.030612 | 86 | 0.581737 | 4.985772 | false | false | false | false |
cloudofpoints/Pachinko | Pachinko/Model/Feature/FeatureContext.swift | 1 | 2754 | //
// FeatureContext.swift
// Pachinko
//
// Created by Antrobus, Tim on 12/10/2015.
// Copyright © 2015 cloudofpoints. All rights reserved.
//
import Foundation
public func ==(lhs: FeatureContext, rhs: FeatureContext) -> Bool {
return (lhs.id == rhs.id && lhs.name == rhs.name && lhs.synopsis == rhs.synopsis)
}
public struct FeatureContext : Hashable {
public let id: String
public let name: String
public let synopsis: String
public var features: [BaseFeature]?
public var hashValue: Int {
return (31 &* id.hashValue) &+ name.hashValue &+ synopsis.hashValue
}
public init(id: String, name: String, synopsis: String) {
self.id = id
self.name = name
self.synopsis = synopsis
}
public func featureSet() -> Set<BaseFeature>? {
guard let contextFeatures = features else {
return .None
}
return Set<BaseFeature>(contextFeatures)
}
}
extension FeatureContext: PListTemplatable, Versionable {
public init?(template: NSDictionary?) {
guard let context = template else {
return nil
}
guard let id = context[FeaturePlistKey.CONTEXT_ID.rawValue] as? String,
name = context[FeaturePlistKey.CONTEXT_NAME.rawValue] as? String,
synopsis = context[FeaturePlistKey.CONTEXT_SYNOPSIS.rawValue] as? String else {
return nil
}
self.id = id
self.name = name
self.synopsis = synopsis
if let featureTemplates = context[FeaturePlistKey.CONTEXT_FEATURES.rawValue] as? [NSDictionary] {
if let featureModels: [BaseFeature]? = featureTemplates.map({BaseFeature(template: $0)!}) {
self.features = featureModels
}
}
}
public func plistTemplate() -> NSDictionary {
var template: [String:AnyObject] = [FeaturePlistKey.CONTEXT_ID.rawValue:id,
FeaturePlistKey.CONTEXT_NAME.rawValue:name,
FeaturePlistKey.CONTEXT_SYNOPSIS.rawValue:synopsis]
if let featureModels = features {
let featureTemplates: [AnyObject] = featureModels.flatMap({$0.plistTemplate()})
template[FeaturePlistKey.CONTEXT_FEATURES.rawValue] = featureTemplates
}
return template
}
public func activeVersion() -> FeatureVersion? {
guard let contextFeatures = features else {
return .None
}
guard let maxActiveVersion = contextFeatures.map({$0.signature.versionId}).maxElement() else {
return .None
}
return maxActiveVersion
}
} | bsd-3-clause | d32a8aa98bb303bf4c090f0e62bd25db | 28.612903 | 105 | 0.59862 | 4.787826 | false | false | false | false |
alfishe/mooshimeter-osx | mooshimeter-osx/Common/CoreBluetoothExtensions.swift | 1 | 3937 | //
// CoreBluetoothExtensions.swift
// mooshimeter-osx
//
// Created by Dev on 9/9/16.
// Copyright © 2016 alfishe. All rights reserved.
//
import Foundation
import CoreBluetooth
extension CBUUID
{
class func expandToMooshimUUID(_ sourceUUID: UInt16) -> CBUUID
{
let expandedUUIDBytes: [UInt8] =
[
0x1b, 0xc5, sourceUUID.hiByte(), sourceUUID.loByte(),
0x02, 0x00, 0x62, 0xab,
0xe4, 0x11, 0xf2, 0x54,
0xe0, 0x05, 0xdb, 0xd4
]
let data = NSMutableData(bytes: expandedUUIDBytes, length: expandedUUIDBytes.count)
let result = CBUUID(data: data as Data)
return result
}
class func expandToUUID(_ sourceUUID: UInt16) -> CBUUID
{
let result: CBUUID = CBUUID(string: String(format:"%2X", sourceUUID))
return result
}
}
extension CBCharacteristic
{
func isWritable() -> Bool
{
return (self.properties.intersection(CBCharacteristicProperties.write)) != []
}
func isReadable() -> Bool
{
return (self.properties.intersection(CBCharacteristicProperties.read)) != []
}
func isWritableWithoutResponse() -> Bool
{
return (self.properties.intersection(CBCharacteristicProperties.writeWithoutResponse)) != []
}
func isNotifable() -> Bool
{
return (self.properties.intersection(CBCharacteristicProperties.notify)) != []
}
func isIdicatable() -> Bool
{
return (self.properties.intersection(CBCharacteristicProperties.indicate)) != []
}
func isBroadcastable() -> Bool
{
return (self.properties.intersection(CBCharacteristicProperties.broadcast)) != []
}
func isExtendedProperties() -> Bool
{
return (self.properties.intersection(CBCharacteristicProperties.extendedProperties)) != []
}
func isAuthenticatedSignedWrites() -> Bool
{
return (self.properties.intersection(CBCharacteristicProperties.authenticatedSignedWrites)) != []
}
func isNotifyEncryptionRequired() -> Bool
{
return (self.properties.intersection(CBCharacteristicProperties.notifyEncryptionRequired)) != []
}
func isIndicateEncryptionRequired() -> Bool
{
return (self.properties.intersection(CBCharacteristicProperties.indicateEncryptionRequired)) != []
}
func getPropertyContent() -> String
{
var propContent = ""
if (self.properties.intersection(CBCharacteristicProperties.broadcast)) != []
{
propContent += "Broadcast,"
}
if (self.properties.intersection(CBCharacteristicProperties.read)) != []
{
propContent += "Read,"
}
if (self.properties.intersection(CBCharacteristicProperties.writeWithoutResponse)) != []
{
propContent += "WriteWithoutResponse,"
}
if (self.properties.intersection(CBCharacteristicProperties.write)) != []
{
propContent += "Write,"
}
if (self.properties.intersection(CBCharacteristicProperties.notify)) != []
{
propContent += "Notify,"
}
if (self.properties.intersection(CBCharacteristicProperties.indicate)) != []
{
propContent += "Indicate,"
}
if (self.properties.intersection(CBCharacteristicProperties.authenticatedSignedWrites)) != []
{
propContent += "AuthenticatedSignedWrites,"
}
if (self.properties.intersection(CBCharacteristicProperties.extendedProperties)) != []
{
propContent += "ExtendedProperties,"
}
if (self.properties.intersection(CBCharacteristicProperties.notifyEncryptionRequired)) != []
{
propContent += "NotifyEncryptionRequired,"
}
if (self.properties.intersection(CBCharacteristicProperties.indicateEncryptionRequired)) != []
{
propContent += "IndicateEncryptionRequired,"
}
if !propContent.isEmpty
{
propContent = propContent.substring(to: propContent.characters.index(propContent.endIndex, offsetBy: -1))
}
return propContent
}
}
| mit | fcc28077a4c70cdab9b7603234791268 | 24.72549 | 111 | 0.67251 | 4.736462 | false | false | false | false |
overtake/TelegramSwift | Telegram-Mac/ChannelStatsViewController.swift | 1 | 14665 | //
// ChannelStatsViewController.swift
// Telegram
//
// Created by Mikhail Filimonov on 24.02.2020.
// Copyright © 2020 Telegram. All rights reserved.
//
import Cocoa
import TGUIKit
import SwiftSignalKit
import TelegramCore
import Postbox
import GraphCore
struct UIStatsState : Equatable {
enum RevealSection : Hashable {
case topPosters
case topAdmins
case topInviters
var id: InputDataIdentifier {
switch self {
case .topPosters:
return InputDataIdentifier("_id_top_posters")
case .topAdmins:
return InputDataIdentifier("_id_top_admins")
case .topInviters:
return InputDataIdentifier("_id_top_inviters")
}
}
}
let loading: Set<InputDataIdentifier>
let revealed:Set<RevealSection>
init(loading: Set<InputDataIdentifier>, revealed: Set<RevealSection> = Set()) {
self.loading = loading
self.revealed = revealed
}
func withAddedLoading(_ token: InputDataIdentifier) -> UIStatsState {
var loading = self.loading
loading.insert(token)
return UIStatsState(loading: loading, revealed: self.revealed)
}
func withRemovedLoading(_ token: InputDataIdentifier) -> UIStatsState {
var loading = self.loading
loading.remove(token)
return UIStatsState(loading: loading, revealed: self.revealed)
}
func withRevealedSection(_ section: RevealSection) -> UIStatsState {
var revealed = self.revealed
revealed.insert(section)
return UIStatsState(loading: self.loading, revealed: revealed)
}
}
private func _id_message(_ messageId: MessageId) -> InputDataIdentifier {
return InputDataIdentifier("_id_message_\(messageId)")
}
private func statsEntries(_ state: ChannelStatsContextState, uiState: UIStatsState, messages: [Message]?, interactions: [MessageId : ChannelStatsMessageInteractions]?, updateIsLoading: @escaping(InputDataIdentifier, Bool)->Void, openMessage: @escaping(MessageId)->Void, context: ChannelStatsContext, accountContext: AccountContext, detailedDisposable: DisposableDict<InputDataIdentifier>) -> [InputDataEntry] {
var entries: [InputDataEntry] = []
var sectionId: Int32 = 0
var index: Int32 = 0
if state.stats == nil {
entries.append(.custom(sectionId: sectionId, index: index, value: .none, identifier: InputDataIdentifier("loading"), equatable: nil, comparable: nil, item: { initialSize, stableId in
return StatisticsLoadingRowItem(initialSize, stableId: stableId, context: accountContext, text: strings().channelStatsLoading)
}))
} else if let stats = state.stats {
entries.append(.sectionId(sectionId, type: .normal))
sectionId += 1
entries.append(.desc(sectionId: sectionId, index: index, text: .plain(strings().channelStatsOverview), data: .init(color: theme.colors.listGrayText, viewType: .textTopItem)))
index += 1
var overviewItems:[ChannelOverviewItem] = []
if stats.followers.current > 0 {
overviewItems.append(ChannelOverviewItem(title: strings().channelStatsOverviewFollowers, value: stats.followers.attributedString))
}
if stats.enabledNotifications.total != 0 {
overviewItems.append(ChannelOverviewItem(title: strings().channelStatsOverviewEnabledNotifications, value: stats.enabledNotifications.attributedString))
}
if stats.viewsPerPost.current > 0 {
overviewItems.append(ChannelOverviewItem(title: strings().channelStatsOverviewViewsPerPost, value: stats.viewsPerPost.attributedString))
}
if stats.sharesPerPost.current > 0 {
overviewItems.append(ChannelOverviewItem(title: strings().channelStatsOverviewSharesPerPost, value: stats.sharesPerPost.attributedString))
}
entries.append(.custom(sectionId: sectionId, index: index, value: .none, identifier: InputDataIdentifier("overview"), equatable: InputDataEquatable(overviewItems), comparable: nil, item: { initialSize, stableId in
return ChannelOverviewStatsRowItem(initialSize, stableId: stableId, items: overviewItems, viewType: .singleItem)
}))
index += 1
struct Graph {
let graph: StatsGraph
let title: String
let identifier: InputDataIdentifier
let type: ChartItemType
let load:(InputDataIdentifier)->Void
}
var graphs: [Graph] = []
graphs.append(Graph(graph: stats.growthGraph, title: strings().channelStatsGraphGrowth, identifier: InputDataIdentifier("growthGraph"), type: .lines, load: { identifier in
context.loadGrowthGraph()
updateIsLoading(identifier, true)
}))
graphs.append(Graph(graph: stats.followersGraph, title: strings().channelStatsGraphFollowers, identifier: InputDataIdentifier("followersGraph"), type: .lines, load: { identifier in
context.loadFollowersGraph()
updateIsLoading(identifier, true)
}))
graphs.append(Graph(graph: stats.muteGraph, title: strings().channelStatsGraphNotifications, identifier: InputDataIdentifier("muteGraph"), type: .lines, load: { identifier in
context.loadMuteGraph()
updateIsLoading(identifier, true)
}))
graphs.append(Graph(graph: stats.topHoursGraph, title: strings().channelStatsGraphViewsByHours, identifier: InputDataIdentifier("topHoursGraph"), type: .hourlyStep, load: { identifier in
context.loadTopHoursGraph()
updateIsLoading(identifier, true)
}))
if !stats.viewsBySourceGraph.isEmpty {
graphs.append(Graph(graph: stats.viewsBySourceGraph, title: strings().channelStatsGraphViewsBySource, identifier: InputDataIdentifier("viewsBySourceGraph"), type: .bars, load: { identifier in
context.loadViewsBySourceGraph()
updateIsLoading(identifier, true)
}))
}
if !stats.newFollowersBySourceGraph.isEmpty {
graphs.append(Graph(graph: stats.newFollowersBySourceGraph, title: strings().channelStatsGraphNewFollowersBySource, identifier: InputDataIdentifier("newFollowersBySourceGraph"), type: .bars, load: { identifier in
context.loadNewFollowersBySourceGraph()
updateIsLoading(identifier, true)
}))
}
if !stats.languagesGraph.isEmpty {
graphs.append(Graph(graph: stats.languagesGraph, title: strings().channelStatsGraphLanguage, identifier: InputDataIdentifier("languagesGraph"), type: .pie, load: { identifier in
context.loadLanguagesGraph()
updateIsLoading(identifier, true)
}))
}
if !stats.interactionsGraph.isEmpty {
graphs.append(Graph(graph: stats.interactionsGraph, title: strings().channelStatsGraphInteractions, identifier: InputDataIdentifier("interactionsGraph"), type: .twoAxisStep, load: { identifier in
context.loadInteractionsGraph()
updateIsLoading(identifier, true)
}))
}
for graph in graphs {
entries.append(.sectionId(sectionId, type: .normal))
sectionId += 1
entries.append(.desc(sectionId: sectionId, index: index, text: .plain(graph.title), data: .init(color: theme.colors.listGrayText, viewType: .textTopItem)))
index += 1
switch graph.graph {
case let .Loaded(_, string):
ChartsDataManager.readChart(data: string.data(using: .utf8)!, sync: true, success: { collection in
entries.append(.custom(sectionId: sectionId, index: index, value: .none, identifier: graph.identifier, equatable: InputDataEquatable(graph.graph), comparable: nil, item: { initialSize, stableId in
return StatisticRowItem(initialSize, stableId: stableId, context: accountContext, collection: collection, viewType: .singleItem, type: graph.type, getDetailsData: { date, completion in
detailedDisposable.set(context.loadDetailedGraph(graph.graph, x: Int64(date.timeIntervalSince1970) * 1000).start(next: { graph in
if let graph = graph, case let .Loaded(_, data) = graph {
completion(data)
}
}), forKey: graph.identifier)
})
}))
}, failure: { error in
entries.append(.custom(sectionId: sectionId, index: index, value: .none, identifier: graph.identifier, equatable: InputDataEquatable(graph.graph), comparable: nil, item: { initialSize, stableId in
return StatisticLoadingRowItem(initialSize, stableId: stableId, error: error.localizedDescription)
}))
})
updateIsLoading(graph.identifier, false)
index += 1
case .OnDemand:
entries.append(.custom(sectionId: sectionId, index: index, value: .none, identifier: graph.identifier, equatable: InputDataEquatable(graph.graph), comparable: nil, item: { initialSize, stableId in
return StatisticLoadingRowItem(initialSize, stableId: stableId, error: nil)
}))
index += 1
if !uiState.loading.contains(graph.identifier) {
graph.load(graph.identifier)
}
case let .Failed(error):
entries.append(.custom(sectionId: sectionId, index: index, value: .none, identifier: graph.identifier, equatable: InputDataEquatable(graph.graph), comparable: nil, item: { initialSize, stableId in
return StatisticLoadingRowItem(initialSize, stableId: stableId, error: error)
}))
index += 1
updateIsLoading(graph.identifier, false)
case .Empty:
break
}
}
entries.append(.sectionId(sectionId, type: .normal))
sectionId += 1
if let messages = messages, let interactions = interactions, !messages.isEmpty {
entries.append(.desc(sectionId: sectionId, index: index, text: .plain(strings().channelStatsRecentHeader), data: .init(color: theme.colors.listGrayText, viewType: .textTopItem)))
index += 1
for (i, message) in messages.enumerated() {
entries.append(.custom(sectionId: sectionId, index: index, value: .none, identifier: _id_message(message.id), equatable: InputDataEquatable(message), comparable: nil, item: { initialSize, stableId in
return ChannelRecentPostRowItem(initialSize, stableId: stableId, context: accountContext, message: message, interactions: interactions[message.id], viewType: bestGeneralViewType(messages, for: i), action: {
openMessage(message.id)
})
}))
index += 1
}
entries.append(.sectionId(sectionId, type: .normal))
sectionId += 1
}
}
return entries
}
func ChannelStatsViewController(_ context: AccountContext, peerId: PeerId, datacenterId: Int32) -> ViewController {
let initialState = UIStatsState(loading: [])
let statePromise = ValuePromise(initialState, ignoreRepeated: true)
let stateValue = Atomic(value: initialState)
let updateState: ((UIStatsState) -> UIStatsState) -> Void = { f in
statePromise.set(stateValue.modify { f($0) })
}
let statsContext = ChannelStatsContext(postbox: context.account.postbox, network: context.account.network, datacenterId: datacenterId, peerId: peerId)
let messagesPromise = Promise<MessageHistoryView?>(nil)
let messageView = context.account.viewTracker.aroundMessageHistoryViewForLocation(.peer(peerId: peerId, threadId: nil), index: .upperBound, anchorIndex: .upperBound, count: 100, fixedCombinedReadStates: nil)
|> map { messageHistoryView, _, _ -> MessageHistoryView? in
return messageHistoryView
}
messagesPromise.set(.single(nil) |> then(messageView))
let openMessage: (MessageId)->Void = { messageId in
context.bindings.rootNavigation().push(MessageStatsController(context, messageId: messageId, datacenterId: datacenterId))
}
let detailedDisposable = DisposableDict<InputDataIdentifier>()
let signal = combineLatest(queue: prepareQueue, statePromise.get(), statsContext.state, messagesPromise.get()) |> map { uiState, state, messageView in
let interactions = state.stats?.messageInteractions.reduce([MessageId : ChannelStatsMessageInteractions]()) { (map, interactions) -> [MessageId : ChannelStatsMessageInteractions] in
var map = map
map[interactions.messageId] = interactions
return map
}
let messages = messageView?.entries.map { $0.message }.filter { interactions?[$0.id] != nil }.sorted(by: { (lhsMessage, rhsMessage) -> Bool in
return lhsMessage.timestamp > rhsMessage.timestamp
})
return statsEntries(state, uiState: uiState, messages: messages, interactions: interactions, updateIsLoading: { identifier, isLoading in
updateState { state in
if isLoading {
return state.withAddedLoading(identifier)
} else {
return state.withRemovedLoading(identifier)
}
}
}, openMessage: openMessage, context: statsContext, accountContext: context, detailedDisposable: detailedDisposable)
} |> map {
return InputDataSignalValue(entries: $0)
}
let controller = InputDataController(dataSignal: signal, title: strings().channelStatsTitle, removeAfterDisappear: false, hasDone: false)
controller.contextObject = statsContext
controller.didLoaded = { controller, _ in
controller.tableView.alwaysOpenRowsOnMouseUp = true
controller.tableView.needUpdateVisibleAfterScroll = true
}
controller.onDeinit = {
detailedDisposable.dispose()
}
return controller
}
| gpl-2.0 | 345ae3ae5324b4d3c6a56a13d9a49440 | 46.303226 | 410 | 0.640616 | 5.365532 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.