repo_name
stringlengths
6
91
ref
stringlengths
12
59
path
stringlengths
7
936
license
stringclasses
15 values
copies
stringlengths
1
3
content
stringlengths
61
711k
hash
stringlengths
32
32
line_mean
float64
4.88
60.8
line_max
int64
12
421
alpha_frac
float64
0.1
0.92
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
openHPI/xikolo-ios
refs/heads/dev
Common/Branding/Brand.swift
gpl-3.0
1
// // Created for xikolo-ios under GPL-3.0 license. // Copyright © HPI. All rights reserved. // import Foundation import UIKit public struct Brand: Decodable { private enum CodingKeys: CodingKey { case host case imprintURL case privacyURL case faqURL case singleSignOn case copyrightName case poweredByText case colors case courseDateLabelStyle case showCurrentCoursesInSelfPacedSection case features case courseClassifierSearchFilters case additionalLearningMaterial case testAccountUserId } public static let `default`: Brand = { let data = NSDataAsset(name: "BrandConfiguration")?.data let decoder = PropertyListDecoder() return try! decoder.decode(Brand.self, from: data!) // swiftlint:disable:this force_try }() private let copyrightName: String public let host: String let imprintURL: URL let privacyURL: URL let faqURL: URL public let colors: BrandColors public let singleSignOn: SingleSignOnConfiguration? public let poweredByText: String? public let courseDateLabelStyle: CourseDateLabelStyle public let showCurrentCoursesInSelfPacedSection: Bool public let features: BrandFeatures public let courseClassifierSearchFilters: CourseClassifierSearchFilters? public let additionalLearningMaterial: [AdditionalLearningMaterial] public let testAccountUserId: String? public var copyrightText: String { let currentYear = Calendar.current.component(.year, from: Date()) return "Copyright © \(currentYear) \(self.copyrightName). All rights reserved." } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) self.host = try container.decode(String.self, forKey: .host) self.imprintURL = try container.decodeURL(forKey: .imprintURL) self.privacyURL = try container.decodeURL(forKey: .privacyURL) self.faqURL = try container.decodeURL(forKey: .faqURL) self.singleSignOn = try? container.decode(SingleSignOnConfiguration.self, forKey: .singleSignOn) self.copyrightName = try container.decode(String.self, forKey: .copyrightName) self.poweredByText = try container.decodeIfPresent(String.self, forKey: .poweredByText) self.colors = try container.decode(BrandColors.self, forKey: .colors) self.courseDateLabelStyle = try container.decodeCourseDateLabelStyle(forKey: .courseDateLabelStyle) self.showCurrentCoursesInSelfPacedSection = try container.decodeIfPresent(Bool.self, forKey: .showCurrentCoursesInSelfPacedSection) ?? false self.features = try container.decode(BrandFeatures.self, forKey: .features) self.courseClassifierSearchFilters = try? container.decode(CourseClassifierSearchFilters.self, forKey: .courseClassifierSearchFilters) self.additionalLearningMaterial = try container.decodeIfPresent([AdditionalLearningMaterial].self, forKey: .additionalLearningMaterial) ?? [] self.testAccountUserId = try? container.decode(String.self, forKey: .testAccountUserId) } } private extension KeyedDecodingContainer { func decodeURL(forKey key: K) throws -> URL { let value = try self.decode(String.self, forKey: key) return URL(string: value)! } func decodeCourseDateLabelStyle(forKey key: K) throws -> CourseDateLabelStyle { let defaultValue = CourseDateLabelStyle.normal guard let value = try self.decodeIfPresent(String.self, forKey: key) else { return defaultValue } return CourseDateLabelStyle(rawValue: value) ?? defaultValue } }
ee735f14f4de90173c28d22e37334024
40.764045
149
0.724778
false
false
false
false
NobodyNada/FireAlarm
refs/heads/master
Sources/Frontend/RowEncoder.swift
mit
3
// // RowEncoder.swift // FireAlarm // // Created by NobodyNada on 7/14/17. // import Foundation import SwiftChatSE internal func nestedObject() -> Never { fatalError("Arrays and nested dictionaries may not be encoded into database rows") } public class RowEncoder { public init() {} public func encode(_ value: Codable) throws -> Row { let encoder = _RowEncoder() try value.encode(to: encoder) var columns = [DatabaseNativeType?]() var columnIndices = [String:Int]() for (key, value) in encoder.storage { columnIndices[key] = columns.count columns.append(value?.asNative) } return Row(columns: columns, columnNames: columnIndices) } } private class _RowEncoder: Encoder { var codingPath: [CodingKey] = [] var userInfo: [CodingUserInfoKey : Any] = [:] var storage: [String:DatabaseType?] = [:] func container<Key>(keyedBy type: Key.Type) -> KeyedEncodingContainer<Key> where Key : CodingKey { return KeyedEncodingContainer(_KeyedEncoder<Key>(encoder: self, codingPath: codingPath)) } func unkeyedContainer() -> UnkeyedEncodingContainer { nestedObject() } func singleValueContainer() -> SingleValueEncodingContainer { guard !codingPath.isEmpty else { fatalError("Root object for a database row must be a dictionary") } return _SingleValueContainer(encoder: self, key: codingPath.last!, codingPath: codingPath) } } private class _KeyedEncoder<K: CodingKey>: KeyedEncodingContainerProtocol { typealias Key = K let encoder: _RowEncoder let codingPath: [CodingKey] init(encoder: _RowEncoder, codingPath: [CodingKey]) { self.encoder = encoder self.codingPath = codingPath } func encodeNil(forKey key: K) throws { encoder.storage[key.stringValue] = nil as DatabaseType? } func encode(_ value: DatabaseType, forKey key: K) throws { encoder.storage[key.stringValue] = value } func encode<T>(_ value: T, forKey key: K) throws where T : Encodable { if let v = value as? DatabaseType { try encode(v, forKey: key) return } encoder.codingPath.append(key) try value.encode(to: encoder) encoder.codingPath.removeLast() } func nestedContainer<NestedKey: CodingKey>(keyedBy keyType: NestedKey.Type, forKey key: K) -> KeyedEncodingContainer<NestedKey> { nestedObject() } func nestedUnkeyedContainer(forKey key: K) -> UnkeyedEncodingContainer { nestedObject() } func superEncoder() -> Encoder { nestedObject() } func superEncoder(forKey key: K) -> Encoder { nestedObject() } } private class _SingleValueContainer: SingleValueEncodingContainer { let encoder: _RowEncoder let key: CodingKey let codingPath: [CodingKey] init(encoder: _RowEncoder, key: CodingKey, codingPath: [CodingKey]) { self.encoder = encoder self.key = key self.codingPath = codingPath } func encodeNil() throws { try encode(nil as DatabaseType?) } func encode(_ value: DatabaseType?) throws { encoder.storage[key.stringValue] = value } func encode<T>(_ value: T) throws where T : Encodable { fatalError("Single-value containers may only encode DatabaseTypes") } }
2870f4d213d0873fd4db8eb806f1e44a
26.585938
133
0.626735
false
false
false
false
DonMag/ScratchPad
refs/heads/master
Swift3/scratchy/XC8.playground/Pages/TableView.xcplaygroundpage/Contents.swift
mit
1
//: [Previous](@previous) import Foundation import UIKit import PlaygroundSupport class rndCell: UITableViewCell { var myLabel1: UILabel! var myLabel2: UILabel! var myBKGView: UIView! required init(coder aDecoder: NSCoder) { fatalError("init(coder:)") } override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) let gap : CGFloat = 10 let labelHeight: CGFloat = 30 let labelWidth: CGFloat = 150 let lineGap : CGFloat = 5 let label2Y : CGFloat = gap + labelHeight + lineGap let v = UIView(frame: CGRect.zero) v.backgroundColor = UIColor.red v.translatesAutoresizingMaskIntoConstraints = false contentView.addSubview(v) v.leadingAnchor.constraint(equalTo: contentView.leadingAnchor).isActive = true v.trailingAnchor.constraint(equalTo: contentView.trailingAnchor).isActive = true v.topAnchor.constraint(equalTo: contentView.topAnchor).isActive = true v.bottomAnchor.constraint(equalTo: contentView.bottomAnchor).isActive = true myBKGView = v myLabel1 = UILabel() myLabel1.frame = CGRect(x: gap, y: gap, width: labelWidth, height: labelHeight) // CGRectMake(gap, gap, labelWidth, labelHeight) myLabel1.textColor = UIColor.black contentView.addSubview(myLabel1) myLabel2 = UILabel() myLabel2.frame = CGRect(x: gap, y: label2Y, width: labelWidth, height: labelHeight) //CGRectMake(gap, label2Y, labelWidth, labelHeight) myLabel2.textColor = UIColor.blue contentView.addSubview(myLabel2) } override func layoutSubviews() { super.layoutSubviews() myBKGView.layer.cornerRadius = myBKGView.frame.height / 2 } } class TableViewController: UITableViewController { override func viewDidLoad() { // tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell") tableView.register(rndCell.self, forCellReuseIdentifier: "Cell") tableView.contentInset.top = 76.0 tableView.backgroundColor = UIColor.clear } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) var r = tableView.bounds let wImg = UIImage(named: "wtran") let bImg = UIImage(named: "bt") let imgLayer = CALayer() imgLayer.contents = bImg?.cgImage r.size = (bImg?.size)! imgLayer.frame = r tableView.superview?.layer.mask = imgLayer // let theLayer = CAShapeLayer() //// theLayer.backgroundColor = UIColor.orange.cgColor // // theLayer.frame = r // // r.size.height = 260 // r.origin.x = 40 // r.size.width -= 80 // //// let pth = UIBezierPath() //// pth.move(to: CGPoint(x: 0, y: 0)) //// pth.addLine(to: CGPoint(x: 200, y: 0)) //// pth.addLine(to: CGPoint(x: 200, y: 100)) //// pth.addLine(to: CGPoint(x: 0, y: 100)) //// pth.close() // // let pth = CGPath(rect: r, transform: nil) // // theLayer.path = pth // theLayer.fillColor = UIColor.gray.cgColor //// theLayer.fillRule = kCAFillRuleNonZero // // tableView.layer.mask = theLayer // tableView.superview?.layer.mask = theLayer // let theLayer = CALayer() // var r = tableView.frame //// r.size.height = 176 // theLayer.frame = r // CGRect(x: 0, y: 0, width: tableView.frame.width, height: 76) //CGRectMake(0, 0, self.tableView.frame.width, 76) // var clr = UIColor(white: 0.0, alpha: 0.5) // UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 0.5) // theLayer.backgroundColor = clr.cgColor // // r.size.height = 100 // // var pth = CGPath(rect: r, transform: nil) // // // // tableView.superview?.layer.mask = theLayer // tableView.superview?.layer.addSublayer(theLayer) // r.origin.y = 76 // // let theGradLayer = CAGradientLayer() // theGradLayer.frame = r // // var trC = UIColor.darkGray.cgColor // var opC = UIColor.clear.cgColor // // theGradLayer.colors = [trC, trC, opC, opC] // theGradLayer.locations = [0.0, 0.31, 0.31, 1] // // tableView.superview?.layer.mask = theGradLayer // tableView.superview?.layer.addSublayer(theGradLayer) // CAGradientLayer *gradientLayer = [CAGradientLayer layer]; // gradientLayer.frame = self.tableView.frame; // id transparent = (id)[UIColor clearColor].CGColor; // id opaque = (id)[UIColor blackColor].CGColor; // gradientLayer.colors = @[transparent, opaque, opaque]; // gradientLayer.locations = @[@0.1, @0.11, @1]; // self.tableView.superview.layer.mask = gradientLayer; } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 15 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath as IndexPath) as! rndCell cell.myLabel1.text = "Sec: \(indexPath.section)" cell.myLabel2.text = "Row: \(indexPath.row)" // cell.textLabel?.text = "Row: \(indexPath.row)" return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let next = TableViewController() next.title = "Row: \(indexPath.row)" navigationController?.pushViewController(next, animated: true) print(navigationController?.viewControllers.count ?? "Hö?") } } let tableViewController = TableViewController() tableViewController.title = "start" let navigationController = UINavigationController(rootViewController: tableViewController) navigationController.view.frame.size = CGSize(width: 320, height: 400) navigationController.navigationBar.barTintColor = UIColor.white navigationController.view.backgroundColor = UIColor.green // PlaygroundPage.current.liveView = navigationController.view PlaygroundPage.current.needsIndefiniteExecution = true
cc522d45de16afee2b15fbdafb41376e
26.760976
137
0.708311
false
false
false
false
abellono/IssueReporter
refs/heads/master
IssueReporter/Core/Image.swift
mit
1
// // Image.swift // IssueReporter // // Created by Hakon Hanesand on 10/6/16. // Copyright © 2017 abello. All rights reserved. // // import Foundation internal class Image { let image: UIImage let identifier: String = UUID().uuidString let compressionRatio: Double = 0.5 var localImageURL: URL? = nil var cloudImageURL: URL? = nil var state: State = .initial var compressionCompletionBlock: (Image) -> () = { _ in } init(image: UIImage) { self.image = image.applyRotationToImageData() DispatchQueue.global(qos: .userInitiated).async { [weak self] in guard let strongSelf = self else { return } strongSelf.imageData = strongSelf.image.jpegData(compressionQuality: CGFloat(strongSelf.compressionRatio)) } } var imageData: Data? { didSet { DispatchQueue.main.async { self.compressionCompletionBlock(self) } } } } extension Image: Equatable { public static func ==(lhs: Image, rhs: Image) -> Bool { return lhs.identifier == rhs.identifier } }
4cddae13dea3413000838425b1430ac7
23.145833
118
0.599655
false
false
false
false
xocialize/Kiosk
refs/heads/master
kiosk/DataManager.swift
mit
1
// // DataManager.swift // kiosk // // Created by Dustin Nielson on 5/1/15. // Copyright (c) 2015 Dustin Nielson. All rights reserved. // import Foundation import UIKit import CoreData class DataManager: NSObject, NSFileManagerDelegate { var appDel:AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate // *** Mark Core Data Functions *** func getSettings() -> Dictionary<String,AnyObject> { var context:NSManagedObjectContext = appDel.managedObjectContext! var request = NSFetchRequest(entityName: "Settings") request.returnsObjectsAsFaults = false var results = context.executeFetchRequest(request, error: nil) if results!.count > 0 { for result: AnyObject in results! { var xset = result.valueForKey("settingsData") as? NSData let settings:Dictionary<String,AnyObject> = NSKeyedUnarchiver.unarchiveObjectWithData(xset!)! as! Dictionary return settings } } return Dictionary<String,AnyObject>() } func checkForIndex() -> Bool{ var folderPath = NSSearchPathForDirectoriesInDomains(.LibraryDirectory, .UserDomainMask, true)[0] as! String let fileManager = NSFileManager.defaultManager() var filePath: String = "kiosk_index.html" folderPath = folderPath + "/webFiles/" + filePath if NSFileManager.defaultManager().fileExistsAtPath(folderPath){ return true } return false } func saveSettings(dict: Dictionary<String,AnyObject> ){ var settings:Dictionary<String,AnyObject> = dict var context:NSManagedObjectContext = appDel.managedObjectContext! var request = NSFetchRequest(entityName: "Settings") request.returnsObjectsAsFaults = false var results = context.executeFetchRequest(request, error: nil) if results!.count > 0 { let data : NSData = NSKeyedArchiver.archivedDataWithRootObject(settings) let settingsTest:Dictionary<String,AnyObject> = NSKeyedUnarchiver.unarchiveObjectWithData(data)! as! Dictionary for result: AnyObject in results! { result.setValue(data, forKey: "settingsData") } } else { var uuid = NSUUID().UUIDString var uuidString = uuid as String settings["systemUUID"] = uuidString let data : NSData = NSKeyedArchiver.archivedDataWithRootObject(settings) var newPref = NSEntityDescription.insertNewObjectForEntityForName("Settings", inManagedObjectContext: context) as! NSManagedObject newPref.setValue(data, forKey: "settingsData") } context.save(nil) } // *** Mark File Directory Functions *** func showLibraryFiles(){ var folderPath = NSSearchPathForDirectoriesInDomains(.LibraryDirectory, .UserDomainMask, true)[0] as! String let fileManager = NSFileManager.defaultManager() let enumerator:NSDirectoryEnumerator = fileManager.enumeratorAtPath(folderPath)! while let element = enumerator.nextObject() as? String { if element != "" { let filePath = folderPath + "/" + element println(filePath) } } } func clearLibraryDirectory(){ var folderPath = NSSearchPathForDirectoriesInDomains(.LibraryDirectory, .UserDomainMask, true)[0] as! String let fileManager = NSFileManager.defaultManager() folderPath = folderPath + "/webFiles" if NSFileManager.defaultManager().fileExistsAtPath(folderPath){ fileManager.removeItemAtPath(folderPath, error: nil) } } func saveToLibrary(file:NSData, path:String){ let newPath = path.stringByReplacingOccurrencesOfString("/", withString: "_") FileSave.saveData(file, directory:NSSearchPathDirectory.LibraryDirectory, path: newPath, subdirectory: "webFiles") var paths = NSSearchPathForDirectoriesInDomains(.LibraryDirectory, .UserDomainMask, true)[0] as! String // Don't backup these files to iCloud var localUrl:NSURL = NSURL.fileURLWithPath(paths + "/webFiles/" + newPath)! var num:NSNumber = 1 if localUrl.setResourceValue(num, forKey: "NSURLIsExcludedFromBackupKey", error: nil) { println("Backup Disabled") } else { println("Backup Enabled") } } }
83b81babd7911cbbfad9a074c17acc5a
28.519774
142
0.564976
false
false
false
false
Longhanks/qlift
refs/heads/master
Sources/Qlift/QGroupBox.swift
mit
1
import CQlift open class QGroupBox: QWidget { public var alignment: Qt.Alignment = .AlignLeft { didSet { QGroupBox_setAlignment(self.ptr, alignment.rawValue) } } public var title: String = "" { didSet { QGroupBox_setTitle(self.ptr, title) } } public init(title: String = "", parent: QWidget? = nil) { self.title = title super.init(ptr: QGroupBox_new(title, parent?.ptr), parent: parent) } override init(ptr: UnsafeMutableRawPointer, parent: QWidget? = nil) { super.init(ptr: ptr, parent: parent) } deinit { if self.ptr != nil { if QObject_parent(self.ptr) == nil { QGroupBox_delete(self.ptr) } self.ptr = nil } } }
315e2f7748a1566f9b1e8e088b96e9e6
22.142857
74
0.540741
false
false
false
false
karstengresch/rw_studies
refs/heads/master
Apprentice/Checklists09/Checklists/ItemDetailViewController.swift
unlicense
1
// // ItemDetailViewController.swift // Checklists // // Created by Karsten Gresch on 02.12.15. // Copyright © 2015 Closure One. All rights reserved. // import Foundation import UIKit protocol ItemDetailViewControllerDelegate: class { func itemDetailViewControllerDidCancel(_ controller: ItemDetailViewController) func itemDetailViewController(_ controller: ItemDetailViewController, didFinishAddingItem checklistItem: ChecklistItem) func itemDetailViewController(_ controller: ItemDetailViewController, didFinishEditingItem checklistItem: ChecklistItem) } class ItemDetailViewController: UITableViewController, UITextFieldDelegate { var checklistItemToEdit: ChecklistItem? var dueDate = Date() var datePickerVisible = false @IBOutlet weak var addItemTextField: UITextField? @IBOutlet weak var doneBarButton: UIBarButtonItem? @IBOutlet weak var shouldRemindSwitch: UISwitch? @IBOutlet weak var dueDateLabel: UILabel? @IBOutlet weak var datePickerCell: UITableViewCell? @IBOutlet weak var datePicker: UIDatePicker? weak var delegate: ItemDetailViewControllerDelegate? // MARK: View related override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) addItemTextField?.becomeFirstResponder() } override func viewDidLoad() { super.viewDidLoad() if let itemToEdit = checklistItemToEdit { title = "Edit item" addItemTextField?.text = itemToEdit.text doneBarButton?.isEnabled = true shouldRemindSwitch?.isOn = itemToEdit.shouldRemind dueDate = itemToEdit.dueDate as Date } updateDueDateLabel() } func updateDueDateLabel() { print("updateDueDateLabel") let formatter = DateFormatter() formatter.dateStyle = .medium formatter.timeStyle = .short dueDateLabel?.text = formatter.string(from: dueDate) } // MARK: Table specific // MARK: Action handlers @IBAction func cancel() { // dismissViewControllerAnimated(true, completion: nil) delegate?.itemDetailViewControllerDidCancel(self); } @IBAction func done() { print("done()") if let checklistItem = checklistItemToEdit { print("done() - checklistItem exists") checklistItem.text = (addItemTextField?.text)! checklistItem.shouldRemind = (shouldRemindSwitch?.isOn)! checklistItem.dueDate = dueDate delegate?.itemDetailViewController(self, didFinishEditingItem: checklistItem) } else { print("done() - checklistItem does not exist") let checklistItem = ChecklistItem() checklistItem.text = (addItemTextField?.text)! checklistItem.checked = false checklistItem.shouldRemind = (shouldRemindSwitch?.isOn)! checklistItem.dueDate = dueDate delegate?.itemDetailViewController(self, didFinishAddingItem: checklistItem) } } // MARK: Text field specific func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { if let oldText: NSString = textField.text as NSString? { let newText: NSString = oldText.replacingCharacters(in: range, with: string) as NSString doneBarButton?.isEnabled = (newText.length > 0) } return true } func showDatePicker() { print("showDatePicker()") datePickerVisible = true let indexPathDatePicker = IndexPath(row: 2, section: 1) tableView.insertRows(at: [indexPathDatePicker], with: .fade) } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { print("cellForRowAtIndexPath() indexPath.section: \((indexPath as NSIndexPath).section) - indexPath.row: \((indexPath as NSIndexPath).row)") if (indexPath as NSIndexPath).section == 1 && (indexPath as NSIndexPath).row == 2 { // dangerous return datePickerCell! } else { return super.tableView(tableView, cellForRowAt: indexPath) } } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if section == 1 && datePickerVisible { print("numberOfRowsInSection(): section 1 AND datePickerVisible") return 3 } else { print("numberOfRowsInSection(): section 1 ?XOR datePickerVisible") return super.tableView(tableView, numberOfRowsInSection: section) } } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { if (indexPath as NSIndexPath).section == 1 && (indexPath as NSIndexPath).row == 2 { return 217 } else { return super.tableView(tableView, heightForRowAt: indexPath) } } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { print("didSelectRowAtIndexPath: \((indexPath as NSIndexPath).row) - didSelectRowAtIndexPath: \((indexPath as NSIndexPath).section)") tableView.deselectRow(at: indexPath, animated: true) addItemTextField?.resignFirstResponder() if (indexPath as NSIndexPath).section == 1 && (indexPath as NSIndexPath).row == 1 { print("Trying to show date picker") showDatePicker() } } override func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? { if (indexPath as NSIndexPath).section == 1 && (indexPath as NSIndexPath).row == 1 { return indexPath } else { return nil } } override func tableView(_ tableView: UITableView, indentationLevelForRowAt indexPath: IndexPath) -> Int { var indexPath = indexPath if (indexPath as NSIndexPath).section == 1 && (indexPath as NSIndexPath).row == 2 { indexPath = IndexPath(row: 0, section: (indexPath as NSIndexPath).section) } return super.tableView(tableView, indentationLevelForRowAt: indexPath) } }
faee776e6f436649487b824c43e26416
31.672222
144
0.706342
false
false
false
false
iAugux/SlideMenu-Swift
refs/heads/master
SlideMenu/AppDelegate.swift
mit
2
// // AppDelegate.swift // SlideMenu // // Created by Augus on 4/27/15. // Copyright (c) 2015 Augus. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? var storyboard = UIStoryboard(name: "Main", bundle: nil) func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. application.statusBarStyle = .LightContent let titleDict: NSDictionary = [NSForegroundColorAttributeName: UIColor.whiteColor()] UINavigationBar.appearance().titleTextAttributes = titleDict as? [String : AnyObject] UINavigationBar.appearance().tintColor = UIColor.whiteColor() let containerViewController = ContainerViewController() let homeNav = storyboard.instantiateViewControllerWithIdentifier("homeNav") as! UINavigationController homeNav.viewControllers[0] = containerViewController homeNav.setNavigationBarHidden(true, animated: false) window?.rootViewController = homeNav 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:. } }
e8883dbaeff2698ae774be63a29ad0e3
45.887097
285
0.73581
false
false
false
false
christiankm/FinanceKit
refs/heads/master
Sources/FinanceKit/ComparableToZero.swift
mit
1
// // FinanceKit // Copyright © 2022 Christian Mitteldorf. All rights reserved. // MIT license, see LICENSE file for details. // import Foundation /// Conforming to this protocol requires the conformer to provide methods comparing a numeric value against zero. /// The protocol provides methods to check if a number is zero, positive, negative or greater than zero. public protocol ComparableToZero { /// - returns: True if the amount is exactly zero. var isZero: Bool { get } /// - returns: True if the rounded amount is positive, i.e. zero or more. var isPositive: Bool { get } /// - returns: True if the rounded amount is less than zero, or false if the amount is zero or more. var isNegative: Bool { get } /// - returns: True if the rounded amount is greater than zero, or false if the amount is zero or less. var isGreaterThanZero: Bool { get } } extension Int: ComparableToZero { /// - returns: True if the amount is exactly zero. public var isZero: Bool { self == 0 } /// - returns: True if the rounded amount is positive, i.e. zero or more. public var isPositive: Bool { isZero || isGreaterThanZero } /// - returns: True if the rounded amount is less than zero, or false if the amount is zero or more. public var isNegative: Bool { self < Self(0) } /// - returns: True if the rounded amount is greater than zero, or false if the amount is zero or less. public var isGreaterThanZero: Bool { self > Self(0) } } extension Decimal: ComparableToZero { /// - returns: True if the amount is exactly zero. public var isZero: Bool { self == 0 } /// - returns: True if the rounded amount is positive, i.e. zero or more. public var isPositive: Bool { isZero || isGreaterThanZero } /// - returns: True if the rounded amount is less than zero, or false if the amount is zero or more. public var isNegative: Bool { self < Self(0) } /// - returns: True if the rounded amount is greater than zero, or false if the amount is zero or less. public var isGreaterThanZero: Bool { self > Self(0) } } extension FloatingPoint { /// - returns: True if the amount is exactly zero. public var isZero: Bool { self == Self(0) } /// - returns: True if the rounded amount is positive, i.e. zero or more. public var isPositive: Bool { isZero || isGreaterThanZero } /// - returns: True if the rounded amount is less than zero, or false if the amount is zero or more. public var isNegative: Bool { self < Self(0) } /// - returns: True if the rounded amount is greater than zero, or false if the amount is zero or less. public var isGreaterThanZero: Bool { self > Self(0) } }
45c35b8d5b34e3de5ddfe4fcada7cbf4
29.591398
113
0.648506
false
false
false
false
Drakken-Engine/GameEngine
refs/heads/master
DrakkenEngine/dSimpleSceneRender.swift
gpl-3.0
1
// // dSimpleSceneRender.swift // DrakkenEngine // // Created by Allison Lindner on 26/08/16. // Copyright © 2016 Drakken Studio. All rights reserved. // import simd import Metal import MetalKit import Foundation internal class dMaterialMeshBind { fileprivate var material: dMaterialData! fileprivate var mesh: dMeshData! fileprivate var instanceTransforms: [dTransform] = [] fileprivate var instanceTexCoordIDs: [Int32] = [] fileprivate var transformsBuffer: dBuffer<float4x4>! fileprivate var texCoordIDsBuffer: dBuffer<Int32>! fileprivate func addTransform(_ t: dTransform) { instanceTransforms.append(t) t.materialMeshBind = self t.materialMeshBindTransformID = instanceTransforms.index(of: t) } fileprivate func addTexCoordID(_ s: dSprite, _ frame: Int32) { instanceTexCoordIDs.append(frame) s.materialMeshBindTexCoordID = instanceTexCoordIDs.index(of: frame) } internal func remove(_ t: dTransform) { if t.materialMeshBindTransformID != nil { instanceTransforms.remove(at: t.materialMeshBindTransformID!) } if t.sprite != nil { if t.sprite!.materialMeshBindTexCoordID != nil { instanceTexCoordIDs.remove(at: t.sprite!.materialMeshBindTexCoordID!) } } } } internal class dSimpleSceneRender { private var renderGraph: [String : [String : dMaterialMeshBind]] = [:] private var _animatorToBeUpdated: [(materialMeshBind: dMaterialMeshBind, index: Int, animator: dAnimator)] = [] private var _jsScriptToBeUpdated: [dJSScript] = [] private var ids: [Int] = [] private var _scene: dScene! private var uCameraBuffer: dBuffer<dCameraUniform>! private var messagesToSend: [NSString] = [] internal init() { } internal func load(scene: dScene) { DrakkenEngine.Setup() self._scene = scene self._scene.simpleRender = self process() } internal func process() { self.renderGraph.removeAll() self._jsScriptToBeUpdated.removeAll() self._animatorToBeUpdated.removeAll() self.ids.removeAll() self.process(transforms: _scene.root.childrenTransforms) } private func process(transforms: [Int: dTransform]) { for transform in transforms { self.process(components: transform.value.components) self.process(transforms: transform.value.childrenTransforms) } } private func process(components: [dComponent]) { var materialMeshBind: dMaterialMeshBind? = nil var animatorToBeProcess: dAnimator? = nil var spriteToBeProcess: dSprite? = nil var hasSprite: Bool = false var hasAnimator: Bool = false for component in components { switch component.self { case is dMeshRender: //##################################################################################### //####################################################################### MESH RENDER let meshRender = component as! dMeshRender if meshRender.material != nil { if meshRender.mesh != nil { materialMeshBind = process(mesh: meshRender.mesh!, with: meshRender.material!, transform: meshRender.parentTransform!) } } //##################################################################### //################################################################### break case is dSprite: //##################################################################################### //############################################################################ SPRITE hasSprite = true spriteToBeProcess = component as? dSprite //##################################################################### //################################################################### break case is dAnimator: //##################################################################################### //########################################################################## ANIMATOR hasAnimator = true let animator = component as! dAnimator if materialMeshBind == nil { animatorToBeProcess = animator } else { self.process(animator: animator, materialMeshBind: materialMeshBind!) animatorToBeProcess = nil } //##################################################################### //################################################################### break case is dJSScript: //##################################################################################### //############################################################################ SCRIPT let script = component as! dJSScript _jsScriptToBeUpdated.append(script) //##################################################################### //################################################################### break default: break } if component is dAnimator { if materialMeshBind != nil && animatorToBeProcess != nil { self.process(animator: component as! dAnimator, materialMeshBind: materialMeshBind!) } } } if hasSprite && !hasAnimator { if materialMeshBind != nil && spriteToBeProcess != nil { self.process(sprite: spriteToBeProcess!, materialMeshBind: materialMeshBind!) } } } private func process(mesh: String, with material: String, transform: dTransform) -> dMaterialMeshBind { if renderGraph[material] != nil { if let materialMeshBind = renderGraph[material]![mesh] { materialMeshBind.addTransform(transform) return materialMeshBind } else { let materialMeshBind = dMaterialMeshBind() materialMeshBind.material = dCore.instance.mtManager.get(material: material) materialMeshBind.mesh = dCore.instance.mshManager.get(mesh: mesh) materialMeshBind.addTransform(transform) renderGraph[material]![mesh] = materialMeshBind return materialMeshBind } } else { renderGraph[material] = [:] let materialMeshBind = dMaterialMeshBind() materialMeshBind.material = dCore.instance.mtManager.get(material: material) materialMeshBind.mesh = dCore.instance.mshManager.get(mesh: mesh) materialMeshBind.addTransform(transform) renderGraph[material]![mesh] = materialMeshBind return materialMeshBind } } private func generateBufferOf(materialMeshBind: dMaterialMeshBind) { var matrixArray: [float4x4] = [] for transform in materialMeshBind.instanceTransforms { var matrix = transform.worldMatrix4x4 if transform._transformData.meshScale != nil { matrix = matrix * dMath.newScale(transform._transformData.meshScale!.Get().x, y: transform._transformData.meshScale!.Get().y, z: 1.0) } matrixArray.append(matrix) } if materialMeshBind.transformsBuffer == nil || materialMeshBind.transformsBuffer.count != materialMeshBind.instanceTransforms.count { materialMeshBind.transformsBuffer = dBuffer<float4x4>(data: matrixArray, index: 1) } else { materialMeshBind.transformsBuffer.change(matrixArray) } if materialMeshBind.texCoordIDsBuffer == nil || materialMeshBind.texCoordIDsBuffer.count != materialMeshBind.instanceTexCoordIDs.count { materialMeshBind.texCoordIDsBuffer = dBuffer<Int32>(data: materialMeshBind.instanceTexCoordIDs, index: 6) } else { materialMeshBind.texCoordIDsBuffer.change(materialMeshBind.instanceTexCoordIDs) } } private func generateCameraBuffer() { let projectionMatrix = dMath.newOrtho( -_scene.size.x/2.0, right: _scene.size.x/2.0, bottom: -_scene.size.y/2.0, top: _scene.size.y/2.0, near: -1000, far: 1000) let viewMatrix = dMath.newTranslation(float3(0.0, 0.0, -500.0)) * dMath.newScale(_scene.scale) let uCamera = dCameraUniform(viewMatrix: viewMatrix, projectionMatrix: projectionMatrix) if uCameraBuffer == nil { uCameraBuffer = dBuffer(data: uCamera, index: 0) } else { uCameraBuffer.change([uCamera]) } } private func process(animator: dAnimator, materialMeshBind: dMaterialMeshBind) { let index = materialMeshBind.instanceTexCoordIDs.count materialMeshBind.addTexCoordID(animator.sprite, animator.frame) _animatorToBeUpdated.append((materialMeshBind: materialMeshBind, index: index, animator: animator)) } private func process(sprite: dSprite, materialMeshBind: dMaterialMeshBind) { materialMeshBind.addTexCoordID(sprite, sprite.frame) } internal func update(deltaTime: Float) { for value in _animatorToBeUpdated { #if os(iOS) if #available(iOS 10, *) { let thread = Thread(block: { value.animator.update(deltaTime: deltaTime) return }) thread.start() } else { value.animator.update(deltaTime: deltaTime) } #endif #if os(tvOS) if #available(tvOS 10, *) { let thread = Thread(block: { value.animator.update(deltaTime: deltaTime) return }) thread.start() } else { value.animator.update(deltaTime: deltaTime) } #endif #if os(OSX) if #available(OSX 10.12, *) { let thread = Thread(block: { value.animator.update(deltaTime: deltaTime) return }) thread.start() } else { value.animator.update(deltaTime: deltaTime) } #endif value.materialMeshBind.instanceTexCoordIDs[value.index] = value.animator.frame } for script in _jsScriptToBeUpdated { for message in messagesToSend { script.receiveMessage(message) } messagesToSend.removeAll() script.run(function: "Update") } } internal func draw(drawable: CAMetalDrawable) { let id = dCore.instance.renderer.startFrame(drawable.texture) self.ids.append(id) let renderer = dCore.instance.renderer generateCameraBuffer() renderer?.bind(uCameraBuffer, encoderID: id) for m in renderGraph { for materialMeshBind in m.value { if materialMeshBind.value.material != nil && materialMeshBind.value.mesh != nil { generateBufferOf(materialMeshBind: materialMeshBind.value) renderer?.bind(materialMeshBind.value.material, encoderID: id) renderer?.bind(materialMeshBind.value.texCoordIDsBuffer, encoderID: id) renderer?.draw(materialMeshBind.value.mesh, encoderID: id, modelMatrixBuffer: materialMeshBind.value.transformsBuffer!) } } } renderer?.endFrame(id) renderer?.present(drawable) } internal func start() { for script in _jsScriptToBeUpdated { script.start() } } internal func rightClick(_ x: Float, _ y: Float) { for script in _jsScriptToBeUpdated { script.rightClick(x, y) } } internal func leftClick(_ x: Float, _ y: Float) { for script in _jsScriptToBeUpdated { script.leftClick(x, y) } } internal func touch(_ x: Float, _ y: Float) { for script in _jsScriptToBeUpdated { script.touch(x, y) } } internal func keyDown(_ keyCode: UInt16, _ modifier: UInt16? = nil) { for script in _jsScriptToBeUpdated { script.keyDown(keyCode, modifier) } } internal func keyUp(_ keyCode: UInt16, _ modifier: UInt16? = nil) { for script in _jsScriptToBeUpdated { script.keyUp(keyCode, modifier) } } internal func sendMessage(_ message: NSString) { messagesToSend.append(message) } }
4f2b5d29e6f77c6acc4a3e09077944a4
34.22905
144
0.549635
false
false
false
false
hernanc/swift-1
refs/heads/master
Pitch Perfect/recordSoundsViewController.swift
mit
1
// // recordSoundsViewController.swift // Pitch Perfect // // Created by HernanGCalabrese on 4/6/15. // Copyright (c) 2015 Ouiea. All rights reserved. // import UIKit import AVFoundation class recordSoundsViewController: UIViewController, AVAudioRecorderDelegate { @IBOutlet weak var labelStatus: UILabel! @IBOutlet weak var stopButton: UIButton! @IBOutlet weak var recordButton: UIButton! var audioRecorder:AVAudioRecorder! var recordedAudio:RecordedAudio! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func viewWillAppear(animated: Bool) { stopButton.hidden = true } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func recordAudio(sender: UIButton) { stopButton.hidden = false labelStatus.text = "Recording in Progress" recordButton.enabled = false let dirPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as! String var currentDateTime = NSDate() var formatter = NSDateFormatter() formatter.dateFormat = "ddMMyyyy-HHmmss" var recordingName = formatter.stringFromDate(currentDateTime)+".wav" var pathArray = [dirPath, recordingName] let filePath = NSURL.fileURLWithPathComponents(pathArray) println(filePath) // Setup Audio session var session = AVAudioSession.sharedInstance() session.setCategory(AVAudioSessionCategoryPlayAndRecord, error: nil) // Initialize and prepare the recorder audioRecorder = AVAudioRecorder(URL: filePath, settings: nil, error:nil) audioRecorder.delegate = self audioRecorder.meteringEnabled = true audioRecorder.prepareToRecord() audioRecorder.record() } func audioRecorderDidFinishRecording(recorder: AVAudioRecorder!, successfully flag: Bool) { if(flag){ recordedAudio = RecordedAudio(title: recorder.url.lastPathComponent!, filePathURL: recorder.url) self.performSegueWithIdentifier("stopRecording", sender: recordedAudio) }else{ println("Error recording") recordButton.enabled = true stopButton.hidden = true } } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if(segue.identifier == "stopRecording"){ let playSoundsVC:PlaySoundsViewController = segue.destinationViewController as! PlaySoundsViewController let data = sender as! RecordedAudio playSoundsVC.receivedAudio = data } } @IBAction func stopAudio(sender: UIButton) { labelStatus.text = "Tap to Record" stopButton.hidden = true recordButton.enabled = true audioRecorder.stop() var audioSession = AVAudioSession.sharedInstance() audioSession.setActive(false, error: nil) } }
5c3a3814b6bce90a6e805a4b9f942115
31.09901
116
0.652684
false
false
false
false
bourdakos1/Visual-Recognition-Tool
refs/heads/master
iOS/Visual Recognition/FaceResult.swift
mit
1
// // FaceResult.swift // Visual Recognition // // Created by Nicholas Bourdakos on 7/19/17. // Copyright © 2017 Nicholas Bourdakos. All rights reserved. // import UIKit struct FaceResult { let age: Age let location: Location let gender: Gender struct Age { let max: Int let min: Int let score: CGFloat } struct Location { let height: CGFloat let left: CGFloat let top: CGFloat let width: CGFloat } struct Gender { enum Sex: String { case male, female } let sex: Sex let score: CGFloat } } extension FaceResult { init?(json: Any) { guard let json = json as? [String: Any], let age = json["age"] as? [String: Any], let location = json["face_location"] as? [String: Any], let gender = json["gender"] as? [String: Any], let ageScore = age["score"] as? CGFloat, let height = location["height"] as? CGFloat, let left = location["left"] as? CGFloat, let top = location["top"] as? CGFloat, let width = location["width"] as? CGFloat, let genderSex = gender["gender"] as? String, let genderScore = gender["score"] as? CGFloat else { return nil } // The age max or min might be empty let maxAge: Int = age["max"] as? Int ?? 0 let minAge: Int = age["min"] as? Int ?? 0 self.age = Age(max: maxAge, min: minAge, score: ageScore) self.location = Location(height: height, left: left, top: top, width: width) self.gender = Gender(sex: Gender.Sex(rawValue: genderSex.lowercased())!, score: genderScore) } }
9ffa332ecc13f701ccfc3f1c38077ab4
25.867647
100
0.532567
false
false
false
false
withcopper/CopperKit
refs/heads/master
CopperKit/JWTDecode.swift
mit
1
// JWTDecode.swift // // Copyright (c) 2015 Auth0 (http://auth0.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation /** Decodes a JWT token into an object that holds the decoded body (along with token header and signature parts). If the token cannot be decoded a `NSError` will be thrown. :param: jwt string value to decode :returns: a decoded token as an instance of JWT */ public func decodeJWT(jwt: String) throws -> JWT { return try DecodedJWT(jwt: jwt) } struct DecodedJWT: JWT { let header: [String: AnyObject] let body: [String: AnyObject] let signature: String? init(jwt: String) throws { let parts = jwt.componentsSeparatedByString(".") guard parts.count == 3 else { throw invalidPartCountInJWT(jwt, parts: parts.count) } self.header = try decodeJWTPart(parts[0]) self.body = try decodeJWTPart(parts[1]) self.signature = parts[2] } var expiresAt: NSDate? { return claim("exp") } var issuer: String? { return claim("iss") } var subject: String? { return claim("sub") } var audience: [String]? { guard let aud: String = claim("aud") else { return claim("aud") } return [aud] } var issuedAt: NSDate? { return claim("iat") } var notBefore: NSDate? { return claim("nbf") } var identifier: String? { return claim("jti") } private func claim(name: String) -> NSDate? { guard let timestamp:Double = claim(name) else { return nil } return NSDate(timeIntervalSince1970: timestamp) } var expired: Bool { guard let date = self.expiresAt else { return false } return date.compare(NSDate()) != NSComparisonResult.OrderedDescending } } private func base64UrlDecode(value: String) -> NSData? { var base64 = value .stringByReplacingOccurrencesOfString("-", withString: "+") .stringByReplacingOccurrencesOfString("_", withString: "/") let length = Double(base64.lengthOfBytesUsingEncoding(NSUTF8StringEncoding)) let requiredLength = 4 * ceil(length / 4.0) let paddingLength = requiredLength - length if paddingLength > 0 { let padding = "".stringByPaddingToLength(Int(paddingLength), withString: "=", startingAtIndex: 0) base64 = base64.stringByAppendingString(padding) } return NSData(base64EncodedString: base64, options: .IgnoreUnknownCharacters) } private func decodeJWTPart(value: String) throws -> [String: AnyObject] { guard let bodyData = base64UrlDecode(value) else { throw invalidBase64UrlValue(value) } do { guard let json = try NSJSONSerialization.JSONObjectWithData(bodyData, options: NSJSONReadingOptions()) as? [String: AnyObject] else { throw invalidJSONValue(value) } return json } catch { throw invalidJSONValue(value) } }
7d31ecda1af91f217bc83e3430c4e91f
35.366972
141
0.682311
false
false
false
false
yonaskolb/XcodeGen
refs/heads/master
Sources/XcodeGenKit/GraphVizGenerator.swift
mit
1
import DOT import Foundation import GraphViz import ProjectSpec extension Dependency { var graphVizName: String { switch self.type { case .bundle, .package, .sdk, .framework, .carthage: return "[\(self.type)]\\n\(reference)" case .target: return reference } } } extension Dependency.DependencyType: CustomStringConvertible { public var description: String { switch self { case .bundle: return "bundle" case .package: return "package" case .framework: return "framework" case .carthage: return "carthage" case .sdk: return "sdk" case .target: return "target" } } } extension Node { init(target: Target) { self.init(target.name) self.shape = .box } init(dependency: Dependency) { self.init(dependency.reference) self.shape = .box self.label = dependency.graphVizName } } public class GraphVizGenerator { public init() {} public func generateModuleGraphViz(targets: [Target]) -> String { return DOTEncoder().encode(generateGraph(targets: targets)) } func generateGraph(targets: [Target]) -> Graph { var graph = Graph(directed: true) targets.forEach { target in target.dependencies.forEach { dependency in let from = Node(target: target) graph.append(from) let to = Node(dependency: dependency) graph.append(to) var edge = Edge(from: from, to: to) edge.style = .dashed graph.append(edge) } } return graph } }
477d25d7dd1386eca4dd6fcb2e8ccd30
24.772727
69
0.576132
false
false
false
false
totocaster/JSONFeed
refs/heads/master
Classes/JSONFeedAttachment.swift
mit
1
// // JSONFeedAttachment.swift // JSONFeed // // Created by Toto Tvalavadze on 2017/05/18. // Copyright © 2017 Toto Tvalavadze. All rights reserved. // import Foundation public struct JSONFeedAttachment { /// Specifies the location of the attachment. public let url: URL /// Specifies the type of the attachment, such as `audio/mpeg`. public let mimeType: String /// name for the attachment. /// - important: if there are multiple attachments, and two or more have the exact same title (when title is present), then they are considered as alternate representations of the same thing. In this way a podcaster, for instance, might provide an audio recording in different formats. public let title: String? /// Specifies how large the file is in *bytes*. public let size: UInt64? /// Specifies how long the attachment takes to listen to or watch in *seconds*. public let duration: UInt? // MARK: - Parsing internal init?(json: JsonDictionary) { let keys = JSONFeedSpecV1Keys.Attachment.self guard let url = URL(for: keys.url, inJson: json), let mimeType = json[keys.mimeType] as? String else { return nil } // items without id will be discarded, per spec self.url = url self.mimeType = mimeType self.title = json[keys.title] as? String self.duration = json[keys.durationSeconds] as? UInt self.size = json[keys.sizeBytes] as? UInt64 } }
0b4f0f4f32a9918529f250f9f04ba081
30.938776
289
0.641534
false
false
false
false
timbodeit/RegexNamedCaptureGroups
refs/heads/master
RegexNamedCaptureGroups/Classes/GroupnameResolver.swift
mit
1
import unicode import Regex /** Resolves a capture group's name to its index for a given regex. To do this, GroupnameResolver calls into the ICU regex library, that NSRegularExpression is based on. */ class GroupnameResolver { private let uregex: COpaquePointer init?(regex: NSRegularExpression) { let cPattern = (regex.pattern as NSString).UTF8String let flag = regex.options.uregexFlag var errorCode = U_ZERO_ERROR uregex = uregex_openC(cPattern, flag, nil, &errorCode) if errorCode.isFailure { return nil } } func numberForCaptureGroupWithName(name: String) -> Int? { let cName = (name as NSString).UTF8String let nullTerminatedStringFlag: Int32 = -1 var errorCode = U_ZERO_ERROR let groupNumber = uregex_groupNumberFromCName(uregex, cName, nullTerminatedStringFlag, &errorCode) if errorCode.isSuccess { return Int(groupNumber) } else { return nil } } deinit { uregex_close(uregex) } } private extension UErrorCode { var isSuccess: Bool { return self.rawValue <= U_ZERO_ERROR.rawValue } var isFailure: Bool { return self.rawValue > U_ZERO_ERROR.rawValue } } private extension NSRegularExpressionOptions { var uregexFlag: UInt32 { var flag = 0 as UInt32 if self.contains(.CaseInsensitive) { flag |= UREGEX_CASE_INSENSITIVE.rawValue } if self.contains(.AllowCommentsAndWhitespace) { flag |= UREGEX_COMMENTS.rawValue } if self.contains(.DotMatchesLineSeparators) { flag |= UREGEX_DOTALL.rawValue } if self.contains(.AnchorsMatchLines) { flag |= UREGEX_MULTILINE.rawValue } if self.contains(.UseUnixLineSeparators) { flag |= UREGEX_UNIX_LINES.rawValue } if self.contains(.UseUnicodeWordBoundaries) { flag |= UREGEX_UWORD.rawValue } return flag } }
bdffb1b486a1dd9f3d4a05104f25f1ff
23.307692
102
0.676688
false
false
false
false
wavecos/curso_ios_3
refs/heads/master
Playgrounds/Arrays.playground/section-1.swift
apache-2.0
1
// Playground - Arrays import UIKit // Declaracion de un Arrays usando Literals let diasEnMes = [31,28,31,30,31,30,31,31,30,31,30,31] var opcionesColor = ["Negro", "Azul", "Verde"] var sabores : [String] sabores = ["Vainilla", "Chocolate", "Mora"] println("El segundo sabor es \(sabores[1])") sabores[0] = "Limon" sabores // Adicionando un Item al array sabores.append("Durazno") sabores // Otra forma de adicionar un Item sabores += ["Tamarindo"] sabores // Insertar un Item en una posicion especifica sabores.insert("Papaya", atIndex: 1) sabores // Removiendo Elementos de un Array let saborEliminado = sabores.removeAtIndex(3) sabores sabores.removeLast() sabores // Para saber el numero de elementos de un Array println("Tenemos actualmente \(sabores.count) sabores") if diasEnMes.isEmpty { println("El array esta vacio") } else { println("Tenemos \(diasEnMes.count) meses en el año") } // iterar un Array for mes in diasEnMes { println(mes) }
835a06bc99bdcc0c77744fff2003ed51
13.924242
55
0.707614
false
false
false
false
silt-lang/silt
refs/heads/master
Sources/Seismography/Value.swift
mit
1
/// Value.swift /// /// Copyright 2017-2018, The Silt Language Project. /// /// This project is released under the MIT license, a copy of which is /// available in the repository. import Foundation import Moho public class Value: Hashable, ManglingEntity { public enum Category { case object case address } public private(set) var type: Value public let category: Value.Category init(type: Value, category: Value.Category) { self.type = type self.category = category } /// Query the type information of a GIR type to determine whether it is /// "trivial". /// /// Values of trivial type requires no further work to copy, move, or destroy. /// /// - Parameter module: The module in which the type resides. /// - Returns: `true` if the lowered type is trivial, else `false`. public func isTrivial(_ module: GIRModule) -> Bool { return module.typeConverter.lowerType(self).trivial } /// All values are equatable and hashable using reference equality and /// the hash of their ObjectIdentifiers. public static func == (lhs: Value, rhs: Value) -> Bool { return lhs.equals(rhs) } public func equals(_ other: Value) -> Bool { return self === other } public func hash(into hasher: inout Hasher) { "\(ObjectIdentifier(self).hashValue)".hash(into: &hasher) } fileprivate var firstUse: Operand? public var hasUsers: Bool { return self.firstUse != nil } public var users: AnySequence<Operand> { guard let first = self.firstUse else { return AnySequence<Operand>([]) } return AnySequence<Operand>(sequence(first: first) { use in return use.nextUse }) } public func replaceAllUsesWith(_ RHS: Value) { precondition(self !== RHS, "Cannot RAUW a value with itself") for user in self.users { user.value = RHS } } public func mangle<M: Mangler>(into mangler: inout M) { fatalError("Generic Value may not be mangled; this must be overriden") } } public class NominalValue: Value { public let name: QualifiedName public init(name: QualifiedName, type: Value, category: Value.Category) { self.name = name super.init(type: type, category: category) } public var baseName: String { return self.name.name.description } } public enum Ownership { case trivial case unowned case owned } public class Parameter: Value { unowned public let parent: Continuation public let index: Int public let ownership: Ownership = .owned init(parent: Continuation, index: Int, type: Value) { self.parent = parent self.index = index super.init(type: type, category: type.category) } public override func mangle<M: Mangler>(into mangler: inout M) { self.type.mangle(into: &mangler) } } public enum Copy { case trivial case malloc case custom(Continuation) } public enum Destructor { case trivial case free case custom(Continuation) } /// A formal reference to a value, suitable for use as a stored operand. public final class Operand: Hashable { /// The next operand in the use-chain. Note that the chain holds /// every use of the current ValueBase, not just those of the /// designated result. var nextUse: Operand? /// A back-pointer in the use-chain, required for fast patching /// of use-chains. weak var back: Operand? /// The owner of this operand. /// FIXME: this could be space-compressed. weak var owningOp: PrimOp? init(owner: PrimOp, value: Value) { self.value = value self.owningOp = owner self.insertIntoCurrent() } deinit { self.removeFromCurrent() } public static func == (lhs: Operand, rhs: Operand) -> Bool { return lhs.value == rhs.value } public func hash(into hasher: inout Hasher) { self.value.hash(into: &hasher) } /// The value used as this operand. public var value: Value { willSet { self.removeFromCurrent() } didSet { self.insertIntoCurrent() } } /// Remove this use of the operand. public func drop() { self.removeFromCurrent() self.nextUse = nil self.back = nil self.owningOp = nil } /// Return the user that owns this use. public var user: PrimOp { return self.owningOp! } private func removeFromCurrent() { guard let backPtr = self.back else { return } self.back = self.nextUse if let next = self.nextUse { next.back = backPtr } } private func insertIntoCurrent() { self.back = self.value.firstUse self.nextUse = self.value.firstUse if let next = self.nextUse { next.back = self.nextUse } self.value.firstUse = self } }
2cd131af7359d307e33389335673c562
22.275
80
0.667884
false
false
false
false
donmichael41/helloVapor
refs/heads/master
Sources/App/Controllers/PostController.swift
mit
1
import Vapor import HTTP import Foundation import VaporPostgreSQL final class PostController { func addRoutes(drop: Droplet) { drop.group("posts") { group in group.post("create", handler: create) group.get(handler: index) group.post("update", Post.self, handler: update) group.post("show", Post.self, handler: show) group.post("delete", Post.self, handler: delete) group.post("deleteAll", handler: deleteAll) } } func create(request: Request) throws -> ResponseRepresentable { guard let content = request.parameters["content"]?.string else { throw Abort.badRequest } var mediaurl = "" var post = Post(createdon: Date().stringForDate(), content: content, mediaurl: mediaurl) try post.save() return Response(redirect: "/posts") } func index(request: Request) throws -> ResponseRepresentable { var parametes = [String: Node]() if let db = drop.database?.driver as? PostgreSQLDriver { let query = try db.raw("Select * from posts order by createdon desc") parametes = ["posts": query] } return try drop.view.make("manage", parametes) } func show(request: Request, post: Post) throws -> ResponseRepresentable { return post } func update(request: Request, post: Post) throws -> ResponseRepresentable { let new = try request.post() var post = post post.createdon = new.createdon post.content = new.content post.mediaurl = new.mediaurl try post.save() return post } func delete(request: Request, post: Post) throws -> ResponseRepresentable { try post.delete() return Response(redirect: "/posts") } func deleteAll(request: Request) throws -> ResponseRepresentable { let posts = try Post.all() try posts.forEach { (post) in try post.delete() } return "Delete all" } } extension Request { func post() throws -> Post { guard let json = json else { throw Abort.badRequest } return try Post(node: json) } } extension Date { func stringForDate() -> String { let formatter = DateFormatter() formatter.dateFormat = "EEEE, MMM d, yyyy 'at' hh:mm" return formatter.string(from: self) } }
5d61b2c8ecb176cc276b1795fb6fb630
27.51087
81
0.556233
false
false
false
false
Hansoncoder/SpriteDemo
refs/heads/master
SpriteKitDemo/SpriteKitDemo/MyGameScene.swift
apache-2.0
1
// // MyGameScene.swift // SpriteKitDemo // // Created by Hanson on 16/5/10. // Copyright © 2016年 Hanson. All rights reserved. // import SpriteKit import AVFoundation let playerName = "player" class MyGameScene: SKScene { // 敌人 var monsters = [SKSpriteNode]() // 飞镖 var projectiles = [SKSpriteNode]() // 音效 lazy var projectileSoundEffectAction = SKAction.playSoundFileNamed("pew-pew-lei", waitForCompletion: false) // 击退敌人 var monstersDestroyed = 0 var bgmPlayer: AVAudioPlayer? = { let bgmPath = NSBundle.mainBundle().pathForResource("background-music-aac", ofType: "caf") let bgmPlayer = try! AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: bgmPath!)) bgmPlayer.numberOfLoops = -1 return bgmPlayer }() override init(size: CGSize) { super.init(size: size) // 添加英雄 backgroundColor = SKColor(colorLiteralRed: 1.0, green: 1.0, blue: 1.0, alpha: 1.0) let player = SKSpriteNode(imageNamed: "player") player.name = playerName player.position = CGPointMake(player.size.width * 0.5, frame.size.height * 0.5) addChild(player) // 添加敌人 let actionAddMonster = SKAction.runBlock { [unowned self] in self.addMonster() } let actionWaitNextMonster = SKAction.waitForDuration(1.0) runAction(SKAction.repeatActionForever(SKAction.sequence([actionAddMonster,actionWaitNextMonster]))) // 播放背景音乐 bgmPlayer?.play() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // 添加敌人 func addMonster() { let monster = SKSpriteNode(imageNamed: "monster") let winSize = size let minY = monster.size.height * 0.5 let maxY = winSize.height - monster.size.height * 0.5 let rangeY = maxY - minY let actualY = (CGFloat(arc4random()) % rangeY) + minY // 显示敌人 monster.position = CGPointMake(winSize.width - monster.size.width * 0.5, actualY) addChild(monster) monsters.append(monster) // 计算敌人移动参数 let minDuration = 2.00 let maxDuration = 4.00 let rangeDuration = maxDuration - minDuration let actualDuration = (Double(arc4random()) % rangeDuration) + minDuration let actionMove = SKAction.moveTo(CGPointMake(-monster.size.width * 0.5, actualY), duration: actualDuration) let actionMoveDone = SKAction.runBlock { [unowned self] in self.monsters.removeAtIndex(self.monsters.indexOf(monster)!) monster.removeFromParent() // 敌人移动到屏幕边缘,跳转场景(输) self.changeToResultSceneWithWon(false) } monster.runAction(SKAction.sequence([actionMove,actionMoveDone])) } // 点击屏幕发射飞镖 override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { for touch in touches { let winSize = size // 取出英雄 guard let player = childNodeWithName(playerName) else { return } // 当前点击的点 let touchPoint = touch.locationInNode(self) let offSet = CGPointMake(touchPoint.x - player.position.x, touchPoint.y - player.position.y) // 点击英雄左边无效 if offSet.x <= 0 { return } // 创建飞镖 let projectile = SKSpriteNode(imageNamed: "projectile.png") projectile.position = player.position addChild(projectile) projectiles.append(projectile) // 计算偏移量 let realX = winSize.width - projectile.size.width * 0.5 let ratio = offSet.y / offSet.x let realY = (realX * ratio) + projectile.position.y let realDest = CGPointMake(realX, realY) // 计算飞镖移动时间 let offRealX = realX - projectile.position.x let offRealY = realY - projectile.position.y let length = sqrtf(Float((offRealX * offRealX) + (offRealY * offRealY))) let velocity = self.size.width let realMoveDuration = CGFloat(length) / velocity // 执行飞镖移动操作,移动结束将移除飞镖 let moveAction = SKAction.moveTo(realDest, duration: Double(realMoveDuration)) let projectileCastAction = SKAction.group([moveAction, projectileSoundEffectAction]) projectile.runAction(projectileCastAction){ [unowned self] in self.projectiles.removeAtIndex(self.projectiles.indexOf(projectile)!) projectile.removeFromParent() } } } // 检测飞镖和敌人是否碰撞,碰撞即移除飞镖和敌人 override func update(currentTime: NSTimeInterval) { var projectilesToDelete = [SKSpriteNode]() for projectile in projectiles { // 标记中飞镖的敌人monster var monstersToDelete = [SKSpriteNode]() for monster in monsters { if CGRectIntersectsRect(projectile.frame, monster.frame) { monstersToDelete.append(monster) // 击中敌人,统计数量 monstersDestroyed += 1 if monstersDestroyed >= 30 { // 击中人数达到30人,跳转场景(赢) changeToResultSceneWithWon(true) } } } // 将中飞镖的敌人移除 for monster in monstersToDelete { monsters.removeAtIndex(monsters.indexOf(monster)!) monster.removeFromParent() } // 若该飞镖击中敌人,标记飞镖 if monstersToDelete.count > 0 { projectilesToDelete.append(projectile) } } // 移除击中敌人的飞镖 for projectile in projectilesToDelete { projectiles.removeAtIndex(projectiles.indexOf(projectile)!) projectile.removeFromParent() } } func changeToResultSceneWithWon(won: Bool) { bgmPlayer?.stop() bgmPlayer = nil let resultScene = MyGameResultScene(size: self.size, won: won) let reveal = SKTransition.revealWithDirection(SKTransitionDirection.Up, duration: 1.0) self.scene?.view?.presentScene(resultScene, transition: reveal) } }
f8b138d842b49b885d9441e814a8348f
33.13089
115
0.573401
false
false
false
false
jcleblanc/box-examples
refs/heads/master
swift/JWTSampleApp/JWTSampleApp/ViewController.swift
mit
1
// // ViewController.swift // JWTSampleApp-carthage // // Created by Martina Stremenova on 28/06/2019. // Copyright © 2019 Box. All rights reserved. // import BoxSDK import UIKit class ViewController: UITableViewController { private var sdk: BoxSDK! private var client: BoxClient! private var folderItems: [FolderItem] = [] private lazy var dateFormatter: DateFormatter = { let formatter = DateFormatter() formatter.dateFormat = "MMM dd,yyyy at HH:mm a" return formatter }() override func viewDidLoad() { super.viewDidLoad() setUpBoxSDK() setUpUI() } // MARK: - Actions @objc private func loginButtonPressed() { authorizeWithJWClient() } @objc private func loadItemsButtonPressed() { getRootFolderItems() } // MARK: - Set up private func setUpBoxSDK() { sdk = BoxSDK( clientId: Constants.clientID, clientSecret: Constants.clientSecret ) } private func setUpUI() { title = "JWT Example" navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Login", style: .plain, target: self, action: #selector(loginButtonPressed)) tableView.tableFooterView = UIView() } } // MARK: - TableView extension ViewController { override func numberOfSections(in _: UITableView) -> Int { return 1 } override func tableView(_: UITableView, numberOfRowsInSection _: Int) -> Int { return folderItems.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let item = folderItems[indexPath.row] let cell = tableView.dequeueReusableCell(withIdentifier: "ItemCell", for: indexPath) cell.textLabel?.numberOfLines = 0 switch item.itemValue { case let .file(file): cell.textLabel?.text = file.name cell.detailTextLabel?.text = String(format: "Date Modified %@", dateFormatter.string(from: file.modifiedAt ?? Date())) cell.accessoryType = .none case let .folder(folder): cell.textLabel?.text = folder.name cell.detailTextLabel?.text = String(format: "Date Modified %@", dateFormatter.string(from: folder.modifiedAt ?? Date())) cell.accessoryType = .disclosureIndicator cell.imageView?.image = UIImage(named: "folder") default: break } return cell } } // MARK: - Loading items private extension ViewController { func getRootFolderItems() { let iterator: PaginationIterator<FolderItem> = client.folders.getFolderItems( folderId: "0", usemarker: true, fields: ["modified_at", "name"] ) iterator.nextItems { [weak self] result in switch result { case let .failure(error): print(error) case let .success(items): self?.folderItems = items DispatchQueue.main.async { self?.tableView.reloadData() self?.navigationItem.rightBarButtonItem?.title = "Refresh" } } } } } // MARK: - JWT Helpers private extension ViewController { func authorizeWithJWClient() { #warning("Get uniqueID from your server. It's a way for your server to identify the app it's generating JWT token for.") sdk.getDelegatedAuthClient(authClosure: obtainJWTTokenFromExternalSources(), uniqueID: "dummyID") { [weak self] result in switch result { case let .success(client): guard let self = self else { return } self.client = client self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Load items", style: .plain, target: self, action: #selector(self.loadItemsButtonPressed)) case let .failure(error): print(error) } } } func obtainJWTTokenFromExternalSources() -> DelegatedAuthClosure { return { uniqueID, completion in // The code below is an example implementation of the delegate function — please provide your own // implementation let session = URLSession(configuration: .default) //REPLACE WITH YOUR HEROKU APPLICATION LINK let tokenUrl = "https://myapp.herokuapp.com/" let urlRequest = URLRequest(url: URL(string: tokenUrl)!) let task = session.dataTask(with: urlRequest) { data, response, error in if let unwrappedError = error { print(error.debugDescription) completion(.failure(unwrappedError)) return } if let body = data, let token = String(data: body, encoding: .utf8) { print("\nFetched new token: \(token)\n") completion(.success((accessToken: token, expiresIn: 999))) } else { completion(.failure(BoxError.tokenRetrieval)) } } task.resume() } } }
10df630c4ee661e533fd2a83aef64f69
31.8875
170
0.58875
false
false
false
false
SerjKultenko/Calculator3
refs/heads/master
Calculator/GraphicViewController.swift
mit
1
// // GraphicViewController.swift // Calculator // // Created by Sergei Kultenko on 05/09/2017. // Copyright © 2017 Sergey Kultenko. All rights reserved. // import UIKit class GraphicViewController: UIViewController, UIScrollViewDelegate { let kGraphicSettingsKey = "GraphicSettingsKey" @IBOutlet weak var scrollView: UIScrollView! { didSet { scrollView.delegate = self } } private var lastScrollViewContentOffset: CGPoint = CGPoint.zero @IBOutlet weak var graphicView: GraphicView! public var graphDataSource: GraphDataSource? { didSet { graphicView?.graphDataSource = graphDataSource navigationItem.title = graphDataSource?.description } } var settingsLoaded = false override func viewDidLoad() { super.viewDidLoad() automaticallyAdjustsScrollViewInsets = false graphicView?.graphDataSource = graphDataSource NotificationCenter.default.addObserver(self, selector: #selector(deviceOrientationDidChange), name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil) } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() if !settingsLoaded { _ = loadSettings() settingsLoaded = true } if graphicView.scale <= 1 { graphicView.frame = scrollView.bounds scrollView.contentSize = graphicView.frame.size scrollView.contentOffset = CGPoint.zero graphicView.setNeedsDisplay() } } @IBAction func scaleChangeAction(_ sender: UIPinchGestureRecognizer) { if sender.state == .began { sender.scale = graphicView.scale } else { if sender.scale < 4 && sender.scale > 0.1 { if sender.scale < 1 { graphicView.frame = scrollView.bounds scrollView.contentSize = graphicView.frame.size scrollView.contentOffset = CGPoint.zero } else { let graphicNewWidth = view.frame.width * sender.scale let graphicNewHeight = view.frame.height * sender.scale graphicView.frame = CGRect(x: 0, y: 0, width: graphicNewWidth, height: graphicNewHeight) scrollView.contentSize = CGSize(width: graphicNewWidth, height: graphicNewHeight) scrollView.contentOffset = CGPoint(x: graphicNewWidth/2 - scrollView.frame.width/2 , y: graphicNewHeight/2 - scrollView.frame.height/2) } graphicView.setNeedsDisplay() graphicView.scale = sender.scale } } saveSettings() } @IBAction func doubleTapAction(_ sender: UITapGestureRecognizer) { let centerPoint = sender.location(in: view) scrollView.contentOffset = CGPoint(x: graphicView.frame.width/2 - centerPoint.x , y: graphicView.frame.height/2 - centerPoint.y) saveSettings() } func scrollViewDidScroll(_ scrollView: UIScrollView) { lastScrollViewContentOffset = scrollView.contentOffset saveSettings() } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) // if UIDevice.current.orientation.isLandscape { // print("Landscape \(size)") // } else { // print("Portrait \(size)") // } } @objc func deviceOrientationDidChange() { // switch UIDevice.current.orientation { // case .faceDown: // print("Face down") // case .faceUp: // print("Face up") // case .unknown: // print("Unknown") // case .landscapeLeft: // print("Landscape left") // case .landscapeRight: // print("Landscape right") // case .portrait: // print("Portrait") // case .portraitUpsideDown: // print("Portrait upside down") // } } func saveSettings() { guard settingsLoaded else { return } let graphicSettings = GraphicSettings(graphicViewFrame: graphicView.frame, scrollViewContentSize: scrollView.contentSize, scrollViewContentOffset: scrollView.contentOffset, scale: graphicView.scale) //print("saved \(graphicSettings)") UserDefaults.standard.set(graphicSettings.encode(), forKey: kGraphicSettingsKey) UserDefaults.standard.synchronize() } func loadSettings()->Bool { guard let graphicSettingsData = UserDefaults.standard.object(forKey: kGraphicSettingsKey) as? Data, let graphicSettings = GraphicSettings(data:graphicSettingsData) else { return false } graphicView.frame = graphicSettings.graphicViewFrame scrollView.contentSize = graphicSettings.scrollViewContentSize scrollView.contentOffset = graphicSettings.scrollViewContentOffset graphicView.scale = graphicSettings.scale return true } deinit { NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil) } } struct GraphicSettings: Codable { let graphicViewFrame: CGRect let scrollViewContentSize: CGSize let scrollViewContentOffset: CGPoint let scale: CGFloat init(graphicViewFrame: CGRect, scrollViewContentSize: CGSize, scrollViewContentOffset: CGPoint, scale: CGFloat) { self.graphicViewFrame = graphicViewFrame self.scrollViewContentSize = scrollViewContentSize self.scrollViewContentOffset = scrollViewContentOffset self.scale = scale } init?(data: Data) { let decoder = JSONDecoder() if let decoded = try? decoder.decode(GraphicSettings.self, from: data) { self = decoded } else { return nil } } func encode() -> Data? { let encoder = JSONEncoder() return try? encoder.encode(self) } } //extension GraphicSettings { // init?(data: Data) { // if let coding = NSKeyedUnarchiver.unarchiveObject(with: data) as? GraphicSettingsEncoding { // graphicViewFrame = coding.graphicViewFrame as CGRect // scrollViewContentSize = coding.scrollViewContentSize as CGSize // scrollViewContentOffset = coding.scrollViewContentOffset as CGPoint // scale = coding.scale as CGFloat // } else { // return nil // } // } // // func encode() -> Data { // return NSKeyedArchiver.archivedData(withRootObject: GraphicSettingsEncoding(self)) // } // // private class GraphicSettingsEncoding: NSObject, NSCoding { // let graphicViewFrame: CGRect // let scrollViewContentSize: CGSize // let scrollViewContentOffset: CGPoint // let scale: CGFloat // // init(_ graphicSettings: GraphicSettings) { // graphicViewFrame = graphicSettings.graphicViewFrame // scrollViewContentSize = graphicSettings.scrollViewContentSize // scrollViewContentOffset = graphicSettings.scrollViewContentOffset // scale = graphicSettings.scale // } // // required init?(coder aDecoder: NSCoder) { // graphicViewFrame = aDecoder.decodeCGRect(forKey: "graphicViewFrame") // scrollViewContentSize = aDecoder.decodeCGSize(forKey: "scrollViewContentSize") // scrollViewContentOffset = aDecoder.decodeCGPoint(forKey: "scrollViewContentOffset") // scale = CGFloat(aDecoder.decodeFloat(forKey: "scale")) // } // // public func encode(with aCoder: NSCoder) { // aCoder.encode(graphicViewFrame, forKey: "graphicViewFrame") // aCoder.encode(scrollViewContentSize, forKey: "scrollViewContentSize") // aCoder.encode(scrollViewContentOffset, forKey: "scrollViewContentOffset") // aCoder.encode(Float(scale), forKey: "scale") // } // } //}
c0022b2d59fa92a4aa657d258ba09154
36.026667
170
0.622974
false
false
false
false
jigneshsheth/Datastructures
refs/heads/master
DataStructure/DataStructure/FindMedianSortedArray.swift
mit
1
// // FindMedianSortedArray.swift // DataStructure // // Created by Jigs Sheth on 11/2/21. // Copyright © 2021 jigneshsheth.com. All rights reserved. // import Foundation class FindMedianSortedArray { public static func findMedianSortedArrays(_ nums1: [Int], _ nums2: [Int]) -> Double { let arr = mergeSortedArrays(nums1, nums2) if arr.count % 2 == 1{ return Double(arr[Int((arr.count + 1) / 2) - 1]) }else{ let midIndex = arr.count/2 return Double(arr[midIndex-1] + arr[midIndex]) / 2 } } public static func mergeSortedArrays(_ arr1:[Int],_ arr2:[Int]) -> [Int] { var arr = arr1 for i in arr2 { arr.append(i) } return arr.sorted() } }
ac717a5034a20eae662d0e6a8a31a36c
19.470588
86
0.632184
false
false
false
false
wireapp/wire-ios
refs/heads/develop
Wire-iOS/Sources/Helpers/syncengine/ProfileImageFetchable.swift
gpl-3.0
1
// // Wire // Copyright (C) 2018 Wire Swiss GmbH // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // import Foundation import WireSyncEngine extension CIContext { static var shared: CIContext = CIContext(options: nil) } typealias ProfileImageFetchableUser = UserType & ProfileImageFetchable protocol ProfileImageFetchable { func fetchProfileImage(session: ZMUserSessionInterface, cache: ImageCache<UIImage>, sizeLimit: Int?, desaturate: Bool, completion: @escaping (_ image: UIImage?, _ cacheHit: Bool) -> Void) } extension ProfileImageFetchable where Self: UserType { private func cacheKey(for size: ProfileImageSize, sizeLimit: Int?, desaturate: Bool) -> String? { guard let baseKey = (size == .preview ? smallProfileImageCacheKey : mediumProfileImageCacheKey) else { return nil } var derivedKey = baseKey if desaturate { derivedKey = "\(derivedKey)_desaturated" } if let sizeLimit = sizeLimit { derivedKey = "\(derivedKey)_\(sizeLimit)" } return derivedKey } func fetchProfileImage(session: ZMUserSessionInterface, cache: ImageCache<UIImage> = UIImage.defaultUserImageCache, sizeLimit: Int? = nil, desaturate: Bool = false, completion: @escaping (_ image: UIImage?, _ cacheHit: Bool) -> Void) { let screenScale = UIScreen.main.scale let previewSizeLimit: CGFloat = 280 let size: ProfileImageSize if let sizeLimit = sizeLimit { size = CGFloat(sizeLimit) * screenScale < previewSizeLimit ? .preview : .complete } else { size = .complete } guard let cacheKey = cacheKey(for: size, sizeLimit: sizeLimit, desaturate: desaturate) as NSString? else { return completion(nil, false) } if let image = cache.cache.object(forKey: cacheKey) { return completion(image, true) } switch size { case .preview: self.requestPreviewProfileImage() default: self.requestCompleteProfileImage() } imageData(for: size, queue: cache.processingQueue) { (imageData) in guard let imageData = imageData else { return DispatchQueue.main.async { completion(nil, false) } } var image: UIImage? if let sizeLimit = sizeLimit { image = UIImage(from: imageData, withMaxSize: CGFloat(sizeLimit) * screenScale) } else { image = UIImage(data: imageData)?.decoded } if desaturate { image = image?.desaturatedImage(with: CIContext.shared) } if let image = image { cache.cache.setObject(image, forKey: cacheKey) } DispatchQueue.main.async { completion(image, false) } } } } extension ZMUser: ProfileImageFetchable {} extension ZMSearchUser: ProfileImageFetchable {}
48c52690ff4ff8096db66cb577bf6f77
31.711864
114
0.598964
false
false
false
false
testpress/ios-app
refs/heads/master
ios-app/Model/Course.swift
mit
1
// // Course.swift // ios-app // // Copyright © 2017 Testpress. 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 ObjectMapper import Realm import RealmSwift class Course: DBModel { @objc dynamic var url: String = "" @objc dynamic var id = 0 @objc dynamic var title: String = "" @objc dynamic var image: String = "" @objc dynamic var modified: String = "" @objc dynamic var modifiedDate: Double = 0 @objc dynamic var contentsUrl: String = "" @objc dynamic var chaptersUrl: String = "" @objc dynamic var slug: String = "" @objc dynamic var trophiesCount = 0 @objc dynamic var chaptersCount = 0 @objc dynamic var contentsCount = 0 @objc dynamic var order = 0 @objc dynamic var active = true @objc dynamic var external_content_link: String = "" @objc dynamic var external_link_label: String = "" var tags = List<String>() public override func mapping(map: Map) { url <- map["url"] id <- map["id"] title <- map["title"] image <- map["image"] modified <- map["modified"] modifiedDate = FormatDate.getDate(from: modified)?.timeIntervalSince1970 ?? 0 contentsUrl <- map["contents_url"] chaptersUrl <- map["chapters_url"] slug <- map["slug"] trophiesCount <- map["trophies_count"] chaptersCount <- map["chapters_count"] contentsCount <- map["contents_count"] order <- map["order"] active <- map["active"] external_content_link <- map["external_content_link"] external_link_label <- map["external_link_label"] tags <- (map["tags"], StringArrayTransform()) } override public static func primaryKey() -> String? { return "id" } }
116a624dde3e429188811b1b0cb6cca6
37.821918
85
0.667255
false
false
false
false
reproto/reproto
refs/heads/main
it/versions/structures/simple/swift/Foo/V4.swift
apache-2.0
1
public struct Foo_V4_Thing { let name: String? let other: Bar_V1_Other? let other2: Bar_V20_Other? let other21: Bar_V21_Other? } public extension Foo_V4_Thing { static func decode(json: Any) throws -> Foo_V4_Thing { let json = try decode_value(json as? [String: Any]) var name: String? = Optional.none if let value = json["name"] { name = Optional.some(try decode_name(unbox(value, as: String.self), name: "name")) } var other: Bar_V1_Other? = Optional.none if let value = json["other"] { other = Optional.some(try Bar_V1_Other.decode(json: value)) } var other2: Bar_V20_Other? = Optional.none if let value = json["other2"] { other2 = Optional.some(try Bar_V20_Other.decode(json: value)) } var other21: Bar_V21_Other? = Optional.none if let value = json["other21"] { other21 = Optional.some(try Bar_V21_Other.decode(json: value)) } return Foo_V4_Thing(name: name, other: other, other2: other2, other21: other21) } func encode() throws -> [String: Any] { var json = [String: Any]() if let value = self.name { json["name"] = value } if let value = self.other { json["other"] = try value.encode() } if let value = self.other2 { json["other2"] = try value.encode() } if let value = self.other21 { json["other21"] = try value.encode() } return json } }
c47507a9e33092ff05af8062d29b2a4b
23.929825
88
0.608726
false
false
false
false
frootloops/swift
refs/heads/master
tools/SwiftSyntax/Trivia.swift
apache-2.0
1
//===------------------- Trivia.swift - Source Trivia Enum ----------------===// // // 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 // //===----------------------------------------------------------------------===// import Foundation /// A contiguous stretch of a single kind of trivia. The constituent part of /// a `Trivia` collection. /// /// For example, four spaces would be represented by /// `.spaces(4)` /// /// In general, you should deal with the actual Trivia collection instead /// of individual pieces whenever possible. public enum TriviaPiece: Codable { enum CodingKeys: CodingKey { case kind, value } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) let kind = try container.decode(String.self, forKey: .kind) switch kind { case "Space": let value = try container.decode(Int.self, forKey: .value) self = .spaces(value) case "Tab": let value = try container.decode(Int.self, forKey: .value) self = .tabs(value) case "VerticalTab": let value = try container.decode(Int.self, forKey: .value) self = .verticalTabs(value) case "Formfeed": let value = try container.decode(Int.self, forKey: .value) self = .formfeeds(value) case "Newline": let value = try container.decode(Int.self, forKey: .value) self = .newlines(value) case "Backtick": let value = try container.decode(Int.self, forKey: .value) self = .backticks(value) case "LineComment": let value = try container.decode(String.self, forKey: .value) self = .lineComment(value) case "BlockComment": let value = try container.decode(String.self, forKey: .value) self = .blockComment(value) case "DocLineComment": let value = try container.decode(String.self, forKey: .value) self = .docLineComment(value) case "DocBlockComment": let value = try container.decode(String.self, forKey: .value) self = .docLineComment(value) case "GarbageText": let value = try container.decode(String.self, forKey: .value) self = .garbageText(value) default: let context = DecodingError.Context(codingPath: [CodingKeys.kind], debugDescription: "invalid TriviaPiece kind \(kind)") throw DecodingError.valueNotFound(String.self, context) } } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) switch self { case .blockComment(let comment): try container.encode("BlockComment", forKey: .kind) try container.encode(comment, forKey: .value) case .docBlockComment(let comment): try container.encode("DocBlockComment", forKey: .kind) try container.encode(comment, forKey: .value) case .docLineComment(let comment): try container.encode("DocLineComment", forKey: .kind) try container.encode(comment, forKey: .value) case .lineComment(let comment): try container.encode("LineComment", forKey: .kind) try container.encode(comment, forKey: .value) case .garbageText(let text): try container.encode("GarbageText", forKey: .kind) try container.encode(text, forKey: .value) case .formfeeds(let count): try container.encode("Formfeed", forKey: .kind) try container.encode(count, forKey: .value) case .backticks(let count): try container.encode("Backtick", forKey: .kind) try container.encode(count, forKey: .value) case .newlines(let count): try container.encode("Newline", forKey: .kind) try container.encode(count, forKey: .value) case .spaces(let count): try container.encode("Space", forKey: .kind) try container.encode(count, forKey: .value) case .tabs(let count): try container.encode("Tab", forKey: .kind) try container.encode(count, forKey: .value) case .verticalTabs(let count): try container.encode("VerticalTab", forKey: .kind) try container.encode(count, forKey: .value) } } /// A space ' ' character. case spaces(Int) /// A tab '\t' character. case tabs(Int) /// A vertical tab '\v' character. case verticalTabs(Int) /// A form-feed '\f' character. case formfeeds(Int) /// A newline '\n' character. case newlines(Int) /// A backtick '`' character, used to escape identifiers. case backticks(Int) /// A developer line comment, starting with '//' case lineComment(String) /// A developer block comment, starting with '/*' and ending with '*/'. case blockComment(String) /// A documentation line comment, starting with '///'. case docLineComment(String) /// A documentation block comment, starting with '/**' and ending with '*/. case docBlockComment(String) /// Any skipped text. case garbageText(String) } extension TriviaPiece: TextOutputStreamable { /// Prints the provided trivia as they would be written in a source file. /// /// - Parameter stream: The stream to which to print the trivia. public func write<Target>(to target: inout Target) where Target: TextOutputStream { func printRepeated(_ character: String, count: Int) { for _ in 0..<count { target.write(character) } } switch self { case let .spaces(count): printRepeated(" ", count: count) case let .tabs(count): printRepeated("\t", count: count) case let .verticalTabs(count): printRepeated("\u{2B7F}", count: count) case let .formfeeds(count): printRepeated("\u{240C}", count: count) case let .newlines(count): printRepeated("\n", count: count) case let .backticks(count): printRepeated("`", count: count) case let .lineComment(text), let .blockComment(text), let .docLineComment(text), let .docBlockComment(text), let .garbageText(text): target.write(text) } } /// Computes the information from this trivia to inform the source locations /// of the associated tokens. /// Specifically, walks through the trivia and keeps track of every newline /// to give a number of how many newlines and UTF8 characters appear in the /// trivia, along with the UTF8 offset of the last column. func characterSizes() -> (lines: Int, lastColumn: Int, utf8Length: Int) { switch self { case .spaces(let n), .tabs(let n), .verticalTabs(let n), .formfeeds(let n), .backticks(let n): return (lines: 0, lastColumn: n, utf8Length: n) case .newlines(let n): return (lines: n, lastColumn: 0, utf8Length: n) case .lineComment(let text), .docLineComment(let text): let length = text.utf8.count return (lines: 0, lastColumn: length, utf8Length: length) case .blockComment(let text), .docBlockComment(let text), .garbageText(let text): var lines = 0 var col = 0 var total = 0 for char in text.utf8 { total += 1 if char == 10 /* ASCII newline */ { col = 0 lines += 1 } else { col += 1 } } return (lines: lines, lastColumn: col, utf8Length: total) } } } /// A collection of leading or trailing trivia. This is the main data structure /// for thinking about trivia. public struct Trivia: Codable { let pieces: [TriviaPiece] /// Creates Trivia with the provided underlying pieces. public init(pieces: [TriviaPiece]) { self.pieces = pieces } public init(from decoder: Decoder) throws { var container = try decoder.unkeyedContainer() var pieces = [TriviaPiece]() while let piece = try container.decodeIfPresent(TriviaPiece.self) { pieces.append(piece) } self.pieces = pieces } public func encode(to encoder: Encoder) throws { var container = encoder.unkeyedContainer() for piece in pieces { try container.encode(piece) } } /// Creates Trivia with no pieces. public static var zero: Trivia { return Trivia(pieces: []) } /// Creates a new `Trivia` by appending the provided `TriviaPiece` to the end. public func appending(_ piece: TriviaPiece) -> Trivia { var copy = pieces copy.append(piece) return Trivia(pieces: copy) } /// Return a piece of trivia for some number of space characters in a row. public static func spaces(_ count: Int) -> Trivia { return [.spaces(count)] } /// Return a piece of trivia for some number of tab characters in a row. public static func tabs(_ count: Int) -> Trivia { return [.tabs(count)] } /// A vertical tab '\v' character. public static func verticalTabs(_ count: Int) -> Trivia { return [.verticalTabs(count)] } /// A form-feed '\f' character. public static func formfeeds(_ count: Int) -> Trivia { return [.formfeeds(count)] } /// Return a piece of trivia for some number of newline characters /// in a row. public static func newlines(_ count: Int) -> Trivia { return [.newlines(count)] } /// Return a piece of trivia for some number of backtick '`' characters /// in a row. public static func backticks(_ count: Int) -> Trivia { return [.backticks(count)] } /// Return a piece of trivia for a single line of ('//') developer comment. public static func lineComment(_ text: String) -> Trivia { return [.lineComment(text)] } /// Return a piece of trivia for a block comment ('/* ... */') public static func blockComment(_ text: String) -> Trivia { return [.blockComment(text)] } /// Return a piece of trivia for a single line of ('///') doc comment. public static func docLineComment(_ text: String) -> Trivia { return [.docLineComment(text)] } /// Return a piece of trivia for a documentation block comment ('/** ... */') public static func docBlockComment(_ text: String) -> Trivia { return [.docBlockComment(text)] } /// Return a piece of trivia for any garbage text. public static func garbageText(_ text: String) -> Trivia { return [.garbageText(text)] } /// Computes the total sizes and offsets of all pieces in this Trivia. func characterSizes() -> (lines: Int, lastColumn: Int, utf8Length: Int) { var lines = 0 var lastColumn = 0 var length = 0 for piece in pieces { let (ln, col, len) = piece.characterSizes() lines += ln lastColumn = col length += len } return (lines: lines, lastColumn: lastColumn, utf8Length: length) } } /// Conformance for Trivia to the Collection protocol. extension Trivia: Collection { public var startIndex: Int { return pieces.startIndex } public var endIndex: Int { return pieces.endIndex } public func index(after i: Int) -> Int { return pieces.index(after: i) } public subscript(_ index: Int) -> TriviaPiece { return pieces[index] } } extension Trivia: ExpressibleByArrayLiteral { /// Creates Trivia from the provided pieces. public init(arrayLiteral elements: TriviaPiece...) { self.pieces = elements } } /// Concatenates two collections of `Trivia` into one collection. public func +(lhs: Trivia, rhs: Trivia) -> Trivia { return Trivia(pieces: lhs.pieces + rhs.pieces) }
ae1c23ca1dcaa129cac791e3816d03bb
31.88
83
0.650852
false
false
false
false
JGiola/swift
refs/heads/main
test/IDE/complete_rdar80489548.swift
apache-2.0
6
// RUN: %empty-directory(%t.ccp) // RUN: %target-swift-ide-test -batch-code-completion -source-filename %s -filecheck %raw-FileCheck -completion-output-dir %t // KW_IN: Keyword[in]/None: in{{; name=.+$}} // KW_NO_IN-NOT: Keyword[in] func test(value: [Int]) { value.map { #^NOIN_IMMEDIATE?check=KW_IN^# } value.map { value#^NOIN_AFTER_EXPR_NOSPCACE?check=KW_NO_IN^# } value.map { value #^NOIN_AFTER_EXPR?check=KW_IN^# } value.map { value #^NOIN_NEWLINE?check=KW_IN^# } value.map { value in #^IN_AFTER_IN?check=KW_NO_IN^# } value.map { value in #^IN_NEWLINE?check=KW_NO_IN^# } #^FUNCBODY_STMT?check=KW_NO_IN^# value #^FUNCBODY_POSTFIX?check=KW_NO_IN^# } #^GLOBAL_STMT?check=KW_NO_IN^# value #^GLOBAL_POSTFIX?check=KW_NO_IN^#
47ea08d330f14ed05b6ba04a05c7745f
28.115385
125
0.648613
false
true
false
false
itsaboutcode/WordPress-iOS
refs/heads/develop
WordPress/Classes/ViewRelated/Jetpack/Jetpack Restore/Restore Status/BaseRestoreStatusViewController.swift
gpl-2.0
2
import Foundation import CocoaLumberjack import WordPressShared struct JetpackRestoreStatusConfiguration { let title: String let iconImage: UIImage let messageTitle: String let messageDescription: String let hint: String let primaryButtonTitle: String let placeholderProgressTitle: String? let progressDescription: String? } class BaseRestoreStatusViewController: UIViewController { // MARK: - Public Properties lazy var statusView: RestoreStatusView = { let statusView = RestoreStatusView.loadFromNib() statusView.translatesAutoresizingMaskIntoConstraints = false return statusView }() // MARK: - Private Properties private(set) var site: JetpackSiteRef private(set) var activity: Activity private(set) var configuration: JetpackRestoreStatusConfiguration private lazy var dateFormatter: DateFormatter = { return ActivityDateFormatting.mediumDateFormatterWithTime(for: site) }() // MARK: - Initialization init(site: JetpackSiteRef, activity: Activity) { fatalError("A configuration struct needs to be provided") } init(site: JetpackSiteRef, activity: Activity, configuration: JetpackRestoreStatusConfiguration) { self.site = site self.activity = activity self.configuration = configuration super.init(nibName: nil, bundle: nil) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - View Lifecycle override func viewDidLoad() { super.viewDidLoad() configureTitle() configureNavigation() configureRestoreStatusView() } // MARK: - Public func primaryButtonTapped() { fatalError("Must override in subclass") } // MARK: - Configure private func configureTitle() { title = configuration.title } private func configureNavigation() { navigationItem.hidesBackButton = true navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(doneTapped)) } private func configureRestoreStatusView() { let publishedDate = dateFormatter.string(from: activity.published) statusView.configure( iconImage: configuration.iconImage, title: configuration.messageTitle, description: String(format: configuration.messageDescription, publishedDate), hint: configuration.hint ) statusView.update(progress: 0, progressTitle: configuration.placeholderProgressTitle, progressDescription: nil) view.addSubview(statusView) view.pinSubviewToAllEdges(statusView) } @objc private func doneTapped() { primaryButtonTapped() } }
9d8b16d09a0c2f0fd977fb3b388157bc
27.921569
119
0.660678
false
true
false
false
jmgc/swift
refs/heads/master
test/SILGen/hop_to_executor.swift
apache-2.0
1
// RUN: %target-swift-frontend -emit-silgen %s -module-name test -swift-version 5 -enable-experimental-concurrency | %FileCheck --enable-var-scope %s // REQUIRES: concurrency actor class MyActor { private var p: Int // CHECK-LABEL: sil hidden [ossa] @$s4test7MyActorC6calleeyySiYF : $@convention(method) @async (Int, @guaranteed MyActor) -> () { // CHECK-NOT: hop_to_executor // CHECK: } // end sil function '$s4test7MyActorC6calleeyySiYF' @actorIndependent func callee(_ x: Int) async { print(x) } // CHECK-LABEL: sil hidden [ossa] @$s4test7MyActorC14throwingCalleeyySiYKF : $@convention(method) @async (Int, @guaranteed MyActor) -> @error Error { // CHECK-NOT: hop_to_executor // CHECK: } // end sil function '$s4test7MyActorC14throwingCalleeyySiYKF' @actorIndependent func throwingCallee(_ x: Int) async throws { print(x) } // CHECK-LABEL: sil hidden [ossa] @$s4test7MyActorC0A13AsyncFunctionyyYKF : $@convention(method) @async (@guaranteed MyActor) -> @error Error { // CHECK: hop_to_executor %0 : $MyActor // CHECK: = apply {{.*}} : $@convention(method) @async (Int, @guaranteed MyActor) -> () // CHECK-NEXT: hop_to_executor %0 : $MyActor // CHECK: try_apply {{.*}}, normal bb1, error bb2 // CHECK: bb1({{.*}}): // CHECK-NEXT: hop_to_executor %0 : $MyActor // CHECK: bb2({{.*}}): // CHECK-NEXT: hop_to_executor %0 : $MyActor // CHECK: } // end sil function '$s4test7MyActorC0A13AsyncFunctionyyYKF' func testAsyncFunction() async throws { await callee(p) await try throwingCallee(p) } // CHECK-LABEL: sil hidden [ossa] @$s4test7MyActorC0A22ConsumingAsyncFunctionyyYF : $@convention(method) @async (@owned MyActor) -> () { // CHECK: [[BORROWED_SELF:%[0-9]+]] = begin_borrow %0 : $MyActor // CHECK: hop_to_executor [[BORROWED_SELF]] : $MyActor // CHECK: = apply {{.*}} : $@convention(method) @async (Int, @guaranteed MyActor) -> () // CHECK-NEXT: hop_to_executor [[BORROWED_SELF]] : $MyActor // CHECK: } // end sil function '$s4test7MyActorC0A22ConsumingAsyncFunctionyyYF' __consuming func testConsumingAsyncFunction() async { await callee(p) } // CHECK-LABEL: sil private [ossa] @$s4test7MyActorC0A7ClosureSiyYFSiyYXEfU_ : $@convention(thin) @async (@guaranteed MyActor) -> Int { // CHECK: [[COPIED_SELF:%[0-9]+]] = copy_value %0 : $MyActor // CHECK: [[BORROWED_SELF:%[0-9]+]] = begin_borrow [[COPIED_SELF]] : $MyActor // CHECK: hop_to_executor [[BORROWED_SELF]] : $MyActor // CHECK: = apply // CHECK: } // end sil function '$s4test7MyActorC0A7ClosureSiyYFSiyYXEfU_' func testClosure() async -> Int { return await { () async in p }() } // CHECK-LABEL: sil hidden [ossa] @$s4test7MyActorC13dontInsertHTESiyF : $@convention(method) (@guaranteed MyActor) -> Int { // CHECK-NOT: hop_to_executor // CHECK: } // end sil function '$s4test7MyActorC13dontInsertHTESiyF' func dontInsertHTE() -> Int { return p } init() { p = 27 } } @globalActor struct GlobalActor { static var shared: MyActor = MyActor() } // CHECK-LABEL: sil hidden [ossa] @$s4test0A11GlobalActoryyYF : $@convention(thin) @async () -> () { // CHECK: [[F:%[0-9]+]] = function_ref @$s4test11GlobalActorV6sharedAA02MyC0Cvau : $@convention(thin) () -> Builtin.RawPointer // CHECK: [[P:%[0-9]+]] = apply [[F]]() : $@convention(thin) () -> Builtin.RawPointer // CHECK: [[A:%[0-9]+]] = pointer_to_address %2 : $Builtin.RawPointer to [strict] $*MyActor // CHECK: [[ACC:%[0-9]+]] = begin_access [read] [dynamic] [[A]] : $*MyActor // CHECK: [[L:%[0-9]+]] = load [copy] [[ACC]] : $*MyActor // CHECK: [[B:%[0-9]+]] = begin_borrow [[L]] : $MyActor // CHECK: hop_to_executor [[B]] : $MyActor // CHECK: } // end sil function '$s4test0A11GlobalActoryyYF' @GlobalActor func testGlobalActor() async { } // CHECK-LABEL: sil private [ossa] @$s4test0A22GlobalActorWithClosureyyYFyyYXEfU_ : $@convention(thin) @async () -> () { // CHECK: [[F:%[0-9]+]] = function_ref @$s4test11GlobalActorV6sharedAA02MyC0Cvau : $@convention(thin) () -> Builtin.RawPointer // CHECK: [[P:%[0-9]+]] = apply [[F]]() : $@convention(thin) () -> Builtin.RawPointer // CHECK: [[A:%[0-9]+]] = pointer_to_address %2 : $Builtin.RawPointer to [strict] $*MyActor // CHECK: [[ACC:%[0-9]+]] = begin_access [read] [dynamic] [[A]] : $*MyActor // CHECK: [[L:%[0-9]+]] = load [copy] [[ACC]] : $*MyActor // CHECK: [[B:%[0-9]+]] = begin_borrow [[L]] : $MyActor // CHECK: hop_to_executor [[B]] : $MyActor // CHECK: } // end sil function '$s4test0A22GlobalActorWithClosureyyYFyyYXEfU_' @GlobalActor func testGlobalActorWithClosure() async { await { () async in }() } @globalActor struct GenericGlobalActorWithGetter<T> { static var shared: MyActor { return MyActor() } } // CHECK-LABEL: sil hidden [ossa] @$s4test0A28GenericGlobalActorWithGetteryyYF : $@convention(thin) @async () -> () { // CHECK: [[MT:%[0-9]+]] = metatype $@thin GenericGlobalActorWithGetter<Int>.Type // CHECK: [[F:%[0-9]+]] = function_ref @$s4test28GenericGlobalActorWithGetterV6sharedAA02MyD0CvgZ : $@convention(method) <τ_0_0> (@thin GenericGlobalActorWithGetter<τ_0_0>.Type) -> @owned MyActor // CHECK: [[A:%[0-9]+]] = apply [[F]]<Int>([[MT]]) : $@convention(method) <τ_0_0> (@thin GenericGlobalActorWithGetter<τ_0_0>.Type) -> @owned MyActor // CHECK: [[B:%[0-9]+]] = begin_borrow [[A]] : $MyActor // CHECK: hop_to_executor [[B]] : $MyActor // CHECK: } // end sil function '$s4test0A28GenericGlobalActorWithGetteryyYF' @GenericGlobalActorWithGetter<Int> func testGenericGlobalActorWithGetter() async { } actor class RedActorImpl { // CHECK-LABEL: sil hidden [ossa] @$s4test12RedActorImplC5helloyySiF : $@convention(method) (Int, @guaranteed RedActorImpl) -> () { // CHECK-NOT: hop_to_executor // CHECK: } // end sil function '$s4test12RedActorImplC5helloyySiF' func hello(_ x : Int) {} } actor class BlueActorImpl { // CHECK-LABEL: sil hidden [ossa] @$s4test13BlueActorImplC4poke6personyAA03RedcD0C_tYF : $@convention(method) @async (@guaranteed RedActorImpl, @guaranteed BlueActorImpl) -> () { // CHECK: bb0([[RED:%[0-9]+]] : @guaranteed $RedActorImpl, [[BLUE:%[0-9]+]] : @guaranteed $BlueActorImpl): // CHECK: hop_to_executor [[BLUE]] : $BlueActorImpl // CHECK-NOT: hop_to_executor // CHECK: [[INTARG:%[0-9]+]] = apply {{%[0-9]+}}({{%[0-9]+}}, {{%[0-9]+}}) : $@convention(method) (Builtin.IntLiteral, @thin Int.Type) -> Int // CHECK-NOT: hop_to_executor // CHECK: [[METH:%[0-9]+]] = class_method [[RED]] : $RedActorImpl, #RedActorImpl.hello : (RedActorImpl) -> (Int) -> (), $@convention(method) (Int, @guaranteed RedActorImpl) -> () // CHECK: hop_to_executor [[RED]] : $RedActorImpl // CHECK-NEXT: {{%[0-9]+}} = apply [[METH]]([[INTARG]], [[RED]]) : $@convention(method) (Int, @guaranteed RedActorImpl) -> () // CHECK-NEXT: hop_to_executor [[BLUE]] : $BlueActorImpl // CHECK-NOT: hop_to_executor // CHECK: } // end sil function '$s4test13BlueActorImplC4poke6personyAA03RedcD0C_tYF' func poke(person red : RedActorImpl) async { await red.hello(42) } // CHECK-LABEL: sil hidden [ossa] @$s4test13BlueActorImplC14createAndGreetyyYF : $@convention(method) @async (@guaranteed BlueActorImpl) -> () { // CHECK: bb0([[BLUE:%[0-9]+]] : @guaranteed $BlueActorImpl): // CHECK: hop_to_executor [[BLUE]] : $BlueActorImpl // CHECK: [[RED:%[0-9]+]] = apply {{%[0-9]+}}({{%[0-9]+}}) : $@convention(method) (@thick RedActorImpl.Type) -> @owned RedActorImpl // CHECK: [[REDBORROW:%[0-9]+]] = begin_borrow [[RED]] : $RedActorImpl // CHECK: [[INTARG:%[0-9]+]] = apply {{%[0-9]+}}({{%[0-9]+}}, {{%[0-9]+}}) : $@convention(method) (Builtin.IntLiteral, @thin Int.Type) -> Int // CHECK: [[METH:%[0-9]+]] = class_method [[REDBORROW]] : $RedActorImpl, #RedActorImpl.hello : (RedActorImpl) -> (Int) -> (), $@convention(method) (Int, @guaranteed RedActorImpl) -> () // CHECK: hop_to_executor [[REDBORROW]] : $RedActorImpl // CHECK-NEXT: = apply [[METH]]([[INTARG]], [[REDBORROW]]) : $@convention(method) (Int, @guaranteed RedActorImpl) -> () // CHECK-NEXT: hop_to_executor [[BLUE]] : $BlueActorImpl // CHECK: end_borrow [[REDBORROW]] : $RedActorImpl // CHECK: destroy_value [[RED]] : $RedActorImpl // CHECK: } // end sil function '$s4test13BlueActorImplC14createAndGreetyyYF' func createAndGreet() async { let red = RedActorImpl() // <- key difference from `poke` is local construction of the actor await red.hello(42) } } @globalActor struct RedActor { static var shared: RedActorImpl { RedActorImpl() } } @globalActor struct BlueActor { static var shared: BlueActorImpl { BlueActorImpl() } } // CHECK-LABEL: sil hidden [ossa] @$s4test5redFnyySiF : $@convention(thin) (Int) -> () { // CHECK-NOT: hop_to_executor // CHECK: } // end sil function '$s4test5redFnyySiF' @RedActor func redFn(_ x : Int) {} // CHECK-LABEL: sil hidden [ossa] @$s4test6blueFnyyYF : $@convention(thin) @async () -> () { // ---- switch to blue actor, since we're an async function ---- // CHECK: [[MT:%[0-9]+]] = metatype $@thin BlueActor.Type // CHECK: [[F:%[0-9]+]] = function_ref @$s4test9BlueActorV6sharedAA0bC4ImplCvgZ : $@convention(method) (@thin BlueActor.Type) -> @owned BlueActorImpl // CHECK: [[B:%[0-9]+]] = apply [[F]]([[MT]]) : $@convention(method) (@thin BlueActor.Type) -> @owned BlueActorImpl // CHECK: [[BLUEEXE:%[0-9]+]] = begin_borrow [[B]] : $BlueActorImpl // CHECK: hop_to_executor [[BLUEEXE]] : $BlueActorImpl // ---- evaluate the argument to redFn ---- // CHECK: [[LIT:%[0-9]+]] = integer_literal $Builtin.IntLiteral, 100 // CHECK: [[INTMT:%[0-9]+]] = metatype $@thin Int.Type // CHECK: [[CTOR:%[0-9]+]] = function_ref @$sSi22_builtinIntegerLiteralSiBI_tcfC : $@convention(method) (Builtin.IntLiteral, @thin Int.Type) -> Int // CHECK: [[ARG:%[0-9]+]] = apply [[CTOR]]([[LIT]], [[INTMT]]) : $@convention(method) (Builtin.IntLiteral, @thin Int.Type) -> Int // ---- prepare to invoke redFn ---- // CHECK: [[CALLEE:%[0-9]+]] = function_ref @$s4test5redFnyySiF : $@convention(thin) (Int) -> () // ---- obtain and hop to RedActor's executor ---- // CHECK: [[REDMT:%[0-9]+]] = metatype $@thin RedActor.Type // CHECK: [[GETTER:%[0-9]+]] = function_ref @$s4test8RedActorV6sharedAA0bC4ImplCvgZ : $@convention(method) (@thin RedActor.Type) -> @owned RedActorImpl // CHECK: [[R:%[0-9]+]] = apply [[GETTER]]([[REDMT]]) : $@convention(method) (@thin RedActor.Type) -> @owned RedActorImpl // CHECK: [[REDEXE:%[0-9]+]] = begin_borrow [[R]] : $RedActorImpl // CHECK: hop_to_executor [[REDEXE]] : $RedActorImpl // ---- now invoke redFn, hop back to Blue, and clean-up ---- // CHECK-NEXT: {{%[0-9]+}} = apply [[CALLEE]]([[ARG]]) : $@convention(thin) (Int) -> () // CHECK-NEXT: hop_to_executor [[BLUEEXE]] : $BlueActorImpl // CHECK: end_borrow [[REDEXE]] : $RedActorImpl // CHECK: destroy_value [[R]] : $RedActorImpl // CHECK: end_borrow [[BLUEEXE]] : $BlueActorImpl // CHECK: destroy_value [[B]] : $BlueActorImpl // CHECK-NOT: hop_to_executor // CHECK: } // end sil function '$s4test6blueFnyyYF' @BlueActor func blueFn() async { await redFn(100) } // CHECK-LABEL: sil hidden [ossa] @$s4test20unspecifiedAsyncFuncyyYF : $@convention(thin) @async () -> () { // CHECK-NOT: hop_to_executor // CHECK: [[BORROW:%[0-9]+]] = begin_borrow {{%[0-9]+}} : $RedActorImpl // CHECK-NEXT: hop_to_executor [[BORROW]] : $RedActorImpl // CHECK-NEXT: {{%[0-9]+}} = apply {{%[0-9]+}}({{%[0-9]+}}) : $@convention(thin) (Int) -> () // CHECK-NEXT: end_borrow [[BORROW]] : $RedActorImpl // CHECK-NOT: hop_to_executor // CHECK: } // end sil function '$s4test20unspecifiedAsyncFuncyyYF' func unspecifiedAsyncFunc() async { await redFn(200) } // CHECK-LABEL: sil hidden [ossa] @$s4test27anotherUnspecifiedAsyncFuncyyAA12RedActorImplCYF : $@convention(thin) @async (@guaranteed RedActorImpl) -> () { // CHECK: bb0([[RED:%[0-9]+]] : @guaranteed $RedActorImpl): // CHECK-NOT: hop_to_executor // CHECK: [[INTARG:%[0-9]+]] = apply {{%[0-9]+}}({{%[0-9]+}}, {{%[0-9]+}}) : $@convention(method) (Builtin.IntLiteral, @thin Int.Type) -> Int // CHECK-NOT: hop_to_executor // CHECK: [[METH:%[0-9]+]] = class_method [[RED]] : $RedActorImpl, #RedActorImpl.hello : (RedActorImpl) -> (Int) -> (), $@convention(method) (Int, @guaranteed RedActorImpl) -> () // CHECK-NEXT: hop_to_executor [[RED]] : $RedActorImpl // CHECK-NEXT: {{%[0-9]+}} = apply [[METH]]([[INTARG]], [[RED]]) : $@convention(method) (Int, @guaranteed RedActorImpl) -> () // CHECK-NOT: hop_to_executor // CHECK: } // end sil function '$s4test27anotherUnspecifiedAsyncFuncyyAA12RedActorImplCYF' func anotherUnspecifiedAsyncFunc(_ red : RedActorImpl) async { await red.hello(12); }
a49d6a85835573897b29fc14fb4b45f0
53.970464
199
0.626008
false
true
false
false
ahmadbaraka/SwiftLayoutConstraints
refs/heads/master
Example/Tests/RhsLayoutConstraintSpec.swift
mit
1
// // RhsLayoutConstraintSpec.swift // SwiftLayoutConstraints // // Created by Ahmad Baraka on 7/22/16. // Copyright © 2016 CocoaPods. All rights reserved. // import Nimble import Quick import SwiftLayoutConstraints class RhsLayoutConstraintSpec: QuickSpec { override func spec() { describe("inits") { var object: NSObject! var constraint: RhsLayoutConstraint<NSObject>! beforeEach { object = NSObject() } it("should init with all values") { let attribute = NSLayoutAttribute.Top constraint = RhsLayoutConstraint(object, attribute: attribute, constant: 10, multiplier: 0.5) expect(constraint.object) == object expect(constraint.attribute) == attribute expect(constraint.constant) == 10 expect(constraint.multiplier) == 0.5 } it("should init with constant") { constraint = RhsLayoutConstraint(constant: 10) expect(constraint.object).to(beNil()) expect(constraint.attribute) == NSLayoutAttribute.NotAnAttribute expect(constraint.constant) == 10 expect(constraint.multiplier) == 1 } it("should init with object and attribute") { let attribute = NSLayoutAttribute.Bottom constraint = RhsLayoutConstraint(object, attribute: attribute) expect(constraint.object) == object expect(constraint.attribute) == attribute expect(constraint.constant) == 0 expect(constraint.multiplier) == 1 } it("should init with object") { constraint = RhsLayoutConstraint(object) expect(constraint.object) == object expect(constraint.attribute) == NSLayoutAttribute.NotAnAttribute expect(constraint.constant) == 0 expect(constraint.multiplier) == 1 } it("should copy values from another constraint with other type") { let object2 = NSURL() let attribute = NSLayoutAttribute.Bottom let org = RhsLayoutConstraint(object2, attribute: attribute) constraint = RhsLayoutConstraint(object, constraint: org) expect(constraint.object) == object expect(constraint.attribute) == attribute expect(constraint.constant) == 0 expect(constraint.multiplier) == 1 } it("should copy values from another constraint") { let attribute = NSLayoutAttribute.Bottom let org = RhsLayoutConstraint(object, attribute: attribute, constant: 10, multiplier: 0.5) constraint = RhsLayoutConstraint(constraint: org) expect(constraint.object) == object expect(constraint.attribute) == attribute expect(constraint.constant) == 10 expect(constraint.multiplier) == 0.5 } it("should copy values from lhs constraint") { let attribute = NSLayoutAttribute.Bottom let org = LhsLayoutConstraint(object, attribute: attribute) constraint = RhsLayoutConstraint(constraint: org) expect(constraint.object) == object expect(constraint.attribute) == attribute expect(constraint.constant) == 0 expect(constraint.multiplier) == 1 } } } }
2fba858d9a350c263f51cf5b2db7afe5
37.90099
109
0.530415
false
false
false
false
hollarab/LearningSwiftWorkshop
refs/heads/master
DaVinciWeekendWorkshop.playground/Pages/Review.xcplaygroundpage/Contents.swift
mit
1
/*: [Previous](@previous) # Review ## Variables and Constants * Constants don't change * Variables can change * Both are *strongly typed* ## Types Swift is a *strongly-typed* language, this means the compiler must know what *type* an variable or constant is. We've been able to skip this, because Swift *implies* the type for you. Code examples were chosen to avoid this problem while some basics were learned. All our examples in Part 1 were one of the four types below. var anIntValue:Int = 1 var aFloatValue:Float = 1.3 var aBool:Bool = true var someWords:String = "a string" So when we wrote `var isReady = true` Swift knew it was really `var isReady:Bool = true`. ## Functions *Functions* are self-contained chunks of code that perform a specific task. You give a function a name that identifies what it does, and this name is used to "call" the function to perform its task when needed. Functions allow us to re-use code and make our code readable. Functions have a *name*, take zero to many *parameters* and have a *return type*. func printHi() -> Void { print("Hi") } printHi() // calls the printHi method. prints "Hi" func add(a:Int, b:Int) -> Int { return a + b; } add(1,2) // calls the add method, passing two parameters. returns 3 func addStrings(strOne:String, strTwo:String) -> String { return strOne + strTwo; } addStrings("Hi ", "there!) // calls addStrings, passing two Strings retuns "Hi there!" ## Casting *Casting* is when you change a type from one to another. function squareAFloat(floatValue:Float) -> Float { return floatValue * floatValue } var intValue:Int = 10 squareAFloat( Float(intValue) ) // cast to a Float to pass to the method ## Conditions, Comparison We use `if`, `if/else`, `if/elseif` statements (and others) to create conditional flows. Comparisons and functions that evaluate to `true` or `false` help. if this > that { // do a thing } else if this == that { // do another thing } else { // worst case } ## Logic && And || Or ! Not == Equals != Not Equals ## Loops, Ranges Support doing sequences of operations. for ii in 0..<10 { // count from 0 to 9 } ---- [Next](@next) on to Optionals */
576e578cc0711c753d060b71204ed542
23.540816
273
0.641164
false
false
false
false
CarlosMChica/swift-dojos
refs/heads/master
MarsRoverKata/MarsRoverKataTest/actions/TurnLeftActionShould.swift
apache-2.0
1
import XCTest class TurnLeftActionShould: XCTestCase { let action = TurnLeftAction() let position = PositionSpy() let invalidCommand = "invalidCommand" func testTurmLeft_whenExecute() throws { let command = givenAnyCommand() try action.execute(command) XCTAssertTrue(position.turnLeftCalled) } func testReturnCanExecuteCommandTrue_whenCommandInputIsValid() { let command = givenValidCommand() let canExecute = action.canExecute(command) XCTAssertTrue(canExecute) } func testReturnCanExecuteCommandFalse_whenCommandInputIsInvalid() { let command = givenInvalidCommand() let canExecute = action.canExecute(command) XCTAssertFalse(canExecute) } func givenAnyCommand() -> Command { return Command(position: position) } func givenValidCommand() -> Command { return Command(input: TurnLeftAction.commandInput, position: position) } func givenInvalidCommand() -> Command { return Command(input: invalidCommand, position: position) } }
4ae62c9a2996720cc3fa4d233719afbd
22.181818
74
0.739216
false
true
false
false
kevin-zqw/play-swift
refs/heads/master
swift-lang/06. Functions.playground/section-1.swift
apache-2.0
1
// ------------------------------------------------------------------------------------------------ // Things to know: // // * Like most other languages, functions contain units of code to perform a task, but there are // a few key featurs of functions in Swift. // // * Functions are types in Swift. This means that a function can receive another function as an // input parameter or return a function as a result. You can even declare variables that are // functions. // // * Functions can be nested, and the inner function can be returned by the outer function. To // enable this, the current state of any local variables (local to the outer function) that are // used by the inner function are "captured" for use by the inner function. Any time that inner // function is called, it uses this captured state. This is the case even when a nested function // is returned by the parent function. // ------------------------------------------------------------------------------------------------ // Here's a simple function that receives a Single string and returns a String // // Note that each parameter has a local name (for use within the function) and a standard type // annotation. The return value's type is at the end of the function, following the ->. func sayHello(personName: String) -> String { return "Hello, \(personName)" } func mySayHello(name: String) -> String { return "Hello, \(name)" } // If we call the function, we'll receive the greeting sayHello("Peter Parker") mySayHello("Kevin Zhang") // Multiple input parameters are separated by a comma func halfOpenRangeLength(start: Int, end: Int) -> Int { return end - start } func addTwoNumbs(a: Int, b: Int) -> Int { return a + b } addTwoNumbs(1, b: 2) // A function with no parameters simply has an empty set of parenthesis following the function // name: func sayHelloWorld() -> String { return "Hello, world" } // A funciton with no return value can be expressed in two different ways. The first is to replace // the return type with a set of empty parenthesis, which can be thought of as an empty Tuple. func sayGoodbye(name: String) -> () { "Goodbye, \(name)" } // We can also remove the return type (and the -> delimiter) alltogether: func sayGoodbyeToMyLittleFriend(name: String) { "Goodbye, \(name)" } // Functions can return Tuples, which enable them to return multiple values. // // The following function simply returns two hard-coded strings. func getApplicationNameAndVersion() -> (appName: String, version: String) { return ("Modaferator", "v1.0") } let nameVersion = getApplicationNameAndVersion() nameVersion.appName nameVersion.version // Since the return value is a Tuple, we can use the Tuple's naming feature to name the values // being returned: func getApplicationInfo() -> (name: String, version: String) { return ("Modaferator", "v1.0") } var appInfo = getApplicationInfo() appInfo.name appInfo.version func safeMinMax(array: [Int]) -> (min:Int, max: Int)? { if array.isEmpty { return nil } return (1, 2) } var aaa = safeMinMax([]) print(aaa.dynamicType) if let (mm, nn) = safeMinMax([]) { print(mm, nn) } // By default, the first parameter omits its external name, and the second and subsequent parameters use their local name as their external name. All parameters must have unique local names. Although it's possible for multiple parameters to have the same external name, unique external names help make your code more readable. func withExternalParameters(first f: String, second s: String, third t: String) { print(f, s, t) } withExternalParameters(first: "1", second: "2", third: "3") // use _ to omit external parameter names, the first parameter is no external name by default func noExternalParameters(f: String, _ s: String, _ t: String) { print(f, s, t) } noExternalParameters("1", "2", "3") // ------------------------------------------------------------------------------------------------ // External Parameter Names // // We can use Objective-C-like external parameter names so the caller must name the external // parameters when they call the function. The extenal name appears before the local name. func addSeventeen(toNumber value: Int) -> Int { return value + 17 } addSeventeen(toNumber: 42) // If your internal and external names are the same, you can use a shorthand #name syntax to create // both names at once. // // The following declaration creates an internal parameter named "action" as well as an external // parameter named "action": func kangaroosCan(action action: String) -> String { return "A Kangaroo can \(action)" } // We can now use the external name ("action") to make the call: kangaroosCan(action: "jump") kangaroosCan(action: "carry children in their pouches") // We can also have default parameter values. Default parameter values must be placed at the end // of the parameter list. // // In the addMul routine, we'll add two numbers and multiply the result by an optional multiplier // value. We will default the multiplier to 1 so that if the parameter is not specified, the // multiplication won't affect the result. func addMul(firstAdder: Int, secondAdder: Int, multiplier: Int = 1) -> Int { return (firstAdder + secondAdder) * multiplier } // We can call with just two parameters to add them together addMul(1, secondAdder: 2) // Default parameter values and external names // // Swift automatically creates external parameter names for those parameters that have default // values. Since our declaration of addMul did not specify an external name (either explicitly or // using the shorthand method), Swift created one for us based on the name of the internal // parameter name. This acts as if we had defined the third parameter using the "#" shorthand. // // Therefore, when calling the function and specifying a value for the defaulted parameter, we // must provide the default parameter's external name: addMul(1, secondAdder: 2, multiplier: 9) // We can opt out of the automatic external name for default parameter values by specify an // external name of "_" like so: func anotherAddMul(firstAdder: Int, secondAdder: Int, _ multiplier: Int = 1) -> Int { return (firstAdder + secondAdder) * multiplier } // Here, we call without the third parameter as before: anotherAddMul(1, secondAdder: 2) // And now we can call with an un-named third parameter: anotherAddMul(1, secondAdder: 2, 9) // ------------------------------------------------------------------------------------------------ // Variadic Parameters // // Variadic parameters allow you to call functions with zero or more values of a specified type. // // Variadic parameters appear within the receiving function as an array of the given type. // // A function may only have at most one variadic and it must appear as the last parameter. func arithmeticMean(numbers: Double...) -> Double { var total = 0.0 // The variadic, numbers, looks like an array to the internal function so we can just loop // through them for number in numbers { total += number } return numbers.count == 0 ? total : total / Double(numbers.count) } // Let's call it with a few parameter lengths. Note that we can call with no parameters, since that // meets the criteria of a variadic parameter (zero or more). arithmeticMean() arithmeticMean(1) arithmeticMean(1, 2) arithmeticMean(1, 2, 3) arithmeticMean(1, 2, 3, 4) arithmeticMean(1, 2, 3, 4, 5) arithmeticMean(1, 2, 3, 4, 5, 6) // If we want to use variadic parameters and default parameter values, we can do so by making sure // that the default parameters come before the variadic, at the end of the parameter list: func anotherArithmeticMean(initialTotal: Double = 0, numbers: Double...) -> Double { var total = initialTotal for number in numbers { total += number } return numbers.count == 0 ? total : total / Double(numbers.count) } // Here, we can still call with no parameters because of the default parameter anotherArithmeticMean() // Going forward, we must specify the default parameter's external name (because we didn't opt-out // of it.) Also, you can see why Swift attempts to enforce the use of external parameter names for // default parameter values. In this case, it helps us recognize where the defalt parameters leave // off and the variadic parameters begin: anotherArithmeticMean(1) anotherArithmeticMean(1, numbers: 2) anotherArithmeticMean(1, numbers: 2, 3) anotherArithmeticMean(1, numbers: 2, 3, 4) anotherArithmeticMean(3, numbers: 4, 5) anotherArithmeticMean(1, numbers: 2, 3, 4, 5, 6) // Variadic parameters with external parameter names only apply their external name to the first // variadic parameter specified in the function call (if present.) func yetAnotherArithmeticMean(initialTotal: Double = 0, values numbers: Double...) -> Double { var total = initialTotal for number in numbers { total += number } return numbers.count == 0 ? total : total / Double(numbers.count) } // And here we can see the impact on the function call of adding the external name "values" to the // variadic parameter: yetAnotherArithmeticMean() yetAnotherArithmeticMean(1) yetAnotherArithmeticMean(1, values: 2) yetAnotherArithmeticMean(1, values: 2, 3) yetAnotherArithmeticMean(1, values: 2, 3, 4) yetAnotherArithmeticMean(1, values: 2, 3, 4, 5) yetAnotherArithmeticMean(1, values: 2, 3, 4, 5, 6) // ------------------------------------------------------------------------------------------------ // Constant and variable parameters // // All function parameters are constant by default. To make them variable, add the var introducer: func padString(var str: String, pad: Character, count: Int) -> String { str = String(count: count, repeatedValue: pad) + str return str } var paddedString = "padded with dots" padString(paddedString, pad: ".", count: 10) // Note that the function does not modify the caller's copy of the string that was passed in // because the value is still passed by value: paddedString func testArrayInOut(inout array: [Int]) { array = [1, 1, 1, 1] } var myArray = [1, 2, 3] testArrayInOut(&myArray) myArray // ------------------------------------------------------------------------------------------------ // In-Out Parameters // // In-Out parameters allow us to force a parameter to be passed by reference so those changes can // persist after the function call. // // Note that inout parameters cannot be variadic or have default parameter values. // // We'll write a standard swap function to exercise this: func swap(inout a: Int, inout b: Int) { let tmp = a a = b b = tmp } // Let's call the swap function to see what happens. // // To ensure that the caller is aware that the parameter is an inout (and hence, can modify their // variable), we must prefix the parameter name with "&". // // Note that the variables that will be passed as references may not be defined as constants, // because it is expected that their values will change: var one = 1, two = 2 swap(&one, &two) // And we can see that 'one' contains a 2 and 'two' contains a 1: one two // ------------------------------------------------------------------------------------------------ // Function types // // The type of a function is comprised of the specific parameter list (the number of parameters as // well as their type) and the return value's type. // // The following two functions have the same type. // // It's important to note that their type is described as: (Int, Int) -> Int func add(a: Int, b: Int) -> Int {return a+b} func mul(a: Int, b: Int) -> Int {return a*b} // A function that has no parameters or return value would have the type: () -> () func nop() -> () { return } // The type of the function below is the same as the one above: () -> () // // It is written in a shorter form, eliminating the return type entirely, but this syntactic // simplification doesn't alter the way that the function's type is notated: func doNothing() { return } // Using what we know about funciton types, we can define variables that are the type of a function let doMul: (Int, Int) -> Int = mul // We can now use the variable to perform the function: doMul(4, 5) // We can also name our parameters when assigning them to a variable, as well as taking advantage // of un-named parameters ("_"). // // This additional syntactic decoration has a purpose, but it doesn't affect the underlying // function type, which remains: (Int, Int) -> Int let doAddMul: (a: Int, b: Int, Int) -> Int = addMul // Calling the function now requires external names for the first two parameters doAddMul(a: 4, b: 2, 55) // We can pass function types as parameters to funcions, too. // // Here, our first parameter named 'doMulFunc' has the type "(Int, Int) -> Int" followed by two // parameters, 'a' and 'b' that are used as parameters to the 'doMulFunc' function: func doDoMul(doMulFunc: (Int, Int) -> Int, a: Int, b: Int) -> Int { return doMulFunc(a, b) } // We can now pass the function (along with a couple parameters to call it with) to another // function: doDoMul(doMul, a: 5, b: 5) typealias MyFunction = () -> Void func ff() -> Void { } let af: MyFunction = ff // We can also return function types. // // The syntax looks a little wird because of the two sets of arrows. To read this, understand that // the first arrow specifies the return type, and the second arrow is simply part of the function // type being returned: func getDoMul() -> (Int, Int) -> Int { return doMul } let newDoMul = getDoMul() newDoMul(9, 5) // Or, an even shorter version that avoids the additional stored value: getDoMul()(5, 5) // Earlier we discussed how functions that do not return values still have a return type that // includes: -> () // // Here, we'll see this in action by returning a function that doesn't return a value: func getNop() -> () -> () { return nop } // And we'll call nop (note the second set of parenthesis to make the actual call to nop()) getNop()() // We can nest functions inside of other functions: func getFive() -> Int { func returnFive() -> Int { return 5 } // Call returnFive() and return the result of that function return returnFive() } // Calling getFive will return the Int value 5: getFive() // You can return nested functions, too: func getReturnFive() -> () -> Int { func returnFive() -> Int { return 5 } return returnFive } // Calling outerFunc2 will return a function capable of returning the Int value 5: let returnFive = getReturnFive() // Here we call the nested function: returnFive() // Nested function
ec7edfa1ff9beab596a5c53114d96649
32.320366
326
0.691642
false
false
false
false
bradleybernard/EjectBar
refs/heads/master
EjectBar/Extensions/NSWindow+.swift
mit
1
// // NSWindow+.swift // EjectBar // // Created by Bradley Bernard on 10/28/20. // Copyright © 2020 Bradley Bernard. All rights reserved. // import Foundation import AppKit extension NSWindow { private static let fadeDuration = 0.35 // Based on the window's: NSWindow.StyleMask // https://developer.apple.com/documentation/appkit/nswindow/stylemask private static let leftRightPadding: CGFloat = 2 private func makeActiveWindow() { makeKeyAndOrderFront(self) NSApp.activate(ignoringOtherApps: true) } func fadeIn(completion: (() -> Void)? = nil) { guard !isMainWindow else { makeActiveWindow() return } guard !isVisible else { makeActiveWindow() completion?() return } alphaValue = 0 makeActiveWindow() NSAnimationContext.runAnimationGroup { [weak self] context in context.duration = Self.fadeDuration self?.animator().alphaValue = 1 } completionHandler: { [weak self] in self?.makeActiveWindow() completion?() } } func fadeOut(completion: (() -> Void)? = nil) { NSAnimationContext.runAnimationGroup { [weak self] context in context.duration = Self.fadeDuration self?.animator().alphaValue = 0 } completionHandler: { [weak self] in guard let self = self else { return } self.contentViewController?.view.window?.orderOut(self) self.alphaValue = 1 completion?() } } func resizeToFitTableView(tableView: NSTableView?) { guard let tableView = tableView else { return } let widthDifference = frame.size.width - tableView.frame.size.width // A window with a tableView has a 1 pixel line on left and 1 pixel line on right, // so we don't want to shrink the window by 2 pixels each time we redraw the tableView. // If the difference in width's is 2, we don't change the frame guard widthDifference != Self.leftRightPadding else { return } var windowFrame = frame windowFrame.size.width = tableView.frame.size.width setFrame(windowFrame, display: true) } }
8e69eb572057d40f67a2fc5897372fce
26.694118
95
0.598131
false
false
false
false
hGhostD/SwiftLearning
refs/heads/master
Swift设计模式/Swift设计模式/17 观察者模式/17.playground/Contents.swift
apache-2.0
1
import Cocoa /*: > 使用观察者模式可以让一个独享在不对另一个对象产生依赖的情况下,注册并接受该对象发出的通知 */ //实现观察者模式 protocol Observer: class { func notify(user: String, success: Bool) } protocol Subject { func addObservers(observers: [Observer]) func removeObserver(oberver: Observer) } class SubjectBase: Subject { private var observers = [Observer]() private var collectionQueue = DispatchQueue(label: "colQ") func addObservers(observers: [Observer]) { collectionQueue.sync(flags: DispatchWorkItemFlags.barrier) { observers.forEach { self.observers.append($0) } } } func removeObserver(oberver: Observer) { collectionQueue.sync(flags: DispatchWorkItemFlags.barrier) { observers = observers.filter {_ in return true } } } func sendNotification(user: String, success: Bool) { collectionQueue.sync { observers.forEach { $0.notify(user: user, success: success) } } } } class ActivityLog: Observer { func logActivity(_ activitity: String) { print("Log: \(activitity)") } func notify(user: String, success: Bool) { print("Auth request for \(user). Success: \(success)") } } class FileCache: Observer { func loadFiles(user: String) { print("Load files for \(user)") } func notify(user: String, success: Bool) { if success { loadFiles(user: user) } } } class AttackMonitor: Observer { var monitorSuspiciousActivity: Bool = false { didSet { print("Monitoring for attack: \(monitorSuspiciousActivity)") } } func notify(user: String, success: Bool) { monitorSuspiciousActivity = !success } } class AuthenticationManager: SubjectBase { func authenticate(user: String, pass: String) -> Bool { var result = false if (user == "bob" && pass == "secret") { result = true print("User \(user) is authenticated") log.logActivity(user) }else { print("Failed authentication attempt") log.logActivity("Failed authentication : \(user)") } sendNotification(user: user, success: result) return result } } let log = ActivityLog() let cache = FileCache() let montitor = AttackMonitor() let authM = AuthenticationManager() authM.addObservers(observers: [log,cache,montitor]) authM.authenticate(user: "bob", pass: "secret") print("--------") authM.authenticate(user: "joe", pass: "shhh")
d4470dbde52c16ed8e20c4a88a6a70d8
23.867925
72
0.596358
false
false
false
false
kickstarter/ios-oss
refs/heads/main
Library/ViewModels/LoadingButtonViewModel.swift
apache-2.0
1
import Prelude import ReactiveSwift public protocol LoadingButtonViewModelInputs { func isLoading(_ isLoading: Bool) } public protocol LoadingButtonViewModelOutputs { var isUserInteractionEnabled: Signal<Bool, Never> { get } var startLoading: Signal<Void, Never> { get } var stopLoading: Signal<Void, Never> { get } } public protocol LoadingButtonViewModelType { var inputs: LoadingButtonViewModelInputs { get } var outputs: LoadingButtonViewModelOutputs { get } } public final class LoadingButtonViewModel: LoadingButtonViewModelType, LoadingButtonViewModelInputs, LoadingButtonViewModelOutputs { public init() { let isLoading = self.isLoadingProperty.signal .skipNil() self.isUserInteractionEnabled = isLoading .negate() self.startLoading = isLoading .filter(isTrue) .ignoreValues() self.stopLoading = isLoading .filter(isFalse) .ignoreValues() } private let isLoadingProperty = MutableProperty<Bool?>(nil) public func isLoading(_ isLoading: Bool) { self.isLoadingProperty.value = isLoading } public let isUserInteractionEnabled: Signal<Bool, Never> public let startLoading: Signal<Void, Never> public let stopLoading: Signal<Void, Never> public var inputs: LoadingButtonViewModelInputs { return self } public var outputs: LoadingButtonViewModelOutputs { return self } }
b586c56ef77f92686cf6132b7f7a52b6
26.54
67
0.75236
false
false
false
false
Haud/DateTime
refs/heads/master
Carthage/Checkouts/Swinject/Carthage/Checkouts/Nimble/Sources/Nimble/Matchers/MatcherProtocols.swift
apache-2.0
55
import Foundation /// Implement this protocol to implement a custom matcher for Swift public protocol Matcher { typealias ValueType func matches(actualExpression: Expression<ValueType>, failureMessage: FailureMessage) throws -> Bool func doesNotMatch(actualExpression: Expression<ValueType>, failureMessage: FailureMessage) throws -> Bool } #if _runtime(_ObjC) /// Objective-C interface to the Swift variant of Matcher. @objc public protocol NMBMatcher { func matches(actualBlock: () -> NSObject!, failureMessage: FailureMessage, location: SourceLocation) -> Bool func doesNotMatch(actualBlock: () -> NSObject!, failureMessage: FailureMessage, location: SourceLocation) -> Bool } #endif #if _runtime(_ObjC) /// Protocol for types that support contain() matcher. @objc public protocol NMBContainer { func containsObject(object: AnyObject!) -> Bool } extension NSHashTable : NMBContainer {} // Corelibs Foundation does not include this class yet #else public protocol NMBContainer { func containsObject(object: AnyObject) -> Bool } #endif extension NSArray : NMBContainer {} extension NSSet : NMBContainer {} #if _runtime(_ObjC) /// Protocol for types that support only beEmpty(), haveCount() matchers @objc public protocol NMBCollection { var count: Int { get } } extension NSHashTable : NMBCollection {} // Corelibs Foundation does not include these classes yet extension NSMapTable : NMBCollection {} #else public protocol NMBCollection { var count: Int { get } } #endif extension NSSet : NMBCollection {} extension NSDictionary : NMBCollection {} #if _runtime(_ObjC) /// Protocol for types that support beginWith(), endWith(), beEmpty() matchers @objc public protocol NMBOrderedCollection : NMBCollection { func indexOfObject(object: AnyObject!) -> Int } #else public protocol NMBOrderedCollection : NMBCollection { func indexOfObject(object: AnyObject) -> Int } #endif extension NSArray : NMBOrderedCollection {} #if _runtime(_ObjC) /// Protocol for types to support beCloseTo() matcher @objc public protocol NMBDoubleConvertible { var doubleValue: CDouble { get } } #else public protocol NMBDoubleConvertible { var doubleValue: CDouble { get } } extension Double : NMBDoubleConvertible { public var doubleValue: CDouble { get { return self } } } extension Float : NMBDoubleConvertible { public var doubleValue: CDouble { get { return CDouble(self) } } } #endif extension NSNumber : NMBDoubleConvertible { } private let dateFormatter: NSDateFormatter = { let formatter = NSDateFormatter() formatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SSSS" formatter.locale = NSLocale(localeIdentifier: "en_US_POSIX") return formatter }() #if _runtime(_ObjC) extension NSDate: NMBDoubleConvertible { public var doubleValue: CDouble { get { return self.timeIntervalSinceReferenceDate } } } #endif extension NMBDoubleConvertible { public var stringRepresentation: String { get { if let date = self as? NSDate { return dateFormatter.stringFromDate(date) } if let debugStringConvertible = self as? CustomDebugStringConvertible { return debugStringConvertible.debugDescription } if let stringConvertible = self as? CustomStringConvertible { return stringConvertible.description } return "" } } } /// Protocol for types to support beLessThan(), beLessThanOrEqualTo(), /// beGreaterThan(), beGreaterThanOrEqualTo(), and equal() matchers. /// /// Types that conform to Swift's Comparable protocol will work implicitly too #if _runtime(_ObjC) @objc public protocol NMBComparable { func NMB_compare(otherObject: NMBComparable!) -> NSComparisonResult } #else // This should become obsolete once Corelibs Foundation adds Comparable conformance to NSNumber public protocol NMBComparable { func NMB_compare(otherObject: NMBComparable!) -> NSComparisonResult } #endif extension NSNumber : NMBComparable { public func NMB_compare(otherObject: NMBComparable!) -> NSComparisonResult { return compare(otherObject as! NSNumber) } } extension NSString : NMBComparable { public func NMB_compare(otherObject: NMBComparable!) -> NSComparisonResult { return compare(otherObject as! String) } }
219f12a4b21bb60eda2549111db89570
27.585987
117
0.705214
false
false
false
false
SioJL13/tec_ios
refs/heads/master
velocimetro.playground/velocimetro.swift
gpl-2.0
1
//: HW2. Velocimetro para automovil import UIKit enum Velocidades: Int{ case Apagado = 0, VelocidadBaja = 20, VelocidadMedia = 50, VelocidadAlta = 120 init(velocidadInicial: Velocidades){ self = velocidadInicial } } class Auto{ var velocidad = Velocidades(velocidadInicial: .Apagado) init(velocidad: Velocidades){ self.velocidad = velocidad } func cambioDeVelocidad()->(actual: Int, velocidadEnCadena: String){ var actual: Int var velocidadEnCadena: String actual = velocidad.rawValue switch velocidad { case .Apagado: velocidad = Velocidades.VelocidadBaja velocidadEnCadena = "Apagado" case .VelocidadBaja: velocidad = Velocidades.VelocidadMedia velocidadEnCadena = "Velocidad Baja" case .VelocidadMedia: velocidad = Velocidades.VelocidadAlta velocidadEnCadena = "Velocidad Media" case .VelocidadAlta: velocidad = Velocidades.VelocidadMedia velocidadEnCadena = "Velocidad Alta" } return (actual, velocidadEnCadena) } } var auto = Auto(velocidad: .Apagado) for n in 1...20 { var resultado = auto.cambioDeVelocidad() println("\(n): \(resultado.actual), \(resultado.velocidadEnCadena)") }
f0b66fe34dd4ed5e0e309b0e8ca8b0aa
25.056604
82
0.619117
false
false
false
false
stomp1128/TIY-Assignments
refs/heads/master
CollectEmAll-Sports/CollectEmAll-Sports/PlayerDetailViewController.swift
cc0-1.0
1
// // TeamDetailViewController.swift // CollectEmAll-Sports // // Created by Chris Stomp on 11/6/15. // Copyright © 2015 The Iron Yard. All rights reserved. // import UIKit class PlayerDetailViewController: UIViewController { @IBOutlet weak var name: UILabel! @IBOutlet weak var birthPlace: UILabel! @IBOutlet weak var highSchool: UILabel! @IBOutlet weak var height: UILabel! @IBOutlet weak var weight: UILabel! @IBOutlet weak var position: UILabel! @IBOutlet weak var jerseyNumber: UILabel! @IBOutlet weak var experience: UILabel! var player: Player? override func viewDidLoad() { super.viewDidLoad() name.text = "Name: \(player!.name)" birthPlace.text = "Born: \(player!.birthPlace)" highSchool.text = "High School: \(player!.highSchool)" let heightInFeet = (player!.height)/12 let inches = (player!.height) % 12 let heightString = "\(heightInFeet)\' \(inches)\"" height.text = "Height: \(heightString)" weight.text = "Weight: \(player!.weight) lbs" position.text = "Position: \(player!.position)" jerseyNumber.text = "Number: \(player!.jerseyNumber)" experience.text = "Experience: \(player!.experience)" } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
f3ca2b52f9cc3b3550628871654fbbf0
28
106
0.639009
false
false
false
false
wireapp/wire-ios-sync-engine
refs/heads/develop
Source/Calling/AVS/AVSWrapper+Handlers.swift
gpl-3.0
1
// // Wire // Copyright (C) 2018 Wire Swiss GmbH // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // import Foundation import avs extension AVSWrapper { enum Handler { typealias StringPtr = UnsafePointer<Int8>? typealias VoidPtr = UnsafeMutableRawPointer? typealias ContextRef = VoidPtr /// Callback used to inform user that call uses CBR (in both directions). /// /// typedef void (wcall_audio_cbr_change_h)(const char *userid, /// const char *clientid, /// int enabled, /// void *arg); typealias ConstantBitRateChange = @convention(c) (StringPtr, StringPtr, Int32, ContextRef) -> Void /// Callback used to inform user that received video has started or stopped. /// /// typedef void (wcall_video_state_change_h)(const char *convid, /// const char *userid, /// const char *clientid, /// int state, /// void *arg); typealias VideoStateChange = @convention(c) (StringPtr, StringPtr, StringPtr, Int32, ContextRef) -> Void /// Callback used to inform the user of an incoming call. /// /// typedef void (wcall_incoming_h)(const char *convid, /// uint32_t msg_time, /// const char *userid, /// const char *clientid, /// int video_call /*bool*/, /// int should_ring /*bool*/, /// int conv_type /*WCALL_CONV_TYPE...*/, /// void *arg); typealias IncomingCall = @convention(c) (StringPtr, UInt32, StringPtr, StringPtr, Int32, Int32, Int32, ContextRef) -> Void /// Callback used to inform the user of a missed call. /// /// typedef void (wcall_missed_h)(const char *convid, /// uint32_t msg_time, /// const char *userid, /// const char *clientid, /// int video_call /*bool*/, /// void *arg); typealias MissedCall = @convention(c) (StringPtr, UInt32, StringPtr, StringPtr, Int32, ContextRef) -> Void /// Callback used to inform user that a 1:1 call was answered. /// /// typedef void (wcall_answered_h)(const char *convid, void *arg); typealias AnsweredCall = @convention(c) (StringPtr, ContextRef) -> Void /// Callback used to inform the user that a data channel was established. /// /// typedef void (wcall_data_chan_estab_h)(const char *convid, /// const char *userid, /// const char *clientid, /// void *arg); typealias DataChannelEstablished = @convention(c) (StringPtr, StringPtr, StringPtr, ContextRef) -> Void /// Callback used to inform the user that a call was established (with media). /// /// typedef void (wcall_estab_h)(const char *convid, /// const char *userid, /// const char *clientid, /// void *arg); typealias CallEstablished = @convention(c) (StringPtr, StringPtr, StringPtr, ContextRef) -> Void /// Callback used to inform the user that a call was terminated. /// /// typedef void (wcall_close_h)(int reason, /// const char *convid, /// uint32_t msg_time, /// const char *userid, /// const char *clientid, /// void *arg); typealias CloseCall = @convention(c) (Int32, StringPtr, UInt32, StringPtr, StringPtr, ContextRef) -> Void /// Callback used to inform the user of call metrics. /// /// typedef void (wcall_metrics_h)(const char *convid, /// const char *metrics_json, /// void *arg); typealias CallMetrics = @convention(c) (StringPtr, StringPtr, ContextRef) -> Void /// Callback used to request a refresh of the call config. /// /// typedef int (wcall_config_req_h)(WUSER_HANDLE wuser, void *arg); typealias CallConfigRefresh = @convention(c) (UInt32, ContextRef) -> Int32 /// Callback used when the calling system is ready for calling. The version parameter specifies the call config /// version to use. /// /// typedef void (wcall_ready_h)(int version, void *arg); typealias CallReady = @convention(c) (Int32, ContextRef) -> Void /// Callback used to send an OTR call message. /// /// The `targets` argument contains a json payload listing the clients for which the message is targeted. /// They payload has the following structure: /// /// ``` /// { /// "clients": [ /// {"userid": "xxxx", "clientid" "xxxx"}, /// {"userid": "xxxx", "clientid" "xxxx"}, /// ... /// ] /// } /// ``` /// /// typedef int (wcall_send_h)(void *ctx, /// const char *convid, /// const char *userid_self, /// const char *clientid_self, /// const char *targets /*optional*/, /// const char *clientid_dest /*deprecated - always null*/, /// const uint8_t *data, /// size_t len, /// int transient /*bool*/, /// void *arg); typealias CallMessageSend = @convention(c) (VoidPtr, StringPtr, StringPtr, StringPtr, StringPtr, StringPtr, UnsafePointer<UInt8>?, Int, Int32, ContextRef) -> Int32 /// Callback used to inform the user when the list of participants in a call changes. /// /// typedef void (wcall_participant_changed_h)(const char *convid, /// const char *mjson, /// void *arg); typealias CallParticipantChange = @convention(c) (StringPtr, StringPtr, ContextRef) -> Void /// Callback used to inform the user that all media has stopped. /// /// typedef void (wcall_media_stopped_h)(const char *convid, void *arg); typealias MediaStoppedChange = @convention(c) (StringPtr, ContextRef) -> Void /// Callback used to inform the user of a change in network quality for a participant. /// /// typedef void (wcall_network_quality_h)(const char *convid, /// const char *userid, /// const char *clientid, /// int quality, /* WCALL_QUALITY_ */ /// int rtt, /* round trip time in ms */ /// int uploss, /* upstream pkt loss % */ /// int downloss, /* dnstream pkt loss % */ /// void *arg); typealias NetworkQualityChange = @convention(c) (StringPtr, StringPtr, StringPtr, Int32, Int32, Int32, Int32, ContextRef) -> Void /// Callback used to inform the user when the mute state changes. /// /// typedef void (wcall_mute_h)(int muted, void *arg); typealias MuteChange = @convention(c) (Int32, ContextRef) -> Void /// Callback used to request a the list of clients in a conversation. /// /// typedef void (wcall_req_clients_h)(WUSER_HANDLE wuser, const char *convid, void *arg); typealias RequestClients = @convention(c) (UInt32, StringPtr, ContextRef) -> Void /// Callback used to request SFT communication. /// /// typedef int (wcall_sft_req_h)(void *ctx, const char *url, const uint8_t *data, size_t len, void *arg); typealias SFTCallMessageSend = @convention(c) (VoidPtr, StringPtr, UnsafePointer<UInt8>?, Int, ContextRef) -> Int32 /// Callback used to inform the user of a change in the list of active speakers /// /// typedef void (wcall_active_speaker_h)(WUSER_HANDLE wuser, const char *convid, const char *json_levels, void *arg); typealias ActiveSpeakersChange = @convention(c) (UInt32, StringPtr, StringPtr, ContextRef) -> Void } }
aa605431c368dddc24b55e464a379819
46.668269
171
0.498336
false
false
false
false
neoneye/SwiftyFORM
refs/heads/master
Source/Cells/PickerViewCell.swift
mit
1
// MIT license. Copyright (c) 2021 SwiftyFORM. All rights reserved. import UIKit struct PickerViewCellConstants { struct CellExpanded { static let height: CGFloat = 216 } } public class PickerViewCellModel { var title: String = "" var expandCollapseWhenSelectingRow = true var selectionStyle = UITableViewCell.SelectionStyle.default var titleFont: UIFont = .preferredFont(forTextStyle: .body) var titleTextColor: UIColor = Colors.text var detailFont: UIFont = .preferredFont(forTextStyle: .body) var detailTextColor: UIColor = Colors.secondaryText var titles = [[String]]() var value = [Int]() var humanReadableValueSeparator: String? var valueDidChange: ([Int]) -> Void = { (selectedRows: [Int]) in SwiftyFormLog("selectedRows \(selectedRows)") } var humanReadableValue: String { var result = [String]() for (component, row) in value.enumerated() { let title = titles[component][row] result.append(title) } return result.joined(separator: humanReadableValueSeparator ?? ",") } } /** # Picker view toggle-cell ### Tap this row to toggle This causes the inline picker view to expand/collapse */ public class PickerViewToggleCell: UITableViewCell, SelectRowDelegate, DontCollapseWhenScrolling, AssignAppearance { weak var expandedCell: PickerViewExpandedCell? public let model: PickerViewCellModel public init(model: PickerViewCellModel) { self.model = model super.init(style: .value1, reuseIdentifier: nil) selectionStyle = model.selectionStyle textLabel?.text = model.title textLabel?.font = model.titleFont detailTextLabel?.font = model.detailFont updateValue() assignDefaultColors() } public required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } public func updateValue() { detailTextLabel?.text = model.humanReadableValue } func setValueWithoutSync(_ value: [Int], animated: Bool) { if value.count != model.titles.count { print("Expected the number of components to be the same") return } SwiftyFormLog("set value \(value), animated \(animated)") model.value = value updateValue() expandedCell?.pickerView.form_selectRows(value, animated: animated) } public func form_cellHeight(_ indexPath: IndexPath, tableView: UITableView) -> CGFloat { 60 } public func form_didSelectRow(indexPath: IndexPath, tableView: UITableView) { if model.expandCollapseWhenSelectingRow == false { //print("cell is always expanded") return } if isExpandedCellVisible { _ = resignFirstResponder() } else { _ = becomeFirstResponder() } form_deselectRow() } // MARK: UIResponder public override var canBecomeFirstResponder: Bool { if model.expandCollapseWhenSelectingRow == false { return false } return true } public override func becomeFirstResponder() -> Bool { if !super.becomeFirstResponder() { return false } expand() return true } public override func resignFirstResponder() -> Bool { collapse() return super.resignFirstResponder() } // MARK: Expand collapse var isExpandedCellVisible: Bool { guard let sectionArray = form_tableView()?.dataSource as? TableViewSectionArray else { return false } guard let expandedItem = sectionArray.findItem(expandedCell) else { return false } if expandedItem.hidden { return false } return true } func toggleExpandCollapse() { guard let tableView = form_tableView() else { return } guard let sectionArray = tableView.dataSource as? TableViewSectionArray else { return } guard let expandedCell = expandedCell else { return } ToggleExpandCollapse.execute( toggleCell: self, expandedCell: expandedCell, tableView: tableView, sectionArray: sectionArray ) } func expand() { if isExpandedCellVisible { assignTintColors() } else { toggleExpandCollapse() } } func collapse() { if isExpandedCellVisible { toggleExpandCollapse() } } // MARK: AssignAppearance public func assignDefaultColors() { textLabel?.textColor = model.titleTextColor detailTextLabel?.textColor = model.detailTextColor } public func assignTintColors() { textLabel?.textColor = tintColor detailTextLabel?.textColor = tintColor } } /** # Picker view expanded-cell Row containing only a `UIPickerView` */ public class PickerViewExpandedCell: UITableViewCell { weak var collapsedCell: PickerViewToggleCell? lazy var pickerView: UIPickerView = { let instance = UIPickerView() instance.dataSource = self instance.delegate = self return instance }() var titles = [[String]]() func configure(_ model: PickerViewCellModel) { titles = model.titles pickerView.reloadAllComponents() pickerView.setNeedsLayout() pickerView.form_selectRows(model.value, animated: false) } public func valueChanged() { guard let collapsedCell = collapsedCell else { return } let model = collapsedCell.model var selectedRows = [Int]() for (component, _) in titles.enumerated() { let row: Int = pickerView.selectedRow(inComponent: component) selectedRows.append(row) } //print("selected rows: \(selectedRows)") model.value = selectedRows collapsedCell.updateValue() model.valueDidChange(selectedRows) } public init() { super.init(style: .default, reuseIdentifier: nil) contentView.addSubview(pickerView) } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } fileprivate var componentWidth: CGFloat = 0 public override func layoutSubviews() { super.layoutSubviews() pickerView.frame = contentView.bounds // Ensures that all UIPickerView components stay within the left/right layoutMargins let rect = pickerView.frame.inset(by: layoutMargins) let numberOfComponents = titles.count if numberOfComponents >= 1 { componentWidth = rect.width / CGFloat(numberOfComponents) } else { componentWidth = rect.width } /* Workaround: UIPickerView gets messed up on orientation change This is a very old problem On iOS9, as of 29 aug 2016, it's still a problem. http://stackoverflow.com/questions/7576679/uipickerview-as-inputview-gets-messed-up-on-orientation-change http://stackoverflow.com/questions/9767234/why-wont-uipickerview-resize-the-first-time-i-change-device-orientation-on-its The following line solves the problem. */ pickerView.setNeedsLayout() } } extension PickerViewExpandedCell: UIPickerViewDataSource { public func numberOfComponents(in pickerView: UIPickerView) -> Int { titles.count } public func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { titles[component].count } } extension PickerViewExpandedCell: UIPickerViewDelegate { public func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { titles[component][row] } public func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { valueChanged() } public func pickerView(_ pickerView: UIPickerView, rowHeightForComponent component: Int) -> CGFloat { 44 } public func pickerView(_ pickerView: UIPickerView, widthForComponent component: Int) -> CGFloat { componentWidth } } extension PickerViewExpandedCell: CellHeightProvider { public func form_cellHeight(indexPath: IndexPath, tableView: UITableView) -> CGFloat { PickerViewCellConstants.CellExpanded.height } } extension PickerViewExpandedCell: WillDisplayCellDelegate { public func form_willDisplay(tableView: UITableView, forRowAtIndexPath indexPath: IndexPath) { if let model = collapsedCell?.model { configure(model) } } } extension PickerViewExpandedCell: ExpandedCell { public var toggleCell: UITableViewCell? { collapsedCell } public var isCollapsable: Bool { collapsedCell?.model.expandCollapseWhenSelectingRow ?? false } } extension UIPickerView { func form_selectRows(_ rows: [Int], animated: Bool) { for (component, row) in rows.enumerated() { selectRow(row, inComponent: component, animated: animated) } } }
169082c80307c0ec4aaf5e1762175e86
24.3625
123
0.737432
false
false
false
false
starrpatty28/MJMusicApp
refs/heads/master
MJMusicApp/MJMusicApp/ThrillerAlbumVC.swift
mit
1
// // ThrillerAlbumVC.swift // MJMusicApp // // Created by Noi-Ariella Baht Israel on 3/22/17. // Copyright © 2017 Plant A Seed of Code. All rights reserved. // import UIKit import AVFoundation class ThrillerAlbumVC: UIViewController { var audioPlayer = AVAudioPlayer() override func viewDidLoad() { super.viewDidLoad() do { audioPlayer = try AVAudioPlayer(contentsOf: URL.init(fileURLWithPath: Bundle.main.path(forResource: "40 Thriller", ofType: "mp3")!)) audioPlayer.prepareToPlay() } catch{ print(error) } } @IBAction func youtubeClkd(_ sender: Any) { openURL(url: "https://www.youtube.com/watch?v=CZqM_PgQ7BM&list=PLDs_1K5H3Lco3c8l0IMj0ZpOARsaDuwj1") } func openURL(url:String!) { if let url = NSURL(string:url) { UIApplication.shared.openURL(url as URL) } } @IBAction func backBtnPressed(_ sender: Any) { dismiss(animated: true, completion: nil) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func playMusic(_ sender: Any) { audioPlayer.play() } }
a944e3bcfe9a193396cd90f2bfd818e1
23.54717
144
0.607225
false
false
false
false
Fenrikur/ef-app_ios
refs/heads/master
EurofurenceTests/Presenter Tests/Schedule/Presenter Tests/WhenSceneChangesSearchScopeToAllEvents_SchedulePresenterShould.swift
mit
1
@testable import Eurofurence import EurofurenceModel import XCTest class WhenSceneChangesSearchScopeToAllEvents_SchedulePresenterShould: XCTestCase { func testTellTheSearchViewModelToFilterToFavourites() { let searchViewModel = CapturingScheduleSearchViewModel() let interactor = FakeScheduleInteractor(searchViewModel: searchViewModel) let context = SchedulePresenterTestBuilder().with(interactor).build() context.simulateSceneDidLoad() context.scene.delegate?.scheduleSceneDidChangeSearchScopeToAllEvents() XCTAssertTrue(searchViewModel.didFilterToAllEvents) } func testTellTheSearchResultsToHide() { let context = SchedulePresenterTestBuilder().build() context.simulateSceneDidLoad() context.scene.delegate?.scheduleSceneDidChangeSearchScopeToAllEvents() XCTAssertTrue(context.scene.didHideSearchResults) } func testNotHideTheSearchResultsWhenQueryActive() { let context = SchedulePresenterTestBuilder().build() context.simulateSceneDidLoad() context.scene.delegate?.scheduleSceneDidUpdateSearchQuery("Something") context.scene.delegate?.scheduleSceneDidChangeSearchScopeToAllEvents() XCTAssertFalse(context.scene.didHideSearchResults) } func testNotTellTheSearchResultsToAppearWhenQueryChangesToEmptyString() { let context = SchedulePresenterTestBuilder().build() context.simulateSceneDidLoad() context.scene.delegate?.scheduleSceneDidChangeSearchScopeToFavouriteEvents() context.scene.delegate?.scheduleSceneDidChangeSearchScopeToAllEvents() context.scene.delegate?.scheduleSceneDidUpdateSearchQuery("") XCTAssertEqual(1, context.scene.didShowSearchResultsCount) } }
3b47f32137b5ee1318949070be18f3d8
39.5
84
0.771044
false
true
false
false
moked/iuob
refs/heads/master
iUOB 2/Controllers/Schedule Builder/ScheduleDetailsVC.swift
mit
1
// // ScheduleDetailsVC.swift // iUOB 2 // // Created by Miqdad Altaitoon on 1/16/17. // Copyright © 2017 Miqdad Altaitoon. All rights reserved. // import UIKit /// details of the option + ability to share class ScheduleDetailsVC: UIViewController { var sections = [Section]() // user choosen sections @IBOutlet weak var detailsTextView: UITextView! var summaryText = "" // MARK: - Life Cycle override func viewDidLoad() { super.viewDidLoad() googleAnalytics() buildSummary() } func googleAnalytics() { if let tracker = GAI.sharedInstance().defaultTracker { tracker.set(kGAIScreenName, value: NSStringFromClass(type(of: self)).components(separatedBy: ".").last!) let builder: NSObject = GAIDictionaryBuilder.createScreenView().build() tracker.send(builder as! [NSObject : AnyObject]) } } func buildSummary() { for section in sections { summaryText += "Course: \(section.note)\nSection #: \(section.sectionNo)\nDoctor: \(section.doctor)\n" if let finalDate = section.finalExam.date { summaryText += "Final Exam: \(finalDate.formattedLong) @\(section.finalExam.startTime)-\(section.finalExam.endTime)\n" } else { summaryText += "Final Exam: No Exam\n" } summaryText += "Time: " for timing in section.timing { summaryText += "\(timing.day) [\(timing.timeFrom)-\(timing.timeTo)] in [\(timing.room)]\n" } summaryText += "-------------------------------\n" } self.detailsTextView.text = summaryText } @IBAction func actionShareButton(_ sender: Any) { // text to share let text = summaryText // set up activity view controller let textToShare = [ text ] let activityViewController = UIActivityViewController(activityItems: textToShare, applicationActivities: nil) activityViewController.popoverPresentationController?.sourceView = self.view // so that iPads won't crash // exclude some activity types from the list (optional) //activityViewController.excludedActivityTypes = [ UIActivityType.airDrop, UIActivityType.postToFacebook ] // present the view controller self.present(activityViewController, animated: true, completion: nil) } @IBAction func doneButton(_ sender: Any) { dismiss(animated: true, completion: nil) } }
cb5f676e0f43458180980663d3c8c52b
29.494382
134
0.582167
false
false
false
false
lyp1992/douyu-Swift
refs/heads/master
YPTV/YPTV/Classes/Tools/YPPageView/YPTitleView.swift
mit
1
// // HYTitleView.swift // HYContentPageView // // Created by xiaomage on 2016/10/27. // Copyright © 2016年 seemygo. All rights reserved. // import UIKit // MARK:- 定义协议 protocol YPTitleViewDelegate : class { func titleView(_ titleView : YPTitleView, selectedIndex index : Int) } class YPTitleView: UIView { // MARK: 对外属性 weak var delegate : YPTitleViewDelegate? // MARK: 定义属性 fileprivate var titles : [String]! fileprivate var style : YPPageStyle! fileprivate var currentIndex : Int = 0 // MARK: 存储属性 fileprivate lazy var titleLabels : [UILabel] = [UILabel]() // MARK: 控件属性 fileprivate lazy var scrollView : UIScrollView = { let scrollV = UIScrollView() scrollV.frame = self.bounds scrollV.showsHorizontalScrollIndicator = false scrollV.scrollsToTop = false return scrollV }() fileprivate lazy var splitLineView : UIView = { let splitView = UIView() splitView.backgroundColor = UIColor.lightGray let h : CGFloat = 0.5 splitView.frame = CGRect(x: 0, y: self.frame.height - h, width: self.frame.width, height: h) return splitView }() fileprivate lazy var bottomLine : UIView = { let bottomLine = UIView() bottomLine.backgroundColor = self.style.bottomLineColor return bottomLine }() fileprivate lazy var coverView : UIView = { let coverView = UIView() coverView.backgroundColor = self.style.coverBgColor coverView.alpha = 0.7 return coverView }() // MARK: 计算属性 fileprivate lazy var normalColorRGB : (r : CGFloat, g : CGFloat, b : CGFloat) = self.getRGBWithColor(self.style.normalColor) fileprivate lazy var selectedColorRGB : (r : CGFloat, g : CGFloat, b : CGFloat) = self.getRGBWithColor(self.style.selectColor) // MARK: 自定义构造函数 init(frame: CGRect, titles : [String], style : YPPageStyle) { super.init(frame: frame) self.titles = titles self.style = style setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } // MARK:- 设置UI界面内容 extension YPTitleView { fileprivate func setupUI() { // 1.添加Scrollview addSubview(scrollView) // 2.添加底部分割线 addSubview(splitLineView) // 3.设置所有的标题Label setupTitleLabels() // 4.设置Label的位置 setupTitleLabelsPosition() // 5.设置底部的滚动条 if style.isBottomLineShow { setupBottomLine() } // 6.设置遮盖的View if style.isShowCoverView { setupCoverView() } } fileprivate func setupTitleLabels() { for (index, title) in titles.enumerated() { let label = UILabel() label.tag = index label.text = title label.textColor = index == 0 ? style.selectColor : style.normalColor label.font = UIFont.systemFont(ofSize: style.fontSize) label.textAlignment = .center label.isUserInteractionEnabled = true let tapGes = UITapGestureRecognizer(target: self, action: #selector(titleLabelClick(_ :))) label.addGestureRecognizer(tapGes) titleLabels.append(label) scrollView.addSubview(label) } } fileprivate func setupTitleLabelsPosition() { var titleX: CGFloat = 0.0 var titleW: CGFloat = 0.0 let titleY: CGFloat = 0.0 let titleH : CGFloat = frame.height let count = titles.count for (index, label) in titleLabels.enumerated() { if style.isScrollEnable { let rect = (label.text! as NSString).boundingRect(with: CGSize(width: CGFloat(MAXFLOAT), height: 0.0), options: .usesLineFragmentOrigin, attributes: [NSAttributedStringKey.font : UIFont.systemFont(ofSize: style.fontSize)], context: nil) titleW = rect.width if index == 0 { titleX = style.titleMargin * 0.5 } else { let preLabel = titleLabels[index - 1] titleX = preLabel.frame.maxX + style.titleMargin } } else { titleW = frame.width / CGFloat(count) titleX = titleW * CGFloat(index) } label.frame = CGRect(x: titleX, y: titleY, width: titleW, height: titleH) // 放大的代码 if index == 0 { let scale = style.isScaleAble ? style.scale : 1.0 label.transform = CGAffineTransform(scaleX: scale, y: scale) } } if style.isScrollEnable { scrollView.contentSize = CGSize(width: titleLabels.last!.frame.maxX + style.titleMargin * 0.5, height: 0) } } fileprivate func setupBottomLine() { scrollView.addSubview(bottomLine) bottomLine.frame = titleLabels.first!.frame bottomLine.frame.size.height = style.bottomLineHeight bottomLine.frame.origin.y = bounds.height - style.bottomLineHeight } fileprivate func setupCoverView() { scrollView.insertSubview(coverView, at: 0) let firstLabel = titleLabels[0] var coverW = firstLabel.frame.width let coverH = style.coverHeight var coverX = firstLabel.frame.origin.x let coverY = (bounds.height - coverH) * 0.5 if style.isScrollEnable { coverX -= style.coverMargin coverW += style.coverMargin * 2 } coverView.frame = CGRect(x: coverX, y: coverY, width: coverW, height: coverH) coverView.layer.cornerRadius = style.coverRadius coverView.layer.masksToBounds = true } } // MARK:- 事件处理 extension YPTitleView { @objc fileprivate func titleLabelClick(_ tap : UITapGestureRecognizer) { // 0.获取当前Label guard let currentLabel = tap.view as? UILabel else { return } // 1.如果是重复点击同一个Title,那么直接返回 if currentLabel.tag == currentIndex { return } // 2.获取之前的Label let oldLabel = titleLabels[currentIndex] // 3.切换文字的颜色 currentLabel.textColor = style.selectColor oldLabel.textColor = style.normalColor // 4.保存最新Label的下标值 currentIndex = currentLabel.tag // 5.通知代理 delegate?.titleView(self, selectedIndex: currentIndex) // 6.居中显示 contentViewDidEndScroll() // 7.调整bottomLine if style.isBottomLineShow { UIView.animate(withDuration: 0.15, animations: { self.bottomLine.frame.origin.x = currentLabel.frame.origin.x self.bottomLine.frame.size.width = currentLabel.frame.size.width }) } // 8.调整比例 if style.isScaleAble { oldLabel.transform = CGAffineTransform.identity currentLabel.transform = CGAffineTransform(scaleX: style.scale, y: style.scale) } // 9.遮盖移动 if style.isShowCoverView { let coverX = style.isScrollEnable ? (currentLabel.frame.origin.x - style.coverMargin) : currentLabel.frame.origin.x let coverW = style.isScrollEnable ? (currentLabel.frame.width + style.coverMargin * 2) : currentLabel.frame.width UIView.animate(withDuration: 0.15, animations: { self.coverView.frame.origin.x = coverX self.coverView.frame.size.width = coverW }) } } } // MARK:- 获取RGB的值 extension YPTitleView { fileprivate func getRGBWithColor(_ color : UIColor) -> (CGFloat, CGFloat, CGFloat) { guard let components = color.cgColor.components else { fatalError("请使用RGB方式给Title赋值颜色") } return (components[0] * 255, components[1] * 255, components[2] * 255) } } // MARK:- 对外暴露的方法 extension YPTitleView { func setTitleWithProgress(_ progress : CGFloat, sourceIndex : Int, targetIndex : Int) { // 1.取出sourceLabel/targetLabel let sourceLabel = titleLabels[sourceIndex] let targetLabel = titleLabels[targetIndex] // 3.颜色的渐变(复杂) // 3.1.取出变化的范围 let colorDelta = (selectedColorRGB.0 - normalColorRGB.0, selectedColorRGB.1 - normalColorRGB.1, selectedColorRGB.2 - normalColorRGB.2) // 3.2.变化sourceLabel sourceLabel.textColor = UIColor(r: selectedColorRGB.0 - colorDelta.0 * progress, g: selectedColorRGB.1 - colorDelta.1 * progress, b: selectedColorRGB.2 - colorDelta.2 * progress) // 3.2.变化targetLabel targetLabel.textColor = UIColor(r: normalColorRGB.0 + colorDelta.0 * progress, g: normalColorRGB.1 + colorDelta.1 * progress, b: normalColorRGB.2 + colorDelta.2 * progress) // 4.记录最新的index currentIndex = targetIndex let moveTotalX = targetLabel.frame.origin.x - sourceLabel.frame.origin.x let moveTotalW = targetLabel.frame.width - sourceLabel.frame.width // 5.计算滚动的范围差值 if style.isBottomLineShow { bottomLine.frame.size.width = sourceLabel.frame.width + moveTotalW * progress bottomLine.frame.origin.x = sourceLabel.frame.origin.x + moveTotalX * progress } // 6.放大的比例 if style.isScaleAble { let scaleDelta = (style.scale - 1.0) * progress sourceLabel.transform = CGAffineTransform(scaleX: style.scale - scaleDelta, y: style.scale - scaleDelta) targetLabel.transform = CGAffineTransform(scaleX: 1.0 + scaleDelta, y: 1.0 + scaleDelta) } // 7.计算cover的滚动 if style.isShowCoverView { coverView.frame.size.width = style.isScrollEnable ? (sourceLabel.frame.width + 2 * style.coverMargin + moveTotalW * progress) : (sourceLabel.frame.width + moveTotalW * progress) coverView.frame.origin.x = style.isScrollEnable ? (sourceLabel.frame.origin.x - style.coverMargin + moveTotalX * progress) : (sourceLabel.frame.origin.x + moveTotalX * progress) } } func contentViewDidEndScroll() { // 0.如果是不需要滚动,则不需要调整中间位置 guard style.isScrollEnable else { return } // 1.获取获取目标的Label let targetLabel = titleLabels[currentIndex] // 2.计算和中间位置的偏移量 var offSetX = targetLabel.center.x - bounds.width * 0.5 if offSetX < 0 { offSetX = 0 } let maxOffset = scrollView.contentSize.width - bounds.width if offSetX > maxOffset { offSetX = maxOffset } // 3.滚动UIScrollView scrollView.setContentOffset(CGPoint(x: offSetX, y: 0), animated: true) } }
587fd91c1578cba420f3dd9e0754cf82
33.523511
252
0.595206
false
false
false
false
iOSWizards/AwesomeMedia
refs/heads/master
Example/Pods/AwesomeCore/AwesomeCore/Classes/ModelParser/CategoryTrainingsMP.swift
mit
1
// // CategoryTrainingsMP.swift // AwesomeCore // // Created by Leonardo Vinicius Kaminski Ferreira on 06/09/17. // import Foundation struct CategoryTrainingsMP { static func parseCategoryTrainingsFrom(_ categoryTrainingsJSON: [String: AnyObject]) -> CategoryTrainings { var subcategoriesArray: [String] = [] if let subcategories = categoryTrainingsJSON["sub_categories"] as? [String] { for subcategory in subcategories { subcategoriesArray.append(subcategory) } } var trainingsArray: [TrainingCard] = [] if let trainings = categoryTrainingsJSON["trainings"] as? [[String: AnyObject]] { for training in trainings { if let train = TrainingCardMP.parseTrainingCardFrom(training) { trainingsArray.append(train) } } } return CategoryTrainings(subcategories: subcategoriesArray, trainings: trainingsArray) } }
dd45202e94b6ad5c274fdcad1a0cfec0
30.176471
111
0.596226
false
false
false
false
SuperAwesomeLTD/sa-mobile-sdk-ios-demo
refs/heads/master
AwesomeAdsDemo/Events.swift
apache-2.0
1
// // Events.swift // AwesomeAdsDemo // // Created by Gabriel Coman on 29/09/2017. // Copyright © 2017 Gabriel Coman. All rights reserved. // import UIKit import RxSwift import SuperAwesome enum Event { // jwt token + login case LoadingJwtToken case NoJwtToken case JwtTokenError case EditLoginDetails case GotJwtToken(token: String) // profile case GotUserProfile(profile: UserProfile) case UserProfileError // apps & placements case GotAppsForCompany(apps: [App]) case FilterApps(withSearchTerm: String?) case SelectPlacement(placementId: Int?) // companies case LoadingCompanies case GotCompanies(comps: [Company]) case FilterCompanies(withSearchTerm: String?) case SelectCompany(company: Company) // ads case GotAds(ads: [DemoAd]) case FilterAds(withSearchTerm: String?) case SelectAd(ad: DemoAd) // selected ad & response for settings case GotResponse(response: SAResponse?, format: AdFormat) } extension Event { static func checkIsUserLoggedIn () -> Observable<Event> { if let jwtToken = UserDefaults.standard.string(forKey: "jwtToken"), let metadata = UserMetadata.processMetadata(jwtToken: jwtToken), metadata.isValid { return Observable.just(Event.GotJwtToken(token: jwtToken)) } else { return Observable.just(Event.NoJwtToken) } } } extension Event { static func loginUser (withUsername username: String, andPassword password: String) -> Observable<Event> { let operation = NetworkOperation.login(forUsername: username, andPassword: password) let request = NetworkRequest(withOperation: operation) let task = NetworkTask() return task.execute(withInput: request) .flatMap { rawData -> Single<LogedUser> in return ParseTask<LogedUser>().execute(withInput: rawData) } .map { loggedUser -> String? in return loggedUser.token } .asObservable() .do(onNext: { token in if let token = token { UserDefaults.standard.set(token, forKey: "jwtToken") UserDefaults.standard.synchronize() } }) .flatMap{ (token: String?) -> Observable<Event> in guard let token = token else { return Observable.just(Event.JwtTokenError) } return Observable.just(Event.GotJwtToken(token: token)) } .catchError { error -> Observable<Event> in return Observable.just(Event.JwtTokenError) } } } extension Event { static func loadUser (withJwtToken jwtToken: String) -> Observable<Event> { let operation = NetworkOperation.getProfile(forJWTToken: jwtToken) let request = NetworkRequest(withOperation: operation) let task = NetworkTask() return task.execute(withInput: request) .flatMap { rawData -> Single<UserProfile> in return ParseTask<UserProfile>().execute(withInput: rawData) } .asObservable() .flatMap { (profile: UserProfile) -> Observable<Event> in return Observable.just(Event.GotUserProfile(profile: profile)) } .catchError { error -> Observable<Event> in return Observable.just(Event.UserProfileError) } } } extension Event { static func loadApps (forCompany company: Int, andJwtToken token: String) -> Observable<Event> { let operation = NetworkOperation.getApps(forCompany: company, andJWTToken: token) let request = NetworkRequest(withOperation: operation) let task = NetworkTask() return task.execute(withInput: request) .flatMap { rawData -> Single<NetworkData<App>> in return ParseTask<NetworkData<App>>().execute(withInput: rawData) } .asObservable() .flatMap { (data: NetworkData<App>) -> Observable<Event> in return Observable.just(Event.GotAppsForCompany(apps: data.data)) } .catchError { error -> Observable<Event> in return Observable.just(Event.UserProfileError) } } } extension Event { static func loadCompanies (forJwtToken token: String) -> Observable<Event> { let operation = NetworkOperation.getCompanies(forJWTToken: token) let request = NetworkRequest(withOperation: operation) let task = NetworkTask() return task.execute(withInput: request) .flatMap { rawData -> Single<NetworkData<Company>> in let task = ParseTask<NetworkData<Company>>() return task.execute(withInput: rawData) } .map { data -> [Company] in return data.data } .asObservable() .flatMap { (companies: [Company]) -> Observable<Event> in return Observable.just(Event.GotCompanies(comps: companies)) } .catchError { error -> Observable<Event> in return Observable.just(Event.UserProfileError) } } } extension Event { static func loadAds (forPlacementId placementId: Int, andJwtToken token: String, withCompany company: Int?) -> Observable<Event> { guard let company = company else { return Observable.just(Event.GotAds(ads: [])) } let request = LoadAdsRequest(placementId: placementId, token: token, company: company) let task = LoadAdsTask() return task.execute(withInput: request) .toArray() .asObservable() .map({ (ads: [DemoAd]) -> Event in return Event.GotAds(ads: ads) }) .catchError { error -> Observable<Event> in return Observable.just(Event.GotAds(ads: [])) } } } extension Event { static func loadAdResponse (forAd ad: DemoAd?, withPlacementId placementId: Int?) -> Observable<Event> { // return error if not a valid ad somehow guard var ad = ad, let placementId = placementId else { return Observable.just(Event.GotResponse(response: nil, format: AdFormat.unknown)) } ad.placementId = placementId let request = ProcessAdRequest(ad: ad) let task = ProcessAdTask() return task.execute(withInput: request) .flatMap { (response: SAResponse) -> Single<Event> in let format = AdFormat.fromCreative(ad.creative) return Single.just(Event.GotResponse(response: response, format: format)) } .catchError { error -> Single<Event> in return Single.just(Event.GotResponse(response: nil, format: AdFormat.unknown)) } .asObservable() } }
131fd4506335ae9888e452e8c4ae7e0f
34.351485
134
0.595015
false
false
false
false
bananafish911/SmartReceiptsiOS
refs/heads/master
SmartReceipts/ViewControllers/Ad/AdPresentingContainerViewController.swift
agpl-3.0
1
// // AdPresentingContainerViewController.swift // SmartReceipts // // Created by Bogdan Evsenev on 04/06/2017. // Copyright © 2017 Will Baumann. All rights reserved. // import GoogleMobileAds import Viperit fileprivate let BANNER_HEIGHT: CGFloat = 80 class AdPresentingContainerViewController: UIViewController { @IBOutlet fileprivate var adContainerHeight: NSLayoutConstraint? @IBOutlet fileprivate var nativeExpressAdView: GADNativeExpressAdView? @IBOutlet var container: UIView! override func viewDidLoad() { super.viewDidLoad() adContainerHeight?.constant = 0 nativeExpressAdView?.rootViewController = self nativeExpressAdView?.adUnitID = AD_UNIT_ID nativeExpressAdView?.delegate = self DispatchQueue.main.async { self.loadAd() } NotificationCenter.default.addObserver(self, selector: #selector(loadAd), name: NSNotification.Name.SmartReceiptsAdsRemoved, object: nil) } @objc private func loadAd() { if !Database.sharedInstance().hasValidSubscription() { let request = GADRequest() request.testDevices = [kGADSimulatorID, "b5c0a5fccf83835150ed1fac6dd636e6"] nativeExpressAdView?.adSize = getAdSize() nativeExpressAdView?.load(request) } } fileprivate func getAdSize() -> GADAdSize { let adSize = CGSize(width: view.bounds.width, height: BANNER_HEIGHT) return GADAdSizeFromCGSize(adSize) } private func checkAdsStatus() { if Database.sharedInstance().hasValidSubscription() { Logger.debug("Remove ads") UIView.animate(withDuration: 0.3, animations: { self.adContainerHeight?.constant = 0 self.view.layoutSubviews() }) nativeExpressAdView = nil } } deinit { NotificationCenter.default.removeObserver(self) } } extension AdPresentingContainerViewController: GADNativeExpressAdViewDelegate { func nativeExpressAdViewDidReceiveAd(_ nativeExpressAdView: GADNativeExpressAdView) { UIView.animate(withDuration: 0.3, animations: { self.adContainerHeight?.constant = BANNER_HEIGHT self.view.layoutSubviews() }) } func nativeExpressAdView(_ nativeExpressAdView: GADNativeExpressAdView, didFailToReceiveAdWithError error: GADRequestError) { UIView.animate(withDuration: 0.3, animations: { self.adContainerHeight?.constant = 0 self.view.layoutSubviews() }) { _ in nativeExpressAdView.adSize = self.getAdSize() } } } class AdNavigationEntryPoint: UINavigationController { override func viewDidLoad() { let module = Module.build(AppModules.trips) show(module.view, sender: nil) } }
3b8ca021cfe049f883b813d46adcf059
31.208791
129
0.654043
false
false
false
false
NobodyNada/SwiftStack
refs/heads/master
Sources/SwiftStack/Post.swift
mit
1
// // Post.swift // SwiftStack // // Created by FelixSFD on 06.12.16. // // import Foundation // - MARK: The type of the post /** Defines the type of a post. Either a question or an answer - author: FelixSFD */ public enum PostType: String, StringRepresentable { case answer = "answer" case question = "question" } // - MARK: Post /** The base class of `Question`s and `Answer`s - author: FelixSFD - seealso: [StackExchange API](https://api.stackexchange.com/docs/types/post) */ public class Post: Content { // - MARK: Post.Notice /** Represents a notice on a post. - author: FelixSFD */ public struct Notice: JsonConvertible { public init?(jsonString json: String) { do { guard let dictionary = try JSONSerialization.jsonObject(with: json.data(using: String.Encoding.utf8)!, options: .allowFragments) as? [String: Any] else { return nil } self.init(dictionary: dictionary) } catch { return nil } } public init(dictionary: [String: Any]) { self.body = dictionary["body"] as? String if let timestamp = dictionary["creation_date"] as? Int { self.creation_date = Date(timeIntervalSince1970: Double(timestamp)) } self.owner_user_id = dictionary["owner_user_id"] as? Int } public var dictionary: [String: Any] { var dict = [String: Any]() dict["body"] = body dict["creation_date"] = creation_date dict["owner_user_id"] = owner_user_id return dict } public var jsonString: String? { return (try? JsonHelper.jsonString(from: self)) ?? nil } public var body: String? public var creation_date: Date? public var owner_user_id: Int? } // - MARK: Initializers /** Basic initializer without default values */ public override init() { super.init() } /** Initializes the object from a JSON string. - parameter json: The JSON string returned by the API - author: FelixSFD */ public required convenience init?(jsonString json: String) { do { guard let dictionary = try JSONSerialization.jsonObject(with: json.data(using: String.Encoding.utf8)!, options: .allowFragments) as? [String: Any] else { return nil } self.init(dictionary: dictionary) } catch { return nil } } public required init(dictionary: [String: Any]) { super.init(dictionary: dictionary) //only initialize the properties that are not part of the superclass self.comment_count = dictionary["comment_count"] as? Int if let commentsArray = dictionary["comments"] as? [[String: Any]] { var commentsTmp = [Comment]() for commentDictionary in commentsArray { let commentTmp = Comment(dictionary: commentDictionary) commentsTmp.append(commentTmp) } } self.down_vote_count = dictionary["down_vote_count"] as? Int self.downvoted = dictionary["downvoted"] as? Bool if let timestamp = dictionary["creation_date"] as? Int { self.creation_date = Date(timeIntervalSince1970: Double(timestamp)) } if let timestamp = dictionary["last_activity_date"] as? Int { self.last_activity_date = Date(timeIntervalSince1970: Double(timestamp)) } if let timestamp = dictionary["last_edit_date"] as? Int { self.last_edit_date = Date(timeIntervalSince1970: Double(timestamp)) } if let user = dictionary["last_editor"] as? [String: Any] { self.last_editor = User(dictionary: user) } if let urlString = dictionary["share_link"] as? String { self.share_link = URL(string: urlString) } self.title = (dictionary["title"] as? String)?.stringByDecodingHTMLEntities self.up_vote_count = dictionary["up_vote_count"] as? Int } // - MARK: JsonConvertible public override var dictionary: [String: Any] { var dict = super.dictionary dict["creation_date"] = creation_date dict["comment_count"] = comment_count if comments != nil && (comments?.count)! > 0 { var tmpComments = [[String: Any]]() for comment in comments! { tmpComments.append(comment.dictionary) } dict["comments"] = tmpComments } dict["down_vote_count"] = down_vote_count dict["downvoted"] = downvoted dict["last_activity_date"] = last_activity_date dict["last_edit_date"] = last_edit_date dict["last_editor"] = last_editor?.dictionary dict["share_link"] = share_link dict["title"] = title dict["up_vote_count"] = up_vote_count return dict } // - MARK: Fields public var creation_date: Date? public var comment_count: Int? public var comments: [Comment]? public var down_vote_count: Int? public var downvoted: Bool? public var last_activity_date: Date? public var last_edit_date: Date? public var last_editor: User? public var share_link: URL? public var title: String? public var up_vote_count: Int? }
8920704b374567708dcc689d2707399a
26.75
169
0.54479
false
false
false
false
dsantosp12/DResume
refs/heads/master
Sources/App/Controllers/UserController.swift
mit
1
import Vapor import FluentProvider class UserController { func addRoutes(to drop: Droplet) { let userGroup = drop.grouped("api", "v1", "user") // Post userGroup.post(handler: createUser) userGroup.post(User.parameter, "skills", handler: addSkill) userGroup.post(User.parameter, "languages", handler: addLanguage) userGroup.post(User.parameter, "educations", handler: addEducation) userGroup.post(User.parameter, "attachments", handler: addAttachment) // Get userGroup.get(User.parameter, handler: getUser) userGroup.get(User.parameter, "skills", handler: getUserSkills) userGroup.get(User.parameter, "languages", handler: getLanguages) userGroup.get(User.parameter, "educations", handler: getEducation) userGroup.get(User.parameter, "attachments", handler: getAttachment) // Delete userGroup.delete(User.parameter, handler: removeUser) userGroup.delete("skill", Skill.parameter, handler: removeSkill) userGroup.delete("language", Language.parameter, handler: removeLanguage) userGroup.delete("education", Education.parameter, handler: removeEducation) userGroup.delete("attachment", Attachment.parameter, handler: removeAttachment) // Put userGroup.put(User.parameter, handler: updateUser) userGroup.put("skill", Skill.parameter, handler: updateSkill) userGroup.put("language", Language.parameter, handler: updateLanguage) userGroup.put("education", Education.parameter, handler: updateEducation) } // MARK: POSTERS func createUser(_ req: Request) throws -> ResponseRepresentable { guard let json = req.json else { throw Abort.badRequest } let user = try User(json: json) try user.save() return user } func addSkill(_ req: Request) throws -> ResponseRepresentable { guard let json = req.json else { throw Abort.badRequest } let skill = try Skill(json: json) try skill.save() return skill } func addLanguage(_ req: Request) throws -> ResponseRepresentable { let user = try req.parameters.next(User.self) guard var json = req.json else { throw Abort.badRequest } try json.set(Language.userIDKey, user.id) let language = try Language(json: json) try language.save() return language } func addEducation(_ req: Request) throws -> ResponseRepresentable { guard let json = req.json else { throw Abort.badRequest } let education = try Education(json: json) try education.save() return education } func addAttachment(_ req: Request) throws -> ResponseRepresentable { guard let json = req.json else { throw Abort.badRequest } let attachment = try Attachment(json: json) try attachment.save() return attachment } // MARK: GETTERS func getUser(_ req: Request) throws -> ResponseRepresentable { let user = try req.parameters.next(User.self) return user } func getUserSkills(_ req: Request) throws -> ResponseRepresentable { let user = try req.parameters.next(User.self) return try user.skills.all().makeJSON() } func getLanguages(_ req: Request) throws -> ResponseRepresentable { let user = try req.parameters.next(User.self) return try user.languages.all().makeJSON() } func getEducation(_ req: Request) throws -> ResponseRepresentable { let user = try req.parameters.next(User.self) return try user.educations.all().makeJSON() } func getAttachment(_ req: Request) throws -> ResponseRepresentable { let user = try req.parameters.next(User.self) return try user.attachments.all().makeJSON() } // MARK: DELETERS func removeUser(_ req: Request) throws -> ResponseRepresentable { let user = try req.parameters.next(User.self) try user.delete() return Response(status: .ok) } func removeSkill(_ req: Request) throws -> ResponseRepresentable { let skill = try req.parameters.next(Skill.self) try skill.delete() return Response(status: .ok) } func removeLanguage(_ req: Request) throws -> ResponseRepresentable { let language = try req.parameters.next(Language.self) try language.delete() return Response(status: .ok) } func removeEducation(_ req: Request) throws -> ResponseRepresentable { let education = try req.parameters.next(Education.self) try education.delete() return Response(status: .ok) } func removeAttachment(_ req: Request) throws -> ResponseRepresentable { let attachment = try req.parameters.next(Attachment.self) try attachment.delete() return Response(status: .ok) } // MARK: PUTTERS func updateUser(_ req: Request) throws -> ResponseRepresentable { let user = try req.parameters.next(User.self) guard let json = req.json else { throw Abort.badRequest } try user.update(with: json) return user } func updateSkill(_ req: Request) throws -> ResponseRepresentable { let skill = try req.parameters.next(Skill.self) guard let json = req.json else { throw Abort.badRequest } try skill.update(with: json) return skill } func updateLanguage(_ req: Request) throws -> ResponseRepresentable { let language = try req.parameters.next(Language.self) guard let json = req.json else { throw Abort.badRequest } try language.update(with: json) return language } func updateEducation(_ req: Request) throws -> ResponseRepresentable { let education = try req.parameters.next(Education.self) guard let json = req.json else { throw Abort.badRequest } try education.update(with: json) return education } }
a47160bb4e41f13c986ed44b2691714f
24.033898
80
0.663846
false
false
false
false
githubError/KaraNotes
refs/heads/master
KaraNotes/KaraNotes/Attention/Controller/CPFAttentionController.swift
apache-2.0
1
// // CPFAttentionController.swift // KaraNotes // // Created by 崔鹏飞 on 2017/2/15. // Copyright © 2017年 崔鹏飞. All rights reserved. // import UIKit import Alamofire class CPFAttentionController: BaseViewController { fileprivate var collectionView: UICollectionView? fileprivate let flowLayout = UICollectionViewFlowLayout() fileprivate let modalTransitioningDelegate = CPFModalTransitioningDelegate() fileprivate let cellID = "AttentionCell" fileprivate var pageNum:Int = 0 fileprivate var attentionArticleModels: [AttentionArticleModel] = [] override func viewDidLoad() { super.viewDidLoad() setupSubviews() } } // MARK: - setup extension CPFAttentionController { func setupSubviews() -> Void { setupNavigation() // init collectionView setupCollectionView() } func setupNavigation() -> Void { let searchBtn = UIButton(type: .custom) searchBtn.setImage(UIImage.init(named: "search"), for: .normal) searchBtn.frame = CGRect(x: 0, y: 0, width: 20, height: 20) searchBtn.addTarget(self, action: #selector(searchBtnClick), for: .touchUpInside) navigationItem.rightBarButtonItem = UIBarButtonItem(customView: searchBtn) } func setupCollectionView() -> Void { flowLayout.scrollDirection = .vertical flowLayout.itemSize = CGSize(width: self.view.width, height: 250*CPFFitHeight) flowLayout.minimumLineSpacing = 0 collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: flowLayout) if let collectionView = collectionView { view.addSubview(collectionView) collectionView.snp.makeConstraints { make in make.top.left.right.bottom.equalTo(view) } collectionView.backgroundColor = CPFGlobalColor collectionView.register(CPFAttentionCell.self, forCellWithReuseIdentifier: cellID) collectionView.contentInset = UIEdgeInsets(top: 10, left: 0, bottom: 0, right: 0) collectionView.delegate = self collectionView.dataSource = self let refreshHeader = MJRefreshNormalHeader(refreshingTarget: self, refreshingAction: #selector(loadNewDatas)) collectionView.mj_header = refreshHeader collectionView.mj_header.beginRefreshing() collectionView.mj_header.isAutomaticallyChangeAlpha = true let refreshFooter = MJRefreshBackNormalFooter(refreshingTarget: self, refreshingAction: #selector(loadMoreDatas)) refreshFooter?.setTitle("没有更多啦", for: .noMoreData) collectionView.mj_footer = refreshFooter collectionView.mj_footer.isAutomaticallyChangeAlpha = true } } } // MARK: - custom methods extension CPFAttentionController { @objc fileprivate func searchBtnClick() -> Void { let searchCtr = CPFSearchController() navigationController?.pushViewController(searchCtr, animated: true) } } // MARK: - Refresh extension CPFAttentionController { func loadNewDatas() -> Void { print("下拉加载更多") pageNum = 0 let params = ["token_id": getUserInfoForKey(key: CPFUserToken), "pagenum": String(pageNum), "pagesize": "10"] as [String : Any] Alamofire.request(CPFNetworkRoute.getAPIFromRouteType(route: .followArticleList), method: .post, parameters: params, encoding: JSONEncoding.default, headers: [:]).responseJSON { (response) in switch response.result { case .success(let json as JSONDictionary): guard let code = json["code"] as? String else {fatalError()} if code == "1" { guard let results = json["result"] as? [JSONDictionary] else {fatalError("Json 解析失败")} self.attentionArticleModels = results.map({ (json) -> AttentionArticleModel in return AttentionArticleModel.parse(json: json) }) self.collectionView?.reloadData() } else { print("--解析错误--") } case .failure(let error): print("--------\(error.localizedDescription)") default: print("unknow type error") } } self.collectionView?.mj_header.endRefreshing() } func loadMoreDatas() -> Void { pageNum += 1 let params = ["token_id": getUserInfoForKey(key: CPFUserToken), "pagenum": String(pageNum), "pagesize": "10"] as [String : Any] Alamofire.request(CPFNetworkRoute.getAPIFromRouteType(route: .followArticleList), method: .post, parameters: params, encoding: JSONEncoding.default, headers: [:]).responseJSON { (response) in switch response.result { case .success(let json as JSONDictionary): guard let code = json["code"] as? String else {fatalError()} if code == "1" { guard let results = json["result"] as? [JSONDictionary] else {fatalError("Json 解析失败")} let moreModels = results.map({ (json) -> AttentionArticleModel in return AttentionArticleModel.parse(json: json) }) self.attentionArticleModels.append(contentsOf: moreModels) self.collectionView?.reloadData() } else { print("--解析错误--") } case .failure(let error): self.pageNum -= 1 print("--------\(error.localizedDescription)") default: self.pageNum -= 1 print("unknow type error") } } collectionView?.mj_footer.endRefreshingWithNoMoreData() } } extension CPFAttentionController: UICollectionViewDelegate, UICollectionViewDataSource { // DataSource func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return attentionArticleModels.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let attentionCell = collectionView.dequeueReusableCell(withReuseIdentifier: cellID, for: indexPath) as! CPFAttentionCell attentionCell.attentionArticleModel = attentionArticleModels[indexPath.row] if traitCollection.forceTouchCapability == .available { registerForPreviewing(with: self, sourceView: attentionCell) } return attentionCell } // delegate func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let attentModel = attentionArticleModels[indexPath.row] // 相对 keyWindow 的位置 let currentCellItem = collectionView.cellForItem(at: indexPath) as! CPFAttentionCell let keyWindow = UIApplication.shared.keyWindow let currentCellItemRectInSuperView = currentCellItem.superview?.convert(currentCellItem.frame, to: keyWindow) modalTransitioningDelegate.startRect = CGRect(x: 0.0, y: (currentCellItemRectInSuperView?.origin.y)!, width: CPFScreenW, height: currentCellItem.height) let browseArticleVC = CPFBrowseArticleController() browseArticleVC.thumbImage = currentCellItem.thumbImage browseArticleVC.articleTitle = attentModel.article_title browseArticleVC.articleCreateTime = attentModel.article_create_formatTime browseArticleVC.articleAuthorName = getUserInfoForKey(key: CPFUserName) browseArticleVC.articleID = attentModel.article_id browseArticleVC.isMyArticle = false browseArticleVC.transitioningDelegate = modalTransitioningDelegate browseArticleVC.modalPresentationStyle = .custom present(browseArticleVC, animated: true, completion: nil) } } // MARK: - 3D Touch extension CPFAttentionController: UIViewControllerPreviewingDelegate { func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? { let currentCell = previewingContext.sourceView as! CPFAttentionCell let currentIndexPath = collectionView?.indexPath(for: currentCell) let attentModel = attentionArticleModels[(currentIndexPath?.row)!] let keyWindow = UIApplication.shared.keyWindow let currentCellItemRectInSuperView = currentCell.superview?.convert(currentCell.frame, to: keyWindow) modalTransitioningDelegate.startRect = CGRect(x: 0.0, y: (currentCellItemRectInSuperView?.origin.y)!, width: CPFScreenW, height: currentCell.height) let browseArticleVC = CPFBrowseArticleController() browseArticleVC.thumbImage = currentCell.thumbImage browseArticleVC.articleTitle = attentModel.article_title browseArticleVC.articleCreateTime = attentModel.article_create_formatTime browseArticleVC.articleAuthorName = getUserInfoForKey(key: CPFUserName) browseArticleVC.articleID = attentModel.article_id browseArticleVC.isMyArticle = false browseArticleVC.transitioningDelegate = modalTransitioningDelegate browseArticleVC.modalPresentationStyle = .custom browseArticleVC.is3DTouchPreviewing = true return browseArticleVC } func previewingContext(_ previewingContext: UIViewControllerPreviewing, commit viewControllerToCommit: UIViewController) { present(viewControllerToCommit, animated: true, completion: nil) } }
6c0b6ceaf21553993d46419b60ae49e1
39.829268
199
0.643469
false
false
false
false
teaxus/TSAppEninge
refs/heads/master
Source/Basic/View/BasicView/TSBasicTextField.swift
mit
1
// // TSBasicTextField.swift // TSAppEngine // // Created by teaxus on 15/12/14. // Copyright © 2015年 teaxus. All rights reserved. // import UIKit public typealias TSTextFieldFinishEdit = (_ textfield:UITextField,_ message:String)->Void public class TSBasicTextField: UITextField { public var blockFinishEdit:TSTextFieldFinishEdit? public var max_char:Int=Int.max//最大输入 public func BlockFinishEdit(action:@escaping TSTextFieldFinishEdit){ blockFinishEdit=action } public var size_design = CGSize(width: Screen_width,height: Screen_height){ didSet{ self.frame = CGRect(x: self.frame.origin.x, y: self.frame.origin.y, width: self.frame.size.width, height: self.frame.size.height) } } override public var frame:CGRect{ set(newValue){ super.frame = CGRect(x: newValue.origin.x/Screen_width*size_design.width, y: newValue.origin.y/Screen_height*size_design.height, width: newValue.size.width/Screen_width*size_design.width, height: newValue.size.height/Screen_height*size_design.height) } get{ return super.frame } } public override init(frame: CGRect) { super.init(frame: frame) initializer() self.frame = frame } func initializer(){ #if swift(>=2.2) NotificationCenter.default.addObserver(self, selector: #selector(self.textfieldDidChange(noti:)), name: NSNotification.Name.UITextFieldTextDidChange, object: nil) #else NSNotificationCenter.defaultCenter().addObserver(self, selector: "textfieldDidChange:", name: UITextFieldTextDidChangeNotification, object: nil) #endif } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) initializer() } deinit{ NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UITextFieldTextDidChange, object: nil) } //MARK:textfield在改变的时候 func textfieldDidChange(noti:NSNotification){ let textfield = noti.object as? TSBasicTextField var string_message = "" if textfield != nil{ if textfield!.text!.length > textfield!.max_char{ textfield?.text = textfield?.text![0..<(textfield!.max_char-1)] string_message = "超出范围" } if textfield!.blockFinishEdit != nil{ textfield!.blockFinishEdit!(textfield!,string_message) } } } }
e6dbdafa8b7d210eacc2b7c0c323ca25
35.277778
174
0.625574
false
false
false
false
Eonil/Editor
refs/heads/develop
Editor4/BashSubprocess.swift
mit
1
// // BashSubprocess.swift // Editor4 // // Created by Hoon H. on 2016/05/15. // Copyright © 2016 Eonil. All rights reserved. // import Foundation.NSData import Foundation.NSString enum BashSubprocessEvent { /// - Parameter 0: /// Printed line. This does not contain ending new-line character. Only line content. case StandardOutputDidPrintLine(String) /// - Parameter 0: /// Printed line. This does not contain ending new-line character. Only line content. case StandardErrorDidPrintLine(String) /// Process finished gracefully. case DidExitGracefully(exitCode: Int32) /// Process halted disgracefully by whatever reason. case DidHaltAbnormally } enum BashSubprocessError: ErrorType { case CannotEncodeCommandUsingUTF8(command: String) } final class BashSubprocess { var onEvent: (BashSubprocessEvent -> ())? private let subproc = SubprocessController() init() throws { subproc.onEvent = { [weak self] in guard let S = self else { return } switch $0 { case .DidReceiveStandardOutput(let data): S.pushStandardOutputData(data) case .DidReceiveStandardError(let data): S.pushStandardErrorData(data) case .DidTerminate: S.emitIncompleteLinesAndClear() switch S.subproc.state { case .Terminated(let exitCode): S.onEvent?(.DidExitGracefully(exitCode: exitCode)) default: fatalError("Bad state management in `Subprocess` class.") } } } try subproc.launchWithProgram(NSURL(fileURLWithPath: "/bin/bash"), arguments: ["--login", "-s"]) } deinit { switch subproc.state { case .Terminated: break default: // Force quitting subproc.kill() } } /// You need to send `exit` command to quit BASH gracefully. func runCommand(command: String) throws { guard let data = (command + "\n").dataUsingEncoding(NSUTF8StringEncoding) else { throw BashSubprocessError.CannotEncodeCommandUsingUTF8(command: command) } subproc.sendToStandardInput(data) } func kill() { subproc.kill() } //////////////////////////////////////////////////////////////// private var standardOutputDecoder = UTF8LineDecoder() private var standardErrorDecoder = UTF8LineDecoder() private func pushStandardOutputData(data: NSData) { standardOutputDecoder.push(data) while let line = standardOutputDecoder.popFirstLine() { onEvent?(.StandardOutputDidPrintLine(line)) } } private func pushStandardErrorData(data: NSData) { standardErrorDecoder.push(data) while let line = standardErrorDecoder.popFirstLine() { onEvent?(.StandardErrorDidPrintLine(line)) } } /// Ensures remaining text to be sent to event observer. /// Called on process finish. private func emitIncompleteLinesAndClear() { onEvent?(.StandardOutputDidPrintLine(standardOutputDecoder.newLineBuffer)) onEvent?(.StandardErrorDidPrintLine(standardErrorDecoder.newLineBuffer)) standardOutputDecoder = UTF8LineDecoder() standardErrorDecoder = UTF8LineDecoder() } } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // MARK: - //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// private struct UTF8LineDecoder { /// UTF-8 decoder needs to be state-ful. var decoder = UTF8() var lines = [String]() var newLineBuffer = "" mutating func push(data: NSData) { // TODO: We can remove this copying with a clever generator. let startPointer = UnsafePointer<UInt8>(data.bytes) let endPointer = startPointer.advancedBy(data.length) var iteratingPointer = startPointer // We need to keep a strong reference to data to make it alive until generator dies. var g = AnyGenerator<UInt8> { [data] in if iteratingPointer == endPointer { return nil } let unit = iteratingPointer.memory iteratingPointer += 1 return unit } push(&g) } mutating func push<G: GeneratorType where G.Element == UInt8>(inout codeUnitGenerator: G) { var ok = true while ok { let result = decoder.decode(&codeUnitGenerator) switch result { case .Result(let unicodeScalar): newLineBuffer.append(unicodeScalar) if newLineBuffer.hasSuffix("\n") { func getLastCharacterDeletedOf(string: String) -> String { var copy = string let endIndex = copy.endIndex copy.removeRange((endIndex.predecessor())..<(endIndex)) return copy } lines.append(getLastCharacterDeletedOf(newLineBuffer)) newLineBuffer = "" } case .EmptyInput: ok = false case .Error: ok = false } } } /// Gets first line and removes it from the buffer if available. /// Otherwise returns `nil`. mutating func popFirstLine() -> String? { return lines.popFirst() } }
ec8b8c4fd2bd00e01e30a8e228e49427
31.695906
128
0.569666
false
false
false
false
envoyproxy/envoy
refs/heads/main
library/swift/mocks/MockStreamPrototype.swift
apache-2.0
2
import Dispatch @_implementationOnly import EnvoyEngine import Foundation /// Mock implementation of `StreamPrototype` which is used to produce `MockStream` instances. @objcMembers public final class MockStreamPrototype: StreamPrototype { private let onStart: ((MockStream) -> Void)? /// Initialize a new instance of the mock prototype. /// /// - parameter onStart: Closure that will be called each time a new stream /// is started from the prototype. init(onStart: @escaping (MockStream) -> Void) { self.onStart = onStart super.init(engine: MockEnvoyEngine()) } public override func start(queue: DispatchQueue = .main) -> Stream { let callbacks = self.createCallbacks(queue: queue) let underlyingStream = MockEnvoyHTTPStream(handle: 0, engine: 0, callbacks: callbacks, explicitFlowControl: false) let stream = MockStream(mockStream: underlyingStream) self.onStart?(stream) return stream } }
6a6373fe448704c43db413303389e9e5
36.37037
93
0.68781
false
false
false
false
FsThatOne/VOne
refs/heads/master
VOne/Classes/Controller/Main/FSMainViewController.swift
mit
1
// // FSMainViewController.swift // VOne // // Created by 王正一 on 16/7/19. // Copyright © 2016年 FsThatOne. All rights reserved. // import UIKit class FSMainViewController: UITabBarController { fileprivate lazy var funnyBtn: UIButton = UIButton(type: .custom) override func viewDidLoad() { super.viewDidLoad() setupChildViewControllers() // rainbowTabbar() // setupFunnyButton() } // 设置支持的屏幕方向, 设置之后, 当前控制器和其子控制器都遵循这个道理, modal视图不受影响 override var supportedInterfaceOrientations: UIInterfaceOrientationMask { return .portrait } } // MARK: 设置界面 extension FSMainViewController { fileprivate func setupChildViewControllers() { let dictArr = [ ["name": "SessionsViewController", "title": "聊天", "imageName": "chat"], ["name": "ContactViewController", "title": "通讯录", "imageName": "contact"], ["name": "MomentsViewController", "title": "圈子", "imageName": "mycircle"], ["name": "MineViewController", "title": "个人中心", "imageName": "mine_center"], ] var controllersArray = [UIViewController]() for item in dictArr { controllersArray.append(controller(item)) } viewControllers = controllersArray } fileprivate func controller(_ dict: [String: String]) -> UIViewController { // 配置字典内容 guard let vcName = dict["name"], let vcTitle = dict["title"], let vcImage = dict["imageName"], // 反射机制取得vc let cls = NSClassFromString(Bundle.main.nameSpace + "." + vcName) as? FSBaseViewController.Type else { return UIViewController() } // 根据字典内容设置UI let vc = cls.init() vc.title = vcTitle vc.tabBarItem.image = UIImage(named: vcImage)?.withRenderingMode(.alwaysOriginal) vc.tabBarItem.selectedImage = UIImage(named: vcImage) let nav = FSNavigationController(rootViewController: vc) return nav } // fileprivate func rainbowTabbar() { // let rainbowLayer: CAGradientLayer = CAGradientLayer() // rainbowLayer.frame = tabBar.bounds // rainbowLayer.colors = [UIColor(red:0.244, green:0.673, blue:0.183, alpha:1).cgColor, UIColor(red:0.376, green:0.564, blue:0.984, alpha:1).cgColor] // tabBar.layer.insertSublayer(rainbowLayer, at: 0) // } // // fileprivate func setupFunnyButton() { // // let itemCount = CGFloat(childViewControllers.count) // let itemWidth = (tabBar.bounds.width / itemCount) - 1 // // funnyBtn.setBackgroundImage(UIImage(named: "heartBeat")?.withRenderingMode(.alwaysOriginal), for: .normal) // funnyBtn.contentMode = .center // funnyBtn.frame = tabBar.bounds.insetBy(dx: 2 * itemWidth, dy: 0) // // tabBar.addSubview(funnyBtn) // } }
250d86b2778c4df5d1fdb4e423ed7e68
33.282353
156
0.615305
false
false
false
false
honishi/Hakumai
refs/heads/main
Hakumai/Controllers/MainWindowController/TableCellView/TimeTableCellView.swift
mit
1
// // TimeTableCellView.swift // Hakumai // // Created by Hiroyuki Onishi on 11/25/14. // Copyright (c) 2014 Hiroyuki Onishi. All rights reserved. // import Foundation import AppKit private let defaultTimeValue = "-" final class TimeTableCellView: NSTableCellView { @IBOutlet weak var coloredView: ColoredView! @IBOutlet weak var timeLabel: NSTextField! var fontSize: CGFloat? { didSet { set(fontSize: fontSize) } } } extension TimeTableCellView { func configure(live: Live?, message: Message?) { coloredView.fillColor = color(message: message) timeLabel.stringValue = time(live: live, message: message) } } private extension TimeTableCellView { func color(message: Message?) -> NSColor { guard let message = message else { return UIHelper.systemMessageBgColor() } switch message.content { case .system: return UIHelper.systemMessageBgColor() case .chat(let chat): return chat.isSystem ? UIHelper.systemMessageBgColor() : UIHelper.greenScoreColor() case .debug: return UIHelper.debugMessageBgColor() } } func time(live: Live?, message: Message?) -> String { guard let message = message else { return defaultTimeValue } switch message.content { case .system, .debug: return "[\(message.date.toLocalTimeString())]" case .chat(chat: let chat): guard let beginDate = live?.beginTime, let elapsed = chat.date.toElapsedTimeString(from: beginDate) else { return defaultTimeValue } return elapsed } } func set(fontSize: CGFloat?) { let size = fontSize ?? CGFloat(kDefaultFontSize) timeLabel.font = NSFont.systemFont(ofSize: size) } } private extension Date { func toElapsedTimeString(from fromDate: Date) -> String? { let comps = Calendar.current.dateComponents( [.hour, .minute, .second], from: fromDate, to: self) guard let h = comps.hour, let m = comps.minute, let s = comps.second else { return nil } return "\(h):\(m.zeroPadded):\(s.zeroPadded)" } func toLocalTimeString() -> String { let formatter = DateFormatter() formatter.dateFormat = "H:mm:ss" return formatter.string(from: self) } } private extension Int { var zeroPadded: String { String(format: "%02d", self) } }
f5875ebfadb936b88455a785fd5969a9
30.358974
96
0.634914
false
false
false
false
CatchChat/Yep
refs/heads/master
Yep/Views/FriendRequest/FriendRequestView.swift
mit
1
// // FriendRequestView.swift // Yep // // Created by nixzhu on 15/8/14. // Copyright (c) 2015年 Catch Inc. All rights reserved. // import UIKit import YepKit final class FriendRequestView: UIView { static let height: CGFloat = 60 enum State { case Add(prompt: String) case Consider(prompt: String, friendRequestID: String) var prompt: String { switch self { case .Add(let prompt): return prompt case .Consider(let prompt, _): return prompt } } var friendRequestID: String? { switch self { case .Consider( _, let friendRequestID): return friendRequestID default: return nil } } } let state: State init(state: State) { self.state = state super.init(frame: CGRectZero) self.stateLabel.text = state.prompt } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } var user: User? { willSet { if let user = newValue { let userAvatar = UserAvatar(userID: user.userID, avatarURLString: user.avatarURLString, avatarStyle: nanoAvatarStyle) avatarImageView.navi_setAvatar(userAvatar, withFadeTransitionDuration: avatarFadeTransitionDuration) nicknameLabel.text = user.nickname } } } var addAction: (FriendRequestView -> Void)? var acceptAction: (FriendRequestView -> Void)? var rejectAction: (FriendRequestView -> Void)? lazy var avatarImageView: UIImageView = { let imageView = UIImageView() return imageView }() lazy var nicknameLabel: UILabel = { let label = UILabel() label.font = UIFont.systemFontOfSize(16) label.text = "NIX" label.textColor = UIColor.blackColor().colorWithAlphaComponent(0.9) return label }() lazy var stateLabel: UILabel = { let label = UILabel() label.font = UIFont.systemFontOfSize(14) label.numberOfLines = 0 label.textColor = UIColor.grayColor().colorWithAlphaComponent(0.9) return label }() func baseButton() -> UIButton { let button = UIButton() button.setContentHuggingPriority(300, forAxis: UILayoutConstraintAxis.Horizontal) button.contentEdgeInsets = UIEdgeInsets(top: 5, left: 15, bottom: 5, right: 15) button.setTitleColor(UIColor.whiteColor(), forState: .Normal) button.setTitleColor(UIColor.grayColor(), forState: .Highlighted) button.setTitleColor(UIColor.lightGrayColor(), forState: .Disabled) button.layer.cornerRadius = 5 return button } lazy var addButton: UIButton = { let button = self.baseButton() button.setTitle(NSLocalizedString("button.add", comment: ""), forState: .Normal) button.backgroundColor = UIColor.yepTintColor() button.addTarget(self, action: #selector(FriendRequestView.tryAddAction), forControlEvents: .TouchUpInside) return button }() lazy var acceptButton: UIButton = { let button = self.baseButton() button.setTitle(NSLocalizedString("button.accept", comment: ""), forState: .Normal) button.backgroundColor = UIColor.yepTintColor() button.addTarget(self, action: #selector(FriendRequestView.tryAcceptAction), forControlEvents: .TouchUpInside) return button }() lazy var rejectButton: UIButton = { let button = self.baseButton() button.setTitle(NSLocalizedString("Reject", comment: ""), forState: .Normal) button.backgroundColor = UIColor(red: 230/255.0, green: 230/255.0, blue: 230/255.0, alpha: 1.0) button.setTitleColor(UIColor.darkGrayColor(), forState: UIControlState.Normal) button.addTarget(self, action: #selector(FriendRequestView.tryRejectAction), forControlEvents: .TouchUpInside) return button }() // MARK: Actions func tryAddAction() { addAction?(self) } func tryAcceptAction() { acceptAction?(self) } func tryRejectAction() { rejectAction?(self) } // MARK: UI override func didMoveToSuperview() { super.didMoveToSuperview() backgroundColor = UIColor.clearColor() makeUI() } class ContainerView: UIView { override func didMoveToSuperview() { super.didMoveToSuperview() backgroundColor = UIColor.clearColor() } override func drawRect(rect: CGRect) { super.drawRect(rect) let context = UIGraphicsGetCurrentContext() let y = CGRectGetHeight(rect) CGContextMoveToPoint(context, 0, y) CGContextAddLineToPoint(context, CGRectGetWidth(rect), y) let bottomLineWidth: CGFloat = 1 / UIScreen.mainScreen().scale CGContextSetLineWidth(context, bottomLineWidth) UIColor.lightGrayColor().setStroke() CGContextStrokePath(context) } } func makeUI() { let blurEffect = UIBlurEffect(style: .ExtraLight) let visualEffectView = UIVisualEffectView(effect: blurEffect) visualEffectView.translatesAutoresizingMaskIntoConstraints = false addSubview(visualEffectView) let containerView = ContainerView() containerView.translatesAutoresizingMaskIntoConstraints = false addSubview(containerView) avatarImageView.translatesAutoresizingMaskIntoConstraints = false containerView.addSubview(avatarImageView) nicknameLabel.translatesAutoresizingMaskIntoConstraints = false containerView.addSubview(nicknameLabel) stateLabel.translatesAutoresizingMaskIntoConstraints = false containerView.addSubview(stateLabel) let viewsDictionary: [String: AnyObject] = [ "visualEffectView": visualEffectView, "containerView": containerView, ] // visualEffectView let visualEffectViewConstraintH = NSLayoutConstraint.constraintsWithVisualFormat("H:|[visualEffectView]|", options: [], metrics: nil, views: viewsDictionary) let visualEffectViewConstraintV = NSLayoutConstraint.constraintsWithVisualFormat("V:|[visualEffectView]|", options: [], metrics: nil, views: viewsDictionary) NSLayoutConstraint.activateConstraints(visualEffectViewConstraintH) NSLayoutConstraint.activateConstraints(visualEffectViewConstraintV) // containerView let containerViewConstraintH = NSLayoutConstraint.constraintsWithVisualFormat("H:|[containerView]|", options: [], metrics: nil, views: viewsDictionary) let containerViewConstraintV = NSLayoutConstraint.constraintsWithVisualFormat("V:|[containerView]|", options: [], metrics: nil, views: viewsDictionary) NSLayoutConstraint.activateConstraints(containerViewConstraintH) NSLayoutConstraint.activateConstraints(containerViewConstraintV) // avatarImageView let avatarImageViewCenterY = NSLayoutConstraint(item: avatarImageView, attribute: .CenterY, relatedBy: .Equal, toItem: containerView, attribute: .CenterY, multiplier: 1, constant: 0) let avatarImageViewLeading = NSLayoutConstraint(item: avatarImageView, attribute: .Leading, relatedBy: .Equal, toItem: containerView, attribute: .Leading, multiplier: 1, constant: YepConfig.chatCellGapBetweenWallAndAvatar()) let avatarImageViewWidth = NSLayoutConstraint(item: avatarImageView, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: YepConfig.chatCellAvatarSize()) let avatarImageViewHeight = NSLayoutConstraint(item: avatarImageView, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: YepConfig.chatCellAvatarSize()) NSLayoutConstraint.activateConstraints([avatarImageViewCenterY, avatarImageViewLeading, avatarImageViewWidth, avatarImageViewHeight]) // nicknameLabel let nicknameLabelTop = NSLayoutConstraint(item: nicknameLabel, attribute: .Top, relatedBy: .Equal, toItem: avatarImageView, attribute: .Top, multiplier: 1, constant: 0) let nicknameLabelLeft = NSLayoutConstraint(item: nicknameLabel, attribute: .Left, relatedBy: .Equal, toItem: avatarImageView, attribute: .Right, multiplier: 1, constant: 8) NSLayoutConstraint.activateConstraints([nicknameLabelTop, nicknameLabelLeft]) // stateLabel let stateLabelTop = NSLayoutConstraint(item: stateLabel, attribute: .Top, relatedBy: .Equal, toItem: nicknameLabel, attribute: .Bottom, multiplier: 1, constant: 0) let stateLabelBottom = NSLayoutConstraint(item: stateLabel, attribute: .Bottom, relatedBy: .LessThanOrEqual, toItem: containerView, attribute: .Bottom, multiplier: 1, constant: -4) let stateLabelLeft = NSLayoutConstraint(item: stateLabel, attribute: .Left, relatedBy: .Equal, toItem: nicknameLabel, attribute: .Left, multiplier: 1, constant: 0) NSLayoutConstraint.activateConstraints([stateLabelTop, stateLabelBottom, stateLabelLeft]) switch state { case .Add: // addButton addButton.translatesAutoresizingMaskIntoConstraints = false addButton.setContentCompressionResistancePriority(UILayoutPriorityRequired, forAxis: .Horizontal) containerView.addSubview(addButton) let addButtonTrailing = NSLayoutConstraint(item: addButton, attribute: .Trailing, relatedBy: .Equal, toItem: containerView, attribute: .Trailing, multiplier: 1, constant: -YepConfig.chatCellGapBetweenWallAndAvatar()) let addButtonCenterY = NSLayoutConstraint(item: addButton, attribute: .CenterY, relatedBy: .Equal, toItem: containerView, attribute: .CenterY, multiplier: 1, constant: 0) NSLayoutConstraint.activateConstraints([addButtonTrailing, addButtonCenterY]) // labels' right let nicknameLabelRight = NSLayoutConstraint(item: nicknameLabel, attribute: .Right, relatedBy: .Equal, toItem: addButton, attribute: .Left, multiplier: 1, constant: -8) let stateLabelRight = NSLayoutConstraint(item: stateLabel, attribute: .Right, relatedBy: .Equal, toItem: addButton, attribute: .Left, multiplier: 1, constant: -8) NSLayoutConstraint.activateConstraints([nicknameLabelRight, stateLabelRight]) case .Consider: // acceptButton acceptButton.translatesAutoresizingMaskIntoConstraints = false acceptButton.setContentCompressionResistancePriority(UILayoutPriorityRequired, forAxis: .Horizontal) containerView.addSubview(acceptButton) let acceptButtonTrailing = NSLayoutConstraint(item: acceptButton, attribute: .Trailing, relatedBy: .Equal, toItem: containerView, attribute: .Trailing, multiplier: 1, constant: -YepConfig.chatCellGapBetweenWallAndAvatar()) let acceptButtonCenterY = NSLayoutConstraint(item: acceptButton, attribute: .CenterY, relatedBy: .Equal, toItem: containerView, attribute: .CenterY, multiplier: 1, constant: 0) NSLayoutConstraint.activateConstraints([acceptButtonTrailing, acceptButtonCenterY]) // rejectButton rejectButton.translatesAutoresizingMaskIntoConstraints = false rejectButton.setContentCompressionResistancePriority(UILayoutPriorityRequired, forAxis: .Horizontal) containerView.addSubview(rejectButton) let rejectButtonRight = NSLayoutConstraint(item: rejectButton, attribute: .Right, relatedBy: .Equal, toItem: acceptButton, attribute: .Left, multiplier: 1, constant: -8) let rejectButtonCenterY = NSLayoutConstraint(item: rejectButton, attribute: .CenterY, relatedBy: .Equal, toItem: containerView, attribute: .CenterY, multiplier: 1, constant: 0) NSLayoutConstraint.activateConstraints([rejectButtonRight, rejectButtonCenterY]) // labels' right let nicknameLabelRight = NSLayoutConstraint(item: nicknameLabel, attribute: .Right, relatedBy: .Equal, toItem: rejectButton, attribute: .Left, multiplier: 1, constant: -8) let stateLabelRight = NSLayoutConstraint(item: stateLabel, attribute: .Right, relatedBy: .Equal, toItem: rejectButton, attribute: .Left, multiplier: 1, constant: -8) NSLayoutConstraint.activateConstraints([nicknameLabelRight, stateLabelRight]) } } }
b464f2667100fd6332f83aa8e1c6dd66
41.698305
234
0.693792
false
false
false
false
MatheusGodinho/SnapKitLearning
refs/heads/master
SnapKitCRUD/ViewController.swift
mit
1
// // ViewController.swift // SnapKitCRUD // // Created by Matheus Godinho on 15/09/16. // Copyright © 2016 Godinho. All rights reserved. // import UIKit import SnapKit class ViewController: UIViewController{ //Declare controller let userController = UserController() // Center View let fieldsView = CenterFieldView() let buttonBox = SocialView() let finalPage = ButtonPageView() let logoView = LogoView() //Background let backgroundView = UIImageView() let faceButton = UIButton() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.configureBackgroundView(superview: self.view!) fieldsView.configureCenterView(superview: self) buttonBox.configureButtonBox(superview: self.view!) finalPage.configureButtonPageView(superview: self.view!) logoView.configureView(superview: self.view!) self.setDelegates() self.addObservers() self.dismissKeyboard() } override func viewWillDisappear(_ animated: Bool) { self.removeObservers() } private func configureBackgroundView(superview:UIView){ superview.addSubview(self.backgroundView) let image = #imageLiteral(resourceName: "ui_bg_login") self.backgroundView.image = image backgroundView.snp.makeConstraints { (make) in make.size.equalTo(superview) } self.hideKeyboardWhenTappedAround() } func addObservers() { NotificationCenter.default.addObserver(self, selector: #selector(ViewController.keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(ViewController.keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil) } func removeObservers() { NotificationCenter.default.removeObserver(self, name: .UIKeyboardWillShow, object: view.window) NotificationCenter.default.removeObserver(self, name: .UIKeyboardWillHide, object: view.window) } func keyboardWillShow(notification: NSNotification) { if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue { if self.view.frame.origin.y == 0{ self.view.frame.origin.y -= keyboardSize.height/2 } } } func keyboardWillHide(notification: NSNotification) { if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue { if self.view.frame.origin.y != 0{ self.view.frame.origin.y += keyboardSize.height/2 } } } }
f5d543bb38acbb5f352b0105a715e569
30.703297
165
0.658579
false
true
false
false
brentsimmons/Evergreen
refs/heads/ios-candidate
Shared/Activity/ActivityType.swift
mit
1
// // ActivityType.swift // NetNewsWire-iOS // // Created by Maurice Parker on 8/24/19. // Copyright © 2019 Ranchero Software. All rights reserved. // import Foundation enum ActivityType: String { case restoration = "Restoration" case selectFeed = "SelectFeed" case nextUnread = "NextUnread" case readArticle = "ReadArticle" case addFeedIntent = "AddFeedIntent" }
3db045d6a1f700ab81929af698409648
21.058824
60
0.730667
false
false
false
false
iamyuiwong/swift-common
refs/heads/master
errno/PosixErrno.swift
lgpl-3.0
1
/* * NAME PosixErrno.swift * * C 15/9/30 +0800 * * DESC * - Xcode 7.0.1 / Swift 2.0.1 supported (Created) * * V1.0.0.0_ */ import Foundation /* * NAME PosixErrno - class PosixErrno */ class PosixErrno { static func errno2string (posixErrno _en: Int32) -> String { var en: Int32 = 0 if (_en < 0) { en = -_en; } else { en = _en; } let cs = strerror(en) let ret = StringUtil.toString(fromCstring: cs, encoding: NSUTF8StringEncoding) if (nil != ret) { return ret! } else { return "Unresolved \(en)" } } }
b538f55c4873287dc78afac72b77194a
13.578947
61
0.581227
false
false
false
false
koba-uy/chivia-app-ios
refs/heads/master
src/Chivia/Services/Internal/GeocodingService.swift
lgpl-3.0
1
// // File.swift // Chivia // // Created by Agustín Rodríguez on 10/21/17. // Copyright © 2017 Agustín Rodríguez. All rights reserved. // import Alamofire import CoreLocation import PromiseKit import SwiftyJSON class GeocodingService { let GEOCODING_SERVICE_URL = "https://maps.googleapis.com/maps/api/geocode/json?key=AIzaSyC_LXnJZa7FXv_xsz8_WCL_4Ltt1MdExNU" func get(address: String) -> Promise<CLLocationCoordinate2D> { return Promise { fulfill, reject in Alamofire .request("\(GEOCODING_SERVICE_URL)&address=\(address.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)!)") .validate() .responseJSON { response in if response.result.isSuccess, let data = response.data { let json = JSON(data: data) let location = json["results"][0]["geometry"]["location"] let lat = location["lat"].doubleValue let lng = location["lng"].doubleValue fulfill(CLLocationCoordinate2D(latitude: lat, longitude: lng)) } else if let data = response.data { let json = JSON(data: data) reject(GenericError(message: json["message"].stringValue)) } else if let err = response.error { reject(err) } } } } }
2b6b2a27bb28116ffd4ca2254d0dcbb8
35.642857
147
0.545809
false
false
false
false
iosphere/ISHPullUp
refs/heads/master
ISHPullUpSample/ISHPullUpSample/BottomVC.swift
mit
1
// // ScrollViewController.swift // ISHPullUpSample // // Created by Felix Lamouroux on 25.06.16. // Copyright © 2016 iosphere GmbH. All rights reserved. // import UIKit import ISHPullUp import MapKit class BottomVC: UIViewController, ISHPullUpSizingDelegate, ISHPullUpStateDelegate { @IBOutlet private weak var handleView: ISHPullUpHandleView! @IBOutlet private weak var rootView: UIView! @IBOutlet private weak var scrollView: UIScrollView! @IBOutlet private weak var topLabel: UILabel! @IBOutlet private weak var topView: UIView! @IBOutlet private weak var buttonLock: UIButton? private var firstAppearanceCompleted = false weak var pullUpController: ISHPullUpViewController! // we allow the pullUp to snap to the half way point private var halfWayPoint = CGFloat(0) override func viewDidLoad() { super.viewDidLoad() let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleTapGesture)) topView.addGestureRecognizer(tapGesture) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) firstAppearanceCompleted = true; } @objc private func handleTapGesture(gesture: UITapGestureRecognizer) { if pullUpController.isLocked { return } pullUpController.toggleState(animated: true) } @IBAction private func buttonTappedLearnMore(_ sender: AnyObject) { // for demo purposes we replace the bottomViewController with a web view controller // there is no way back in the sample app though // This also highlights the behaviour of the pullup view controller without a sizing and state delegate let webVC = WebViewController() webVC.loadURL(URL(string: "https://iosphere.de")!) pullUpController.bottomViewController = webVC } @IBAction private func buttonTappedLock(_ sender: AnyObject) { pullUpController.isLocked = !pullUpController.isLocked buttonLock?.setTitle(pullUpController.isLocked ? "Unlock" : "Lock", for: .normal) } // MARK: ISHPullUpSizingDelegate func pullUpViewController(_ pullUpViewController: ISHPullUpViewController, maximumHeightForBottomViewController bottomVC: UIViewController, maximumAvailableHeight: CGFloat) -> CGFloat { let totalHeight = rootView.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize).height // we allow the pullUp to snap to the half way point // we "calculate" the cached value here // and perform the snapping in ..targetHeightForBottomViewController.. halfWayPoint = totalHeight / 2.0 return totalHeight } func pullUpViewController(_ pullUpViewController: ISHPullUpViewController, minimumHeightForBottomViewController bottomVC: UIViewController) -> CGFloat { return topView.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize).height; } func pullUpViewController(_ pullUpViewController: ISHPullUpViewController, targetHeightForBottomViewController bottomVC: UIViewController, fromCurrentHeight height: CGFloat) -> CGFloat { // if around 30pt of the half way point -> snap to it if abs(height - halfWayPoint) < 30 { return halfWayPoint } // default behaviour return height } func pullUpViewController(_ pullUpViewController: ISHPullUpViewController, update edgeInsets: UIEdgeInsets, forBottomViewController bottomVC: UIViewController) { // we update the scroll view's content inset // to properly support scrolling in the intermediate states scrollView.contentInset = edgeInsets; } // MARK: ISHPullUpStateDelegate func pullUpViewController(_ pullUpViewController: ISHPullUpViewController, didChangeTo state: ISHPullUpState) { topLabel.text = textForState(state); handleView.setState(ISHPullUpHandleView.handleState(for: state), animated: firstAppearanceCompleted) // Hide the scrollview in the collapsed state to avoid collision // with the soft home button on iPhone X UIView.animate(withDuration: 0.25) { [weak self] in self?.scrollView.alpha = (state == .collapsed) ? 0 : 1; } } private func textForState(_ state: ISHPullUpState) -> String { switch state { case .collapsed: return "Drag up or tap" case .intermediate: return "Intermediate" case .dragging: return "Hold on" case .expanded: return "Drag down or tap" @unknown default: return "Unknown value" } } } class ModalViewController: UIViewController { @IBAction func buttonTappedDone(_ sender: UIBarButtonItem) { dismiss(animated: true, completion: nil) } }
81418bcecd90b1da9f59d5b182dbf514
37.244094
190
0.701256
false
false
false
false
safx/TypetalkApp
refs/heads/master
TypetalkApp/iOS/ViewControllers/MessageListViewController.swift
mit
1
// // MessageListViewController.swift // TypetalkApp // // Created by Safx Developer on 2014/11/08. // Copyright (c) 2014年 Safx Developers. All rights reserved. // import UIKit import TypetalkKit import RxSwift import SlackTextViewController class MessageListViewController: SLKTextViewController { private let viewModel = MessageListViewModel() typealias CompletionModel = CompletionDataSource.CompletionModel var completionList = [CompletionModel]() var oldNumberOfRows = 0 private let disposeBag = DisposeBag() var topic: TopicWithUserInfo? { didSet { self.configureView() self.viewModel.fetch(topic!.topic.id) } } /*override init!(tableViewStyle style: UITableViewStyle) { super.init(tableViewStyle: .Plain) } required init!(coder decoder: NSCoder!) { fatalError("init(coder:) has not been implemented") }*/ override class func tableViewStyleForCoder(decoder: NSCoder) -> UITableViewStyle { return .Plain } func configureView() { // Update the user interface for the detail item. if let t = self.topic { self.title = t.topic.name } } override func viewDidLoad() { super.viewDidLoad() inverted = true shouldScrollToBottomAfterKeyboardShows = true bounces = true shakeToClearEnabled = true keyboardPanningEnabled = true tableView?.separatorStyle = .None tableView?.estimatedRowHeight = 64 tableView?.rowHeight = UITableViewAutomaticDimension tableView?.registerClass(MessageCell.self, forCellReuseIdentifier: "MessageCell") textView.placeholder = NSLocalizedString("Message", comment: "Message") //let icon = IonIcons.imageWithIcon(icon_arrow_down_c, size: 30, color:UIColor.grayColor()) //leftButton.setImage(icon, forState: .Normal) registerPrefixesForAutoCompletion(["@", "#", ":"]) autoCompletionView.registerClass(AutoCompletionCell.self, forCellReuseIdentifier: "AutoCompletionCell") self.configureView() weak var weakTableView = tableView viewModel.model.posts.rx_events() .observeOn(MainScheduler.instance) .subscribeNext { next in if self.oldNumberOfRows == 0 { self.tableView?.reloadData() } else { if let t = weakTableView { let c = self.viewModel.model.posts.count - 1 let f = { NSIndexPath(forRow: c - $0, inSection: 0) } let i = next.insertedIndices.map(f) let d = next.deletedIndices.map(f) let u = next.updatedIndices.map(f) t.beginUpdates() t.insertRowsAtIndexPaths(i, withRowAnimation: .None) t.deleteRowsAtIndexPaths(d, withRowAnimation: .Automatic) t.reloadRowsAtIndexPaths(u, withRowAnimation: .Automatic) t.endUpdates() } } self.oldNumberOfRows = self.viewModel.model.posts.count } .addDisposableTo(disposeBag) tableView?.dataSource = viewModel //viewModel.fetch() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //MARK: - Text Editing /*override func didPressReturnKey(sender: AnyObject!) { post(textView.text) super.didPressReturnKey(sender) }*/ override func didPressRightButton(sender: AnyObject!) { viewModel.post(textView.text) super.didPressRightButton(sender) } override func didCommitTextEditing(sender: AnyObject) { super.didCommitTextEditing(sender) } // MARK: - completion override func didChangeAutoCompletionPrefix(prefix: String, andWord word: String) { completionList = viewModel.autoCompletionElements(foundPrefix!, foundWord: foundWord!) showAutoCompletionView(!completionList.isEmpty) } override func heightForAutoCompletionView() -> CGFloat { let len = completionList.count return CGFloat(len * 36) } // MARK: UITableViewDataSource Methods (for Completion) override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return completionList.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("AutoCompletionCell", forIndexPath: indexPath) as! AutoCompletionCell cell.setModel(completionList[indexPath.row]) return cell } // MARK: UITableViewDelegate Methods override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { if tableView == autoCompletionView { let c = completionList[indexPath.row] acceptAutoCompletionWithString("\(c.completionString) ") } } // MARK: - load func handleMore(sender: AnyObject!) { self.viewModel.fetchMore(topic!.topic.id) } }
df805397770478e76d6bbaf7bee4b90a
31.969697
132
0.638419
false
false
false
false
cloudinary/cloudinary_ios
refs/heads/master
Example/Tests/BaseNetwork/Extensions/FileManager+CloudinaryTests.swift
mit
1
// // FileManager+CloudinaryTests.swift // // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation extension FileManager { // MARK: - Common Directories static var temporaryDirectoryPath: String { return NSTemporaryDirectory() } static var temporaryDirectoryURL: URL { return URL(fileURLWithPath: FileManager.temporaryDirectoryPath, isDirectory: true) } // MARK: - File System Modification @discardableResult static func createDirectory(atPath path: String) -> Bool { do { try FileManager.default.createDirectory(atPath: path, withIntermediateDirectories: true, attributes: nil) return true } catch { return false } } @discardableResult static func createDirectory(at url: URL) -> Bool { return createDirectory(atPath: url.path) } @discardableResult static func removeItem(atPath path: String) -> Bool { do { try FileManager.default.removeItem(atPath: path) return true } catch { return false } } @discardableResult static func removeItem(at url: URL) -> Bool { return removeItem(atPath: url.path) } @discardableResult static func removeAllItemsInsideDirectory(atPath path: String) -> Bool { let enumerator = FileManager.default.enumerator(atPath: path) var result = true while let fileName = enumerator?.nextObject() as? String { let success = removeItem(atPath: path + "/\(fileName)") if !success { result = false } } return result } @discardableResult static func removeAllItemsInsideDirectory(at url: URL) -> Bool { return removeAllItemsInsideDirectory(atPath: url.path) } }
b529fa27ea42aca31724746f8b3496e3
31.977011
117
0.679679
false
false
false
false
d-date/SwiftBarcodeReader
refs/heads/master
SwiftBarcodeReader/Sources/UIViewController+BarcodeReader.swift
mit
1
import UIKit import AVFoundation private var AssociationKey: UInt8 = 0 public extension UIViewController { var layer: AVCaptureVideoPreviewLayer! { get { return objc_getAssociatedObject(self, &AssociationKey) as? AVCaptureVideoPreviewLayer } set(newValue) { objc_setAssociatedObject(self, &AssociationKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } //MARK: - Private private func addDeviceOrientationChangeNotification() { UIDevice.current.beginGeneratingDeviceOrientationNotifications() NotificationCenter.default.addObserver(self, selector: #selector(UIViewController.onChangedOrientation), name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil) } private func removeDeviceOrientationChangeNotification() { NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil) UIDevice.current.endGeneratingDeviceOrientationNotifications() } @objc private func onChangedOrientation() { setDeviceOrientation(orientation: UIDevice.current.orientation) } private func setDeviceOrientation(orientation: UIDeviceOrientation) { if (orientation == .landscapeLeft) || (orientation == .landscapeRight) { layer.connection.videoOrientation = captureVideoOrientation(deviceOrientation: orientation) } else { layer.connection.videoOrientation = captureVideoOrientation(deviceOrientation: orientation) } } private func captureVideoOrientation(deviceOrientation: UIDeviceOrientation) -> AVCaptureVideoOrientation { var orientation: AVCaptureVideoOrientation switch deviceOrientation { case .portraitUpsideDown: orientation = .portraitUpsideDown case .landscapeLeft: orientation = .landscapeRight case .landscapeRight: orientation = .landscapeLeft default: orientation = .portrait } return orientation } //MARK: - Public func presentBarcodeReader(scanTypes: [AVMetadataObjectType], needChangePositionButton: Bool, success: ((_ type:AVMetadataObjectType, _ value: String) -> ())?, failure: @escaping ((_ cancel: Bool, _ error: Error?) -> ())) { let bundle = Bundle(identifier: "SBRResource") let storyboard = UIStoryboard(name: "BarcodeReader", bundle: bundle) let vc: BarcodeReaderViewController = storyboard.instantiateInitialViewController() as! BarcodeReaderViewController vc.successClosure = success vc.failureClosure = failure vc.scanType = scanTypes vc.needChangePositionButton = needChangePositionButton present(vc, animated: true, completion: nil) } func startCodeCapture(position: AVCaptureDevicePosition, captureType: [AVMetadataObjectType]) { addDeviceOrientationChangeNotification() if DMCodeCaptureHandler.shared.session.outputs.count == 0 { DMCodeCaptureHandler.shared.prepareCaptureSession(position: position) } layer = AVCaptureVideoPreviewLayer(session: DMCodeCaptureHandler.shared.session) layer.frame = view.bounds layer.videoGravity = AVLayerVideoGravityResizeAspectFill setDeviceOrientation(orientation: UIDevice.current.orientation) view.layer.addSublayer(layer) DMCodeCaptureHandler.shared.session.startRunning() } func switchCamera(to position: AVCaptureDevicePosition) { DMCodeCaptureHandler.shared.switchInputDevice(for: position) } func endCodeCapture() { DMCodeCaptureHandler.shared.session.stopRunning() removeDeviceOrientationChangeNotification() } }
f470c2a0e73b7057fd005622b0ed9ce1
44.139535
181
0.69526
false
false
false
false
BronxDupaix/WaffleLuv
refs/heads/master
WaffleLuv/MyColors.swift
apache-2.0
1
// // UIColor extension.swift // WaffleLuv // // Created by Bronson Dupaix on 4/7/16. // Copyright © 2016 Bronson Dupaix. All rights reserved. // import Foundation struct MyColors{ static var getCustomPurpleColor = { return UIColor(red:0.55, green:0.5 , blue:1.00, alpha:1.0) } static var getCustomCyanColor = { return UIColor(red:1.00, green:0.93, blue:0.88, alpha:1.00) } static var getCustomPinkColor = { return UIColor(red:1.0, green:0.4 ,blue:0.78 , alpha:1.00) } static var getCustomRedColor = { return UIColor(red:1.0, green:0.00, blue:0.00, alpha:1.00) } static var getCustomCreamColor = { return UIColor(red:0.9, green:0.9, blue:1.00, alpha:1.00) } static var getCustomBananaColor = { return UIColor(red:1.00, green:0.93, blue:0.50, alpha:1.00 ) } static var getCustomBlueGreenColor = { return UIColor(red:0.00, green:1 , blue:1 , alpha:0.75) } static var getCustomYellowColor = { return UIColor(red:1.00, green:0.93, blue:0.00, alpha:1.00) } static var getCustomlightPurpleColor = { return UIColor(red:0.8, green:0.18 , blue:1.00, alpha:0.6) } static var getCustomOrangeColor = { return UIColor(red:1.00, green:0.66 , blue:0.00, alpha:1.00) } }
7998cca4a6fcf6a11279d81f2e84d257
21.661538
68
0.562118
false
false
false
false
deege/deegeu-swift-eventkit
refs/heads/master
CalendarTest/ViewController.swift
mit
1
// // ViewController.swift // CalendarTest // // Created by Daniel Spiess on 9/2/15. // Copyright © 2015 Daniel Spiess. All rights reserved. // import UIKit import EventKit class ViewController: UIViewController { var savedEventId : String = "" 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. } // Creates an event in the EKEventStore. The method assumes the eventStore is created and // accessible func createEvent(eventStore: EKEventStore, title: String, startDate: NSDate, endDate: NSDate) { let event = EKEvent(eventStore: eventStore) event.title = title event.startDate = startDate event.endDate = endDate event.calendar = eventStore.defaultCalendarForNewEvents do { try eventStore.saveEvent(event, span: .ThisEvent) savedEventId = event.eventIdentifier } catch { print("Bad things happened") } } // Removes an event from the EKEventStore. The method assumes the eventStore is created and // accessible func deleteEvent(eventStore: EKEventStore, eventIdentifier: String) { let eventToRemove = eventStore.eventWithIdentifier(eventIdentifier) if (eventToRemove != nil) { do { try eventStore.removeEvent(eventToRemove!, span: .ThisEvent) } catch { print("Bad things happened") } } } // Responds to button to add event. This checks that we have permission first, before adding the // event @IBAction func addEvent(sender: UIButton) { let eventStore = EKEventStore() let startDate = NSDate() let endDate = startDate.dateByAddingTimeInterval(60 * 60) // One hour if (EKEventStore.authorizationStatusForEntityType(.Event) != EKAuthorizationStatus.Authorized) { eventStore.requestAccessToEntityType(.Event, completion: { granted, error in self.createEvent(eventStore, title: "DJ's Test Event", startDate: startDate, endDate: endDate) }) } else { createEvent(eventStore, title: "DJ's Test Event", startDate: startDate, endDate: endDate) } } // Responds to button to remove event. This checks that we have permission first, before removing the // event @IBAction func removeEvent(sender: UIButton) { let eventStore = EKEventStore() if (EKEventStore.authorizationStatusForEntityType(.Event) != EKAuthorizationStatus.Authorized) { eventStore.requestAccessToEntityType(.Event, completion: { (granted, error) -> Void in self.deleteEvent(eventStore, eventIdentifier: self.savedEventId) }) } else { deleteEvent(eventStore, eventIdentifier: savedEventId) } } }
b060ca6adccd9aded981d9dcfbad0d82
33.395604
110
0.635783
false
false
false
false
zonble/MRTSwift
refs/heads/master
MRTTransitSwift/MRTRouteTableViewController.swift
mit
1
import UIKit import MRTLib class MRTRouteTableViewController: UITableViewController { var route: MRTRoute? { didSet { self.tableView.reloadData() } } override func viewDidLoad() { super.viewDidLoad() self.title = "台北捷運轉乘" } override func numberOfSections(in tableView: UITableView) -> Int { return self.route?.transitions.count ?? 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.route?.transitions[section].count ?? 0 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var cell: UITableViewCell? = tableView.dequeueReusableCell(withIdentifier: "Cell") if cell == nil { cell = UITableViewCell(style: .value1, reuseIdentifier: "Cell") } if let cell = cell { cell.textLabel?.textColor = UIColor.label cell.textLabel?.textAlignment = .left cell.selectionStyle = .none if let route = self.route { let routeSection = route.transitions[indexPath.section] let (lineID, from, to) = routeSection[indexPath.row] cell.textLabel?.text = indexPath.row == 0 ? "\(from.name) - \(to.name)" : to.name cell.detailTextLabel?.text = MRTLineName(lineID: lineID) cell.detailTextLabel?.textColor = MRTLineColor(lineID: lineID) } } return cell! } override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { if section == 0 { if let route = self.route { return "共 \(route.links.count) 站,轉乘 \(route.transitions.count - 1) 次" } } return nil } }
79e2bb58516750d8816cc345e8d39fc4
28.277778
106
0.704617
false
false
false
false
warren-gavin/OBehave
refs/heads/master
OBehave/Classes/Tools/ChangeLocalization/OBChangeLocalizationBehavior.swift
mit
1
// // OBChangeLocalizationBehavior.swift // OBehave // // Created by Warren Gavin on 26/11/15. // Copyright © 2015 Apokrupto. All rights reserved. // import UIKit /** * Perform a runtime switch of an app's language. * * Normally when an app has its language changed the user won't see the * change until the next time the app is run. For apps that provide the * user with the abiltity to change language in-app there are a number * of solutions, all of which involve having to create custom code that * overrides, mimics or wraps NSLocalizedString() in some way. * * While this is a reasonable solution it does not handle localization * of visual elements very well. Localized storyboards cannot delegate * to the custom solution and any properly localized storyboard will * result in a call to NSLocalizedString(). * * Some solutions I've seen included using a localize method that had * to be called on each load, which meant absolutely every text element * was forced to be an outlet of the view controller. This is not an * elegant solution. * * This behavior swizzles localizedStringForKey:value:table: so that * NSLocalizedString calls a new implementation using the bundle that * corresponds to the localization specified in the data source. * * This behavior will post a notification to view controllers that are * already loaded so they can reset any labels. You must make sure that * your view controllers listen for this notification for best results. * * @param localization ISO country code for the localization to switch * to. */ public final class OBChangeLocalizationBehavior: OBBehavior { private var localizationObserver: NSKeyValueObservation? override public func setup() { super.setup() localizationObserver = owner?.observe(\.view, options: .new) { [unowned self] (owner, _) in owner.observeLocalizationChanges() self.localizationObserver?.invalidate() } } deinit { if let owner = owner { NotificationCenter.default.removeObserver(owner) } } @IBAction func switchLocalization(_ sender: AnyObject?) { // If we have switched to a different bundle we reset the runtime bundle and // post a notification to all listeners (any loaded view controllers) if let path = pathForLocalizationBundle(), let bundle = Bundle(path: path) { NotificationCenter.default.post(name: .appLanguageWillChange, object: nil) Bundle.switchToLocalizationInBundle(bundle) NotificationCenter.default.post(name: .appLanguageDidChange, object: nil) } } } private extension OBChangeLocalizationBehavior { func pathForLocalizationBundle() -> String? { guard let dataSource: OBChangeLocalizationBehaviorDataSource = getDataSource() else { return nil } let localization = dataSource.localizationToChangeTo(self) if localization == Bundle.Localization.currentLocalization { return nil } return Bundle.main.path(forResource: localization, ofType: .projectFileExt) } } extension Notification.Name { static let appLanguageWillChange = Notification.Name(rawValue: "com.apokrupto.OBChangeLocalizationBehavior.languageWillChange") static let appLanguageDidChange = Notification.Name(rawValue: "com.apokrupto.OBChangeLocalizationBehavior.languageDidChange") } /** * The behavior's data source must supply the localization to switch to. If there is * no data source this behavior will do nothing. */ @objc protocol OBChangeLocalizationBehaviorDataSource: OBBehaviorDataSource { func localizationToChangeTo(_ behavior: OBChangeLocalizationBehavior) -> String } private let swizzleLocalizationMethods: () = { guard let originalMethod = class_getInstanceMethod(Bundle.self, .originalSelector), let swizzledMethod = class_getInstanceMethod(Bundle.self, .swizzledSelector) else { return } method_exchangeImplementations(originalMethod, swizzledMethod) }() /** * Extension for NSBundle to swizzle localization */ extension Bundle { struct Localization { static var currentBundle = Bundle.main static var currentLocalization: String { return currentBundle.preferredLocalizations[0] } } // Swizzled implementation of the localization functionality @objc func swizzledLocalizedString(forKey key: String, value: String?, table tableName: String?) -> String { return Localization.currentBundle.swizzledLocalizedString(forKey: key, value: value, table: tableName) } // Perform the swizzling of the localization functionality & set the active bundle public class func switchToLocalizationInBundle(_ bundle: Bundle) { _ = swizzleLocalizationMethods Localization.currentBundle = bundle } } extension UIViewController { func observeLocalizationChanges() { NotificationCenter.default.addObserver(self, selector: .reloadViewController, name: .appLanguageDidChange, object: nil) } } private extension String { static let projectFileExt = "lproj" } private extension Selector { static let originalSelector = #selector(Bundle.localizedString(forKey:value:table:)) static let swizzledSelector = #selector(Bundle.swizzledLocalizedString(forKey:value:table:)) static let reloadViewController = #selector(UIViewController.loadView) }
edfe0d2a313daea7696f941b9975cbf9
37.311258
131
0.690752
false
false
false
false
noppoMan/aws-sdk-swift
refs/heads/main
Sources/Soto/Services/Snowball/Snowball_Error.swift
apache-2.0
1
//===----------------------------------------------------------------------===// // // This source file is part of the Soto for AWS open source project // // Copyright (c) 2017-2020 the Soto project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of Soto project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// // THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT. import SotoCore /// Error enum for Snowball public struct SnowballErrorType: AWSErrorType { enum Code: String { case clusterLimitExceededException = "ClusterLimitExceededException" case conflictException = "ConflictException" case ec2RequestFailedException = "Ec2RequestFailedException" case invalidAddressException = "InvalidAddressException" case invalidInputCombinationException = "InvalidInputCombinationException" case invalidJobStateException = "InvalidJobStateException" case invalidNextTokenException = "InvalidNextTokenException" case invalidResourceException = "InvalidResourceException" case kMSRequestFailedException = "KMSRequestFailedException" case returnShippingLabelAlreadyExistsException = "ReturnShippingLabelAlreadyExistsException" case unsupportedAddressException = "UnsupportedAddressException" } private let error: Code public let context: AWSErrorContext? /// initialize Snowball public init?(errorCode: String, context: AWSErrorContext) { guard let error = Code(rawValue: errorCode) else { return nil } self.error = error self.context = context } internal init(_ error: Code) { self.error = error self.context = nil } /// return error code string public var errorCode: String { self.error.rawValue } /// Job creation failed. Currently, clusters support five nodes. If you have less than five nodes for your cluster and you have more nodes to create for this cluster, try again and create jobs until your cluster has exactly five notes. public static var clusterLimitExceededException: Self { .init(.clusterLimitExceededException) } /// You get this exception when you call CreateReturnShippingLabel more than once when other requests are not completed. public static var conflictException: Self { .init(.conflictException) } /// Your IAM user lacks the necessary Amazon EC2 permissions to perform the attempted action. public static var ec2RequestFailedException: Self { .init(.ec2RequestFailedException) } /// The address provided was invalid. Check the address with your region's carrier, and try again. public static var invalidAddressException: Self { .init(.invalidAddressException) } /// Job or cluster creation failed. One or more inputs were invalid. Confirm that the CreateClusterRequest$SnowballType value supports your CreateJobRequest$JobType, and try again. public static var invalidInputCombinationException: Self { .init(.invalidInputCombinationException) } /// The action can't be performed because the job's current state doesn't allow that action to be performed. public static var invalidJobStateException: Self { .init(.invalidJobStateException) } /// The NextToken string was altered unexpectedly, and the operation has stopped. Run the operation without changing the NextToken string, and try again. public static var invalidNextTokenException: Self { .init(.invalidNextTokenException) } /// The specified resource can't be found. Check the information you provided in your last request, and try again. public static var invalidResourceException: Self { .init(.invalidResourceException) } /// The provided AWS Key Management Service key lacks the permissions to perform the specified CreateJob or UpdateJob action. public static var kMSRequestFailedException: Self { .init(.kMSRequestFailedException) } /// You get this exception if you call CreateReturnShippingLabel and a valid return shipping label already exists. In this case, use DescribeReturnShippingLabel to get the url. public static var returnShippingLabelAlreadyExistsException: Self { .init(.returnShippingLabelAlreadyExistsException) } /// The address is either outside the serviceable area for your region, or an error occurred. Check the address with your region's carrier and try again. If the issue persists, contact AWS Support. public static var unsupportedAddressException: Self { .init(.unsupportedAddressException) } } extension SnowballErrorType: Equatable { public static func == (lhs: SnowballErrorType, rhs: SnowballErrorType) -> Bool { lhs.error == rhs.error } } extension SnowballErrorType: CustomStringConvertible { public var description: String { return "\(self.error.rawValue): \(self.message ?? "")" } }
62f76f8e2fd046c34c1e71e5de1460ab
56.850575
239
0.733161
false
false
false
false
larryhou/swift
refs/heads/master
VisualEffect/VisualEffect/ViewController.swift
mit
1
// // ViewController.swift // VisualEffect // // Created by larryhou on 28/08/2017. // Copyright © 2017 larryhou. All rights reserved. // import UIKit class BlurController: UIViewController { @IBOutlet weak var blurView: UIVisualEffectView! override func viewDidLoad() { super.viewDidLoad() let pan = UIPanGestureRecognizer(target: self, action: #selector(panUpdate(sender:))) view.addGestureRecognizer(pan) blurView.clipsToBounds = true } var fractionComplete = CGFloat.nan var dismissAnimator: UIViewPropertyAnimator! @objc func panUpdate(sender: UIPanGestureRecognizer) { switch sender.state { case .began: dismissAnimator = UIViewPropertyAnimator(duration: 0.2, curve: .linear) { [unowned self] in self.view.frame.origin.y = self.view.frame.height self.blurView.layer.cornerRadius = 40 } dismissAnimator.addCompletion { [unowned self] position in if position == .end { self.dismiss(animated: false, completion: nil) } self.fractionComplete = CGFloat.nan } dismissAnimator.pauseAnimation() case .changed: if fractionComplete.isNaN {fractionComplete = 0} let translation = sender.translation(in: view) fractionComplete += translation.y / view.frame.height fractionComplete = min(1, max(0, fractionComplete)) dismissAnimator.fractionComplete = fractionComplete sender.setTranslation(CGPoint.zero, in: view) default: if dismissAnimator.fractionComplete <= 0.25 { dismissAnimator.isReversed = true } dismissAnimator.continueAnimation(withTimingParameters: nil, durationFactor: 1.0) } } } class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
ef9e2a584bc2345a009597a634d1704e
35.265625
107
0.607497
false
false
false
false
apple/swift-docc-symbolkit
refs/heads/main
Sources/SymbolKit/SymbolGraph/Symbol/KindIdentifier.swift
apache-2.0
1
/* This source file is part of the Swift.org open source project Copyright (c) 2021-2022 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 Swift project authors */ import Foundation extension SymbolGraph.Symbol { /** A unique identifier of a symbol's kind, such as a structure or protocol. */ public struct KindIdentifier: Equatable, Hashable, Codable, CaseIterable { private var rawValue: String /// Create a new ``SymbolGraph/Symbol/KindIdentifier``. /// /// - Note: Only use this initilaizer for defining a new kind. For initializing instances manually, /// copy the initial initializer. For extracting identifiers form raw strings, use ``init(identifier:)``. public init(rawValue: String) { self.rawValue = rawValue } public static let `associatedtype` = KindIdentifier(rawValue: "associatedtype") public static let `class` = KindIdentifier(rawValue: "class") public static let `deinit` = KindIdentifier(rawValue: "deinit") public static let `enum` = KindIdentifier(rawValue: "enum") public static let `case` = KindIdentifier(rawValue: "enum.case") public static let `func` = KindIdentifier(rawValue: "func") public static let `operator` = KindIdentifier(rawValue: "func.op") public static let `init` = KindIdentifier(rawValue: "init") public static let ivar = KindIdentifier(rawValue: "ivar") public static let macro = KindIdentifier(rawValue: "macro") public static let method = KindIdentifier(rawValue: "method") public static let property = KindIdentifier(rawValue: "property") public static let `protocol` = KindIdentifier(rawValue: "protocol") public static let snippet = KindIdentifier(rawValue: "snippet") public static let snippetGroup = KindIdentifier(rawValue: "snippetGroup") public static let `struct` = KindIdentifier(rawValue: "struct") public static let `subscript` = KindIdentifier(rawValue: "subscript") public static let typeMethod = KindIdentifier(rawValue: "type.method") public static let typeProperty = KindIdentifier(rawValue: "type.property") public static let typeSubscript = KindIdentifier(rawValue: "type.subscript") public static let `typealias` = KindIdentifier(rawValue: "typealias") public static let `var` = KindIdentifier(rawValue: "var") public static let module = KindIdentifier(rawValue: "module") public static let `extension` = KindIdentifier(rawValue: "extension") /// A string that uniquely identifies the symbol kind. /// /// If the original kind string was not recognized, this will return `"unknown"`. public var identifier: String { rawValue } public static var allCases: Dictionary<String, Self>.Values { _allCases.values } private static var _allCases: [String: Self] = [ Self.associatedtype.rawValue: .associatedtype, Self.class.rawValue: .class, Self.deinit.rawValue: .deinit, Self.enum.rawValue: .enum, Self.case.rawValue: .case, Self.func.rawValue: .func, Self.operator.rawValue: .operator, Self.`init`.rawValue: .`init`, Self.ivar.rawValue: .ivar, Self.macro.rawValue: .macro, Self.method.rawValue: .method, Self.property.rawValue: .property, Self.protocol.rawValue: .protocol, Self.snippet.rawValue: .snippet, Self.snippetGroup.rawValue: .snippetGroup, Self.struct.rawValue: .struct, Self.subscript.rawValue: .subscript, Self.typeMethod.rawValue: .typeMethod, Self.typeProperty.rawValue: .typeProperty, Self.typeSubscript.rawValue: .typeSubscript, Self.typealias.rawValue: .typealias, Self.var.rawValue: .var, Self.module.rawValue: .module, Self.extension.rawValue: .extension, ] /// Register custom ``SymbolGraph/Symbol/KindIdentifier``s so they can be parsed correctly and /// appear in ``allCases``. /// /// If a type is not registered, language prefixes cannot be removed correctly. /// /// - Note: When working in an uncontrolled environment where other parts of your executable might be disturbed by your /// modifications to the symbol graph structure or might be registering identifiers concurrently, register identifiers on your /// coder instead using ``register(_:to:)`` and maintain your own list of ``allCases``. public static func register(_ identifiers: Self...) { for identifier in identifiers { _allCases[identifier.rawValue] = identifier } } /// Check the given identifier string against the list of known identifiers. /// /// - Parameter identifier: The identifier string to check. /// - Parameter extensionCases: A set of custom identifiers to be considered in this lookup. /// - Returns: The matching `KindIdentifier` case, or `nil` if there was no match. private static func lookupIdentifier(identifier: String, using extensionCases: [String: Self]? = nil) -> KindIdentifier? { _allCases[identifier] ?? extensionCases?[identifier] } /// Compares the given identifier against the known default symbol kinds, and returns whether it matches one. /// /// The identifier will also be checked without its first component, so that (for example) `"swift.func"` /// will be treated the same as just `"func"`, and match `.func`. /// /// - Parameter identifier: The identifier string to compare. /// - Returns: `true` if the given identifier matches a known symbol kind; otherwise `false`. /// /// - Note: This initializer does only recognize custom identifiers if they were registered previously using /// ``register(_:)``. public static func isKnownIdentifier(_ identifier: String) -> Bool { var kind: KindIdentifier? if let cachedDetail = Self.lookupIdentifier(identifier: identifier) { kind = cachedDetail } else { let cleanIdentifier = KindIdentifier.cleanIdentifier(identifier) kind = Self.lookupIdentifier(identifier: cleanIdentifier) } return kind != nil } /// Parses the given identifier to return a matching symbol kind. /// /// The identifier will also be checked without its first component, so that (for example) `"swift.func"` /// will be treated the same as just `"func"`, and match `.func`. /// /// - Parameter identifier: The identifier string to parse. /// /// - Note: This initializer does only recognize custom identifiers if they were registered previously using /// ``register(_:)``. public init(identifier: String) { self.init(identifier: identifier, using: nil) } private init(identifier: String, using extensionCases: [String: Self]?) { // Check if the identifier matches a symbol kind directly. if let firstParse = Self.lookupIdentifier(identifier: identifier, using: extensionCases) { self = firstParse } else { // For symbol graphs which include a language identifier with their symbol kinds // (e.g. "swift.func" instead of just "func"), strip off the language prefix and // try again. let cleanIdentifier = KindIdentifier.cleanIdentifier(identifier) if let secondParse = Self.lookupIdentifier(identifier: cleanIdentifier, using: extensionCases) { self = secondParse } else { // If that doesn't help either, use the original identifier as a raw value. self = Self.init(rawValue: identifier) } } } public init(from decoder: Decoder) throws { let identifier = try decoder.singleValueContainer().decode(String.self) self = KindIdentifier(identifier: identifier, using: decoder.registeredSymbolKindIdentifiers) } public func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() try container.encode(identifier) } /// Strips the first component of the given identifier string, so that (for example) `"swift.func"` will return `"func"`. /// /// Symbol graphs may store symbol kinds as either bare identifiers (e.g. `"class"`, `"enum"`, etc), or as identifiers /// prefixed with the language identifier (e.g. `"swift.func"`, `"objc.method"`, etc). This method allows us to /// treat the language-prefixed symbol kinds as equivalent to the "bare" symbol kinds. /// /// - Parameter identifier: An identifier string to clean. /// - Returns: A new identifier string without its first component, or the original identifier if there was only one component. private static func cleanIdentifier(_ identifier: String) -> String { // FIXME: Take an "expected" language identifier instead of universally dropping the first component? (rdar://84276085) if let periodIndex = identifier.firstIndex(of: ".") { return String(identifier[identifier.index(after: periodIndex)...]) } return identifier } } } extension SymbolGraph.Symbol.KindIdentifier { /// Register custom ``SymbolGraph/Symbol/KindIdentifier``s so they can be parsed correctly while /// decoding symbols in an uncontrolled environment. /// /// If a type is not registered, language prefixes cannot be removed correctly. /// /// - Note: Registering custom identifiers on your decoder is only necessary when working in an uncontrolled environment where /// other parts of your executable might be disturbed by your modifications to the symbol graph structure. If that is not the case, use /// ``SymbolGraph/Symbol/KindIdentifier/register(_:)``. /// /// - Parameter userInfo: A property which allows editing the `userInfo` member of the /// `Decoder` protocol. public static func register<I: Sequence>(_ identifiers: I, to userInfo: inout [CodingUserInfoKey: Any]) where I.Element == Self { var registeredIdentifiers = userInfo[.symbolKindIdentifierKey] as? [String: SymbolGraph.Symbol.KindIdentifier] ?? [:] for identifier in identifiers { registeredIdentifiers[identifier.identifier] = identifier } userInfo[.symbolKindIdentifierKey] = registeredIdentifiers } } public extension JSONDecoder { /// Register custom ``SymbolGraph/Symbol/KindIdentifier``s so they can be parsed correctly while /// decoding symbols in an uncontrolled environment. /// /// If a type is not registered, language prefixes cannot be removed correctly. /// /// - Note: Registering custom identifiers on your decoder is only necessary when working in an uncontrolled environment where /// other parts of your executable might be disturbed by your modifications to the symbol graph structure. If that is not the case, use /// ``SymbolGraph/Symbol/KindIdentifier/register(_:)``. func register(symbolKinds identifiers: SymbolGraph.Symbol.KindIdentifier...) { SymbolGraph.Symbol.KindIdentifier.register(identifiers, to: &self.userInfo) } } extension Decoder { var registeredSymbolKindIdentifiers: [String: SymbolGraph.Symbol.KindIdentifier]? { self.userInfo[.symbolKindIdentifierKey] as? [String: SymbolGraph.Symbol.KindIdentifier] } } extension CodingUserInfoKey { static let symbolKindIdentifierKey = CodingUserInfoKey(rawValue: "org.swift.symbolkit.symbolKindIdentifierKey")! }
ec03b1fea51f25e40abe781cc5746c87
46.630189
139
0.637775
false
false
false
false
hhsolar/MemoryMaster-iOS
refs/heads/master
MemoryMaster/View/TestCollectionViewCell.swift
mit
1
// // TestCollectionViewCell.swift // MemoryMaster // // Created by apple on 4/10/2017. // Copyright © 2017 greatwall. All rights reserved. // import UIKit import QuartzCore class TestCollectionViewCell: UICollectionViewCell, UITextViewDelegate { // public api var questionAtFront = true @IBOutlet weak var containerView: UIView! let questionView = UIView() let answerView = UIView() let questionLabel = UILabel() let answerLabel = UILabel() let qTextView = UITextView() let aTextView = UITextView() let indexLabel = UILabel() weak var delegate: EnlargeImageCellDelegate? override func awakeFromNib() { super.awakeFromNib() setupUI() } func updateUI(question: NSAttributedString, answer: NSAttributedString, index: Int, total: Int) { qTextView.attributedText = question.addAttributesForText(CustomRichTextAttri.bodyNormal, range: NSRange.init(location: 0, length: question.length)) aTextView.attributedText = answer.addAttributesForText(CustomRichTextAttri.bodyNormal, range: NSRange.init(location: 0, length: answer.length)) indexLabel.text = String(format: "%d / %d", index + 1, total) } private func setupUI() { containerView.addSubview(answerView) containerView.addSubview(questionView) containerView.backgroundColor = UIColor.white questionView.backgroundColor = CustomColor.lightBlue questionView.addSubview(questionLabel) questionView.addSubview(qTextView) questionView.addSubview(indexLabel) answerView.backgroundColor = CustomColor.lightGreen answerView.addSubview(answerLabel) answerView.addSubview(aTextView) questionLabel.text = "QUESTION" questionLabel.textAlignment = .center questionLabel.textColor = CustomColor.deepBlue questionLabel.font = UIFont(name: "Helvetica-Bold", size: CustomFont.FontSizeMid) questionLabel.adjustsFontSizeToFitWidth = true indexLabel.textAlignment = .center indexLabel.textColor = CustomColor.deepBlue indexLabel.font = UIFont(name: "Helvetica-Bold", size: CustomFont.FontSizeMid) answerLabel.text = "ANSWER" answerLabel.textAlignment = .center answerLabel.textColor = CustomColor.deepBlue answerLabel.font = UIFont(name: "Helvetica-Bold", size: CustomFont.FontSizeMid) answerLabel.adjustsFontSizeToFitWidth = true qTextView.isEditable = false qTextView.font = UIFont(name: "Helvetica", size: 16) qTextView.textColor = UIColor.darkGray qTextView.backgroundColor = CustomColor.lightBlue qTextView.showsVerticalScrollIndicator = false qTextView.delegate = self aTextView.isEditable = false aTextView.font = UIFont(name: "Helvetica", size: 16) aTextView.textColor = UIColor.darkGray aTextView.backgroundColor = CustomColor.lightGreen aTextView.showsVerticalScrollIndicator = false aTextView.delegate = self } override func layoutSubviews() { super .layoutSubviews() containerView.layer.cornerRadius = 15 containerView.layer.masksToBounds = true questionView.frame = CGRect(x: 0, y: 0, width: contentView.bounds.width - CustomDistance.midEdge * 2, height: contentView.bounds.height - CustomDistance.midEdge * 2) questionView.layer.cornerRadius = 15 questionView.layer.masksToBounds = true questionView.layer.borderWidth = 3 questionView.layer.borderColor = CustomColor.deepBlue.cgColor questionView.layer.shadowOpacity = 0.8 questionView.layer.shadowColor = UIColor.gray.cgColor questionView.layer.shadowRadius = 10 questionView.layer.shadowOffset = CGSize(width: 1, height: 1) answerView.frame = questionView.frame answerView.layer.cornerRadius = 15 answerView.layer.masksToBounds = true answerView.layer.borderWidth = 3 answerView.layer.borderColor = CustomColor.deepBlue.cgColor answerView.layer.shadowOpacity = 0.8 answerView.layer.shadowColor = UIColor.gray.cgColor answerView.layer.shadowRadius = 10 answerView.layer.shadowOffset = CGSize(width: 1, height: 1) questionLabel.frame = CGRect(x: questionView.bounds.midX - questionView.bounds.width / 6, y: CustomDistance.midEdge, width: questionView.bounds.width / 3, height: CustomSize.titleLabelHeight) qTextView.frame = CGRect(x: 0, y: CustomDistance.midEdge * 2 + CustomSize.titleLabelHeight, width: questionView.bounds.width, height: questionView.bounds.height - CustomDistance.midEdge * 4 - CustomSize.titleLabelHeight * 2) qTextView.textContainerInset = UIEdgeInsets(top: 0, left: CustomDistance.narrowEdge, bottom: 0, right: CustomDistance.narrowEdge) indexLabel.frame = CGRect(x: questionView.bounds.midX - questionView.bounds.width / 6, y: questionView.bounds.height - CustomSize.titleLabelHeight - CustomDistance.midEdge, width: questionView.bounds.width / 3, height: CustomSize.titleLabelHeight) answerLabel.frame = questionLabel.frame aTextView.frame = qTextView.frame aTextView.textContainerInset = UIEdgeInsets(top: 0, left: CustomDistance.narrowEdge, bottom: 0, right: CustomDistance.narrowEdge) aTextView.frame.size.height += (CustomDistance.midEdge + CustomSize.titleLabelHeight) } func textView(_ textView: UITextView, shouldInteractWith textAttachment: NSTextAttachment, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool { var image: UIImage? = nil if textAttachment.image != nil { image = textAttachment.image } else { image = textAttachment.image(forBounds: textAttachment.bounds, textContainer: nil, characterIndex: characterRange.location) } if let image = image { delegate?.enlargeTapedImage(image: image) } return true } }
6017b081720d418f38e8a0b843afec26
44.294118
255
0.69513
false
false
false
false
gerardogrisolini/Webretail
refs/heads/master
Sources/Webretail/Models/AttributeValue.swift
apache-2.0
1
// // AttributeValue.swift // Webretail // // Created by Gerardo Grisolini on 17/02/17. // // import Foundation import StORM class AttributeValue: PostgresSqlORM, Codable { public var attributeValueId : Int = 0 public var attributeId : Int = 0 public var attributeValueCode : String = "" public var attributeValueName : String = "" public var attributeValueTranslates: [Translation] = [Translation]() public var attributeValueCreated : Int = Int.now() public var attributeValueUpdated : Int = Int.now() private enum CodingKeys: String, CodingKey { case attributeValueId case attributeId case attributeValueCode case attributeValueName case attributeValueTranslates = "translations" } open override func table() -> String { return "attributevalues" } open override func tableIndexes() -> [String] { return ["attributeValueCode", "attributeValueName"] } open override func to(_ this: StORMRow) { attributeValueId = this.data["attributevalueid"] as? Int ?? 0 attributeId = this.data["attributeid"] as? Int ?? 0 attributeValueCode = this.data["attributevaluecode"] as? String ?? "" attributeValueName = this.data["attributevaluename"] as? String ?? "" if let translates = this.data["attributevaluetranslates"] { let jsonData = try! JSONSerialization.data(withJSONObject: translates, options: []) attributeValueTranslates = try! JSONDecoder().decode([Translation].self, from: jsonData) } attributeValueCreated = this.data["attributevaluecreated"] as? Int ?? 0 attributeValueUpdated = this.data["attributevalueupdated"] as? Int ?? 0 } func rows() -> [AttributeValue] { var rows = [AttributeValue]() for i in 0..<self.results.rows.count { let row = AttributeValue() row.to(self.results.rows[i]) rows.append(row) } return rows } override init() { super.init() } required init(from decoder: Decoder) throws { super.init() let container = try decoder.container(keyedBy: CodingKeys.self) attributeValueId = try container.decode(Int.self, forKey: .attributeValueId) attributeId = try container.decode(Int.self, forKey: .attributeId) attributeValueCode = try container.decode(String.self, forKey: .attributeValueCode) attributeValueName = try container.decode(String.self, forKey: .attributeValueName) attributeValueTranslates = try container.decodeIfPresent([Translation].self, forKey: .attributeValueTranslates) ?? [Translation]() } func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(attributeValueId, forKey: .attributeValueId) try container.encode(attributeId, forKey: .attributeId) try container.encode(attributeValueCode, forKey: .attributeValueCode) try container.encode(attributeValueName, forKey: .attributeValueName) try container.encode(attributeValueTranslates, forKey: .attributeValueTranslates) } }
4bc5cc8183841ef82abe89698ad2c337
39.417722
138
0.676793
false
false
false
false
svachmic/ios-url-remote
refs/heads/master
URLRemote/Classes/Controllers/LoginTableViewController.swift
apache-2.0
1
// // LoginTableViewController.swift // URLRemote // // Created by Michal Švácha on 23/11/16. // Copyright © 2016 Svacha, Michal. All rights reserved. // import UIKit import Bond import ReactiveKit import Material /// Controller used for logging user in. It is presented when the there is no user logged in. class LoginTableViewController: UITableViewController, PersistenceStackController { var stack: PersistenceStack! { didSet { viewModel = LoginViewModel(authentication: stack.authentication) } } var viewModel: LoginViewModel! override func viewDidLoad() { super.viewDidLoad() self.setupNotificationHandler() tableView.apply(Stylesheet.Login.tableView) self.setupTableView() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } /// Sets up event handlers for sign in/up actions. func setupNotificationHandler() { viewModel.errors.observeNext { [unowned self] error in self.handle(error: error) }.dispose(in: bag) viewModel.dataSource.flatMap {$0}.observeNext { [unowned self] _ in self.parent?.dismiss(animated: true) }.dispose(in: bag) } /// Handles an error simply by displaying an alert dialog with the error message describing the problem that has occurred. /// /// - Parameter error: Error to be handled. func handle(error: Error) { let message = error.localizedDescription self.presentSimpleAlertDialog( header: NSLocalizedString("ERROR", comment: ""), message: message) } /// Sets up the full table view by hooking in up to the view-model. func setupTableView() { self.viewModel.contents.bind(to: self.tableView) { conts, indexPath, tableView in let content = conts[indexPath.row] let identifier = content.identifier let cell = tableView.dequeueReusableCell(withIdentifier: identifier, for: indexPath) cell.selectionStyle = .none cell.backgroundColor = .clear switch identifier { case "emailCell", "passwordCell", "passwordAgainCell": let textField = cell.viewWithTag(1) as! TextField textField.placeholder = content.text textField.apply(Stylesheet.Login.textField) let leftView = UIImageView() if identifier == "emailCell" { leftView.image = Icon.email self.bindEmailCell(textField: textField) } else if identifier == "passwordCell" { leftView.image = Icon.visibility self.bindPasswordCell(index: 0, textField: textField) } else if identifier == "passwordAgainCell" { leftView.image = Icon.visibility self.bindPasswordCell(index: 1, textField: textField) } textField.leftView = leftView case "signUpCell": let button = cell.viewWithTag(1) as! RaisedButton button.titleLabel?.font = RobotoFont.bold(with: 17) button.title = content.text button.backgroundColor = UIColor(named: .red) self.bindSignButton(state: .signIn, button: button) case "signInCell": let button = cell.viewWithTag(1) as! RaisedButton button.titleLabel?.font = RobotoFont.bold(with: 17) button.title = content.text button.backgroundColor = UIColor(named: .yellow) self.bindSignButton(state: .signUp, button: button) case "textCell": let label = cell.viewWithTag(1) as! UILabel label.text = content.text default: break } return cell } } // MARK: - Bindings /// Binds the e-mail TextField to the view-model. Also sets up binding for detail label of the TextField to display when the e-mail is invalid. /// /// - Parameter textField: TextField object to be bound. func bindEmailCell(textField: TextField) { textField.reactive.text .bind(to: viewModel.email) .dispose(in: textField.bag) textField.reactive.text.map { text -> String in if let text = text, !text.isValidEmail(), text != "" { return NSLocalizedString("INVALID_EMAIL", comment: "") } return "" }.bind(to: textField.reactive.detail) .dispose(in: textField.bag) } /// Binds the password and repeated password TextFields to the view-model. /// - First TextField has length validation. /// - Second TextField has similarity validation (to the first one entered). /// /// - Parameter index: Integer indicating which TextField is to be handled. 0 is for the first, 1 is for the second. /// - Parameter textField: TextField object to be bound. func bindPasswordCell(index: Int, textField: TextField) { if index == 0 { // first password field during both sign in/up textField.reactive.text .bind(to: self.viewModel.password) .dispose(in: textField.bag) textField.reactive.text.skip(first: 1).map { text in if let text = text, (text.count < 6 && text.count != 0) { return NSLocalizedString("INVALID_PASSWORD_LENGTH", comment: "") } return "" }.bind(to: textField.reactive.detail) .dispose(in: textField.bag) } else { // second password field during sign up textField.reactive.text .bind(to: self.viewModel.passwordAgain) .dispose(in: textField.bag) combineLatest(self.viewModel.password, self.viewModel.passwordAgain) .map { password, repeated in if let pwd = password, let rep = repeated, pwd != rep { return NSLocalizedString("INVALID_PASSWORD", comment: "") } return "" }.bind(to: textField.reactive.detail) .dispose(in: textField.bag) } } /// Binds the sign-action button to the desired activity. It is used for both "Sign In" and "Sign Up" buttons, because their actions are the same (just reversed). /// - "Sign In" transforms when state is .signUp. /// - "Sign Up" transforms when state is .signIn. /// /// - Parameter state: State to be compared for transformation. /// - Parameter button: RaisedButton object to be bound. func bindSignButton(state: LoginState, button: RaisedButton) { button.reactive.tap.observeNext { [unowned self] _ in self.view.endEditing(true) if self.viewModel.state == state { self.viewModel.transform() } else { if state == .signIn { self.viewModel.signUp() } else { self.viewModel.signIn() } } }.dispose(in: button.bag) } // MARK: - UITableView delegate override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return self.viewModel.contents[indexPath.row].height } }
2f9022023a9af8c9df35bea7c2abc8c4
38.807292
166
0.57726
false
false
false
false
Zewo/HTTPSerializer
refs/heads/master
Sources/Cookie.swift
mit
1
extension Cookie: CustomStringConvertible { public var description: String { var string = "\(name)=\(value)" if let expires = expires { string += "; Expires=\(expires)" } if let maxAge = maxAge { string += "; Max-Age=\(maxAge)" } if let domain = domain { string += "; Domain=\(domain)" } if let path = path { string += "; Path=\(path)" } if secure { string += "; Secure" } if HTTPOnly { string += "; HttpOnly" } return string } }
95b0b17c2cb892496c0d3f18032b66f8
19.290323
44
0.435612
false
false
false
false
designatednerd/EasingExample
refs/heads/master
Easing/ViewController.swift
mit
1
// // ViewController.swift // Easing // // Created by Ellen Shapiro on 10/26/14. // Copyright (c) 2014 Designated Nerd Software. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet var easeInView : UIView? @IBOutlet var easeOutView : UIView? @IBOutlet var easeInOutView : UIView? @IBOutlet var linearView : UIView? @IBOutlet var goButton : UIButton? @IBOutlet var resetButton : UIButton? var targetMove : CGFloat = 0.0 required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } //MARK: View Lifecycle override func viewDidLoad() { super.viewDidLoad() resetButton?.enabled = false; } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() if let reallyAView = easeInView { let fullViewWidth = CGRectGetWidth(self.view.frame) targetMove = fullViewWidth - CGRectGetMinX(reallyAView.frame) - CGRectGetWidth(reallyAView.frame) - 20.0 } } //MARK: Easy Show/Hide @IBAction func toggleAlpha(sender: UITapGestureRecognizer) { if let view = sender.view { if view.alpha == 1 { //Dropping alpha to .01 or below causes the tap gesture recognizers to fail. ಠ_ಠ view.alpha = 0.011 } else { view.alpha = 1 } } } //MARK: Animations @IBAction func fireAnimations() { goButton?.enabled = false; fireAnimations(2.0, reverse: false) } func fireAnimations(duration : NSTimeInterval, reverse : Bool) { fireAnimationForView(easeInView!, easing: .CurveEaseIn, duration: duration, reverse: reverse) fireAnimationForView(easeOutView!, easing: .CurveEaseOut, duration: duration, reverse: reverse) fireAnimationForView(easeInOutView!, easing: .CurveEaseInOut, duration: duration, reverse: reverse) fireAnimationForView(linearView!, easing: .CurveLinear, duration: duration, reverse: reverse) } func fireAnimationForView(view : UIView, easing : UIViewAnimationOptions, duration : NSTimeInterval, reverse : Bool ) { var move = self.targetMove if reverse { move *= -1 } UIView.animateWithDuration(duration, delay: 0, options: easing, animations: { () -> Void in view.frame = CGRectOffset(view.frame, move, 0); }) { (Bool) -> Void in if reverse { self.goButton?.enabled = true; self.resetButton?.enabled = false; } else { self.resetButton?.enabled = true; self.goButton?.enabled = false; } } } @IBAction func reset() { fireAnimations(0.0, reverse: true) } }
1c431b9204d2792d04186107f4ab28ff
30.815217
123
0.591732
false
false
false
false
LincLiu/SuspensionMenu
refs/heads/master
Classes/Tools.swift
mit
1
// // Tools.swift // SuspensionMenu // // Created by YunKuai on 2017/8/8. // Copyright © 2017年 dev.liufeng@gmail. All rights reserved. // import Foundation import UIKit let SCREEN_WIDTH = UIScreen.main.bounds.width let SCREEN_HEIGHT = UIScreen.main.bounds.height let SCREEN_RECT = UIScreen.main.bounds //设置颜色 func RGBA(r:CGFloat,g:CGFloat,b:CGFloat,a:CGFloat)->UIColor {return UIColor.init(red: r/255.0, green: g/255.0, blue: b/255.0, alpha: a)} //设置字体大小 func FONT(size:CGFloat,isBold: Bool=false)->UIFont { if isBold{ return UIFont.boldSystemFont(ofSize: size) }else{ return UIFont.systemFont(ofSize: size) } } //设置Plus的字号,字体名称,其他机型自适应 func FONT(sizePlus:CGFloat,isBold: Bool=false)->UIFont{ if SCREEN_WIDTH == 375{return FONT(size: CGFloat((375.0/414))*sizePlus,isBold: isBold)} if SCREEN_WIDTH == 320{return FONT(size: CGFloat((320.0/414))*sizePlus,isBold: isBold)} return FONT(size: sizePlus) } //输入跟屏宽的比,得到对应的距离 func GET_DISTANCE(ratio:Float)->CGFloat{ let distance = SCREEN_WIDTH*CGFloat(ratio) return distance } extension CGRect{ func getMaxY()->CGFloat{ return self.origin.y+self.size.height } }
46f905bb34a1bcd64db6796dfde2149c
24.12766
136
0.700254
false
false
false
false
maor-eini/Chop-Chop
refs/heads/master
chopchop/chopchop/ModelSql.swift
mit
1
// // ModelSql.swift // chopchop // // Created by Maor Eini on 18/03/2017. // Copyright © 2017 Maor Eini. All rights reserved. // import Foundation extension String { public init?(validatingUTF8 cString: UnsafePointer<UInt8>) { if let (result, _) = String.decodeCString(cString, as: UTF8.self, repairingInvalidCodeUnits: false) { self = result } else { return nil } } } class ModelSql{ var database: OpaquePointer? = nil init?(){ let dbFileName = "database.db" if let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first{ let path = dir.appendingPathComponent(dbFileName) if sqlite3_open(path.absoluteString, &database) != SQLITE_OK { print("Failed to open db file: \(path.absoluteString)") return nil } } if User.createTable(database: database) == false{ return nil } if FeedItem.createTable(database: database) == false{ return nil } if LastUpdateTableService.createTable(database: database) == false{ return nil } } }
208d3cb36dbc509378519431192ae9fc
24.843137
85
0.53566
false
false
false
false
xGoPox/vapor-authentification
refs/heads/master
Sources/App/Models/UserCredentials.swift
mit
1
// // UserCredentials.swift // vapor-authentification // // Created by Clement Yerochewski on 1/13/17. // // import Auth import BCrypt import Node import Vapor typealias HashedPassword = (secret: User.Secret, salt: User.Salt) struct UserCredentials: Credentials { var password: String var email: String private let hash: HashProtocol init(email: String, password: String, hash: HashProtocol) { self.email = email self.hash = hash self.password = password } func hashPassword(using salt: User.Salt = BCryptSalt().string) throws -> HashedPassword { return (try hash.make((password) + salt), salt) } } struct AuthenticatedUserCredentials: Credentials { let id: String /* init(node: Node) throws { guard let id: String = try node.extract(User.Keys.id) else { throw VaporAuthError.couldNotLogIn } self.id = id }*/ }
adf0083d255da06d2a71c16c1dcd5e79
19.630435
93
0.641728
false
false
false
false
hyperoslo/Orchestra
refs/heads/master
Example/OrchestraDemo/OrchestraDemo/Sources/Controllers/MainController.swift
mit
1
import UIKit import Hue class MainController: UITabBarController { lazy var projectListController: UINavigationController = { let controller = ProjectListController() let navigationController = UINavigationController(rootViewController: controller) controller.tabBarItem.title = "Open Source" controller.tabBarItem.image = UIImage(named: "tabProjects") return navigationController }() lazy var teamController: TeamController = { let controller = TeamController() controller.tabBarItem.title = "Team" controller.tabBarItem.image = UIImage(named: "tabTeam") return controller }() lazy var playgroundController: PlaygroundController = { let controller = PlaygroundController() controller.tabBarItem.title = "Playground" controller.tabBarItem.image = UIImage(named: "tabPlayground") return controller }() // MARK: - View Lifecycle override func viewDidLoad() { super.viewDidLoad() configureTabBar() } // MARK: - Configuration func configureTabBar() { tabBar.translucent = true tabBar.tintColor = UIColor.hex("F57D2D") viewControllers = [ projectListController, teamController, playgroundController ] selectedIndex = 0 } }
11eb8c2c721cd0d89b4bdedc9c643f70
23.096154
85
0.71668
false
true
false
false
Fenrikur/ef-app_ios
refs/heads/master
Domain Model/EurofurenceModel/Private/Objects/Entities/EventImpl.swift
mit
1
import EventBus import Foundation class EventImpl: Event { private let eventBus: EventBus private let imageCache: ImagesCache private let shareableURLFactory: ShareableURLFactory private let posterImageId: String? private let bannerImageId: String? var posterGraphicPNGData: Data? { return posterImageId.let(imageCache.cachedImageData) } var bannerGraphicPNGData: Data? { return bannerImageId.let(imageCache.cachedImageData) } var identifier: EventIdentifier var title: String var subtitle: String var abstract: String var room: Room var track: Track var hosts: String var startDate: Date var endDate: Date var eventDescription: String var isSponsorOnly: Bool var isSuperSponsorOnly: Bool var isArtShow: Bool var isKageEvent: Bool var isDealersDen: Bool var isMainStage: Bool var isPhotoshoot: Bool var isAcceptingFeedback: Bool var day: ConferenceDayCharacteristics init(eventBus: EventBus, imageCache: ImagesCache, shareableURLFactory: ShareableURLFactory, isFavourite: Bool, identifier: EventIdentifier, title: String, subtitle: String, abstract: String, room: Room, track: Track, hosts: String, startDate: Date, endDate: Date, eventDescription: String, posterImageId: String?, bannerImageId: String?, isSponsorOnly: Bool, isSuperSponsorOnly: Bool, isArtShow: Bool, isKageEvent: Bool, isDealersDen: Bool, isMainStage: Bool, isPhotoshoot: Bool, isAcceptingFeedback: Bool, day: ConferenceDayCharacteristics) { self.eventBus = eventBus self.imageCache = imageCache self.shareableURLFactory = shareableURLFactory self.isFavourite = isFavourite self.identifier = identifier self.title = title self.subtitle = subtitle self.abstract = abstract self.room = room self.track = track self.hosts = hosts self.startDate = startDate self.endDate = endDate self.eventDescription = eventDescription self.posterImageId = posterImageId self.bannerImageId = bannerImageId self.isSponsorOnly = isSponsorOnly self.isSuperSponsorOnly = isSuperSponsorOnly self.isArtShow = isArtShow self.isKageEvent = isKageEvent self.isDealersDen = isDealersDen self.isMainStage = isMainStage self.isPhotoshoot = isPhotoshoot self.isAcceptingFeedback = isAcceptingFeedback self.day = day } private var observers: [EventObserver] = [] func add(_ observer: EventObserver) { observers.append(observer) provideFavouritedStateToObserver(observer) } func remove(_ observer: EventObserver) { observers.removeAll(where: { $0 === observer }) } private var isFavourite: Bool { didSet { postFavouriteStateChangedEvent() } } func favourite() { isFavourite = true notifyObserversFavouritedStateDidChange() } func unfavourite() { isFavourite = false notifyObserversFavouritedStateDidChange() } func prepareFeedback() -> EventFeedback { if isAcceptingFeedback { return AcceptingEventFeedback(eventBus: eventBus, eventIdentifier: identifier) } else { return NotAcceptingEventFeedback() } } func makeContentURL() -> URL { return shareableURLFactory.makeURL(for: identifier) } private func notifyObserversFavouritedStateDidChange() { observers.forEach(provideFavouritedStateToObserver) } private func provideFavouritedStateToObserver(_ observer: EventObserver) { if isFavourite { observer.eventDidBecomeFavourite(self) } else { observer.eventDidBecomeUnfavourite(self) } } private func postFavouriteStateChangedEvent() { let event: Any if isFavourite { event = DomainEvent.FavouriteEvent(identifier: identifier) } else { event = DomainEvent.UnfavouriteEvent(identifier: identifier) } eventBus.post(event) } }
715ea720c1285f14def2ef0c1a83adfe
27.393548
90
0.642354
false
false
false
false
ps2/rileylink_ios
refs/heads/dev
MinimedKit/Messages/PumpErrorMessageBody.swift
mit
1
// // PumpErrorMessageBody.swift // RileyLink // // Created by Pete Schwamb on 5/10/17. // Copyright © 2017 Pete Schwamb. All rights reserved. // import Foundation public enum PumpErrorCode: UInt8, CustomStringConvertible { // commandRefused can happen when temp basal type is set incorrectly, during suspended pump, or unfinished prime. case commandRefused = 0x08 case maxSettingExceeded = 0x09 case bolusInProgress = 0x0c case pageDoesNotExist = 0x0d public var description: String { switch self { case .commandRefused: return LocalizedString("Command refused", comment: "Pump error code returned when command refused") case .maxSettingExceeded: return LocalizedString("Max setting exceeded", comment: "Pump error code describing max setting exceeded") case .bolusInProgress: return LocalizedString("Bolus in progress", comment: "Pump error code when bolus is in progress") case .pageDoesNotExist: return LocalizedString("History page does not exist", comment: "Pump error code when invalid history page is requested") } } public var recoverySuggestion: String? { switch self { case .commandRefused: return LocalizedString("Check that the pump is not suspended or priming, or has a percent temp basal type", comment: "Suggestions for diagnosing a command refused pump error") default: return nil } } } public class PumpErrorMessageBody: DecodableMessageBody { public static let length = 1 let rxData: Data public let errorCode: PartialDecode<PumpErrorCode, UInt8> public required init?(rxData: Data) { self.rxData = rxData let rawErrorCode = rxData[0] if let errorCode = PumpErrorCode(rawValue: rawErrorCode) { self.errorCode = .known(errorCode) } else { self.errorCode = .unknown(rawErrorCode) } } public var txData: Data { return rxData } public var description: String { return "PumpError(\(errorCode))" } }
f96e4055cec0151f9ec2e2dd51732de5
32.734375
187
0.659101
false
false
false
false
blockchain/My-Wallet-V3-iOS
refs/heads/master
Modules/Metadata/Sources/MetadataKit/Models/MetadataPayload.swift
lgpl-3.0
1
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import Foundation public struct MetadataPayload: Equatable { let version: Int let payload: String let signature: String let prevMagicHash: String? let typeId: Int let createdAt: Int let updatedAt: Int let address: String public init( version: Int, payload: String, signature: String, prevMagicHash: String?, typeId: Int, createdAt: Int, updatedAt: Int, address: String ) { self.version = version self.payload = payload self.signature = signature self.prevMagicHash = prevMagicHash self.typeId = typeId self.createdAt = createdAt self.updatedAt = updatedAt self.address = address } } public struct MetadataBody: Equatable { public let version: Int public let payload: String public let signature: String public let prevMagicHash: String? public let typeId: Int public init( version: Int, payload: String, signature: String, prevMagicHash: String?, typeId: Int ) { self.version = version self.payload = payload self.signature = signature self.prevMagicHash = prevMagicHash self.typeId = typeId } }
23cc72cab94e9e6f979b1c8c9535e624
22.275862
62
0.614815
false
false
false
false
Chovans/WeatherAppDemo
refs/heads/master
Chovans2/BaseViewController.swift
mit
1
// // BaseViewController.swift // Chovans2 // // Created by chovans on 15/9/6. // Copyright © 2015年 chovans. All rights reserved. // import UIKit class BaseViewController: UIViewController { let menuItemView:MenuItemView = MenuItemView() override func viewDidLoad() { super.viewDidLoad() menuItemView.itemArray[1].addTarget(self, action: Selector("trun2Weather:"), forControlEvents: .TouchDown) menuItemView.itemArray[2].addTarget(self, action: Selector("turn2News:"), forControlEvents: .TouchDown) view.addSubview(menuItemView) let rightSwipe = UISwipeGestureRecognizer(target: self, action: Selector("menuItemShow:")) rightSwipe.direction = UISwipeGestureRecognizerDirection.Right view.addGestureRecognizer(rightSwipe) let leftSwipe = UISwipeGestureRecognizer(target: self, action: Selector("menuItemHidden:")) leftSwipe.direction = UISwipeGestureRecognizerDirection.Left view.addGestureRecognizer(leftSwipe) view.addGestureRecognizer(rightSwipe) // modalPresentationStyle = UIModalPresentationStyle.Popover //跳转效果,未实现自定义 modalTransitionStyle = UIModalTransitionStyle.CrossDissolve } func menuItemShow(sender:UISwipeGestureRecognizer){ menuItemView.showAnimation() } func menuItemHidden(sender:UISwipeGestureRecognizer){ menuItemView.hideAnimation(self) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func trun2Weather(sender:AnyObject){ // self.dismissViewControllerAnimated(false, completion: nil) self.presentViewController((storyboard?.instantiateViewControllerWithIdentifier("WeatherScene"))!, animated: true, completion: nil) } func turn2News(sender:AnyObject){ // self.dismissViewControllerAnimated(false, completion: nil) self.presentViewController((storyboard?.instantiateViewControllerWithIdentifier("NewsScene"))!, animated: true, completion: nil) } }
a7d4416caf43cf8c369adbfafa319e76
31.90625
139
0.704179
false
false
false
false
Unipagos/UnipagosIntegrationIOSSwift
refs/heads/master
UnipagosIntegrationTest/ViewController.swift
mit
1
// // ViewController.swift // UnipagosIntegrationTest // // Created by Leonardo Cid on 22/09/14. // Copyright (c) 2014 Unipagos. All rights reserved. // import UIKit let kPaymentURLiteralAmount = "a"; let kPaymentURLiteralRecipientID = "r"; let kPaymentURLiteralReferenceID = "i"; let kPaymentURLiteralCallbackURL = "url"; let kPaymentURLiteralReferenceText = "t"; let kPaymentURLiteralNeedsUserValidation = "v"; let kPaymentURLiteralURLScheme = "unipagos://pay"; //you will use one of these two let kPaymentURLiteralMerchant = "merchant"; let kPaymentURLiteralMDN = "mdn"; class ViewController: UIViewController, UITextFieldDelegate { @IBOutlet weak var recipientText : UITextField! @IBOutlet weak var amountText : UITextField! @IBOutlet weak var refIdText : UITextField! @IBOutlet weak var refText : UITextField! @IBOutlet weak var validationSwitch : UISwitch! 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 payButtonTapped (sender: UIButton) { let uri = NSMutableString() let recipientString = recipientText.text let amountString = amountText.text let refIdString = refIdText.text let refString = refText.text uri.appendFormat("%@?%@=@(%@:%@)&%@=%@",kPaymentURLiteralURLScheme, kPaymentURLiteralRecipientID, kPaymentURLiteralMerchant, recipientString!, kPaymentURLiteralAmount, amountString!) if (!(refIdString?.isEmpty)!) { uri.appendFormat("&%@=%@",kPaymentURLiteralReferenceID, refIdString!) } if (refString?.isEmpty)! { uri.appendFormat("&%@=%@",kPaymentURLiteralReferenceText, refString!) } if(validationSwitch.isOn){ uri.appendFormat("&%@=true", kPaymentURLiteralNeedsUserValidation) } uri.append("&url=unipagosint://") //callback URL print(uri) if let anURL = URL(string: uri as String) { print(anURL); UIApplication.shared.openURL(anURL) } } func textFieldShouldReturn(_ textField: UITextField) -> Bool { if textField.tag == 4 { textField.resignFirstResponder() } else { let txtField : UITextField? = self.view.viewWithTag(textField.tag + 1) as? UITextField txtField?.becomeFirstResponder() } textField.resignFirstResponder() return false; } }
216fec20cb3a6c886fc98ca50b649392
30.842697
98
0.622795
false
false
false
false
MakeSchool/ConvenienceKit
refs/heads/master
Pod/Classes/NSCacheSwift.swift
mit
2
// // NSCacheSwift.swift // ConvenienceKit // // Created by Benjamin Encz on 6/4/15. // Copyright (c) 2015 Benjamin Encz. All rights reserved. // import Foundation public class NSCacheSwift<T: Hashable, U> { private let cache: NSCache public var delegate: NSCacheDelegate? { get { return cache.delegate } set { cache.delegate = delegate } } public var name: String { get { return cache.name } set { cache.name = name } } public var totalCostLimit: Int { get { return cache.totalCostLimit } set { cache.totalCostLimit = totalCostLimit } } public var countLimit: Int { get { return cache.countLimit } set { cache.countLimit = countLimit } } public var evictsObjectsWithDiscardedContent: Bool { get { return cache.evictsObjectsWithDiscardedContent } set { cache.evictsObjectsWithDiscardedContent = evictsObjectsWithDiscardedContent } } public init() { cache = NSCache() } public func objectForKey(key: T) -> U? { let key: AnyObject = replaceKeyIfNeccessary(key) let value = cache.objectForKey(key) as? U ?? (cache.objectForKey(key) as? Container<U>)?.content return value } public func setObject(obj: U, forKey key: T) { let object: AnyObject = obj as? AnyObject ?? Container(content: obj) let key: AnyObject = replaceKeyIfNeccessary(key) cache.setObject(object, forKey: key) } public func setObject(obj: U, forKey key: T, cost g: Int) { cache.setObject(obj as! AnyObject, forKey: key as! AnyObject, cost: g) } public func removeObjectForKey(key: T) { let key: AnyObject = replaceKeyIfNeccessary(key) cache.removeObjectForKey(key) } public func removeAllObjects() { cache.removeAllObjects() } public subscript(key: T) -> U? { get { return objectForKey(key) } set(newValue) { if let newValue = newValue { setObject(newValue, forKey: key) } } } // MARK: Wrapping Value Types into Reference Type Containers /* NSCache can only store types that conform to AnyObject. It compares keys by object identity. To allow value types as keys, NSCacheSwift requires keys to conform to Hashable. NSCacheSwift then creates an NSObject for each unique value (as determined by equality) that acts as the key in NSCache. */ private var keyReplacers = [T : NSObject]() private func replaceKeyIfNeccessary(originalKey :T) -> AnyObject { let key: AnyObject? = originalKey as? AnyObject ?? keyReplacers[originalKey] if let key: AnyObject = key { return key } else { let container = NSObject() keyReplacers[originalKey] = container return container } } } private class Container<T> { private (set) var content: T init(content: T) { self.content = content } }
9ff2767eaa50025dc18bb3af4441132d
21.484848
304
0.641846
false
false
false
false
EvgenyKarkan/Feeds4U
refs/heads/develop
iFeed/Sources/Data/Models/Feed.swift
mit
1
// // Feed.swift // iFeed // // Created by Evgeny Karkan on 9/2/15. // Copyright (c) 2015 Evgeny Karkan. All rights reserved. // import Foundation import CoreData @objc(Feed) class Feed: NSManagedObject { @NSManaged var rssURL: String @NSManaged var title: String! @NSManaged var summary: String? @NSManaged var feedItems: NSSet //sorted 'feedItems' by publish date func sortedItems() -> [FeedItem] { guard let unsortedItems: [FeedItem] = feedItems.allObjects as? [FeedItem] else { return [] } let sortedArray = unsortedItems.sorted(by: { (item1: FeedItem, item2: FeedItem) -> Bool in return item1.publishDate.timeIntervalSince1970 > item2.publishDate.timeIntervalSince1970 }) return sortedArray } //unread 'feedItems' func unreadItems() -> [FeedItem] { guard let items: [FeedItem] = feedItems.allObjects as? [FeedItem] else { return [] } let unReadItem = items.filter({ (item: FeedItem) -> Bool in return item.wasRead.boolValue == false }) return unReadItem } }
8482b928f77baa1aeadd5e4d1b9bacef
24.234043
100
0.602024
false
false
false
false
ikuehne/Papaya
refs/heads/master
Sources/Graph.swift
mit
1
/* This file defines graph types as protocols, as well as related errors. */ /** Errors related to the `Graph` protocol. - `.VertexAlreadyPresent`: Error due to a vertex already being in the graph. - `.VertexNotPresent`: Error due to a vertex not being in the graph. - `.EdgeNotPresent`: Error due to an edge not being in the graph. */ public enum GraphError: ErrorType { case VertexAlreadyPresent case VertexNotPresent case EdgeNotPresent } /** Description of abstract graph type. Provides a generic set of graph operations, without assuming a weighting on the graph. */ public protocol Graph { /** Type representing vertices. All instances of this type in the graph should be unique, so that ∀ v ∈ `vertices`, (v, v') ∈ `edges` & v'' = v ⟹ (v'', v') ∈ `edges`. That is, all edges and vertices should be unique. */ typealias Vertex /** Initializes an empty graph. */ init() /** Initializes a graph with the given vertices and no edges. A *default implementation* using the empty initializer and `addVertex` is provided. - parameter vertices: A collection of vertices to include initially. */ //init<V: CollectionType where V.Generator.Element == Vertex> (vertices: V) // Maybe shouldn't be required? // Default implementation may be good enough without requiring adopters // of the protocol to provide their own? /** Initializes a graph with the same vertices and edges as the given graph. A *default implementation* using the empty initializer, `addVertex`, and `addEdge` is provided. - parameter graph: The graph to copy. */ //init<G: Graph where G.Vertex == Vertex>(graph: G) /** An array of all the vertices in the graph. */ var vertices: [Vertex] { get } /** An array of all the edges in the graph, represented as tuples of vertices. */ var edges: [(Vertex, Vertex)] { get } /** Returns whether there is an edge from one vertex to another in the graph. - parameter from: The vertex to check from. - parameter to: The destination vertex. - returns: `true` if the edge exists; `false` otherwise. - throws: `GraphError.VertexNotPresent` if either vertex is not in the graph. */ func edgeExists(from: Vertex, to: Vertex) throws -> Bool /** Creates an array of all vertices reachable from a vertex. A *default implementation* using `vertices` and `edgeExists` is provided. It works in O(V) time. - parameter vertex: The vertex whose neighbors to retrieve. - returns: An array of all vertices with edges from `vertex` to them, in no particular order, and not including `vertex` unless there is a loop. - throws: `GraphError.VertexNotPresent` if `vertex` is not in the graph. */ func neighbors(vertex: Vertex) throws -> [Vertex] /** Adds a new vertex to the graph with no edges connected to it. Changes the graph in-place to add the vertex. - parameter vertex: The vertex to add. - throws: `GraphError.VertexAlreadyPresent` if `vertex` is already in the graph. */ mutating func addVertex(vertex: Vertex) throws /** Adds a new edge to the graph from one vertex to another. Changes the graph in-place to add the edge. - parameter from: The vertex to start the edge from. - parameter to: The vertex the edge ends on. - throws: `GraphError.VertexNotPresent` if either vertex is not in the graph. */ mutating func addEdge(from: Vertex, to: Vertex) throws /** Removes a vertex and all edges connected to it. - parameter vertex: The vertex to remove. - throws: `GraphError.VertexNotPresent` if the vertex to be deleted is not in the graph. */ mutating func removeVertex(vertex: Vertex) throws /** Removes an edge from one vertex to another. - parameter from: The 'source' of the edge. - parameter to: The 'destination' of the edge. - throws: `GraphError.EdgeNotPresent` if the edge to be removed is not in the graph. */ mutating func removeEdge(from: Vertex, to: Vertex) throws } /** Description of an undirected graph. This protocol is identical to Graph and DirectedGraph, but new types should implement this protocol if the `edgeExists` function is reflexive, i.e. if the edges have no associated direction. */ public protocol UndirectedGraph: Graph { } /** Description of a directed graph. This protocol is identical to Graph and UndirectedGraph, but new types should implement this protocol with the `edgeExists` function not reflexive, i.e. if the edges have an associated direction. */ public protocol DirectedGraph: Graph { } /** Description of a weighted graph. Weighted graphs have a weight associated with each edge. */ public protocol WeightedGraph: Graph { /** Computes the weight associated with the given edge. - parameter to: The 'source' of the edge to use. - parameter from: The 'destination' of the edge to use. - returns: The weight associated with the given edge, or `nil` if the edge is not in the graph. - throws: `GraphError.VertexNotPresent` if either vertex is not in the graph. */ func weight(from: Vertex, to: Vertex) throws -> Double? /** Adds a new weighted edge to the graph from one vertex to another. Changes the graph in-place to add the edge. - parameter from: The 'source' of the edge to use. - parameter to: The 'destination' of the edge to use. - parameter weight: The 'weight' of the new edge to add. - throws: `GraphError.VertexNotPresent` if either vertex in the edge does not exist in the graph. */ mutating func addEdge(from: Vertex, to: Vertex, weight: Double) throws } /** A weighted undirected graph protocol. This protocol is identical to a weighted graph, but it requires that the implementation of `edgeExists` be symmetric, i.e. edges go both ways. */ public protocol WeightedUndirectedGraph : WeightedGraph {} /** A weighted directed graph protocol. This protocol is idential to a weighted graph, but it requires that the implementation of `edgeExists` not be symmetric, i.e. edges go in only one direction */ public protocol WeightedDirectedGraph : WeightedGraph {} // Provides a default implementation for the `neighbors` function. public extension Graph { public init<V: CollectionType where V.Generator.Element == Vertex> (vertices: V) { self = Self() for vertex in vertices { let _ = try? addVertex(vertex) // I believe this is a no-op if it throws. } } public init<G: Graph where G.Vertex == Vertex>(graph: G) { self = Self(vertices: graph.vertices) for (from, to) in graph.edges { // For a properly implemented graph, the edges are all unique and // this will never throw. try! addEdge(from, to: to) } } public func neighbors(vertex: Vertex) throws -> [Vertex] { var neighbors: [Vertex] = [] for vertex2 in vertices { if try edgeExists(vertex, to: vertex2) { neighbors.append(vertex) } } return neighbors } } /** Gives the total weight of all edges in the graph. Useful for minimum spanning trees and setting an effectively infinite weight value in some graph algorithms. A default implementaion using the edges property and weight method is provided here. - returns: the sum of all of the edge weights in the graph, a Double. */ public extension WeightedGraph { public var totalWeight: Double { var result = 0.0 for (from, to) in edges { result += try! weight(from, to: to)! } return result } }
24493250d84c3eabedfd3bd3a6192931
28.313653
80
0.664527
false
false
false
false
masteranca/Flow
refs/heads/master
Flow/Request.swift
mit
1
// // Created by Anders Carlsson on 14/01/16. // Copyright (c) 2016 CoreDev. All rights reserved. // import Foundation public final class Request { private let task: NSURLSessionTask public var isRunning: Bool { return task.state == NSURLSessionTaskState.Running } public var isFinished: Bool { return task.state == NSURLSessionTaskState.Completed } public var isCanceling: Bool { return task.state == NSURLSessionTaskState.Canceling } init(task: NSURLSessionTask) { self.task = task } public func cancel() -> Request { task.cancel() return self } }
fb214385d1a16c0a331ccbb5ee853a44
19.3125
60
0.645609
false
false
false
false
JakobR/XML.swift
refs/heads/master
XML/XPath.swift
mit
1
import libxml2 /// Represents a compiled XPath expression public class XPath { private let ptr: xmlXPathCompExprPtr public init(_ expression: String, namespaces: [String:String] = [:]) throws { // TODO: Namespaces, variables, custom functions // (when adding this, we should probably re-use the XPathContext. (which makes this object very thread-unsafe, but then again, how thread-safe is the rest of this wrapper?)) // Solution for thread-unsafety: // Provide a "copy" method that copies the context. (the xmlXPathCompExpr should be able to be shared between different threads?) // This way the compilation only has to happen once even if someone needs multiple objects for different threads. // (Every thread can make a copy from the previously prepared "master" XPath object.) assert(namespaces.count == 0, "XPath.evaluateOn: Namespace mappings not yet implemented") let context: XPathContext do { context = try XPathContext() } catch let e { ptr = nil; throw e } // If only we could throw errors without initializing all properties first… ptr = xmlXPathCtxtCompile(context.ptr, expression) guard ptr != nil else { throw context.grabAndResetError() ?? XPathError(xmlError: nil) } } deinit { xmlXPathFreeCompExpr(ptr); } /// Evaluates the XPath query with the given node as context node. public func evaluateOn(node: Node) throws -> XPathResult { let context = try XPathContext(node: node) let obj = xmlXPathCompiledEval(ptr, context.ptr) guard obj != nil else { throw context.grabAndResetError() ?? XPathError(xmlError: nil) } return XPathResult(ptr: obj, onNode: node) } /// Evaluates the XPath query with the given document's root node as context node. public func evaluateOn(doc: Document) throws -> XPathResult { return try evaluateOn(doc.root) } } private class XPathContext { private let ptr: xmlXPathContextPtr private var error: XPathError? = nil private init(_doc: xmlDocPtr) throws { ptr = xmlXPathNewContext(_doc); guard ptr != nil else { throw Error.MemoryError } assert(ptr.memory.doc == _doc); // Set up error handling ptr.memory.userData = UnsafeMutablePointer<Void>(Unmanaged.passUnretained(self).toOpaque()) ptr.memory.error = { (userData, error: xmlErrorPtr) in assert(userData != nil) let context = Unmanaged<XPathContext>.fromOpaque(COpaquePointer(userData)).takeUnretainedValue() context.error = XPathError(xmlError: error, previous: context.error) } } /// Create an XPathContext with a NULL document. convenience init() throws { try self.init(_doc: nil); } convenience init(node: Node) throws { try self.init(_doc: node.doc.ptr) ptr.memory.node = node.ptr } deinit { xmlXPathFreeContext(ptr); } func grabAndResetError() -> XPathError? { defer { error = nil } return error } }
ec6b59f60cfade45c2be7194fd1a46dd
37.716049
181
0.655293
false
false
false
false
LeeMZC/MZCWB
refs/heads/master
MZCWB/MZCWB/Classes/Home-首页/Mode/MZCTimeDelegate.swift
artistic-2.0
1
// // MZCTimeDelegate.swift // MZCWB // // Created by 马纵驰 on 16/7/30. // Copyright © 2016年 马纵驰. All rights reserved. // import Foundation protocol MZCTimeDelegate { func handleRequest(time : NSDate) -> String } class MZCBaseTimer : MZCTimeDelegate { var formatterStr = "HH:mm" let calendar = NSCalendar.currentCalendar() private func timeString(dateFormat : String , date : NSDate) -> String { // 昨天 let formatter = NSDateFormatter() formatter.locale = NSLocale(localeIdentifier: "en") formatterStr = dateFormat + formatterStr formatter.dateFormat = formatterStr return formatter.stringFromDate(date) } var nextSuccessor: MZCTimeDelegate? func handleRequest(time : NSDate) -> String{ guard let t_nextSuccessor = nextSuccessor else { return "责任对象错误" } return t_nextSuccessor.handleRequest(time) } } //MARK:- 头 class MZCTimeHead: MZCBaseTimer{ } //MARK:- 当天 X小时前(当天) class MZCToday: MZCBaseTimer{ override func handleRequest(time : NSDate) -> String{ let interval = Int(NSDate().timeIntervalSinceDate(time)) if !calendar.isDateInToday(time) { return (self.nextSuccessor?.handleRequest(time))! } if interval < 60 { return "刚刚" }else if interval < 60 * 60 { return "\(interval / 60)分钟前" }else { return "\(interval / (60 * 60))小时前" } } } //MARK:- 昨天 HH:mm(昨天) class MZCYesterday: MZCBaseTimer{ override func handleRequest(time : NSDate) -> String{ if !calendar.isDateInYesterday(time) { return (self.nextSuccessor?.handleRequest(time))! } // 昨天 return self.timeString("昨天: ", date: time) } } //MARK:- MM-dd HH:mm(一年内) class MZCYear: MZCBaseTimer{ override func handleRequest(time : NSDate) -> String{ let comps = calendar.components(NSCalendarUnit.Year, fromDate: time, toDate: NSDate(), options: NSCalendarOptions(rawValue: 0)) if comps.year >= 1 { return (self.nextSuccessor?.handleRequest(time))! } return self.timeString("MM-dd ", date: time) } } //MARK:- yyyy-MM-dd HH:mm(更早期) class MZCYearAgo: MZCBaseTimer{ override func handleRequest(time : NSDate) -> String{ let comps = calendar.components(NSCalendarUnit.Year, fromDate: time, toDate: NSDate(), options: NSCalendarOptions(rawValue: 0)) if comps.year >= 1 { return self.timeString("yyyy-MM-dd ", date: time) } return (self.nextSuccessor?.handleRequest(time))! } } //MARK:- 尾 class MZCTimeEnd: MZCBaseTimer{ override func handleRequest(time : NSDate) ->String { return "无法获取到正确的时间" } }
2277524c3b17fe6904e100494b83d8b9
22.217054
136
0.577822
false
false
false
false
Karumi/KataTODOApiClientIOS
refs/heads/master
KataTODOAPIClientTests/AnyPublisher+Utils.swift
apache-2.0
1
import Combine import Nimble private extension DispatchTimeInterval { static var defaultGetTimeout: DispatchTimeInterval { .seconds(30) } } extension AnyPublisher { static var neverPublishing: Self { Future { _ in }.eraseToAnyPublisher() } static func fail(_ failure: Failure) -> Self { Fail(outputType: Output.self, failure: failure).eraseToAnyPublisher() } static func just(_ output: Output) -> Self { Just(output).setFailureType(to: Failure.self).eraseToAnyPublisher() } func get(timeout: DispatchTimeInterval = .defaultGetTimeout) throws -> [Output] { var subscriptions = Set<AnyCancellable>() var output: [Output] = [] var error: Error? waitUntil(timeout: timeout) { done in self.sink(receiveCompletion: { if case let .failure(receivedError) = $0 { error = receivedError } done() }, receiveValue: { value in output.append(value) }).store(in: &subscriptions) } if let err = error { throw err } return output } }
0e1dee262393e09f375ac41928f6526d
29.102564
85
0.584327
false
false
false
false
itsaboutcode/WordPress-iOS
refs/heads/develop
WordPress/WordPressTest/Classes/Stores/StatsPeriodStoreTests.swift
gpl-2.0
2
import WordPressKit import XCTest @testable import WordPress class StatsPeriodStoreTests: XCTestCase { private var sut: StatsPeriodStore! override func setUp() { super.setUp() sut = StatsPeriodStore() sut.statsServiceRemote = StatsServiceRemoteV2Mock(wordPressComRestApi: WordPressComRestApi(oAuthToken: nil, userAgent: nil), siteID: 123, siteTimezone: .autoupdatingCurrent) } override func tearDown() { sut = nil super.tearDown() } func testMarkReferrerAsSpam() { guard let firstURL = URL(string: "https://www.domain.com/test"), let secondURL = URL(string: "https://www.someotherdomain.com/test") else { XCTFail("Failed to create URLs") return } let referrerOne = StatsReferrer(title: "A title", viewsCount: 0, url: firstURL, iconURL: nil, children: []) let referrerTwo = StatsReferrer(title: "A title", viewsCount: 0, url: secondURL, iconURL: nil, children: []) sut.state.topReferrers = .init(period: .month, periodEndDate: Date(), referrers: [referrerOne, referrerTwo], totalReferrerViewsCount: 0, otherReferrerViewsCount: 0) sut.toggleSpamState(for: referrerOne.url?.host ?? "", currentValue: referrerOne.isSpam) XCTAssertTrue(sut.state.topReferrers!.referrers[0].isSpam) XCTAssertFalse(sut.state.topReferrers!.referrers[1].isSpam) } func testUnmarkReferrerAsSpam() { guard let firstURL = URL(string: "https://www.domain.com/test"), let secondURL = URL(string: "https://www.someotherdomain.com/test") else { XCTFail("Failed to create URLs") return } var referrerOne = StatsReferrer(title: "A title", viewsCount: 0, url: firstURL, iconURL: nil, children: []) referrerOne.isSpam = true let referrerTwo = StatsReferrer(title: "A title", viewsCount: 0, url: secondURL, iconURL: nil, children: []) sut.state.topReferrers = .init(period: .month, periodEndDate: Date(), referrers: [referrerOne, referrerTwo], totalReferrerViewsCount: 0, otherReferrerViewsCount: 0) sut.toggleSpamState(for: referrerOne.url?.host ?? "", currentValue: referrerOne.isSpam) XCTAssertFalse(sut.state.topReferrers!.referrers[0].isSpam) XCTAssertFalse(sut.state.topReferrers!.referrers[1].isSpam) } } private extension StatsPeriodStoreTests { class StatsServiceRemoteV2Mock: StatsServiceRemoteV2 { override func toggleSpamState(for referrerDomain: String, currentValue: Bool, success: @escaping () -> Void, failure: @escaping (Error) -> Void) { success() } } }
cc37ec55cbc294babd29d03c64d33b0e
42.370968
181
0.670509
false
true
false
false
fuku2014/swift-simple-matt-chat
refs/heads/master
MqttChat/src/HomeViewController.swift
mit
1
import UIKit import SpriteKit class HomeViewController: UIViewController, UITextFieldDelegate { private var roomTextField : UITextField! private var nameTextField : UITextField! private var submitButton : UIButton! override func viewDidLoad() { super.viewDidLoad() self.setComponents() } func setComponents() { self.title = "Home" self.view.backgroundColor = UIColor.whiteColor() // RoomID roomTextField = UITextField(frame: CGRectMake(0,0,self.view.frame.size.width,30)) roomTextField.delegate = self roomTextField.borderStyle = UITextBorderStyle.RoundedRect roomTextField.layer.position = CGPoint(x:self.view.bounds.width / 2, y:self.view.bounds.height / 2) roomTextField.returnKeyType = UIReturnKeyType.Done roomTextField.keyboardType = UIKeyboardType.Default roomTextField.placeholder = "Input Room Name" self.view.addSubview(roomTextField) // Name nameTextField = UITextField(frame: CGRectMake(0,0,self.view.frame.size.width,30)) nameTextField.delegate = self nameTextField.borderStyle = UITextBorderStyle.RoundedRect nameTextField.layer.position = CGPoint(x:self.view.bounds.width / 2, y:self.view.bounds.height / 2 - 50) nameTextField.returnKeyType = UIReturnKeyType.Done nameTextField.keyboardType = UIKeyboardType.Default nameTextField.placeholder = "Input Your Name" self.view.addSubview(nameTextField) // Button submitButton = UIButton(type: UIButtonType.Custom) submitButton.frame = CGRectMake(0, 0, 150, 40) submitButton.layer.masksToBounds = true submitButton.backgroundColor = UIColor.blueColor() submitButton.layer.cornerRadius = 20.0 submitButton.layer.position = CGPoint(x:self.view.bounds.width / 2, y:self.view.bounds.height / 2 + 50) submitButton.setTitle("Enter", forState: UIControlState.Normal) submitButton.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal) submitButton.setTitleColor(UIColor.grayColor(), forState: UIControlState.Disabled) submitButton.addTarget(self, action: "doEnter:", forControlEvents: UIControlEvents.TouchUpInside) submitButton.enabled = false self.view.addSubview(submitButton) } func doEnter(sender: UIButton) { let chatViewController = ChatViewController() chatViewController.roomName = self.roomTextField.text! chatViewController.userName = self.nameTextField.text! self.navigationController?.pushViewController(chatViewController, animated: true) } // UITextFieldDelegate func textFieldShouldReturn(textField: UITextField) -> Bool { textField.resignFirstResponder() return true } // UITextFieldDelegate func textFieldShouldEndEditing(textField: UITextField) -> Bool { submitButton.enabled = !roomTextField.text!.isEmpty && !nameTextField.text!.isEmpty return true } override func prefersStatusBarHidden() -> Bool { return true } }
6ca0931f6e9e7ceba5fe6732765ebaf0
42.986667
116
0.668687
false
false
false
false
lysongzi/iOS-Demon
refs/heads/master
Swift/SwiftDemon/SwiftDemon/Shape.swift
mit
1
// // myClass.swift // SwiftDemon // // Created by lysongzi on 16/1/29. // Copyright © 2016年 lysongzi. All rights reserved. // import Foundation class Shape { var height : Double = 0.0 var width : Double = 0.0 var area : Double{ get { return height * width } set { self.area = height * width } } init(h: Double, w :Double) { self.height = h self.width = w } func Description() -> String { return "Height = \(self.height), Width = \(self.width)" } }
f30a65389646aa193e6067d7d385e20a
15.184211
63
0.480456
false
false
false
false
arikis/Overdrive
refs/heads/master
Tests/OverdriveTests/DependencyTests.swift
mit
1
// // DependencyTests.swift // Overdrive // // Created by Said Sikira on 6/23/16. // Copyright © 2016 Said Sikira. All rights reserved. // import XCTest @testable import Overdrive class DependencyTests: TestCase { /// Test `addDependency(_:)` method func testDependencyAdd() { let testTask = Task<Int>() let dependencyTask = Task<String>() testTask.add(dependency: dependencyTask) XCTAssertEqual(testTask.dependencies.count, 1) } /// Tests `getDependency(_:)` method func testGetDependency() { let testTask = Task<Int>() let dependencyTask = Task<String>() dependencyTask.name = "DependencyTask" testTask.add(dependency: dependencyTask) let dependencies = testTask.get(dependency: type(of: dependencyTask)) XCTAssertEqual(dependencies[0].name, "DependencyTask") } func testRemoveValidDependency() { let task = Task<Int>() let dependency = Task<String>() task.add(dependency: dependency) let status = task.remove(dependency: dependency) XCTAssertEqual(status, true) XCTAssertEqual(task.dependencies.count, 0) } func testRemoveDependencyWithType() { let task = Task<Int>() let dependency = Task<String>() task.add(dependency: dependency) task.remove(dependency: type(of: dependency)) // XCTAssertEqual(status, true) XCTAssertEqual(task.dependencies.count, 0) } func testRemoveUnknownDependencyWithType() { let task = Task<Int>() let dependency = Task<String>() task.add(dependency: dependency) task.remove(dependency: Task<Double>.self) XCTAssertEqual(task.dependencies.count, 1) } func testOrderOfExecution() { let testExpecation = expectation(description: "Dependency order of execution test expectation") var results: [Result<Int>] = [] func add(result: Result<Int>) { dispatchQueue.sync { results.append(result) } } let firstTask = anyTask(withResult: .value(1)) let secondTask = anyTask(withResult: .value(2)) let thirdTask = anyTask(withResult: .value(3)) thirdTask.add(dependency: secondTask) secondTask.add(dependency: firstTask) firstTask.onValue { add(result: .value($0)) } secondTask.onValue { add(result: .value($0)) } thirdTask.onValue { add(result: .value($0)) testExpecation.fulfill() XCTAssertEqual(results[0].value, 1) XCTAssertEqual(results[1].value, 2) XCTAssertEqual(results[2].value, 3) } let queue = TaskQueue(qos: .utility) queue.add(task: thirdTask) queue.add(task: secondTask) queue.add(task: firstTask) waitForExpectations(timeout: 1, handler: nil) } }
ee4dfc890eec424397b3f7ff3802da52
27.472727
103
0.579502
false
true
false
false
wordpress-mobile/WordPress-iOS
refs/heads/trunk
WordPress/Classes/Stores/StatsWidgetsStore.swift
gpl-2.0
1
import WidgetKit import WordPressAuthenticator class StatsWidgetsStore { private let blogService: BlogService init(blogService: BlogService = BlogService(managedObjectContext: ContextManager.shared.mainContext)) { self.blogService = blogService observeAccountChangesForWidgets() observeAccountSignInForWidgets() observeApplicationLaunched() } /// Refreshes the site list used to configure the widgets when sites are added or deleted @objc func refreshStatsWidgetsSiteList() { initializeStatsWidgetsIfNeeded() if let newTodayData = refreshStats(type: HomeWidgetTodayData.self) { HomeWidgetTodayData.write(items: newTodayData) if #available(iOS 14.0, *) { WidgetCenter.shared.reloadTimelines(ofKind: AppConfiguration.Widget.Stats.todayKind) } } if let newAllTimeData = refreshStats(type: HomeWidgetAllTimeData.self) { HomeWidgetAllTimeData.write(items: newAllTimeData) if #available(iOS 14.0, *) { WidgetCenter.shared.reloadTimelines(ofKind: AppConfiguration.Widget.Stats.allTimeKind) } } if let newThisWeekData = refreshStats(type: HomeWidgetThisWeekData.self) { HomeWidgetThisWeekData.write(items: newThisWeekData) if #available(iOS 14.0, *) { WidgetCenter.shared.reloadTimelines(ofKind: AppConfiguration.Widget.Stats.thisWeekKind) } } } /// Initialize the local cache for widgets, if it does not exist func initializeStatsWidgetsIfNeeded() { guard #available(iOS 14.0, *) else { return } if HomeWidgetTodayData.read() == nil { DDLogInfo("StatsWidgets: Writing initialization data into HomeWidgetTodayData.plist") HomeWidgetTodayData.write(items: initializeHomeWidgetData(type: HomeWidgetTodayData.self)) WidgetCenter.shared.reloadTimelines(ofKind: AppConfiguration.Widget.Stats.todayKind) } if HomeWidgetThisWeekData.read() == nil { DDLogInfo("StatsWidgets: Writing initialization data into HomeWidgetThisWeekData.plist") HomeWidgetThisWeekData.write(items: initializeHomeWidgetData(type: HomeWidgetThisWeekData.self)) WidgetCenter.shared.reloadTimelines(ofKind: AppConfiguration.Widget.Stats.thisWeekKind) } if HomeWidgetAllTimeData.read() == nil { DDLogInfo("StatsWidgets: Writing initialization data into HomeWidgetAllTimeData.plist") HomeWidgetAllTimeData.write(items: initializeHomeWidgetData(type: HomeWidgetAllTimeData.self)) WidgetCenter.shared.reloadTimelines(ofKind: AppConfiguration.Widget.Stats.allTimeKind) } } /// Store stats in the widget cache /// - Parameters: /// - widgetType: concrete type of the widget /// - stats: stats to be stored func storeHomeWidgetData<T: HomeWidgetData>(widgetType: T.Type, stats: Codable) { guard #available(iOS 14.0, *), let siteID = SiteStatsInformation.sharedInstance.siteID else { return } var homeWidgetCache = T.read() ?? initializeHomeWidgetData(type: widgetType) guard let oldData = homeWidgetCache[siteID.intValue] else { DDLogError("StatsWidgets: Failed to find a matching site") return } guard let blog = Blog.lookup(withID: siteID, in: ContextManager.shared.mainContext) else { DDLogError("StatsWidgets: the site does not exist anymore") // if for any reason that site does not exist anymore, remove it from the cache. homeWidgetCache.removeValue(forKey: siteID.intValue) T.write(items: homeWidgetCache) return } var widgetKind = "" if widgetType == HomeWidgetTodayData.self, let stats = stats as? TodayWidgetStats { widgetKind = AppConfiguration.Widget.Stats.todayKind homeWidgetCache[siteID.intValue] = HomeWidgetTodayData(siteID: siteID.intValue, siteName: blog.title ?? oldData.siteName, url: blog.url ?? oldData.url, timeZone: blog.timeZone, date: Date(), stats: stats) as? T } else if widgetType == HomeWidgetAllTimeData.self, let stats = stats as? AllTimeWidgetStats { widgetKind = AppConfiguration.Widget.Stats.allTimeKind homeWidgetCache[siteID.intValue] = HomeWidgetAllTimeData(siteID: siteID.intValue, siteName: blog.title ?? oldData.siteName, url: blog.url ?? oldData.url, timeZone: blog.timeZone, date: Date(), stats: stats) as? T } else if widgetType == HomeWidgetThisWeekData.self, let stats = stats as? ThisWeekWidgetStats { homeWidgetCache[siteID.intValue] = HomeWidgetThisWeekData(siteID: siteID.intValue, siteName: blog.title ?? oldData.siteName, url: blog.url ?? oldData.url, timeZone: blog.timeZone, date: Date(), stats: stats) as? T } T.write(items: homeWidgetCache) WidgetCenter.shared.reloadTimelines(ofKind: widgetKind) } } // MARK: - Helper methods private extension StatsWidgetsStore { // creates a list of days from the current date with empty stats to avoid showing an empty widget preview var initializedWeekdays: [ThisWeekWidgetDay] { var days = [ThisWeekWidgetDay]() for index in 0...7 { days.insert(ThisWeekWidgetDay(date: NSCalendar.current.date(byAdding: .day, value: -index, to: Date()) ?? Date(), viewsCount: 0, dailyChangePercent: 0), at: index) } return days } func refreshStats<T: HomeWidgetData>(type: T.Type) -> [Int: T]? { guard let currentData = T.read() else { return nil } let updatedSiteList = (try? BlogQuery().visible(true).hostedByWPCom(true).blogs(in: blogService.managedObjectContext)) ?? [] let newData = updatedSiteList.reduce(into: [Int: T]()) { sitesList, site in guard let blogID = site.dotComID else { return } let existingSite = currentData[blogID.intValue] let siteURL = site.url ?? existingSite?.url ?? "" let siteName = (site.title ?? siteURL).isEmpty ? siteURL : site.title ?? siteURL var timeZone = existingSite?.timeZone ?? TimeZone.current if let blog = Blog.lookup(withID: blogID, in: ContextManager.shared.mainContext) { timeZone = blog.timeZone } let date = existingSite?.date ?? Date() if type == HomeWidgetTodayData.self { let stats = (existingSite as? HomeWidgetTodayData)?.stats ?? TodayWidgetStats() sitesList[blogID.intValue] = HomeWidgetTodayData(siteID: blogID.intValue, siteName: siteName, url: siteURL, timeZone: timeZone, date: date, stats: stats) as? T } else if type == HomeWidgetAllTimeData.self { let stats = (existingSite as? HomeWidgetAllTimeData)?.stats ?? AllTimeWidgetStats() sitesList[blogID.intValue] = HomeWidgetAllTimeData(siteID: blogID.intValue, siteName: siteName, url: siteURL, timeZone: timeZone, date: date, stats: stats) as? T } else if type == HomeWidgetThisWeekData.self { let stats = (existingSite as? HomeWidgetThisWeekData)?.stats ?? ThisWeekWidgetStats(days: initializedWeekdays) sitesList[blogID.intValue] = HomeWidgetThisWeekData(siteID: blogID.intValue, siteName: siteName, url: siteURL, timeZone: timeZone, date: date, stats: stats) as? T } } return newData } func initializeHomeWidgetData<T: HomeWidgetData>(type: T.Type) -> [Int: T] { let blogs = (try? BlogQuery().visible(true).hostedByWPCom(true).blogs(in: blogService.managedObjectContext)) ?? [] return blogs.reduce(into: [Int: T]()) { result, element in if let blogID = element.dotComID, let url = element.url, let blog = Blog.lookup(withID: blogID, in: ContextManager.shared.mainContext) { // set the title to the site title, if it's not nil and not empty; otherwise use the site url let title = (element.title ?? url).isEmpty ? url : element.title ?? url let timeZone = blog.timeZone if type == HomeWidgetTodayData.self { result[blogID.intValue] = HomeWidgetTodayData(siteID: blogID.intValue, siteName: title, url: url, timeZone: timeZone, date: Date(timeIntervalSinceReferenceDate: 0), stats: TodayWidgetStats()) as? T } else if type == HomeWidgetAllTimeData.self { result[blogID.intValue] = HomeWidgetAllTimeData(siteID: blogID.intValue, siteName: title, url: url, timeZone: timeZone, date: Date(timeIntervalSinceReferenceDate: 0), stats: AllTimeWidgetStats()) as? T } else if type == HomeWidgetThisWeekData.self { result[blogID.intValue] = HomeWidgetThisWeekData(siteID: blogID.intValue, siteName: title, url: url, timeZone: timeZone, date: Date(timeIntervalSinceReferenceDate: 0), stats: ThisWeekWidgetStats(days: initializedWeekdays)) as? T } } } } } // MARK: - Extract this week data extension StatsWidgetsStore { func updateThisWeekHomeWidget(summary: StatsSummaryTimeIntervalData?) { guard #available(iOS 14.0, *) else { return } switch summary?.period { case .day: guard summary?.periodEndDate == StatsDataHelper.currentDateForSite().normalizedDate() else { return } let summaryData = Array(summary?.summaryData.reversed().prefix(ThisWeekWidgetStats.maxDaysToDisplay + 1) ?? []) let stats = ThisWeekWidgetStats(days: ThisWeekWidgetStats.daysFrom(summaryData: summaryData)) StoreContainer.shared.statsWidgets.storeHomeWidgetData(widgetType: HomeWidgetThisWeekData.self, stats: stats) case .week: WidgetCenter.shared.reloadTimelines(ofKind: AppConfiguration.Widget.Stats.thisWeekKind) default: break } } } // MARK: - Login/Logout notifications private extension StatsWidgetsStore { /// Observes WPAccountDefaultWordPressComAccountChanged notification and reloads widget data based on the state of account. /// The site data is not yet loaded after this notification and widget data cannot be cached for newly signed in account. func observeAccountChangesForWidgets() { guard #available(iOS 14.0, *) else { return } NotificationCenter.default.addObserver(forName: .WPAccountDefaultWordPressComAccountChanged, object: nil, queue: nil) { notification in UserDefaults(suiteName: WPAppGroupName)?.setValue(AccountHelper.isLoggedIn, forKey: AppConfiguration.Widget.Stats.userDefaultsLoggedInKey) if !AccountHelper.isLoggedIn { HomeWidgetTodayData.delete() HomeWidgetThisWeekData.delete() HomeWidgetAllTimeData.delete() WidgetCenter.shared.reloadTimelines(ofKind: AppConfiguration.Widget.Stats.todayKind) WidgetCenter.shared.reloadTimelines(ofKind: AppConfiguration.Widget.Stats.thisWeekKind) WidgetCenter.shared.reloadTimelines(ofKind: AppConfiguration.Widget.Stats.allTimeKind) } } } /// Observes WPSigninDidFinishNotification notification and initializes the widget. /// The site data is loaded after this notification and widget data can be cached. func observeAccountSignInForWidgets() { guard #available(iOS 14.0, *) else { return } NotificationCenter.default.addObserver(forName: NSNotification.Name(rawValue: WordPressAuthenticator.WPSigninDidFinishNotification), object: nil, queue: nil) { [weak self] _ in self?.initializeStatsWidgetsIfNeeded() } } /// Observes applicationLaunchCompleted notification and runs migration. func observeApplicationLaunched() { guard #available(iOS 14.0, *) else { return } NotificationCenter.default.addObserver(forName: NSNotification.Name.applicationLaunchCompleted, object: nil, queue: nil) { [weak self] _ in self?.handleJetpackWidgetsMigration() } } } private extension StatsWidgetsStore { /// Handles migration to a Jetpack app version that started supporting Stats widgets. /// The required flags in shared UserDefaults are set and widgets are initialized. func handleJetpackWidgetsMigration() { // If user is logged in but defaultSiteIdKey is not set guard let account = try? WPAccount.lookupDefaultWordPressComAccount(in: blogService.managedObjectContext), let siteId = account.defaultBlog?.dotComID, let userDefaults = UserDefaults(suiteName: WPAppGroupName), userDefaults.value(forKey: AppConfiguration.Widget.Stats.userDefaultsSiteIdKey) == nil else { return } userDefaults.setValue(AccountHelper.isLoggedIn, forKey: AppConfiguration.Widget.Stats.userDefaultsLoggedInKey) userDefaults.setValue(siteId, forKey: AppConfiguration.Widget.Stats.userDefaultsSiteIdKey) initializeStatsWidgetsIfNeeded() } } extension StatsViewController { @objc func initializeStatsWidgetsIfNeeded() { StoreContainer.shared.statsWidgets.initializeStatsWidgetsIfNeeded() } } extension BlogListViewController { @objc func refreshStatsWidgetsSiteList() { StoreContainer.shared.statsWidgets.refreshStatsWidgetsSiteList() } }
9a98d5f20078b6b7a0ff4ab2276f49da
48.05949
150
0.533433
false
false
false
false
Shvier/Dota2Helper
refs/heads/master
Dota2Helper/Dota2Helper/Main/Setting/View/DHSDKTableViewCell.swift
apache-2.0
1
// // DHSDKTableViewCell.swift // Dota2Helper // // Created by Shvier on 10/20/16. // Copyright © 2016 Shvier. All rights reserved. // import UIKit class DHSDKTableViewCell: DHBaseTableViewCell { let kSDKNameLabelFontSize: CGFloat = 15 let kSDKNameLabelOffsetTop: CGFloat = 5 let kSDKNameLabelOffsetLeft: CGFloat = 12 let kAuthorNameLabelFontSize: CGFloat = 12 let kAuthorNameLabelOffsetTop: CGFloat = 5 var sdkNameLabel: UILabel! var authorNameLabel: UILabel! // MARK: - Life Cycle override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) self.initUI() self.makeConstraints() } func initUI() { self.accessoryType = .disclosureIndicator sdkNameLabel = ({ let label = UILabel() label.font = UIFont.systemFont(ofSize: kSDKNameLabelFontSize) label.textAlignment = .left label.preferredMaxLayoutWidth = kScreenWidth label.text = "(null)" return label }()) contentView.addSubview(sdkNameLabel) authorNameLabel = ({ let label = UILabel() label.font = UIFont.systemFont(ofSize: kAuthorNameLabelFontSize) label.textAlignment = .left label.preferredMaxLayoutWidth = kScreenWidth label.textColor = .gray label.text = "(null)" return label }()) contentView.addSubview(authorNameLabel) } func makeConstraints() { sdkNameLabel.snp.makeConstraints { (make) in make.left.equalTo(contentView).offset(kSDKNameLabelOffsetLeft) make.top.equalTo(contentView).offset(kSDKNameLabelOffsetTop) } authorNameLabel.snp.makeConstraints { (make) in make.left.equalTo(sdkNameLabel) make.top.equalTo(sdkNameLabel.snp.lastBaseline).offset(kAuthorNameLabelOffsetTop) } } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func awakeFromNib() { super.awakeFromNib() } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) } }
0bac0c5f561fba4e6d8789057ee32f67
28.961538
93
0.627728
false
false
false
false