repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Sephiroth87/C-swifty4
|
C64/Utils/BinaryConvertible.swift
|
1
|
6083
|
//
// BinaryConvertible.swift
// C64
//
// Created by Fabio Ritrovato on 06/06/2016.
// Copyright © 2016 orange in a day. All rights reserved.
//
class BinaryDump {
private let data: ArraySlice<UInt8>
private var offset = 0
convenience init(data: [UInt8]) {
self.init(data: ArraySlice(data))
}
init(data: ArraySlice<UInt8>) {
self.data = data
self.offset = data.startIndex
}
func nextByte() -> UInt8 {
let item = data[offset]
offset += 1
return item
}
func next() -> UInt8 {
return nextByte()
}
func next<T: BinaryConvertible>() -> T {
let item = T.extract(BinaryDump(data: data.suffix(from: offset)))
offset += Int(item.binarySize)
return item
}
func next<T: BinaryConvertible>(_ numberOfItems: Int) -> [T] {
return (0..<numberOfItems).map { _ -> T in
next()
}
}
}
protocol BinaryDumpable {
func dump() -> [UInt8]
var binarySize: UInt { get }
}
protocol BinaryConvertible: BinaryDumpable {
static func extract(_ binaryDump: BinaryDump) -> Self
}
extension BinaryConvertible {
func dump() -> [UInt8] {
let m = Mirror(reflecting: self)
var out = [UInt8]()
m.children.forEach { label, value in
if let value = value as? BinaryDumpable {
out.append(contentsOf: value.dump())
} else {
print("Skipping \(String(describing: label))")
}
}
return out
}
var binarySize: UInt {
let m = Mirror(reflecting: self)
return m.children.compactMap {
$0.value as? BinaryDumpable
}.map {
$0.binarySize
}.reduce(0, +)
}
}
extension Array: BinaryDumpable {
func dump() -> [UInt8] {
return compactMap { $0 as? BinaryDumpable }.flatMap { $0.dump() }
}
var binarySize: UInt {
return compactMap { $0 as? BinaryDumpable }.reduce(0) { $0 + $1.binarySize }
}
}
extension UInt8: BinaryConvertible {
func dump() -> [UInt8] {
return [self]
}
var binarySize: UInt {
return 1
}
static func extract(_ binaryDump: BinaryDump) -> UInt8 {
return binaryDump.next()
}
}
extension UInt16: BinaryConvertible {
func dump() -> [UInt8] {
return [UInt8(truncatingIfNeeded: self >> 8), UInt8(truncatingIfNeeded: self)]
}
var binarySize: UInt {
return 2
}
static func extract(_ binaryDump: BinaryDump) -> UInt16 {
return UInt16(binaryDump.next()) << 8 | UInt16(binaryDump.next())
}
}
extension UInt32: BinaryConvertible {
func dump() -> [UInt8] {
return (0...3).map {
UInt8(truncatingIfNeeded: self >> ($0 * 8))
}.reversed()
}
var binarySize: UInt {
return 4
}
static func extract(_ binaryDump: BinaryDump) -> UInt32 {
return (0...3).reversed().reduce(0) { (v: UInt32, i: Int) -> UInt32 in
return v | UInt32(binaryDump.nextByte()) << UInt32(i * 8)
}
}
}
extension Int8: BinaryConvertible {
func dump() -> [UInt8] {
return [UInt8(bitPattern: self)]
}
var binarySize: UInt {
return 1
}
static func extract(_ binaryDump: BinaryDump) -> Int8 {
return Int8(bitPattern: binaryDump.next())
}
}
extension Int: BinaryConvertible {
func dump() -> [UInt8] {
return (0...7).map {
UInt8(truncatingIfNeeded: self >> ($0 * 8))
}.reversed()
}
var binarySize: UInt {
return 8
}
static func extract(_ binaryDump: BinaryDump) -> Int {
return (0...7).reversed().reduce(0) { (v: Int, i: Int) -> Int in
return v | Int(binaryDump.nextByte()) << Int(i * 8)
}
}
}
extension Bool: BinaryConvertible {
func dump() -> [UInt8] {
return [self ? 1 : 0]
}
var binarySize: UInt {
return 1
}
static func extract(_ binaryDump: BinaryDump) -> Bool {
return binaryDump.nextByte() > 0 ? true : false
}
}
extension FixedArray8: BinaryDumpable where T: BinaryDumpable {
func dump() -> [UInt8] {
return flatMap { $0.dump() }
}
var binarySize: UInt {
return reduce(0) { $0 + $1.binarySize }
}
}
extension FixedArray8: BinaryConvertible where T: BinaryConvertible {
static func extract(_ binaryDump: BinaryDump) -> FixedArray8<T> {
return FixedArray8<T>(values: (binaryDump.next(), binaryDump.next(), binaryDump.next(), binaryDump.next(), binaryDump.next(), binaryDump.next(), binaryDump.next(), binaryDump.next()))
}
}
extension FixedArray40: BinaryDumpable where T: BinaryDumpable {
func dump() -> [UInt8] {
return flatMap { $0.dump() }
}
var binarySize: UInt {
return reduce(0) { $0 + $1.binarySize }
}
}
extension FixedArray40: BinaryConvertible where T: BinaryConvertible {
static func extract(_ binaryDump: BinaryDump) -> FixedArray40<T> {
return FixedArray40<T>(values: (binaryDump.next(), binaryDump.next(), binaryDump.next(), binaryDump.next(), binaryDump.next(), binaryDump.next(), binaryDump.next(), binaryDump.next(), binaryDump.next(), binaryDump.next(), binaryDump.next(), binaryDump.next(), binaryDump.next(), binaryDump.next(), binaryDump.next(), binaryDump.next(), binaryDump.next(), binaryDump.next(), binaryDump.next(), binaryDump.next(), binaryDump.next(), binaryDump.next(), binaryDump.next(), binaryDump.next(), binaryDump.next(), binaryDump.next(), binaryDump.next(), binaryDump.next(), binaryDump.next(), binaryDump.next(), binaryDump.next(), binaryDump.next(), binaryDump.next(), binaryDump.next(), binaryDump.next(), binaryDump.next(), binaryDump.next(), binaryDump.next(), binaryDump.next(), binaryDump.next()))
}
}
|
mit
|
a8c49b1f6f2f9171b10f634c9a73905d
| 24.341667 | 800 | 0.571851 | 3.873885 | false | false | false | false |
lzpfmh/actor-platform
|
actor-apps/app-ios/ActorApp/View/Managed/ACManagedTable.swift
|
1
|
16008
|
//
// Copyright (c) 2014-2015 Actor LLC. <https://actor.im>
//
import Foundation
class ACManagedTable {
//------------------------------------------------------------------------//
// Controller of table
let controller: UIViewController
// Table view
let style: ACContentTableStyle
let tableView: UITableView
var tableViewDelegate: UITableViewDelegate { get { return baseDelegate } }
var tableViewDataSource: UITableViewDataSource { get { return baseDelegate } }
// Scrolling closure
var tableScrollClosure: ((tableView: UITableView) -> ())?
// Is fade in/out animated
var fadeShowing = false
// Sections of table
var sections: [ACManagedSection] = [ACManagedSection]()
// Is Table in editing mode
var isEditing: Bool {
get {
return tableView.editing
}
}
// Is updating sections
private var isUpdating = false
// Reference to table view delegate/data source
private var baseDelegate: AMBaseTableDelegate!
// Search
private var isSearchInited: Bool = false
private var isSearchAutoHide: Bool = false
private var searchDisplayController: UISearchDisplayController!
private var searchManagedController: AnyObject!
//------------------------------------------------------------------------//
init(style: ACContentTableStyle, tableView: UITableView, controller: UIViewController) {
self.style = style
self.controller = controller
self.tableView = tableView
self.baseDelegate = tableView.style == .Plain ? AMPlainTableDelegate(data: self) : AMGrouppedTableDelegate(data: self)
// Init table view
self.tableView.dataSource = self.baseDelegate
self.tableView.delegate = self.baseDelegate
}
//------------------------------------------------------------------------//
// Entry point to adding
func beginUpdates() {
if isUpdating {
fatalError("Already updating table")
}
isUpdating = true
}
func addSection(autoSeparator: Bool = false) -> ACManagedSection {
if !isUpdating {
fatalError("Table is not in updating mode")
}
let res = ACManagedSection(table: self, index: sections.count)
res.autoSeparators = autoSeparator
sections.append(res)
return res
}
func search<C where C: ACBindedSearchCell, C: UITableViewCell>(cell: C.Type, closure: (s: ACManagedSearchConfig<C>) -> ()) {
if !isUpdating {
fatalError("Table is not in updating mode")
}
if isSearchInited {
fatalError("Search already inited")
}
isSearchInited = true
// Configuring search source
let config = ACManagedSearchConfig<C>()
closure(s: config)
// Creating search source
let searchSource = ACManagedSearchController<C>(config: config, controller: controller, tableView: tableView)
self.searchDisplayController = searchSource.searchDisplay
self.searchManagedController = searchSource
self.isSearchAutoHide = config.isSearchAutoHide
}
func endUpdates() {
if !isUpdating {
fatalError("Table is not in editable mode")
}
isUpdating = false
}
// Reloading table
func reload() {
self.tableView.reloadData()
}
func reload(section: Int) {
self.tableView.reloadSections(NSIndexSet(index: section), withRowAnimation: .Automatic)
}
// Binding methods
func bind(binder: Binder) {
for s in sections {
s.bind(self, binder: binder)
}
}
func unbind(binder: Binder) {
for s in sections {
s.unbind(self, binder: binder)
}
}
// Show/hide table
func showTable() {
if isUpdating || !fadeShowing {
self.tableView.alpha = 1
} else {
UIView.animateWithDuration(0.3, animations: { () -> Void in
self.tableView.alpha = 1
})
}
}
func hideTable() {
if isUpdating || !fadeShowing {
self.tableView.alpha = 0
} else {
UIView.animateWithDuration(0.3, animations: { () -> Void in
self.tableView.alpha = 0
})
}
}
// Controller callbacks
func controllerViewWillDisappear(animated: Bool) {
// Auto close search on leaving controller
if isSearchAutoHide {
//dispatchOnUi { () -> Void in
searchDisplayController?.setActive(false, animated: false)
//}
}
}
func controllerViewDidDisappear(animated: Bool) {
// Auto close search on leaving controller
// searchDisplayController?.setActive(false, animated: animated)
}
func controllerViewWillAppear(animated: Bool) {
// Search bar dissapear fixing
// Hack No 1
if searchDisplayController != nil {
let searchBar = searchDisplayController!.searchBar
let superView = searchBar.superview
if !(superView is UITableView) {
searchBar.removeFromSuperview()
superView?.addSubview(searchBar)
}
}
// Hack No 2
tableView.tableHeaderView?.setNeedsLayout()
tableView.tableFooterView?.setNeedsLayout()
// Status bar styles
if (searchDisplayController != nil && searchDisplayController!.active) {
// If search is active: apply search status bar style
MainAppTheme.search.applyStatusBar()
} else {
// If search is not active: apply main status bar style
MainAppTheme.navigation.applyStatusBar()
}
}
}
// Closure based extension
extension ACManagedTable {
func section(closure: (s: ACManagedSection) -> ()){
closure(s: addSection(true))
}
}
// Table view delegates and data sources
private class AMPlainTableDelegate: AMBaseTableDelegate {
@objc func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return CGFloat(data.sections[section].headerHeight)
}
@objc func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return CGFloat(data.sections[section].footerHeight)
}
@objc func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
if (data.sections[section].headerText == nil) {
return UIView()
} else {
return nil
}
}
@objc func tableView(tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
if (data.sections[section].footerText == nil) {
return UIView()
} else {
return nil
}
}
}
private class AMGrouppedTableDelegate: AMBaseTableDelegate {
func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
let header: UITableViewHeaderFooterView = view as! UITableViewHeaderFooterView
header.textLabel!.textColor = MainAppTheme.list.sectionColor
}
func tableView(tableView: UITableView, willDisplayFooterView view: UIView, forSection section: Int) {
let header: UITableViewHeaderFooterView = view as! UITableViewHeaderFooterView
header.textLabel!.textColor = MainAppTheme.list.sectionHintColor
}
}
private class AMBaseTableDelegate: NSObject, UITableViewDelegate, UITableViewDataSource, UIScrollViewDelegate {
unowned private let data: ACManagedTable
init(data: ACManagedTable) {
self.data = data
}
@objc func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return data.sections.count
}
@objc func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data.sections[section].numberOfItems(data)
}
@objc func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
return data.sections[indexPath.section].cellForItem(data, indexPath: indexPath)
}
@objc func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
let text = data.sections[section].headerText
if text != nil {
return localized(text!)
} else {
return text
}
}
@objc func tableView(tableView: UITableView, titleForFooterInSection section: Int) -> String? {
let text = data.sections[section].footerText
if text != nil {
return localized(text!)
} else {
return text
}
}
@objc func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return data.sections[indexPath.section].cellHeightForItem(data, indexPath: indexPath)
}
@objc func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return data.sections[indexPath.section].canDelete(data, indexPath: indexPath)
}
@objc func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return false
}
@objc func tableView(tableView: UITableView, editingStyleForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCellEditingStyle {
return data.sections[indexPath.section].canDelete(data, indexPath: indexPath) ? .Delete : .None
}
@objc func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
return data.sections[indexPath.section].delete(data, indexPath: indexPath)
}
@objc func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let section = data.sections[indexPath.section]
if section.canSelect(data, indexPath: indexPath) {
if section.select(data, indexPath: indexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
} else {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
}
@objc func tableView(tableView: UITableView, canPerformAction action: Selector, forRowAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject?) -> Bool {
if action == "copy:" {
let section = data.sections[indexPath.section]
return section.canCopy(data, indexPath: indexPath)
}
return false
}
@objc func tableView(tableView: UITableView, shouldShowMenuForRowAtIndexPath indexPath: NSIndexPath) -> Bool {
let section = data.sections[indexPath.section]
return section.canCopy(data, indexPath: indexPath)
}
@objc func tableView(tableView: UITableView, performAction action: Selector, forRowAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject?) {
if action == "copy:" {
let section = data.sections[indexPath.section]
if section.canCopy(data, indexPath: indexPath) {
section.copy(data, indexPath: indexPath)
}
}
}
@objc func scrollViewDidScroll(scrollView: UIScrollView) {
if (data.tableView == scrollView) {
data.tableScrollClosure?(tableView: data.tableView)
}
}
}
class ACManagedSearchConfig<BindCell where BindCell: ACBindedSearchCell, BindCell: UITableViewCell> {
var searchList: ARBindedDisplayList!
var selectAction: ((BindCell.BindData) -> ())?
var isSearchAutoHide: Bool = true
var didBind: ((c: BindCell, d: BindCell.BindData) -> ())?
}
class ACManagedSearchController<BindCell where BindCell: ACBindedSearchCell, BindCell: UITableViewCell>: NSObject, UISearchBarDelegate, UISearchDisplayDelegate, UITableViewDataSource, UITableViewDelegate, ARDisplayList_Listener {
let config: ACManagedSearchConfig<BindCell>
let displayList: ARBindedDisplayList
let searchDisplay: UISearchDisplayController
init(config: ACManagedSearchConfig<BindCell>, controller: UIViewController, tableView: UITableView) {
self.config = config
self.displayList = config.searchList
let searchBar = UISearchBar()
MainAppTheme.search.styleSearchBar(searchBar)
self.searchDisplay = UISearchDisplayController(searchBar: searchBar, contentsController: controller)
super.init()
// Creating Search Display Controller
self.searchDisplay.searchBar.delegate = self
self.searchDisplay.searchResultsDataSource = self
self.searchDisplay.searchResultsDelegate = self
self.searchDisplay.delegate = self
// Styling search list
self.searchDisplay.searchResultsTableView.separatorStyle = UITableViewCellSeparatorStyle.None
self.searchDisplay.searchResultsTableView.backgroundColor = MainAppTheme.list.bgColor
// Adding search to table header
let header = TableViewHeader(frame: CGRectMake(0, 0, 320, 44))
header.addSubview(self.searchDisplay.searchBar)
tableView.tableHeaderView = header
// Start receiving events
self.displayList.addListener(self)
}
// Model
func objectAtIndexPath(indexPath: NSIndexPath) -> BindCell.BindData {
return displayList.itemWithIndex(jint(indexPath.row)) as! BindCell.BindData
}
func onCollectionChanged() {
searchDisplay.searchResultsTableView.reloadData()
}
// Table view data
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return Int(displayList.size());
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
let item = objectAtIndexPath(indexPath)
return BindCell.self.bindedCellHeight(item)
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let item = objectAtIndexPath(indexPath)
let cell = tableView.dequeueCell(BindCell.self, indexPath: indexPath) as! BindCell
cell.bind(item, search: nil)
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let item = objectAtIndexPath(indexPath)
config.selectAction!(item)
MainAppTheme.navigation.applyStatusBar()
}
// Search updating
func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
let normalized = searchText.trim().lowercaseString
if (normalized.length > 0) {
displayList.initSearchWithQuery(normalized, withRefresh: false)
} else {
displayList.initEmpty()
}
}
// Search styling
func searchDisplayControllerWillBeginSearch(controller: UISearchDisplayController) {
MainAppTheme.search.applyStatusBar()
}
func searchDisplayControllerWillEndSearch(controller: UISearchDisplayController) {
MainAppTheme.navigation.applyStatusBar()
}
func searchDisplayController(controller: UISearchDisplayController, didShowSearchResultsTableView tableView: UITableView) {
for v in tableView.subviews {
if (v is UIImageView) {
(v as! UIImageView).alpha = 0;
}
}
}
}
|
mit
|
498d54dfdea504a1ad0f36cfef2a3ac4
| 31.938272 | 229 | 0.630622 | 5.546778 | false | false | false | false |
bumrush/iOSCamera
|
Camera/AppDelegate.swift
|
2
|
6110
|
//
// AppDelegate.swift
// Camera
//
// Created by Justin Cano on 4/22/15.
// Copyright (c) 2015 bumrush. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "com.bumrush.Camera" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1] as! NSURL
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("Camera", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
// The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("Camera.sqlite")
var error: NSError? = nil
var failureReason = "There was an error creating or loading the application's saved data."
if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil, error: &error) == nil {
coordinator = nil
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error
error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext? = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
if coordinator == nil {
return nil
}
var managedObjectContext = NSManagedObjectContext()
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if let moc = self.managedObjectContext {
var error: NSError? = nil
if moc.hasChanges && !moc.save(&error) {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
}
}
}
|
mit
|
5f80cb5e50eb9703c342be64f0f800d4
| 54.045045 | 290 | 0.714894 | 5.747883 | false | false | false | false |
KiranJasvanee/OnlyPictures
|
live_property_tracker/OnlyPictures/ViewController.swift
|
1
|
9359
|
//
// ViewController.swift
// OnlyPictures
//
// Created by Kiran Jasvanee on 10/02/2017.
// Copyright (c) 2017 Kiran Jasvanee. All rights reserved.
//
import UIKit
import OnlyPictures
class ViewController: UIViewController {
@IBOutlet weak var onlyPictures: OnlyHorizontalPictures!
//var pictures: [UIImage] = [#imageLiteral(resourceName: "p1"),#imageLiteral(resourceName: "p2"),#imageLiteral(resourceName: "p3"),#imageLiteral(resourceName: "p4"),#imageLiteral(resourceName: "p5"), UIImage(),#imageLiteral(resourceName: "p6"),#imageLiteral(resourceName: "p7"),#imageLiteral(resourceName: "p8"),#imageLiteral(resourceName: "p9"),#imageLiteral(resourceName: "p10"),#imageLiteral(resourceName: "p11"),#imageLiteral(resourceName: "p12"),#imageLiteral(resourceName: "p13"),#imageLiteral(resourceName: "p14"),#imageLiteral(resourceName: "p15")]
var pictures: [UIImage] = [#imageLiteral(resourceName: "p1"),#imageLiteral(resourceName: "p2"),#imageLiteral(resourceName: "p3"),#imageLiteral(resourceName: "p4"),#imageLiteral(resourceName: "p5"),#imageLiteral(resourceName: "p6"),#imageLiteral(resourceName: "p7"),#imageLiteral(resourceName: "p8"),#imageLiteral(resourceName: "p9"),#imageLiteral(resourceName: "p10"),#imageLiteral(resourceName: "p11"),#imageLiteral(resourceName: "p12"),#imageLiteral(resourceName: "p13"),#imageLiteral(resourceName: "p14"),#imageLiteral(resourceName: "p15")]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
onlyPictures.layer.cornerRadius = 20.0
onlyPictures.layer.masksToBounds = true
onlyPictures.dataSource = self
onlyPictures.delegate = self
onlyPictures.order = .descending
onlyPictures.alignment = .center
onlyPictures.countPosition = .right
onlyPictures.recentAt = .left
onlyPictures.spacingColor = UIColor.white
onlyPictures.defaultPicture = #imageLiteral(resourceName: "defaultProfilePicture")
onlyPictures.gap = 36
onlyPictures.spacing = 2
onlyPictures.backgroundColorForCount = UIColor.lightGray
onlyPictures.backgroundColorForCount = UIColor.init(red: 230/255, green: 230/255, blue: 230/255, alpha: 1.0)
onlyPictures.textColorForCount = .red
onlyPictures.fontForCount = UIFont(name: "HelveticaNeue", size: 18)!
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func addMoreWithReloadActionListener(_ sender: Any) {
pictures.append(#imageLiteral(resourceName: "p7"))
pictures.append(#imageLiteral(resourceName: "p8"))
pictures.append(#imageLiteral(resourceName: "p9"))
pictures.append(#imageLiteral(resourceName: "p10"))
pictures.append(#imageLiteral(resourceName: "p11"))
pictures.append(#imageLiteral(resourceName: "p12"))
pictures.append(#imageLiteral(resourceName: "p13"))
pictures.append(#imageLiteral(resourceName: "p14"))
self.onlyPictures.reloadData()
}
@IBAction func insertAtFirstActionListener(_ sender: Any) {
pictures.insert(#imageLiteral(resourceName: "p11"), at: 0)
onlyPictures.insertFirst(image: #imageLiteral(resourceName: "p11"), withAnimation: .popup)
}
@IBAction func insertLastActionListener(_ sender: Any) {
pictures.append(#imageLiteral(resourceName: "p12"))
onlyPictures.insertLast(image: #imageLiteral(resourceName: "p12"), withAnimation: .popup)
}
@IBAction func insertAt2ndPositionActionListener(_ sender: Any) {
pictures.insert(#imageLiteral(resourceName: "p13"), at: 2)
onlyPictures.insertPicture(#imageLiteral(resourceName: "p13"), atIndex: 2, withAnimation: .popup)
}
@IBAction func removeFirstActionListener(_ sender: Any) {
pictures.removeFirst()
onlyPictures.removeFirst(withAnimation: .popdown)
}
@IBAction func removeLastActionListener(_ sender: Any) {
pictures.removeLast()
onlyPictures.removeLast(withAnimation: .popdown)
}
@IBAction func removeAt2ndPositionActionListener(_ sender: Any) {
pictures.remove(at: 2)
onlyPictures.removePicture(atIndex: 2, withAnimation: .popdown)
}
// live trackers ----------------------------------------------
// gap
@IBOutlet weak var labelGapValue: UILabel!
@IBAction func gapValueChange(_ sender: UISlider) {
onlyPictures.gap = sender.value
labelGapValue.text = "\(sender.value.roundTo(places: 2))"
}
@IBOutlet weak var labelSpacingValue: UILabel!
@IBAction func spacingValueChange(_ sender: UISlider) {
onlyPictures.spacing = sender.value.roundTo(places: 2)
labelSpacingValue.text = "\(sender.value.roundTo(places: 2))"
}
// recentAt
@IBOutlet weak var buttonRecentAtLeft: UIButton!
@IBOutlet weak var buttonRecentAtRight: UIButton!
@IBAction func recentAtLeftActionListener(_ sender: UIButton) {
onlyPictures.recentAt = .left
sender.setImage(#imageLiteral(resourceName: "checked"), for: .normal)
self.buttonRecentAtRight.setImage(#imageLiteral(resourceName: "empty"), for: .normal)
}
@IBAction func recentAtRightActionListener(_ sender: UIButton) {
onlyPictures.recentAt = .right
sender.setImage(#imageLiteral(resourceName: "checked"), for: .normal)
self.buttonRecentAtLeft.setImage(#imageLiteral(resourceName: "empty"), for: .normal)
}
// countPosition
@IBOutlet weak var buttonCountPositionLeft: UIButton!
@IBOutlet weak var buttonCountPositionRight: UIButton!
@IBAction func countPositionAtLeftActionListener(_ sender: UIButton) {
onlyPictures.countPosition = .left
sender.setImage(#imageLiteral(resourceName: "checked"), for: .normal)
self.buttonCountPositionRight.setImage(#imageLiteral(resourceName: "empty"), for: .normal)
}
@IBAction func countPositionAtRightActionListener(_ sender: UIButton) {
onlyPictures.countPosition = .right
sender.setImage(#imageLiteral(resourceName: "checked"), for: .normal)
self.buttonCountPositionLeft.setImage(#imageLiteral(resourceName: "empty"), for: .normal)
}
// alignment
@IBOutlet weak var buttonAlignmentLeft: UIButton!
@IBOutlet weak var buttonAlignmentCentre: UIButton!
@IBOutlet weak var buttonAlignmentRight: UIButton!
@IBAction func alignmentLeftActionListener(_ sender: UIButton) {
onlyPictures.alignment = .left
sender.setImage(#imageLiteral(resourceName: "checked"), for: .normal)
self.buttonAlignmentCentre.setImage(#imageLiteral(resourceName: "empty"), for: .normal)
self.buttonAlignmentRight.setImage(#imageLiteral(resourceName: "empty"), for: .normal)
}
@IBAction func alignmentCentreActionListener(_ sender: UIButton) {
onlyPictures.alignment = .center
sender.setImage(#imageLiteral(resourceName: "checked"), for: .normal)
self.buttonAlignmentLeft.setImage(#imageLiteral(resourceName: "empty"), for: .normal)
self.buttonAlignmentRight.setImage(#imageLiteral(resourceName: "empty"), for: .normal)
}
@IBAction func alignmentRightActionListener(_ sender: UIButton) {
onlyPictures.alignment = .right
sender.setImage(#imageLiteral(resourceName: "checked"), for: .normal)
self.buttonAlignmentCentre.setImage(#imageLiteral(resourceName: "empty"), for: .normal)
self.buttonAlignmentLeft.setImage(#imageLiteral(resourceName: "empty"), for: .normal)
}
}
extension Float {
func roundTo(places:Int) -> Float {
let divisor = pow(10.0, Float(places))
return (self * divisor).rounded() / divisor
}
}
extension ViewController: OnlyPicturesDataSource {
func numberOfPictures() -> Int {
return self.pictures.count
}
func visiblePictures() -> Int {
return 6
}
func pictureViews(index: Int) -> UIImage {
return self.pictures[index]
}
}
extension ViewController: OnlyPicturesDelegate {
// ---------------------------------------------------
// receive an action of selected picture tap index
func pictureView(_ imageView: UIImageView, didSelectAt index: Int) {
print("Selected index: \(index)")
}
// ---------------------------------------------------
// receive an action of tap upon count
func pictureViewCountDidSelect() {
print("Tap on count")
}
// ---------------------------------------------------
// receive a count, incase you want to do additionally things with it.
// even if your requirement is to hide count and handle it externally with below fuction, you can hide it using property `isVisibleCount = true`.
func pictureViewCount(value: Int) {
print("count value: \(value)")
}
// ---------------------------------------------------
// receive an action, whem tap occures anywhere in OnlyPicture view.
func pictureViewDidSelect() {
print("tap on picture view")
}
}
|
mit
|
3432fffa7c1a091f8d11d1706fff74c1
| 41.73516 | 561 | 0.66428 | 4.610345 | false | false | false | false |
NUKisZ/MyTools
|
MyTools/MyTools/Class/FirstVC/Controllers/SwiftScan/MyCodeViewController.swift
|
1
|
3243
|
//
// MyCodeViewController.swift
// swiftScan
//
// Created by xialibing on 15/12/10.
// Copyright © 2015年 xialibing. All rights reserved.
//
import UIKit
class MyCodeViewController: BaseViewController {
//二维码
var qrView = UIView()
var qrImgView = UIImageView()
//条形码
var tView = UIView()
var tImgView = UIImageView()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
self.view.backgroundColor = UIColor.white
drawCodeShowView()
createQR1()
createCode128()
}
//MARK: ------二维码、条形码显示位置
func drawCodeShowView()
{
//二维码
let rect = CGRect(x: (self.view.frame.width-self.view.frame.width*5/6)/2, y: 100, width: self.view.frame.width*5/6, height: self.view.frame.width*5/6)
qrView.frame = rect
self.view.addSubview(qrView)
qrView.backgroundColor = UIColor.white
qrView.layer.shadowOffset = CGSize(width: 0, height: 2);
qrView.layer.shadowRadius = 2;
qrView.layer.shadowColor = UIColor.black.cgColor
qrView.layer.shadowOpacity = 0.5;
qrImgView.bounds = CGRect(x: 0, y: 0, width: qrView.frame.width-12, height: qrView.frame.width-12)
qrImgView.center = CGPoint(x: qrView.frame.width/2, y: qrView.frame.height/2);
qrView .addSubview(qrImgView)
//条形码
tView.frame = CGRect(x: (self.view.frame.width-self.view.frame.width*5/6)/2,
y: rect.maxY+20,
width: self.view.frame.width*5/6,
height: self.view.frame.width*5/6*0.5)
self.view .addSubview(tView)
tView.layer.shadowOffset = CGSize(width: 0, height: 2);
tView.layer.shadowRadius = 2;
tView.layer.shadowColor = UIColor.black.cgColor
tView.layer.shadowOpacity = 0.5;
tImgView.bounds = CGRect(x: 0, y: 0, width: tView.frame.width-12, height: tView.frame.height-12);
tImgView.center = CGPoint(x: tView.frame.width/2, y: tView.frame.height/2);
tView .addSubview(tImgView)
}
func createQR1()
{
// qrView.hidden = false
// tView.hidden = true
let qrImg = LBXScanWrapper.createCode(codeType: "CIQRCodeGenerator",codeString:"[email protected]", size: qrImgView.bounds.size, qrColor: UIColor.black, bkColor: UIColor.white)
let logoImg = UIImage(named: "logo.JPG")
qrImgView.image = LBXScanWrapper.addImageLogo(srcImg: qrImg!, logoImg: logoImg!, logoSize: CGSize(width: 30, height: 30))
}
func createCode128()
{
let qrImg = LBXScanWrapper.createCode128(codeString: "005103906002", size: qrImgView.bounds.size, qrColor: UIColor.black, bkColor: UIColor.white)
tImgView.image = qrImg
}
deinit
{
print("MyCodeViewController deinit")
}
}
|
mit
|
c1824a0d657a244e1d007d1f6148db90
| 28.574074 | 192 | 0.590795 | 3.843562 | false | false | false | false |
xuech/OMS-WH
|
OMS-WH/Classes/DeliveryGoods/Controller/OutBoundSendListViewController.swift
|
1
|
3814
|
//
// OutBoundSendListViewController.swift
// OMS
//
// Created by gwy on 16/10/18.
// Copyright © 2016年 文羿 顾. All rights reserved.
//
import UIKit
import SVProgressHUD
class OutBoundSendListViewController: UITableViewController {
fileprivate var viewModel = DeliveryGoodsViewModel()
fileprivate var chooseData = [
["dictValueName":"分秒医配","dictValueCode":"FMYP"],
["dictValueName":"直送发货","dictValueCode":"ZSFH"],
["dictValueName":"快递发货","dictValueCode":"KDFH"],
["dictValueName":"大巴发货","dictValueCode":"DBFH"],
["dictValueName":"航空发货","dictValueCode":"HKFH"],
["dictValueName":"自提发货","dictValueCode":"ZTFH"]
]
var outBoundListModel:[DGOutBoundListModel]?{
didSet{
tableView.reloadData()
}
}
var orderListModel:OrderListModel?
override func viewDidLoad() {
super.viewDidLoad()
title = orderListModel!.sONo
tableView.register(OutBoundListTableViewCell.self)
tableView.separatorStyle = .none
requstOutBoundList()
}
//出库单发货按钮请求出库单列表
fileprivate func requstOutBoundList(){
viewModel.requstOutBoundList(orderListModel!.sONo) { (data, error) in
self.outBoundListModel = data
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "OutBoundListTableViewCell") as! OutBoundListTableViewCell
cell.outBoundModel = outBoundListModel?[indexPath.row]
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let chooseVC = PickViewController(frame: self.view.bounds, dataSource: self.chooseData as [[String : AnyObject]], title: "请选择发货方式", modeBehaviour: ChooseBehaviour.chooseDictValue)
chooseVC.GetCode = {(indexpath:Int) in
if self.chooseData[indexpath]["dictValueCode"] == "FMYP"{
let sendVC = SendByFMYPViewController()
sendVC.orderModel = self.orderListModel
sendVC.outboundModel = self.outBoundListModel?[indexPath.row]
self.navigationController?.pushViewController(sendVC, animated: true)
}else{
let sendVC = SendByOtherViewController()
sendVC.outboundModel = self.outBoundListModel?[indexPath.row]
sendVC.orderModel = self.orderListModel
if self.chooseData[indexpath]["dictValueCode"] == "ZSFH"{
sendVC.modeBehaviour = .byZSFH
}else if self.chooseData[indexpath]["dictValueCode"] == "KDFH"{
sendVC.modeBehaviour = .byKDFH
}else if self.chooseData[indexpath]["dictValueCode"] == "DBFH"{
sendVC.modeBehaviour = .byDBFH
}else if self.chooseData[indexpath]["dictValueCode"] == "HKFH"{
sendVC.modeBehaviour = .byHKFH
}else if self.chooseData[indexpath]["dictValueCode"] == "ZTFH"{
sendVC.modeBehaviour = .byZTFH
}
self.navigationController?.pushViewController(sendVC, animated: true)
}
}
self.view.addSubview(chooseVC.view)
self.addChildViewController(chooseVC)
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return outBoundListModel?.count ?? 0
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 155
}
}
|
mit
|
bceb765877d37723b1ffe3d884276007
| 37.697917 | 187 | 0.626918 | 4.927056 | false | false | false | false |
TarangKhanna/Inspirator
|
WorkoutMotivation/RAMPaperSwitch.swift
|
2
|
5560
|
// RAMPaperSwitch.swift
//
// Copyright (c) 26/11/14 Ramotion Inc. (http://ramotion.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
class RAMPaperSwitch: UISwitch {
@IBInspectable var duration: Double = 0.35
var animationDidStartClosure = {(onAnimation: Bool) -> Void in }
var animationDidStopClosure = {(onAnimation: Bool, finished: Bool) -> Void in }
private var shape: CAShapeLayer! = CAShapeLayer()
private var radius: CGFloat = 0.0
private var oldState = false
override var on: Bool {
didSet(oldValue) {
oldState = on
}
}
override func setOn(on: Bool, animated: Bool) {
let changed:Bool = on != self.on
super.setOn(on, animated: animated)
if changed {
if animated {
switchChanged()
} else {
showShapeIfNeed()
}
}
}
override func layoutSubviews() {
let x:CGFloat = max(frame.midX, superview!.frame.size.width - frame.midX);
let y:CGFloat = max(frame.midY, superview!.frame.size.height - frame.midY);
radius = sqrt(x*x + y*y);
shape.frame = CGRectMake(frame.midX - radius, frame.midY - radius, radius * 2, radius * 2)
shape.anchorPoint = CGPointMake(0.5, 0.5);
shape.path = UIBezierPath(ovalInRect: CGRectMake(0, 0, radius * 2, radius * 2)).CGPath
}
override func awakeFromNib() {
let shapeColor:UIColor = (onTintColor != nil) ? onTintColor! : UIColor.greenColor()
layer.borderWidth = 0.5
layer.borderColor = UIColor.whiteColor().CGColor;
layer.cornerRadius = frame.size.height / 2;
shape.fillColor = shapeColor.CGColor
shape.masksToBounds = true
superview?.layer.insertSublayer(shape, atIndex: 0)
superview?.layer.masksToBounds = true
showShapeIfNeed()
addTarget(self, action: "switchChanged", forControlEvents: UIControlEvents.ValueChanged)
super.awakeFromNib()
}
private func showShapeIfNeed() {
shape.transform = on ? CATransform3DMakeScale(1.0, 1.0, 1.0) : CATransform3DMakeScale(0.0001, 0.0001, 0.0001)
}
internal func switchChanged() {
if on == oldState {
return;
}
oldState = on
if on {
CATransaction.begin()
shape.removeAnimationForKey("scaleDown")
let scaleAnimation:CABasicAnimation = animateKeyPath("transform",
fromValue: NSValue(CATransform3D: CATransform3DMakeScale(0.0001, 0.0001, 0.0001)),
toValue:NSValue(CATransform3D: CATransform3DMakeScale(1.0, 1.0, 1.0)),
timing:kCAMediaTimingFunctionEaseIn);
shape.addAnimation(scaleAnimation, forKey: "scaleUp")
CATransaction.commit();
}
else {
CATransaction.begin()
shape.removeAnimationForKey("scaleUp")
let scaleAnimation:CABasicAnimation = animateKeyPath("transform",
fromValue: NSValue(CATransform3D: CATransform3DMakeScale(1.0, 1.0, 1.0)),
toValue:NSValue(CATransform3D: CATransform3DMakeScale(0.0001, 0.0001, 0.0001)),
timing:kCAMediaTimingFunctionEaseOut);
shape.addAnimation(scaleAnimation, forKey: "scaleDown")
CATransaction.commit();
}
}
private func animateKeyPath(keyPath: String, fromValue from: AnyObject, toValue to: AnyObject, timing timingFunction: String) -> CABasicAnimation {
let animation:CABasicAnimation = CABasicAnimation(keyPath: keyPath)
animation.fromValue = from
animation.toValue = to
animation.repeatCount = 1
animation.timingFunction = CAMediaTimingFunction(name: timingFunction)
animation.removedOnCompletion = false
animation.fillMode = kCAFillModeForwards
animation.duration = duration;
animation.delegate = self
return animation;
}
//CAAnimation delegate
override func animationDidStart(anim: CAAnimation){
animationDidStartClosure(on)
}
override func animationDidStop(anim: CAAnimation, finished flag: Bool){
animationDidStopClosure(on, flag)
}
}
|
apache-2.0
|
df069c589229f4f03f71db25c755d544
| 34.196203 | 151 | 0.62554 | 4.968722 | false | false | false | false |
disrvptor/IPMenu
|
IP Menu/AppDelegate.swift
|
1
|
9976
|
//
// AppDelegate.swift
// IP Menu
//
// Created by Guy Pascarella on 9/2/15.
//
//
import Cocoa
import AppKit
import Foundation
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
//@IBOutlet weak var window: NSWindow!
// https://nsrover.wordpress.com/2014/10/10/creating-a-os-x-menubar-only-app/
//@property (strong, nonatomic) NSStatusItem *statusItem;
internal var statusItem: NSStatusItem?;
//@property (assign, nonatomic) BOOL darkModeOn;
//internal var darkModeOn: Bool = false;
internal var timer: Timer?;
internal var addresses: [String:[sa_family_t:[String]]]?;
internal var defaultIF: String?;
func applicationDidFinishLaunching(_ aNotification: Notification) {
statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength);
// TODO: Figure out ho to modify this for dev/test vs production
ConsoleLog.setCurrentLevel(ConsoleLog.Level.Info);
updateIPAddress();
timer = Timer.scheduledTimer(timeInterval: 1.5, target: self, selector: #selector(AppDelegate.updateIPAddress), userInfo: nil, repeats: true);
timer!.tolerance = 0.5;
}
func applicationWillTerminate(_ aNotification: Notification) {
timer = nil;
NSStatusBar.system.removeStatusItem(statusItem!);
statusItem = nil;
}
@objc func updateIPAddress() {
let _addresses = NetworkUtils.getIFAddresses();
// Disable this for now because it looks like it may be causing the OS to deadlock
//var _defaultIF: String? = "en0";
var _defaultIF: String? = NetworkUtils.getDefaultGatewayInterface();
//var _defaultIF: String? = NetworkUtils.getDefaultGatewayInterfaceShell();
let equal = compareAddresses(self.addresses, newA: _addresses);
if ( !equal ) {
ConsoleLog.info("Detected new addresses \(String(describing: addresses)) -> \(_addresses)");
addresses = _addresses;
// Regenerate menu
let menu = NSMenu();
if ( addresses!.count > 0 ) {
var index: Int = 1;
for (name,protoMap) in Array(addresses!).sorted(by: {$0.0 < $1.0}) {
for (_,addressArray) in protoMap {
for address in addressArray {
menu.addItem(NSMenuItem(title: "\(name): \(address)\n", action: nil, keyEquivalent: ""));
index += 1;
}
}
}
menu.addItem(NSMenuItem.separator());
}
var state: Int = 0;
if ( applicationIsInStartUpItems() ) {
state = 1;
}
menu.addItem(NSMenuItem(title: "Refresh", action: #selector(AppDelegate.updateIPAddress), keyEquivalent: ""));
let item:NSMenuItem = NSMenuItem(title: "Launch at startup", action: #selector(AppDelegate.toggleLaunchAtStartup), keyEquivalent: "");
item.state = NSControl.StateValue(rawValue: state);
menu.addItem(item);
menu.addItem(NSMenuItem(title: "About IP Menu", action: #selector(AppDelegate.about), keyEquivalent: ""));
menu.addItem(NSMenuItem.separator());
//menu.addItem(NSMenuItem(title: "Quit IP Menu", action: #selector(NSInputServiceProvider.Quit), keyEquivalent: "q"));
menu.addItem(NSMenuItem(title: "Quit IP Menu", action: #selector(NSApplication.shared.terminate), keyEquivalent: "q"));
statusItem!.menu = menu;
}
if ( nil == _defaultIF ) {
_defaultIF = "en0";
}
// Debug
if ( nil == defaultIF || ComparisonResult.orderedSame != _defaultIF!.compare(defaultIF!) ) {
ConsoleLog.info("Detected new default interface (\(defaultIF ?? "unknown") -> \(_defaultIF ?? "unknown"))");
}
// Pick the default address as the title
var addr = "127.0.0.1"
if ( nil == defaultIF || ComparisonResult.orderedSame != _defaultIF!.compare(defaultIF!) || !equal ) {
defaultIF = _defaultIF;
if ( nil != addresses && nil != addresses![defaultIF!] ) {
// Prefer ipv4 over ipv6
let defaultProtoMap = addresses![defaultIF!];
let ipv4 = defaultProtoMap![UInt8(AF_INET)];
let ipv6 = defaultProtoMap![UInt8(AF_INET6)];
if ( nil != ipv4 && ipv4!.count > 0 ) {
addr = ipv4![0];
} else if ( nil != ipv6 && ipv6!.count > 0 ) {
addr = ipv6![0];
} else {
print("No ipv4 or ipv6 addresses detected");
addr = "127.0.0.1";
}
}
statusItem!.title = addr;
} else {
print("No Changes \(defaultIF ?? "unknown"), \(_defaultIF ?? "unknown"), \(equal)");
}
}
func compareAddresses(_ oldA:[String:[sa_family_t:[String]]]?, newA:[String:[sa_family_t:[String]]]) -> Bool {
if ( nil == oldA || newA.count != oldA!.count ) {
return false;
} else {
// count is equal, but contents may be different, so
// iterate over the new addresses
for (name,newProtoMap) in newA {
// Check to see if this interface is previously seen
guard let oldProtoMap = oldA![name] else {
return false;
}
for (newProto,newAddresses) in newProtoMap {
guard let oldAddresses = oldProtoMap[newProto] else {
return false;
}
// Check the actual addresses
var found = false;
for newAddr in newAddresses {
for oldAddr in oldAddresses {
// Now check if there are the same addresses as previous
if ( ComparisonResult.orderedSame == newAddr.compare(oldAddr) ) {
found = true;
break;
}
}
if ( !found ) {
return false;
}
}
}
}
}
return true;
}
@objc func about() {
let alert = NSAlert();
alert.messageText = "IP Menu v\(Bundle.main.infoDictionary?["CFBundleShortVersionString"] as! String)";
alert.informativeText = "Developed by @disrvptor (https://github.com/disrvptor/IPMenu)";
alert.alertStyle = .informational;
alert.runModal();
}
// http://stackoverflow.com/questions/26475008/swift-getting-a-mac-app-to-launch-on-startup
func applicationIsInStartUpItems() -> Bool {
return (itemReferencesInLoginItems().existingReference != nil)
}
func itemReferencesInLoginItems() -> (existingReference: LSSharedFileListItem?, lastReference: LSSharedFileListItem?) {
let appUrl : URL = URL(fileURLWithPath: Bundle.main.bundlePath)
let loginItemsRef = LSSharedFileListCreate(
nil,
kLSSharedFileListSessionLoginItems.takeRetainedValue(),
nil
).takeRetainedValue() as LSSharedFileList?
if loginItemsRef != nil {
let loginItems: NSArray = LSSharedFileListCopySnapshot(loginItemsRef, nil).takeRetainedValue() as NSArray
if ( loginItems.count > 0 ) {
let lastItemRef: LSSharedFileListItem = loginItems.lastObject as! LSSharedFileListItem
for i in 0 ..< loginItems.count {
let currentItemRef: LSSharedFileListItem = loginItems.object(at: i) as! LSSharedFileListItem
if let urlRef: Unmanaged<CFURL> = LSSharedFileListItemCopyResolvedURL(currentItemRef, 0, nil) {
let urlRef:URL = urlRef.takeRetainedValue() as URL;
if urlRef == appUrl {
return (currentItemRef, lastItemRef)
}
} else {
print("Unknown login application");
}
}
//The application was not found in the startup list
return (nil, lastItemRef)
} else {
let addatstart: LSSharedFileListItem = kLSSharedFileListItemBeforeFirst.takeRetainedValue()
return(nil,addatstart)
}
}
return (nil, nil)
}
@objc func toggleLaunchAtStartup() {
let itemReferences = itemReferencesInLoginItems()
let shouldBeToggled = (itemReferences.existingReference == nil)
let loginItemsRef = LSSharedFileListCreate(
nil,
kLSSharedFileListSessionLoginItems.takeRetainedValue(),
nil
).takeRetainedValue() as LSSharedFileList?
if loginItemsRef != nil {
if shouldBeToggled {
let appUrl = URL(fileURLWithPath: Bundle.main.bundlePath) as CFURL?;
if (nil != appUrl) {
LSSharedFileListInsertItemURL(
loginItemsRef,
itemReferences.lastReference,
nil,
nil,
appUrl,
nil,
nil
)
print("Application was added to login items")
}
} else {
if let itemRef = itemReferences.existingReference {
LSSharedFileListItemRemove(loginItemsRef,itemRef);
print("Application was removed from login items")
}
}
}
}
}
|
gpl-2.0
|
e6306ce084680358cc7f3d662777c153
| 39.225806 | 150 | 0.540597 | 5.094995 | false | false | false | false |
merlos/iOS-Open-GPX-Tracker
|
Pods/CoreGPX/Classes/GPXEmail.swift
|
1
|
2456
|
//
// GPXEmail.swift
// GPXKit
//
// Created by Vincent on 18/11/18.
//
import Foundation
/**
Used for handling email types
Email is seperated as two variables in order to prevent email harvesting. The GPX v1.1 schema requires that.
For example, an email of **"[email protected]"**, would have an id of **'yourname'** and a domain of **'thisisawebsite.com'**.
*/
public final class GPXEmail: GPXElement, Codable {
/// Codable Implementation
private enum CodingKeys: String, CodingKey {
case emailID = "id"
case domain
case fullAddress
}
/// Email ID refers to the front part of the email address, before the **@**
public var emailID: String?
/// Domain refers to the back part of the email address, after the **@**
public var domain: String?
/// Full email as a string.
public var fullAddress: String?
// MARK:- Instance
public required init() {
super.init()
}
/// Initialize with a full email address.
///
/// Seperation to id and domain will be done by this class itself.
///
/// - Parameters:
/// - email: A full email address. (example: '[email protected]')
public init(withFullEmailAddress email: String) {
let splitedEmail = email.components(separatedBy: "@")
self.emailID = splitedEmail[0]
self.domain = splitedEmail[1]
}
/// Inits native element from raw parser value
///
/// - Parameters:
/// - raw: Raw element expected from parser
init(raw: GPXRawElement) {
self.emailID = raw.attributes["id"]
self.domain = raw.attributes["domain"]
guard let id = raw.attributes["id"] else { return }
guard let domain = raw.attributes["domain"] else { return }
self.fullAddress = id + "@" + domain
}
// MARK:- Tag
override func tagName() -> String {
return "email"
}
// MARK:- GPX
override func addOpenTag(toGPX gpx: NSMutableString, indentationLevel: Int) {
let attribute = NSMutableString(string: "")
if let emailID = emailID {
attribute.append(" id=\"\(emailID)\"")
}
if let domain = domain {
attribute.append(" domain=\"\(domain)\"")
}
gpx.appendOpenTag(indentation: indent(forIndentationLevel: indentationLevel), tag: tagName(), attribute: attribute)
}
}
|
gpl-3.0
|
e0523f0aca74eb01fc40ffcc2673bedb
| 28.590361 | 137 | 0.601792 | 4.301226 | false | false | false | false |
qiuncheng/study-for-swift
|
learn-rx-swift/Chocotastic-starter/Pods/RxSwift/RxSwift/Observables/Implementations/Do.swift
|
6
|
1714
|
//
// Do.swift
// Rx
//
// Created by Krunoslav Zaher on 2/21/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
class DoSink<O: ObserverType> : Sink<O>, ObserverType {
typealias Element = O.E
typealias Parent = Do<Element>
private let _parent: Parent
init(parent: Parent, observer: O) {
_parent = parent
super.init(observer: observer)
}
func on(_ event: Event<Element>) {
do {
try _parent._eventHandler(event)
forwardOn(event)
if event.isStopEvent {
dispose()
}
}
catch let error {
forwardOn(.error(error))
dispose()
}
}
}
class Do<Element> : Producer<Element> {
typealias EventHandler = (Event<Element>) throws -> Void
fileprivate let _source: Observable<Element>
fileprivate let _eventHandler: EventHandler
fileprivate let _onSubscribe: (() -> ())?
fileprivate let _onDispose: (() -> ())?
init(source: Observable<Element>, eventHandler: @escaping EventHandler, onSubscribe: (() -> ())?, onDispose: (() -> ())?) {
_source = source
_eventHandler = eventHandler
_onSubscribe = onSubscribe
_onDispose = onDispose
}
override func run<O: ObserverType>(_ observer: O) -> Disposable where O.E == Element {
_onSubscribe?()
let sink = DoSink(parent: self, observer: observer)
let subscription = _source.subscribe(sink)
let onDispose = _onDispose
sink.disposable = Disposables.create {
subscription.dispose()
onDispose?()
}
return sink
}
}
|
mit
|
acd15bed391ce74f094188dad9e8f9be
| 26.190476 | 127 | 0.572096 | 4.654891 | false | false | false | false |
roycms/FacePerception
|
FacePerceptionClass/FaceAiManager.swift
|
1
|
3216
|
//
// FaceAiManager.swift
// SharePhoto 人脸识别
//
// Created by roycms on 2017/4/6.
// Copyright © 2017年 北京三芳科技有限公司. All rights reserved.
//
import UIKit
import ImageIO
import CoreImage
class FaceAiManager: NSObject {
static let share = FaceAiManager()
// 开始识别脸部
func detectFace(imageId:String,cacheUrl:String) {
let url: NSURL = NSURL(fileURLWithPath:cacheUrl)
let readData = NSData(contentsOfFile: url.path!)
if (readData != nil) {
//处理不同方向的图片
let image = UIImage.init(data: readData! as Data)?.fixOrientation()
let inputImage = CIImage.init(image: image!)
// detector init
let detector = CIDetector(ofType: CIDetectorTypeFace,
context: nil,
options: [CIDetectorAccuracy:CIDetectorAccuracyHigh
])
if detector != nil {
let faces = detector?.features(in: inputImage!) as! [CIFaceFeature]
// 纠正坐标位置
let inputImageSize = inputImage?.extent.size
var transform = CGAffineTransform.identity
transform = transform.scaledBy(x: 1, y: -1)
transform = transform.translatedBy(x: 0, y: -(inputImageSize?.height)!)
for face in faces {
let faceViewBounds = face.bounds.applying(transform)
self.clipFaceImage(rect: faceViewBounds, image: image!)
}
}
} else {
print("识别人脸时读取文件失败")
}
}
func clipFaceImage(rect:CGRect,image:UIImage) {
let resourceRef = image.cgImage
let newImageRef = resourceRef?.cropping(to: rect); //抠图
let newImage = UIImage.init(cgImage: newImageRef!)
let imageData = UIImageJPEGRepresentation(newImage,1.0);
let fileName = String(NSDate().timeIntervalSince1970) + ".jpg"
_ = self.writeFile(fileName: fileName ,fileData:imageData!)
}
func writeFile(fileName:String,fileData:Data) -> String{
let path = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).first
let resourceCacheDir = path!+"/facePhoto/"
let resourceCacheUrl = resourceCacheDir + fileName
if (!FileManager.default.fileExists(atPath: resourceCacheDir)) {
do {
try FileManager.default.createDirectory(at:URL.init(fileURLWithPath: resourceCacheDir), withIntermediateDirectories:true, attributes:nil)
}catch{
print("出现异常 NSHomeDirectory 目录创建失败 error:\(error)")
}
}
do {
try fileData.write(to: URL.init(fileURLWithPath: resourceCacheUrl))
}catch{
print("出现异常 write 创建文件失败 error:\(error)")
}
return resourceCacheUrl
}
}
|
mit
|
dccbbfa628184a75c5f885cb2d513a13
| 32.445652 | 153 | 0.553461 | 4.962903 | false | false | false | false |
Kawoou/FlexibleImage
|
Sources/FlexibleImage.swift
|
1
|
30582
|
//
// FlexibleImage.swift
// FlexibleImage
//
// Created by Kawoou on 2017. 5. 3..
// Copyright © 2017년 Kawoou. All rights reserved.
//
#if !os(OSX)
import UIKit
#else
import AppKit
#endif
#if !os(watchOS)
import Accelerate
#endif
#if !os(watchOS)
import Metal
import CoreMedia
#endif
open class ImagePipeline: ImageChain {
// MARK: - Public
public func image(_ image: FIImage) -> FIImage? {
/// Set Image
self.device.image = image
/// Output
return super.image()
}
public func image(_ image: CGImage) -> CGImage? {
/// Set Image
self.device.cgImage = image
self.device.imageScale = 1.0
self.device.spaceSize = CGSize(
width: image.width,
height: image.height
)
self.device.beginGenerate(self.isAlphaProcess)
self.filterList.forEach { filter in
_ = filter.process(device: self.device)
}
return self.device.endGenerate()
}
#if !os(watchOS)
public func image(_ buffer: CVImageBuffer) -> CGImage? {
let width = CVPixelBufferGetWidth(buffer)
let height = CVPixelBufferGetHeight(buffer)
let ciImage: CIImage
if #available(iOS 9.0, *) {
ciImage = CIImage(cvImageBuffer: buffer)
} else {
ciImage = CIImage(cvPixelBuffer: buffer)
}
let ciContext: CIContext
#if !os(watchOS)
if #available(OSX 10.11, iOS 9, tvOS 9, *) {
if let device = self.device as? ImageMetalDevice {
ciContext = CIContext(mtlDevice: device.device)
} else {
ciContext = CIContext()
}
} else {
ciContext = CIContext()
}
#endif
let cgMakeImage = ciContext.createCGImage(ciImage, from: CGRect(x: 0, y: 0, width: width, height: height))
guard let cgImage = cgMakeImage else { return nil }
return self.image(cgImage)
}
#endif
// MARK: - Lifecycle
public init(isOnlyCoreGraphic: Bool = false) {
super.init(image: nil, isOnlyCoreGraphic: isOnlyCoreGraphic)
}
}
open class ImageChain {
// MARK: - Internal
fileprivate var device: ImageDevice
fileprivate var saveSize: CGSize?
fileprivate var isAlphaProcess: Bool = false
fileprivate var filterList: [ImageFilter] = []
// MARK: - Public
/// Common
public func background(color: FIColor) -> Self {
self.device.background = color
return self
}
public func opacity(_ opacity: CGFloat) -> Self {
self.device.opacity = opacity
return self
}
public func offset(_ offset: CGPoint) -> Self {
self.device.offset = offset
return self
}
public func size(_ size: CGSize) -> Self {
self.device.scale = size
return self
}
public func rotate(_ radius: CGFloat, _ fixedSize: CGSize? = nil) -> Self {
self.device.rotate = (self.device.rotate ?? 0) + radius
guard let saveSize = self.saveSize else { return self }
let size = self.device.scale ?? saveSize
let sinValue = CGFloat(sinf(Float(self.device.rotate!)))
let cosValue = CGFloat(cosf(Float(self.device.rotate!)))
self.device.scale = size
let rotateScale = CGSize(
width: size.width * cosValue + size.height * sinValue,
height: size.width * sinValue + size.height * cosValue
)
if let fixedSize = fixedSize {
self.device.scale = CGSize(
width: fixedSize.width * size.width / rotateScale.width,
height: fixedSize.height * size.height / rotateScale.height
)
return self.outputSize(
CGSize(
width: max(self.device.spaceSize.width, fixedSize.width),
height: max(self.device.spaceSize.height, fixedSize.height)
)
)
} else {
return self.outputSize(
CGSize(
width: max(self.device.spaceSize.width, rotateScale.width),
height: max(self.device.spaceSize.height, rotateScale.height)
)
)
}
}
public func outputSize(_ size: CGSize) -> Self {
self.device.spaceSize = CGSize(
width: size.width - self.device.margin.left - self.device.margin.right - self.device.padding.left - self.device.padding.right,
height: size.height - self.device.margin.top - self.device.margin.bottom - self.device.padding.top - self.device.padding.bottom
)
return self
}
public func scaling(_ size: CGSize) -> Self {
self.device.spaceSize.width *= size.width
self.device.spaceSize.height *= size.height
if self.device.scale != nil {
self.device.scale!.width *= size.width
self.device.scale!.height *= size.height
}
return self
}
public func margin(_ margin: EdgeInsets) -> Self {
self.device.spaceSize = CGSize(
width: self.device.spaceSize.width + self.device.margin.left + self.device.margin.right + self.device.padding.left + self.device.padding.right,
height: self.device.spaceSize.height + self.device.margin.top + self.device.margin.bottom + self.device.padding.top + self.device.padding.bottom
)
self.device.margin = margin
return self.outputSize(self.device.spaceSize)
}
public func padding(_ padding: EdgeInsets) -> Self {
self.device.spaceSize = CGSize(
width: self.device.spaceSize.width + self.device.margin.left + self.device.margin.right + self.device.padding.left + self.device.padding.right,
height: self.device.spaceSize.height + self.device.margin.top + self.device.margin.bottom + self.device.padding.top + self.device.padding.bottom
)
self.device.padding = padding
return self.outputSize(self.device.spaceSize)
}
public func corner(_ corner: CornerType) -> Self {
self.device.corner = corner
return self
}
public func border(color: FIColor, lineWidth: CGFloat, radius: CGFloat) -> Self {
self.device.border = (color, lineWidth, radius)
return self
}
public func alphaProcess(_ isAlphaProcess: Bool) -> Self {
self.isAlphaProcess = isAlphaProcess
return self
}
/// Blend
public func normal(color: FIColor) -> Self {
let filter = NormalFilter(device: self.device)
filter.color = color.imageColor
if self.isAlphaProcess == false {
filter.color.a = 1.0
}
self.filterList.append(filter)
return self
}
public func multiply(color: FIColor) -> Self {
let filter = MultiplyFilter(device: self.device)
filter.color = color.imageColor
if self.isAlphaProcess == false {
filter.color.a = 1.0
}
self.filterList.append(filter)
return self
}
public func lighten(color: FIColor) -> Self {
let filter = LightenFilter(device: self.device)
filter.color = color.imageColor
if self.isAlphaProcess == false {
filter.color.a = 1.0
}
self.filterList.append(filter)
return self
}
public func darken(color: FIColor) -> Self {
let filter = DarkenFilter(device: self.device)
filter.color = color.imageColor
if self.isAlphaProcess == false {
filter.color.a = 1.0
}
self.filterList.append(filter)
return self
}
public func average(color: FIColor) -> Self {
let filter = AverageFilter(device: self.device)
filter.color = color.imageColor
if self.isAlphaProcess == false {
filter.color.a = 1.0
}
self.filterList.append(filter)
return self
}
public func add(color: FIColor) -> Self {
let filter = AddFilter(device: self.device)
filter.color = color.imageColor
if self.isAlphaProcess == false {
filter.color.a = 0.0
}
self.filterList.append(filter)
return self
}
public func subtract(color: FIColor) -> Self {
let filter = SubtractFilter(device: self.device)
filter.color = color.imageColor
if self.isAlphaProcess == false {
filter.color.a = 0.0
}
self.filterList.append(filter)
return self
}
public func difference(color: FIColor) -> Self {
let filter = DifferenceFilter(device: self.device)
filter.color = color.imageColor
if self.isAlphaProcess == false {
filter.color.a = 1.0
}
self.filterList.append(filter)
return self
}
public func negative(color: FIColor) -> Self {
let filter = NegativeFilter(device: self.device)
filter.color = color.imageColor
if self.isAlphaProcess == false {
filter.color.a = 0.0
}
self.filterList.append(filter)
return self
}
public func screen(color: FIColor) -> Self {
let filter = ScreenFilter(device: self.device)
filter.color = color.imageColor
if self.isAlphaProcess == false {
filter.color.a = 1.0
}
self.filterList.append(filter)
return self
}
public func exclusion(color: FIColor) -> Self {
let filter = ExclusionFilter(device: self.device)
filter.color = color.imageColor
if self.isAlphaProcess == false {
filter.color.a = 0.5
}
self.filterList.append(filter)
return self
}
public func overlay(color: FIColor) -> Self {
let filter = OverlayFilter(device: self.device)
filter.color = color.imageColor
if self.isAlphaProcess == false {
filter.color.a = 1.0
}
self.filterList.append(filter)
return self
}
public func softLight(color: FIColor) -> Self {
let filter = SoftLightFilter(device: self.device)
filter.color = color.imageColor
if self.isAlphaProcess == false {
filter.color.a = 1.0
}
self.filterList.append(filter)
return self
}
public func hardLight(color: FIColor) -> Self {
let filter = HardLightFilter(device: self.device)
filter.color = color.imageColor
if self.isAlphaProcess == false {
filter.color.a = 1.0
}
self.filterList.append(filter)
return self
}
public func colorDodge(color: FIColor) -> Self {
let filter = ColorDodgeFilter(device: self.device)
filter.color = color.imageColor
if self.isAlphaProcess == false {
filter.color.a = 1.0
}
self.filterList.append(filter)
return self
}
public func colorBurn(color: FIColor) -> Self {
let filter = ColorBurnFilter(device: self.device)
filter.color = color.imageColor
if self.isAlphaProcess == false {
filter.color.a = 1.0
}
self.filterList.append(filter)
return self
}
public func linearDodge(color: FIColor) -> Self {
let filter = LinearDodgeFilter(device: self.device)
filter.color = color.imageColor
if self.isAlphaProcess == false {
filter.color.a = 0.0
}
self.filterList.append(filter)
return self
}
public func linearBurn(color: FIColor) -> Self {
let filter = LinearBurnFilter(device: self.device)
filter.color = color.imageColor
if self.isAlphaProcess == false {
filter.color.a = 1.0
}
self.filterList.append(filter)
return self
}
public func linearLight(color: FIColor) -> Self {
let filter = LinearLightFilter(device: self.device)
filter.color = color.imageColor
if self.isAlphaProcess == false {
filter.color.a = 0.5
}
self.filterList.append(filter)
return self
}
public func vividLight(color: FIColor) -> Self {
let filter = VividLightFilter(device: self.device)
filter.color = color.imageColor
if self.isAlphaProcess == false {
filter.color.a = 0.5
}
self.filterList.append(filter)
return self
}
public func pinLight(color: FIColor) -> Self {
let filter = PinLightFilter(device: self.device)
filter.color = color.imageColor
if self.isAlphaProcess == false {
filter.color.a = 0.5
}
self.filterList.append(filter)
return self
}
public func hardMix(color: FIColor) -> Self {
let filter = HardMixFilter(device: self.device)
filter.color = color.imageColor
if self.isAlphaProcess == false {
filter.color.a = 0.5
}
self.filterList.append(filter)
return self
}
public func reflect(color: FIColor) -> Self {
let filter = ReflectFilter(device: self.device)
filter.color = color.imageColor
if self.isAlphaProcess == false {
filter.color.a = 0.0
}
self.filterList.append(filter)
return self
}
public func glow(color: FIColor) -> Self {
let filter = GlowFilter(device: self.device)
filter.color = color.imageColor
if self.isAlphaProcess == false {
filter.color.a = 1.0
}
self.filterList.append(filter)
return self
}
public func phoenix(color: FIColor) -> Self {
let filter = PhoenixFilter(device: self.device)
filter.color = color.imageColor
if self.isAlphaProcess == false {
filter.color.a = 1.0
}
self.filterList.append(filter)
return self
}
public func hue(color: FIColor) -> Self {
let filter = HueFilter(device: self.device)
filter.color = color.imageColor
if self.isAlphaProcess == false {
filter.color.a = 1.0
}
self.filterList.append(filter)
return self
}
public func saturation(color: FIColor) -> Self {
let filter = SaturationFilter(device: self.device)
filter.color = color.imageColor
if self.isAlphaProcess == false {
filter.color.a = 1.0
}
self.filterList.append(filter)
return self
}
public func color(color: FIColor) -> Self {
let filter = ColorFilter(device: self.device)
filter.color = color.imageColor
if self.isAlphaProcess == false {
filter.color.a = 1.0
}
self.filterList.append(filter)
return self
}
public func luminosity(color: FIColor) -> Self {
let filter = LuminosityFilter(device: self.device)
filter.color = color.imageColor
if self.isAlphaProcess == false {
filter.color.a = 1.0
}
self.filterList.append(filter)
return self
}
/// Filter
public func greyscale(_ threshold: Float = 1.0) -> Self {
let filter = GreyscaleFilter(device: self.device)
filter.threshold = threshold
self.filterList.append(filter)
return self
}
public func monochrome(_ threshold: Float = 1.0) -> Self {
let filter = MonochromeFilter(device: self.device)
filter.threshold = threshold
self.filterList.append(filter)
return self
}
public func invert() -> Self {
let filter = InvertFilter(device: self.device)
self.filterList.append(filter)
return self
}
public func sepia() -> Self {
let filter = SepiaFilter(device: self.device)
self.filterList.append(filter)
return self
}
public func vibrance(_ vibrance: Float = 5.0) -> Self {
let filter = VibranceFilter(device: self.device)
filter.vibrance = vibrance
self.filterList.append(filter)
return self
}
public func solarize(_ threshold: Float = 0.5) -> Self {
let filter = SolarizeFilter(device: self.device)
filter.threshold = threshold
self.filterList.append(filter)
return self
}
public func posterize(_ colorLevel: Float = 10.0) -> Self {
let filter = PosterizeFilter(device: self.device)
filter.colorLevel = colorLevel
self.filterList.append(filter)
return self
}
#if !os(watchOS)
public func blur(_ blurRadius: Float = 20.0) -> Self {
let filter = BlurFilter(device: self.device)
filter.radius = blurRadius
self.filterList.append(filter)
return self
}
#endif
public func brightness(_ brightness: Float = 0.5) -> Self {
let filter = BrightnessFilter(device: self.device)
filter.brightness = brightness
self.filterList.append(filter)
return self
}
public func chromaKey(color: FIColor, _ threshold: Float = 0.4, _ smoothing: Float = 0.1) -> Self {
let filter = ChromaKeyFilter(device: self.device)
filter.color = color.imageColor
filter.threshold = threshold
filter.smoothing = smoothing
self.filterList.append(filter)
return self
}
public func swizzling() -> Self {
let filter = SwizzlingFilter(device: self.device)
self.filterList.append(filter)
return self
}
public func contrast(_ threshold: Float = 0.5) -> Self {
let filter = ContrastFilter(device: self.device)
filter.threshold = threshold
self.filterList.append(filter)
return self
}
public func gamma(_ gamma: Float = 1.0) -> Self {
let filter = GammaFilter(device: self.device)
filter.gamma = gamma
self.filterList.append(filter)
return self
}
/// Etc
public func append(_ imageChain: ImageChain) -> Self {
return self.append(image: imageChain.image()!)
}
public func append(image: FIImage, offset: CGPoint = .zero, resize: CGSize? = nil, _ threshold: Float = 1.0) -> Self {
let scale = self.device.imageScale
guard let imageRef = image.cgImage else { return self }
let filter = TextureAppendFilter(device: self.device)
filter.image = image
filter.offsetX = Float(offset.x)
filter.offsetY = Float(offset.y)
filter.threshold = threshold
if let resize = resize {
filter.scaleX = Float(CGFloat(imageRef.width) / resize.width) * Float(scale / image.scale)
filter.scaleY = Float(CGFloat(imageRef.height) / resize.height) * Float(scale / image.scale)
} else {
filter.scaleX = Float(scale / image.scale)
filter.scaleY = Float(scale / image.scale)
}
self.filterList.append(filter)
var size = resize
if size == nil {
size = image.size
}
return self.outputSize(
CGSize(
width: max(self.device.spaceSize.width, size!.width + offset.x),
height: max(self.device.spaceSize.height, size!.width + offset.y)
)
)
}
/// Post-processing
public func algorithm(_ algorithm: @escaping AlgorithmType) -> Self {
self.device.postProcessList.append { _, width, height, memoryPool in
var index = 0
for y in 0..<height {
for x in 0..<width {
let r = Float(memoryPool[index + 0]) / 255.0
let g = Float(memoryPool[index + 1]) / 255.0
let b = Float(memoryPool[index + 2]) / 255.0
let a = Float(memoryPool[index + 3]) / 255.0
let inColor = FIColorType(r, g, b, a)
let outColor = algorithm(y, x, inColor, width, height, memoryPool)
memoryPool[index + 0] = UInt8(max(min(outColor.r, 1.0), 0.0) * 255.0)
memoryPool[index + 1] = UInt8(max(min(outColor.g, 1.0), 0.0) * 255.0)
memoryPool[index + 2] = UInt8(max(min(outColor.b, 1.0), 0.0) * 255.0)
memoryPool[index + 3] = UInt8(max(min(outColor.a, 1.0), 0.0) * 255.0)
index += 4
}
}
}
return self
}
public func custom(_ contextBlock: @escaping ContextType) -> Self {
self.device.postProcessList.append(contextBlock)
return self
}
/// Output
public func image() -> FIImage? {
let scale = self.device.imageScale
self.device.beginGenerate(self.isAlphaProcess)
self.filterList.forEach { filter in
_ = filter.process(device: self.device)
}
if let cgImage = self.device.endGenerate() {
#if !os(OSX)
return FIImage(cgImage: cgImage, scale: scale, orientation: .up)
#else
return FIImage(cgImage: cgImage, size: CGSize(width: cgImage.width, height: cgImage.height))
#endif
}
return nil
}
/// Deprecated
@available(*, unavailable, renamed: "opacity()")
public func alpha(_ alpha: CGFloat) -> Self {
return self.opacity(alpha)
}
@available(*, unavailable, renamed: "alphaProcess()")
public func alphaBlend(_ isAlphaBlend: Bool) -> Self {
return self.alphaProcess(isAlphaBlend)
}
@available(*, unavailable, message: "Don't use")
public func blendMode(_ blendMode: CGBlendMode) -> Self {
return self
}
// MARK: - Lifecycle
fileprivate init(image: FIImage?, isOnlyCoreGraphic: Bool = false) {
if isOnlyCoreGraphic {
self.device = ImageNoneDevice()
} else {
#if !os(watchOS)
if #available(OSX 10.11, *) {
if let _ = MTLCreateSystemDefaultDevice() {
self.device = ImageMetalDevice()
} else {
self.device = ImageNoneDevice()
}
} else {
self.device = ImageNoneDevice()
}
#else
self.device = ImageNoneDevice()
#endif
}
guard let image = image else { return }
self.device.image = image
self.saveSize = CGSize(
width: image.size.width,
height: image.size.height
)
}
}
extension FIImage {
// MARK: - Public
/// Generate
public class func rect(color: FIColor, size: CGSize) -> FIImage? {
let scale = FIImage.screenScale()
let newSize: CGSize = CGSize(
width: scale * size.width,
height: scale * size.height
)
#if !os(OSX)
UIGraphicsBeginImageContext(newSize)
defer { UIGraphicsEndImageContext() }
guard let context = UIGraphicsGetCurrentContext() else { return nil }
#else
#if swift(>=4.0)
guard let offscreenRep = NSBitmapImageRep(
bitmapDataPlanes: nil,
pixelsWide: Int(newSize.width),
pixelsHigh: Int(newSize.height),
bitsPerSample: 8,
samplesPerPixel: 4,
hasAlpha: true,
isPlanar: false,
colorSpaceName: NSColorSpaceName.deviceRGB,
bitmapFormat: .alphaFirst,
bytesPerRow: 0,
bitsPerPixel: 0
) else { return nil }
#else
guard let offscreenRep = NSBitmapImageRep(
bitmapDataPlanes: nil,
pixelsWide: Int(newSize.width),
pixelsHigh: Int(newSize.height),
bitsPerSample: 8,
samplesPerPixel: 4,
hasAlpha: true,
isPlanar: false,
colorSpaceName: NSDeviceRGBColorSpace,
bitmapFormat: .alphaFirst,
bytesPerRow: 0,
bitsPerPixel: 0
) else { return nil }
#endif
guard let graphicsContext = NSGraphicsContext(bitmapImageRep: offscreenRep) else { return nil }
NSGraphicsContext.saveGraphicsState()
#if swift(>=4.0)
NSGraphicsContext.current = graphicsContext
#else
NSGraphicsContext.setCurrent(graphicsContext)
#endif
defer { NSGraphicsContext.restoreGraphicsState() }
let context = graphicsContext.cgContext
#endif
context.clear(CGRect(origin: .zero, size: newSize))
context.setFillColor(color.cgColor)
context.fill(CGRect(origin: .zero, size: newSize))
#if !os(OSX)
guard let imageContext = UIGraphicsGetImageFromCurrentImageContext() else { return nil }
guard let cgImage = imageContext.cgImage else { return nil }
return FIImage(
cgImage: cgImage,
scale: scale,
orientation: .up
)
#else
let image = FIImage(size: newSize)
image.addRepresentation(offscreenRep)
return image
#endif
}
public class func circle(color: FIColor, size: CGSize) -> FIImage? {
let scale = FIImage.screenScale()
let newSize: CGSize = CGSize(
width: scale * size.width,
height: scale * size.height
)
#if !os(OSX)
UIGraphicsBeginImageContext(newSize)
defer { UIGraphicsEndImageContext() }
guard let context = UIGraphicsGetCurrentContext() else { return nil }
#else
#if swift(>=4.0)
guard let offscreenRep = NSBitmapImageRep(
bitmapDataPlanes: nil,
pixelsWide: Int(newSize.width),
pixelsHigh: Int(newSize.height),
bitsPerSample: 8,
samplesPerPixel: 4,
hasAlpha: true,
isPlanar: false,
colorSpaceName: NSColorSpaceName.deviceRGB,
bitmapFormat: .alphaFirst,
bytesPerRow: 0,
bitsPerPixel: 0
) else { return nil }
#else
guard let offscreenRep = NSBitmapImageRep(
bitmapDataPlanes: nil,
pixelsWide: Int(newSize.width),
pixelsHigh: Int(newSize.height),
bitsPerSample: 8,
samplesPerPixel: 4,
hasAlpha: true,
isPlanar: false,
colorSpaceName: NSDeviceRGBColorSpace,
bitmapFormat: .alphaFirst,
bytesPerRow: 0,
bitsPerPixel: 0
) else { return nil }
#endif
guard let graphicsContext = NSGraphicsContext(bitmapImageRep: offscreenRep) else { return nil }
NSGraphicsContext.saveGraphicsState()
#if swift(>=4.0)
NSGraphicsContext.current = graphicsContext
#else
NSGraphicsContext.setCurrent(graphicsContext)
#endif
defer { NSGraphicsContext.restoreGraphicsState()}
let context = graphicsContext.cgContext
#endif
context.clear(CGRect(origin: .zero, size: newSize))
context.setFillColor(color.cgColor)
context.fillEllipse(in: CGRect(origin: .zero, size: newSize))
#if !os(OSX)
guard let imageContext = UIGraphicsGetImageFromCurrentImageContext() else { return nil }
guard let cgImage = imageContext.cgImage else { return nil }
return FIImage(
cgImage: cgImage,
scale: scale,
orientation: .up
)
#else
let image = FIImage(size: newSize)
image.addRepresentation(offscreenRep)
return image
#endif
}
/// Adjust
public func adjust(_ isOnlyCoreGraphic: Bool = false) -> ImageChain {
return ImageChain(image: self, isOnlyCoreGraphic: isOnlyCoreGraphic)
}
// MARK: - Private
private class func screenScale() -> CGFloat {
// over iOS 8
#if os(iOS)
if #available(iOS 8, *) {
return UIScreen.main.nativeScale
}
// over iOS 4
if #available(iOS 4, *) {
return UIScreen.main.scale
}
#endif
return 1.0
}
// MARK: - Lifecycle
public convenience init?(_ chain: ImageChain) {
let image = chain.image()
#if !os(OSX)
self.init(cgImage: (image ?? FIImage.rect(color: .white, size: CGSize(width: 1, height: 1)))!.cgImage!)
#else
self.init(cgImage: (image ?? FIImage.rect(color: .white, size: CGSize(width: 1, height: 1)))!.cgImage!, size: CGSize(width: 1, height: 1))
#endif
}
}
public func +(lhs: FIImage?, rhs: FIImage?) -> FIImage? {
guard let left = lhs else { return rhs }
guard let right = rhs else { return lhs }
return left.adjust().append(image: right).image()
}
|
mit
|
45c03a284307d98afc2fd75898b84393
| 31.565495 | 156 | 0.546846 | 4.571535 | false | false | false | false |
FlexMonkey/Filterpedia
|
Filterpedia/customFilters/VImageFilters.swift
|
1
|
17605
|
//
// VImageFilters.swift
// Filterpedia
//
// Created by Simon Gladman on 21/04/2016.
// Copyright © 2016 Simon Gladman. All rights reserved.
//
// These filters don't work nicely in background threads! Execute in dispatch_get_main_queue()!
//
// 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 CoreImage
import Accelerate
// Circular Bokeh
class CircularBokeh: CIFilter, VImageFilter
{
var inputImage: CIImage?
var inputBlurRadius: CGFloat = 2
var inputBokehRadius: CGFloat = 15
{
didSet
{
probe = nil
}
}
var inputBokehBias: CGFloat = 0.25
{
didSet
{
probe = nil
}
}
private var probe: [UInt8]?
override var attributes: [String : AnyObject]
{
return [
kCIAttributeFilterDisplayName: "Circular Bokeh",
"inputImage": [kCIAttributeIdentity: 0,
kCIAttributeClass: "CIImage",
kCIAttributeDisplayName: "Image",
kCIAttributeType: kCIAttributeTypeImage],
"inputBokehRadius": [kCIAttributeIdentity: 0,
kCIAttributeClass: "NSNumber",
kCIAttributeDefault: 15,
kCIAttributeDisplayName: "Bokeh Radius",
kCIAttributeMin: 0,
kCIAttributeSliderMin: 0,
kCIAttributeSliderMax: 20,
kCIAttributeType: kCIAttributeTypeScalar],
"inputBlurRadius": [kCIAttributeIdentity: 0,
kCIAttributeClass: "NSNumber",
kCIAttributeDefault: 2,
kCIAttributeDisplayName: "Blur Radius",
kCIAttributeMin: 0,
kCIAttributeSliderMin: 0,
kCIAttributeSliderMax: 10,
kCIAttributeType: kCIAttributeTypeScalar],
"inputBokehBias": [kCIAttributeIdentity: 0,
kCIAttributeClass: "NSNumber",
kCIAttributeDefault: 0.25,
kCIAttributeDisplayName: "Bokeh Bias",
kCIAttributeMin: 0,
kCIAttributeSliderMin: 0,
kCIAttributeSliderMax: 1,
kCIAttributeType: kCIAttributeTypeScalar],
]
}
lazy var ciContext: CIContext =
{
return CIContext()
}()
override var outputImage: CIImage?
{
guard let inputImage = inputImage else
{
return nil
}
let imageRef = ciContext.createCGImage(
inputImage,
fromRect: inputImage.extent)
var imageBuffer = vImage_Buffer()
vImageBuffer_InitWithCGImage(
&imageBuffer,
&format,
nil,
imageRef,
UInt32(kvImageNoFlags))
let pixelBuffer = malloc(CGImageGetBytesPerRow(imageRef) * CGImageGetHeight(imageRef))
var outBuffer = vImage_Buffer(
data: pixelBuffer,
height: UInt(CGImageGetHeight(imageRef)),
width: UInt(CGImageGetWidth(imageRef)),
rowBytes: CGImageGetBytesPerRow(imageRef))
let probeValue = UInt8((1 - inputBokehBias) * 30)
let radius = Int(inputBokehRadius)
let diameter = (radius * 2) + 1
if probe == nil
{
probe = 0.stride(to: (diameter * diameter), by: 1).map
{
let x = Float(($0 % diameter) - radius)
let y = Float(($0 / diameter) - radius)
let r = Float(radius)
let length = hypot(Float(x), Float(y)) / r
if length <= 1
{
let distanceToEdge = 1 - length
return UInt8(distanceToEdge * Float(probeValue))
}
return 255
}
}
vImageDilate_ARGB8888(
&imageBuffer,
&outBuffer,
0,
0,
probe!,
UInt(diameter),
UInt(diameter),
UInt32(kvImageEdgeExtend))
let outImage = CIImage(fromvImageBuffer: outBuffer)
free(pixelBuffer)
free(imageBuffer.data)
return outImage!.imageByApplyingFilter(
"CIGaussianBlur",
withInputParameters: [kCIInputRadiusKey: inputBlurRadius])
}
}
// Histogram Equalization
class HistogramEqualization: CIFilter, VImageFilter
{
var inputImage: CIImage?
override var attributes: [String : AnyObject]
{
return [
kCIAttributeFilterDisplayName: "Histogram Equalization",
"inputImage": [kCIAttributeIdentity: 0,
kCIAttributeClass: "CIImage",
kCIAttributeDisplayName: "Image",
kCIAttributeType: kCIAttributeTypeImage]
]
}
lazy var ciContext: CIContext =
{
return CIContext()
}()
override var outputImage: CIImage?
{
guard let inputImage = inputImage else
{
return nil
}
let imageRef = ciContext.createCGImage(
inputImage,
fromRect: inputImage.extent)
var imageBuffer = vImage_Buffer()
vImageBuffer_InitWithCGImage(
&imageBuffer,
&format,
nil,
imageRef,
UInt32(kvImageNoFlags))
let pixelBuffer = malloc(CGImageGetBytesPerRow(imageRef) * CGImageGetHeight(imageRef))
var outBuffer = vImage_Buffer(
data: pixelBuffer,
height: UInt(CGImageGetHeight(imageRef)),
width: UInt(CGImageGetWidth(imageRef)),
rowBytes: CGImageGetBytesPerRow(imageRef))
vImageEqualization_ARGB8888(
&imageBuffer,
&outBuffer,
UInt32(kvImageNoFlags))
let outImage = CIImage(fromvImageBuffer: outBuffer)
free(imageBuffer.data)
free(pixelBuffer)
return outImage!
}
}
// MARK: EndsInContrastStretch
class EndsInContrastStretch: CIFilter, VImageFilter
{
var inputImage: CIImage?
var inputPercentLowRed: CGFloat = 0
var inputPercentLowGreen: CGFloat = 0
var inputPercentLowBlue: CGFloat = 0
var inputPercentHiRed: CGFloat = 0
var inputPercentHiGreen: CGFloat = 0
var inputPercentHiBlue: CGFloat = 0
override var attributes: [String : AnyObject]
{
return [
kCIAttributeFilterDisplayName: "Ends In Contrast Stretch",
"inputImage": [kCIAttributeIdentity: 0,
kCIAttributeClass: "CIImage",
kCIAttributeDisplayName: "Image",
kCIAttributeType: kCIAttributeTypeImage],
"inputPercentLowRed": [kCIAttributeIdentity: 0,
kCIAttributeClass: "NSNumber",
kCIAttributeDefault: 0,
kCIAttributeDisplayName: "Percent Low Red",
kCIAttributeMin: 0,
kCIAttributeSliderMin: 0,
kCIAttributeSliderMax: 49,
kCIAttributeType: kCIAttributeTypeScalar],
"inputPercentLowGreen": [kCIAttributeIdentity: 0,
kCIAttributeClass: "NSNumber",
kCIAttributeDefault: 0,
kCIAttributeDisplayName: "Percent Low Green",
kCIAttributeMin: 0,
kCIAttributeSliderMin: 0,
kCIAttributeSliderMax: 49,
kCIAttributeType: kCIAttributeTypeScalar],
"inputPercentLowBlue": [kCIAttributeIdentity: 0,
kCIAttributeClass: "NSNumber",
kCIAttributeDefault: 0,
kCIAttributeDisplayName: "Percent Low Blue",
kCIAttributeMin: 0,
kCIAttributeSliderMin: 0,
kCIAttributeSliderMax: 49,
kCIAttributeType: kCIAttributeTypeScalar],
"inputPercentHiRed": [kCIAttributeIdentity: 0,
kCIAttributeClass: "NSNumber",
kCIAttributeDefault: 0,
kCIAttributeDisplayName: "Percent High Red",
kCIAttributeMin: 0,
kCIAttributeSliderMin: 0,
kCIAttributeSliderMax: 49,
kCIAttributeType: kCIAttributeTypeScalar],
"inputPercentHiGreen": [kCIAttributeIdentity: 0,
kCIAttributeClass: "NSNumber",
kCIAttributeDefault: 0,
kCIAttributeDisplayName: "Percent High Green",
kCIAttributeMin: 0,
kCIAttributeSliderMin: 0,
kCIAttributeSliderMax: 49,
kCIAttributeType: kCIAttributeTypeScalar],
"inputPercentHiBlue": [kCIAttributeIdentity: 0,
kCIAttributeClass: "NSNumber",
kCIAttributeDefault: 0,
kCIAttributeDisplayName: "Percent High Blue",
kCIAttributeMin: 0,
kCIAttributeSliderMin: 0,
kCIAttributeSliderMax: 49,
kCIAttributeType: kCIAttributeTypeScalar],
]
}
lazy var ciContext: CIContext =
{
return CIContext()
}()
override var outputImage: CIImage?
{
guard let inputImage = inputImage else
{
return nil
}
let imageRef = ciContext.createCGImage(
inputImage,
fromRect: inputImage.extent)
var imageBuffer = vImage_Buffer()
vImageBuffer_InitWithCGImage(
&imageBuffer,
&format,
nil,
imageRef,
UInt32(kvImageNoFlags))
let pixelBuffer = malloc(CGImageGetBytesPerRow(imageRef) * CGImageGetHeight(imageRef))
var outBuffer = vImage_Buffer(
data: pixelBuffer,
height: UInt(CGImageGetHeight(imageRef)),
width: UInt(CGImageGetWidth(imageRef)),
rowBytes: CGImageGetBytesPerRow(imageRef))
let low = [inputPercentLowRed, inputPercentLowGreen, inputPercentLowBlue, 0].map { return UInt32($0) }
let hi = [inputPercentHiRed, inputPercentHiGreen, inputPercentHiBlue, 0].map { return UInt32($0) }
vImageEndsInContrastStretch_ARGB8888(
&imageBuffer,
&outBuffer,
low,
hi,
UInt32(kvImageNoFlags))
let outImage = CIImage(fromvImageBuffer: outBuffer)
free(imageBuffer.data)
free(pixelBuffer)
return outImage!
}
}
// MARK: Contrast Stretch
class ContrastStretch: CIFilter, VImageFilter
{
var inputImage: CIImage?
override var attributes: [String : AnyObject]
{
return [
kCIAttributeFilterDisplayName: "Contrast Stretch",
"inputImage": [kCIAttributeIdentity: 0,
kCIAttributeClass: "CIImage",
kCIAttributeDisplayName: "Image",
kCIAttributeType: kCIAttributeTypeImage]
]
}
lazy var ciContext: CIContext =
{
return CIContext()
}()
override var outputImage: CIImage?
{
guard let inputImage = inputImage else
{
return nil
}
let imageRef = ciContext.createCGImage(
inputImage,
fromRect: inputImage.extent)
var imageBuffer = vImage_Buffer()
vImageBuffer_InitWithCGImage(
&imageBuffer,
&format,
nil,
imageRef,
UInt32(kvImageNoFlags))
let pixelBuffer = malloc(CGImageGetBytesPerRow(imageRef) * CGImageGetHeight(imageRef))
var outBuffer = vImage_Buffer(
data: pixelBuffer,
height: UInt(CGImageGetHeight(imageRef)),
width: UInt(CGImageGetWidth(imageRef)),
rowBytes: CGImageGetBytesPerRow(imageRef))
vImageContrastStretch_ARGB8888(
&imageBuffer,
&outBuffer,
UInt32(kvImageNoFlags))
let outImage = CIImage(fromvImageBuffer: outBuffer)
free(imageBuffer.data)
free(pixelBuffer)
return outImage!
}
}
// MARK: HistogramSpecification
class HistogramSpecification: CIFilter, VImageFilter
{
var inputImage: CIImage?
var inputHistogramSource: CIImage?
override var attributes: [String : AnyObject]
{
return [
kCIAttributeFilterDisplayName: "Histogram Specification",
"inputImage": [kCIAttributeIdentity: 0,
kCIAttributeClass: "CIImage",
kCIAttributeDisplayName: "Image",
kCIAttributeType: kCIAttributeTypeImage],
"inputHistogramSource": [kCIAttributeIdentity: 0,
kCIAttributeClass: "CIImage",
kCIAttributeDisplayName: "Histogram Source",
kCIAttributeType: kCIAttributeTypeImage],
]
}
lazy var ciContext: CIContext =
{
return CIContext()
}()
override var outputImage: CIImage?
{
guard let inputImage = inputImage,
inputHistogramSource = inputHistogramSource else
{
return nil
}
let imageRef = ciContext.createCGImage(
inputImage,
fromRect: inputImage.extent)
var imageBuffer = vImageBufferFromCIImage(inputImage, ciContext: ciContext)
var histogramSourceBuffer = vImageBufferFromCIImage(inputHistogramSource, ciContext: ciContext)
let alpha = [UInt](count: 256, repeatedValue: 0)
let red = [UInt](count: 256, repeatedValue: 0)
let green = [UInt](count: 256, repeatedValue: 0)
let blue = [UInt](count: 256, repeatedValue: 0)
let alphaMutablePointer = UnsafeMutablePointer<vImagePixelCount>(alpha)
let redMutablePointer = UnsafeMutablePointer<vImagePixelCount>(red)
let greenMutablePointer = UnsafeMutablePointer<vImagePixelCount>(green)
let blueMutablePointer = UnsafeMutablePointer<vImagePixelCount>(blue)
let rgba = [redMutablePointer, greenMutablePointer, blueMutablePointer, alphaMutablePointer]
let histogram = UnsafeMutablePointer<UnsafeMutablePointer<vImagePixelCount>>(rgba)
vImageHistogramCalculation_ARGB8888(&histogramSourceBuffer, histogram, UInt32(kvImageNoFlags))
let pixelBuffer = malloc(CGImageGetBytesPerRow(imageRef) * CGImageGetHeight(imageRef))
var outBuffer = vImage_Buffer(
data: pixelBuffer,
height: UInt(CGImageGetHeight(imageRef)),
width: UInt(CGImageGetWidth(imageRef)),
rowBytes: CGImageGetBytesPerRow(imageRef))
let alphaPointer = UnsafePointer<vImagePixelCount>(alpha)
let redPointer = UnsafePointer<vImagePixelCount>(red)
let greenPointer = UnsafePointer<vImagePixelCount>(green)
let bluePointer = UnsafePointer<vImagePixelCount>(blue)
let rgbaMutablePointer = UnsafeMutablePointer<UnsafePointer<vImagePixelCount>>([redPointer, greenPointer, bluePointer, alphaPointer])
vImageHistogramSpecification_ARGB8888(&imageBuffer, &outBuffer, rgbaMutablePointer, UInt32(kvImageNoFlags))
let outImage = CIImage(fromvImageBuffer: outBuffer)
free(imageBuffer.data)
free(histogramSourceBuffer.data)
free(pixelBuffer)
return outImage!
}
}
// MARK Support
protocol VImageFilter {
}
let bitmapInfo:CGBitmapInfo = CGBitmapInfo(
rawValue: CGImageAlphaInfo.Last.rawValue)
var format = vImage_CGImageFormat(
bitsPerComponent: 8,
bitsPerPixel: 32,
colorSpace: nil,
bitmapInfo: bitmapInfo,
version: 0,
decode: nil,
renderingIntent: .RenderingIntentDefault)
func vImageBufferFromCIImage(ciImage: CIImage, ciContext: CIContext) -> vImage_Buffer
{
let imageRef = ciContext.createCGImage(
ciImage,
fromRect: ciImage.extent)
var buffer = vImage_Buffer()
vImageBuffer_InitWithCGImage(
&buffer,
&format,
nil,
imageRef,
UInt32(kvImageNoFlags))
return buffer
}
extension CIImage
{
convenience init?(fromvImageBuffer: vImage_Buffer)
{
var mutableBuffer = fromvImageBuffer
var error = vImage_Error()
let cgImage = vImageCreateCGImageFromBuffer(
&mutableBuffer,
&format,
nil,
nil,
UInt32(kvImageNoFlags),
&error)
self.init(CGImage: cgImage.takeRetainedValue())
}
}
|
gpl-3.0
|
4cf72cbfbd78846e38f6ca8f5bb5d733
| 30.212766 | 141 | 0.581118 | 5.698932 | false | false | false | false |
codestergit/swift
|
test/SILGen/reabstract_lvalue.swift
|
2
|
2637
|
// RUN: %target-swift-frontend -emit-silgen %s | %FileCheck %s
struct MyMetatypeIsThin {}
// CHECK-LABEL: sil hidden @_T017reabstract_lvalue19consumeGenericInOut{{[_0-9a-zA-Z]*}}F : $@convention(thin) <T> (@inout T) -> ()
func consumeGenericInOut<T>(_ x: inout T) {}
// CHECK-LABEL: sil hidden @_T017reabstract_lvalue9transformSdSiF : $@convention(thin) (Int) -> Double
func transform(_ i: Int) -> Double {
return Double(i)
}
// CHECK-LABEL: sil hidden @_T017reabstract_lvalue0A13FunctionInOutyyF : $@convention(thin) () -> ()
func reabstractFunctionInOut() {
// CHECK: [[BOX:%.*]] = alloc_box ${ var @callee_owned (Int) -> Double }
// CHECK: [[PB:%.*]] = project_box [[BOX]]
// CHECK: [[ARG:%.*]] = function_ref @_T017reabstract_lvalue9transformSdSiF
// CHECK: [[THICK_ARG:%.*]] = thin_to_thick_function [[ARG]]
// CHECK: store [[THICK_ARG:%.*]] to [init] [[PB]]
// CHECK: [[FUNC:%.*]] = function_ref @_T017reabstract_lvalue19consumeGenericInOut{{[_0-9a-zA-Z]*}}F
// CHECK: [[ABSTRACTED_BOX:%.*]] = alloc_stack $@callee_owned (@in Int) -> @out Double
// CHECK: [[THICK_ARG:%.*]] = load [copy] [[PB]]
// CHECK: [[THUNK1:%.*]] = function_ref @_T0SiSdIxyd_SiSdIxir_TR
// CHECK: [[ABSTRACTED_ARG:%.*]] = partial_apply [[THUNK1]]([[THICK_ARG]])
// CHECK: store [[ABSTRACTED_ARG]] to [init] [[ABSTRACTED_BOX]]
// CHECK: apply [[FUNC]]<(Int) -> Double>([[ABSTRACTED_BOX]])
// CHECK: [[NEW_ABSTRACTED_ARG:%.*]] = load [take] [[ABSTRACTED_BOX]]
// CHECK: [[THUNK2:%.*]] = function_ref @_T0SiSdIxir_SiSdIxyd_TR
// CHECK: [[NEW_ARG:%.*]] = partial_apply [[THUNK2]]([[NEW_ABSTRACTED_ARG]])
var minimallyAbstracted = transform
consumeGenericInOut(&minimallyAbstracted)
}
// CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @_T0SiSdIxyd_SiSdIxir_TR : $@convention(thin) (@in Int, @owned @callee_owned (Int) -> Double) -> @out Double
// CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @_T0SiSdIxir_SiSdIxyd_TR : $@convention(thin) (Int, @owned @callee_owned (@in Int) -> @out Double) -> Double
// CHECK-LABEL: sil hidden @_T017reabstract_lvalue0A13MetatypeInOutyyF : $@convention(thin) () -> ()
func reabstractMetatypeInOut() {
var thinMetatype = MyMetatypeIsThin.self
// CHECK: [[FUNC:%.*]] = function_ref @_T017reabstract_lvalue19consumeGenericInOut{{[_0-9a-zA-Z]*}}F
// CHECK: [[BOX:%.*]] = alloc_stack $@thick MyMetatypeIsThin.Type
// CHECK: [[THICK:%.*]] = metatype $@thick MyMetatypeIsThin.Type
// CHECK: store [[THICK]] to [trivial] [[BOX]]
// CHECK: apply [[FUNC]]<MyMetatypeIsThin.Type>([[BOX]])
consumeGenericInOut(&thinMetatype)
}
|
apache-2.0
|
97e2ebdfac3747b423a75c6fdee97c60
| 56.326087 | 186 | 0.654911 | 3.251541 | false | false | false | false |
icetime17/CSSwiftExtension
|
Sources/UIKit+CSExtension/UITableView+CSExtension.swift
|
1
|
1409
|
//
// UITableView+CSExtension.swift
// CSSwiftExtension
//
// Created by Chris Hu on 17/1/3.
// Copyright © 2017年 com.icetime17. All rights reserved.
//
import UIKit
public extension CSSwift where Base: UITableView {
// number of all rows
var numberOfAllRows: Int {
var rowCount = 0
for section in 0..<base.numberOfSections {
rowCount += base.numberOfRows(inSection: section)
}
return rowCount
}
}
public extension CSSwift where Base: UITableView {
func removeEmptyFooter() {
base.tableFooterView = UIView(frame: CGRect.zero)
}
}
/*
// MARK: - reuse
extension UITableViewCell: ReusableView {
}
extension UITableViewCell: NibLoadable {
}
public extension CSSwift where Base: UITableView {
func registerNib<T: UITableViewCell>(_: T.Type) where T: ReusableView & NibLoadable {
let nib = UINib(nibName: T.nibName, bundle: nil)
base.register(nib, forCellReuseIdentifier: T.reuseIdentifier)
}
func dequeueReusableCell<T: UITableViewCell>(forIndexPath indexPath: IndexPath) -> T where T: ReusableView {
guard let cell = base.dequeueReusableCell(withIdentifier: T.reuseIdentifier, for: indexPath) as? T else {
fatalError("CSSwiftExtension: Could not dequeue cell with identifier \(T.reuseIdentifier)")
}
return cell
}
}
*/
|
mit
|
1675c3313b93bcca71bc63d3adf589a2
| 23.666667 | 113 | 0.662162 | 4.50641 | false | false | false | false |
noppoMan/aws-sdk-swift
|
Sources/Soto/Services/MediaPackage/MediaPackage_Shapes.swift
|
1
|
73161
|
//===----------------------------------------------------------------------===//
//
// 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 Foundation
import SotoCore
extension MediaPackage {
// MARK: Enums
public enum AdMarkers: String, CustomStringConvertible, Codable {
case daterange = "DATERANGE"
case none = "NONE"
case passthrough = "PASSTHROUGH"
case scte35Enhanced = "SCTE35_ENHANCED"
public var description: String { return self.rawValue }
}
public enum AdsOnDeliveryRestrictions: String, CustomStringConvertible, Codable {
case both = "BOTH"
case none = "NONE"
case restricted = "RESTRICTED"
case unrestricted = "UNRESTRICTED"
public var description: String { return self.rawValue }
}
public enum EncryptionMethod: String, CustomStringConvertible, Codable {
case aes128 = "AES_128"
case sampleAes = "SAMPLE_AES"
public var description: String { return self.rawValue }
}
public enum ManifestLayout: String, CustomStringConvertible, Codable {
case compact = "COMPACT"
case full = "FULL"
public var description: String { return self.rawValue }
}
public enum Origination: String, CustomStringConvertible, Codable {
case allow = "ALLOW"
case deny = "DENY"
public var description: String { return self.rawValue }
}
public enum PlaylistType: String, CustomStringConvertible, Codable {
case event = "EVENT"
case none = "NONE"
case vod = "VOD"
public var description: String { return self.rawValue }
}
public enum Profile: String, CustomStringConvertible, Codable {
case hbbtv15 = "HBBTV_1_5"
case none = "NONE"
public var description: String { return self.rawValue }
}
public enum SegmentTemplateFormat: String, CustomStringConvertible, Codable {
case numberWithDuration = "NUMBER_WITH_DURATION"
case numberWithTimeline = "NUMBER_WITH_TIMELINE"
case timeWithTimeline = "TIME_WITH_TIMELINE"
public var description: String { return self.rawValue }
}
public enum Status: String, CustomStringConvertible, Codable {
case failed = "FAILED"
case inProgress = "IN_PROGRESS"
case succeeded = "SUCCEEDED"
public var description: String { return self.rawValue }
}
public enum StreamOrder: String, CustomStringConvertible, Codable {
case original = "ORIGINAL"
case videoBitrateAscending = "VIDEO_BITRATE_ASCENDING"
case videoBitrateDescending = "VIDEO_BITRATE_DESCENDING"
public var description: String { return self.rawValue }
}
public enum UtcTiming: String, CustomStringConvertible, Codable {
case httpHead = "HTTP-HEAD"
case httpIso = "HTTP-ISO"
case none = "NONE"
public var description: String { return self.rawValue }
}
public enum Adtriggerselement: String, CustomStringConvertible, Codable {
case `break` = "BREAK"
case distributorAdvertisement = "DISTRIBUTOR_ADVERTISEMENT"
case distributorOverlayPlacementOpportunity = "DISTRIBUTOR_OVERLAY_PLACEMENT_OPPORTUNITY"
case distributorPlacementOpportunity = "DISTRIBUTOR_PLACEMENT_OPPORTUNITY"
case providerAdvertisement = "PROVIDER_ADVERTISEMENT"
case providerOverlayPlacementOpportunity = "PROVIDER_OVERLAY_PLACEMENT_OPPORTUNITY"
case providerPlacementOpportunity = "PROVIDER_PLACEMENT_OPPORTUNITY"
case spliceInsert = "SPLICE_INSERT"
public var description: String { return self.rawValue }
}
public enum Periodtriggerselement: String, CustomStringConvertible, Codable {
case ads = "ADS"
public var description: String { return self.rawValue }
}
// MARK: Shapes
public struct Authorization: AWSEncodableShape & AWSDecodableShape {
/// The Amazon Resource Name (ARN) for the secret in Secrets Manager that your Content Distribution Network (CDN) uses for authorization to access your endpoint.
public let cdnIdentifierSecret: String
/// The Amazon Resource Name (ARN) for the IAM role that allows MediaPackage to communicate with AWS Secrets Manager.
public let secretsRoleArn: String
public init(cdnIdentifierSecret: String, secretsRoleArn: String) {
self.cdnIdentifierSecret = cdnIdentifierSecret
self.secretsRoleArn = secretsRoleArn
}
private enum CodingKeys: String, CodingKey {
case cdnIdentifierSecret
case secretsRoleArn
}
}
public struct Channel: AWSDecodableShape {
/// The Amazon Resource Name (ARN) assigned to the Channel.
public let arn: String?
/// A short text description of the Channel.
public let description: String?
public let egressAccessLogs: EgressAccessLogs?
public let hlsIngest: HlsIngest?
/// The ID of the Channel.
public let id: String?
public let ingressAccessLogs: IngressAccessLogs?
public let tags: [String: String]?
public init(arn: String? = nil, description: String? = nil, egressAccessLogs: EgressAccessLogs? = nil, hlsIngest: HlsIngest? = nil, id: String? = nil, ingressAccessLogs: IngressAccessLogs? = nil, tags: [String: String]? = nil) {
self.arn = arn
self.description = description
self.egressAccessLogs = egressAccessLogs
self.hlsIngest = hlsIngest
self.id = id
self.ingressAccessLogs = ingressAccessLogs
self.tags = tags
}
private enum CodingKeys: String, CodingKey {
case arn
case description
case egressAccessLogs
case hlsIngest
case id
case ingressAccessLogs
case tags
}
}
public struct CmafEncryption: AWSEncodableShape & AWSDecodableShape {
/// Time (in seconds) between each encryption key rotation.
public let keyRotationIntervalSeconds: Int?
public let spekeKeyProvider: SpekeKeyProvider
public init(keyRotationIntervalSeconds: Int? = nil, spekeKeyProvider: SpekeKeyProvider) {
self.keyRotationIntervalSeconds = keyRotationIntervalSeconds
self.spekeKeyProvider = spekeKeyProvider
}
private enum CodingKeys: String, CodingKey {
case keyRotationIntervalSeconds
case spekeKeyProvider
}
}
public struct CmafPackage: AWSDecodableShape {
public let encryption: CmafEncryption?
/// A list of HLS manifest configurations
public let hlsManifests: [HlsManifest]?
/// Duration (in seconds) of each segment. Actual segments will be
/// rounded to the nearest multiple of the source segment duration.
public let segmentDurationSeconds: Int?
/// An optional custom string that is prepended to the name of each segment. If not specified, it defaults to the ChannelId.
public let segmentPrefix: String?
public let streamSelection: StreamSelection?
public init(encryption: CmafEncryption? = nil, hlsManifests: [HlsManifest]? = nil, segmentDurationSeconds: Int? = nil, segmentPrefix: String? = nil, streamSelection: StreamSelection? = nil) {
self.encryption = encryption
self.hlsManifests = hlsManifests
self.segmentDurationSeconds = segmentDurationSeconds
self.segmentPrefix = segmentPrefix
self.streamSelection = streamSelection
}
private enum CodingKeys: String, CodingKey {
case encryption
case hlsManifests
case segmentDurationSeconds
case segmentPrefix
case streamSelection
}
}
public struct CmafPackageCreateOrUpdateParameters: AWSEncodableShape {
public let encryption: CmafEncryption?
/// A list of HLS manifest configurations
public let hlsManifests: [HlsManifestCreateOrUpdateParameters]?
/// Duration (in seconds) of each segment. Actual segments will be
/// rounded to the nearest multiple of the source segment duration.
public let segmentDurationSeconds: Int?
/// An optional custom string that is prepended to the name of each segment. If not specified, it defaults to the ChannelId.
public let segmentPrefix: String?
public let streamSelection: StreamSelection?
public init(encryption: CmafEncryption? = nil, hlsManifests: [HlsManifestCreateOrUpdateParameters]? = nil, segmentDurationSeconds: Int? = nil, segmentPrefix: String? = nil, streamSelection: StreamSelection? = nil) {
self.encryption = encryption
self.hlsManifests = hlsManifests
self.segmentDurationSeconds = segmentDurationSeconds
self.segmentPrefix = segmentPrefix
self.streamSelection = streamSelection
}
private enum CodingKeys: String, CodingKey {
case encryption
case hlsManifests
case segmentDurationSeconds
case segmentPrefix
case streamSelection
}
}
public struct ConfigureLogsRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "id", location: .uri(locationName: "id"))
]
public let egressAccessLogs: EgressAccessLogs?
public let id: String
public let ingressAccessLogs: IngressAccessLogs?
public init(egressAccessLogs: EgressAccessLogs? = nil, id: String, ingressAccessLogs: IngressAccessLogs? = nil) {
self.egressAccessLogs = egressAccessLogs
self.id = id
self.ingressAccessLogs = ingressAccessLogs
}
private enum CodingKeys: String, CodingKey {
case egressAccessLogs
case ingressAccessLogs
}
}
public struct ConfigureLogsResponse: AWSDecodableShape {
public let arn: String?
public let description: String?
public let egressAccessLogs: EgressAccessLogs?
public let hlsIngest: HlsIngest?
public let id: String?
public let ingressAccessLogs: IngressAccessLogs?
public let tags: [String: String]?
public init(arn: String? = nil, description: String? = nil, egressAccessLogs: EgressAccessLogs? = nil, hlsIngest: HlsIngest? = nil, id: String? = nil, ingressAccessLogs: IngressAccessLogs? = nil, tags: [String: String]? = nil) {
self.arn = arn
self.description = description
self.egressAccessLogs = egressAccessLogs
self.hlsIngest = hlsIngest
self.id = id
self.ingressAccessLogs = ingressAccessLogs
self.tags = tags
}
private enum CodingKeys: String, CodingKey {
case arn
case description
case egressAccessLogs
case hlsIngest
case id
case ingressAccessLogs
case tags
}
}
public struct CreateChannelRequest: AWSEncodableShape {
public let description: String?
public let id: String
public let tags: [String: String]?
public init(description: String? = nil, id: String, tags: [String: String]? = nil) {
self.description = description
self.id = id
self.tags = tags
}
private enum CodingKeys: String, CodingKey {
case description
case id
case tags
}
}
public struct CreateChannelResponse: AWSDecodableShape {
public let arn: String?
public let description: String?
public let egressAccessLogs: EgressAccessLogs?
public let hlsIngest: HlsIngest?
public let id: String?
public let ingressAccessLogs: IngressAccessLogs?
public let tags: [String: String]?
public init(arn: String? = nil, description: String? = nil, egressAccessLogs: EgressAccessLogs? = nil, hlsIngest: HlsIngest? = nil, id: String? = nil, ingressAccessLogs: IngressAccessLogs? = nil, tags: [String: String]? = nil) {
self.arn = arn
self.description = description
self.egressAccessLogs = egressAccessLogs
self.hlsIngest = hlsIngest
self.id = id
self.ingressAccessLogs = ingressAccessLogs
self.tags = tags
}
private enum CodingKeys: String, CodingKey {
case arn
case description
case egressAccessLogs
case hlsIngest
case id
case ingressAccessLogs
case tags
}
}
public struct CreateHarvestJobRequest: AWSEncodableShape {
public let endTime: String
public let id: String
public let originEndpointId: String
public let s3Destination: S3Destination
public let startTime: String
public init(endTime: String, id: String, originEndpointId: String, s3Destination: S3Destination, startTime: String) {
self.endTime = endTime
self.id = id
self.originEndpointId = originEndpointId
self.s3Destination = s3Destination
self.startTime = startTime
}
private enum CodingKeys: String, CodingKey {
case endTime
case id
case originEndpointId
case s3Destination
case startTime
}
}
public struct CreateHarvestJobResponse: AWSDecodableShape {
public let arn: String?
public let channelId: String?
public let createdAt: String?
public let endTime: String?
public let id: String?
public let originEndpointId: String?
public let s3Destination: S3Destination?
public let startTime: String?
public let status: Status?
public init(arn: String? = nil, channelId: String? = nil, createdAt: String? = nil, endTime: String? = nil, id: String? = nil, originEndpointId: String? = nil, s3Destination: S3Destination? = nil, startTime: String? = nil, status: Status? = nil) {
self.arn = arn
self.channelId = channelId
self.createdAt = createdAt
self.endTime = endTime
self.id = id
self.originEndpointId = originEndpointId
self.s3Destination = s3Destination
self.startTime = startTime
self.status = status
}
private enum CodingKeys: String, CodingKey {
case arn
case channelId
case createdAt
case endTime
case id
case originEndpointId
case s3Destination
case startTime
case status
}
}
public struct CreateOriginEndpointRequest: AWSEncodableShape {
public let authorization: Authorization?
public let channelId: String
public let cmafPackage: CmafPackageCreateOrUpdateParameters?
public let dashPackage: DashPackage?
public let description: String?
public let hlsPackage: HlsPackage?
public let id: String
public let manifestName: String?
public let mssPackage: MssPackage?
public let origination: Origination?
public let startoverWindowSeconds: Int?
public let tags: [String: String]?
public let timeDelaySeconds: Int?
public let whitelist: [String]?
public init(authorization: Authorization? = nil, channelId: String, cmafPackage: CmafPackageCreateOrUpdateParameters? = nil, dashPackage: DashPackage? = nil, description: String? = nil, hlsPackage: HlsPackage? = nil, id: String, manifestName: String? = nil, mssPackage: MssPackage? = nil, origination: Origination? = nil, startoverWindowSeconds: Int? = nil, tags: [String: String]? = nil, timeDelaySeconds: Int? = nil, whitelist: [String]? = nil) {
self.authorization = authorization
self.channelId = channelId
self.cmafPackage = cmafPackage
self.dashPackage = dashPackage
self.description = description
self.hlsPackage = hlsPackage
self.id = id
self.manifestName = manifestName
self.mssPackage = mssPackage
self.origination = origination
self.startoverWindowSeconds = startoverWindowSeconds
self.tags = tags
self.timeDelaySeconds = timeDelaySeconds
self.whitelist = whitelist
}
private enum CodingKeys: String, CodingKey {
case authorization
case channelId
case cmafPackage
case dashPackage
case description
case hlsPackage
case id
case manifestName
case mssPackage
case origination
case startoverWindowSeconds
case tags
case timeDelaySeconds
case whitelist
}
}
public struct CreateOriginEndpointResponse: AWSDecodableShape {
public let arn: String?
public let authorization: Authorization?
public let channelId: String?
public let cmafPackage: CmafPackage?
public let dashPackage: DashPackage?
public let description: String?
public let hlsPackage: HlsPackage?
public let id: String?
public let manifestName: String?
public let mssPackage: MssPackage?
public let origination: Origination?
public let startoverWindowSeconds: Int?
public let tags: [String: String]?
public let timeDelaySeconds: Int?
public let url: String?
public let whitelist: [String]?
public init(arn: String? = nil, authorization: Authorization? = nil, channelId: String? = nil, cmafPackage: CmafPackage? = nil, dashPackage: DashPackage? = nil, description: String? = nil, hlsPackage: HlsPackage? = nil, id: String? = nil, manifestName: String? = nil, mssPackage: MssPackage? = nil, origination: Origination? = nil, startoverWindowSeconds: Int? = nil, tags: [String: String]? = nil, timeDelaySeconds: Int? = nil, url: String? = nil, whitelist: [String]? = nil) {
self.arn = arn
self.authorization = authorization
self.channelId = channelId
self.cmafPackage = cmafPackage
self.dashPackage = dashPackage
self.description = description
self.hlsPackage = hlsPackage
self.id = id
self.manifestName = manifestName
self.mssPackage = mssPackage
self.origination = origination
self.startoverWindowSeconds = startoverWindowSeconds
self.tags = tags
self.timeDelaySeconds = timeDelaySeconds
self.url = url
self.whitelist = whitelist
}
private enum CodingKeys: String, CodingKey {
case arn
case authorization
case channelId
case cmafPackage
case dashPackage
case description
case hlsPackage
case id
case manifestName
case mssPackage
case origination
case startoverWindowSeconds
case tags
case timeDelaySeconds
case url
case whitelist
}
}
public struct DashEncryption: AWSEncodableShape & AWSDecodableShape {
/// Time (in seconds) between each encryption key rotation.
public let keyRotationIntervalSeconds: Int?
public let spekeKeyProvider: SpekeKeyProvider
public init(keyRotationIntervalSeconds: Int? = nil, spekeKeyProvider: SpekeKeyProvider) {
self.keyRotationIntervalSeconds = keyRotationIntervalSeconds
self.spekeKeyProvider = spekeKeyProvider
}
private enum CodingKeys: String, CodingKey {
case keyRotationIntervalSeconds
case spekeKeyProvider
}
}
public struct DashPackage: AWSEncodableShape & AWSDecodableShape {
public let adsOnDeliveryRestrictions: AdsOnDeliveryRestrictions?
public let adTriggers: [Adtriggerselement]?
public let encryption: DashEncryption?
/// Determines the position of some tags in the Media Presentation Description (MPD). When set to FULL, elements like SegmentTemplate and ContentProtection are included in each Representation. When set to COMPACT, duplicate elements are combined and presented at the AdaptationSet level.
public let manifestLayout: ManifestLayout?
/// Time window (in seconds) contained in each manifest.
public let manifestWindowSeconds: Int?
/// Minimum duration (in seconds) that a player will buffer media before starting the presentation.
public let minBufferTimeSeconds: Int?
/// Minimum duration (in seconds) between potential changes to the Dynamic Adaptive Streaming over HTTP (DASH) Media Presentation Description (MPD).
public let minUpdatePeriodSeconds: Int?
/// A list of triggers that controls when the outgoing Dynamic Adaptive Streaming over HTTP (DASH)
/// Media Presentation Description (MPD) will be partitioned into multiple periods. If empty, the content will not
/// be partitioned into more than one period. If the list contains "ADS", new periods will be created where
/// the Channel source contains SCTE-35 ad markers.
public let periodTriggers: [Periodtriggerselement]?
/// The Dynamic Adaptive Streaming over HTTP (DASH) profile type. When set to "HBBTV_1_5", HbbTV 1.5 compliant output is enabled.
public let profile: Profile?
/// Duration (in seconds) of each segment. Actual segments will be
/// rounded to the nearest multiple of the source segment duration.
public let segmentDurationSeconds: Int?
/// Determines the type of SegmentTemplate included in the Media Presentation Description (MPD). When set to NUMBER_WITH_TIMELINE, a full timeline is presented in each SegmentTemplate, with $Number$ media URLs. When set to TIME_WITH_TIMELINE, a full timeline is presented in each SegmentTemplate, with $Time$ media URLs. When set to NUMBER_WITH_DURATION, only a duration is included in each SegmentTemplate, with $Number$ media URLs.
public let segmentTemplateFormat: SegmentTemplateFormat?
public let streamSelection: StreamSelection?
/// Duration (in seconds) to delay live content before presentation.
public let suggestedPresentationDelaySeconds: Int?
/// Determines the type of UTCTiming included in the Media Presentation Description (MPD)
public let utcTiming: UtcTiming?
/// Specifies the value attribute of the UTCTiming field when utcTiming is set to HTTP-ISO or HTTP-HEAD
public let utcTimingUri: String?
public init(adsOnDeliveryRestrictions: AdsOnDeliveryRestrictions? = nil, adTriggers: [Adtriggerselement]? = nil, encryption: DashEncryption? = nil, manifestLayout: ManifestLayout? = nil, manifestWindowSeconds: Int? = nil, minBufferTimeSeconds: Int? = nil, minUpdatePeriodSeconds: Int? = nil, periodTriggers: [Periodtriggerselement]? = nil, profile: Profile? = nil, segmentDurationSeconds: Int? = nil, segmentTemplateFormat: SegmentTemplateFormat? = nil, streamSelection: StreamSelection? = nil, suggestedPresentationDelaySeconds: Int? = nil, utcTiming: UtcTiming? = nil, utcTimingUri: String? = nil) {
self.adsOnDeliveryRestrictions = adsOnDeliveryRestrictions
self.adTriggers = adTriggers
self.encryption = encryption
self.manifestLayout = manifestLayout
self.manifestWindowSeconds = manifestWindowSeconds
self.minBufferTimeSeconds = minBufferTimeSeconds
self.minUpdatePeriodSeconds = minUpdatePeriodSeconds
self.periodTriggers = periodTriggers
self.profile = profile
self.segmentDurationSeconds = segmentDurationSeconds
self.segmentTemplateFormat = segmentTemplateFormat
self.streamSelection = streamSelection
self.suggestedPresentationDelaySeconds = suggestedPresentationDelaySeconds
self.utcTiming = utcTiming
self.utcTimingUri = utcTimingUri
}
private enum CodingKeys: String, CodingKey {
case adsOnDeliveryRestrictions
case adTriggers
case encryption
case manifestLayout
case manifestWindowSeconds
case minBufferTimeSeconds
case minUpdatePeriodSeconds
case periodTriggers
case profile
case segmentDurationSeconds
case segmentTemplateFormat
case streamSelection
case suggestedPresentationDelaySeconds
case utcTiming
case utcTimingUri
}
}
public struct DeleteChannelRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "id", location: .uri(locationName: "id"))
]
public let id: String
public init(id: String) {
self.id = id
}
private enum CodingKeys: CodingKey {}
}
public struct DeleteChannelResponse: AWSDecodableShape {
public init() {}
}
public struct DeleteOriginEndpointRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "id", location: .uri(locationName: "id"))
]
public let id: String
public init(id: String) {
self.id = id
}
private enum CodingKeys: CodingKey {}
}
public struct DeleteOriginEndpointResponse: AWSDecodableShape {
public init() {}
}
public struct DescribeChannelRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "id", location: .uri(locationName: "id"))
]
public let id: String
public init(id: String) {
self.id = id
}
private enum CodingKeys: CodingKey {}
}
public struct DescribeChannelResponse: AWSDecodableShape {
public let arn: String?
public let description: String?
public let egressAccessLogs: EgressAccessLogs?
public let hlsIngest: HlsIngest?
public let id: String?
public let ingressAccessLogs: IngressAccessLogs?
public let tags: [String: String]?
public init(arn: String? = nil, description: String? = nil, egressAccessLogs: EgressAccessLogs? = nil, hlsIngest: HlsIngest? = nil, id: String? = nil, ingressAccessLogs: IngressAccessLogs? = nil, tags: [String: String]? = nil) {
self.arn = arn
self.description = description
self.egressAccessLogs = egressAccessLogs
self.hlsIngest = hlsIngest
self.id = id
self.ingressAccessLogs = ingressAccessLogs
self.tags = tags
}
private enum CodingKeys: String, CodingKey {
case arn
case description
case egressAccessLogs
case hlsIngest
case id
case ingressAccessLogs
case tags
}
}
public struct DescribeHarvestJobRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "id", location: .uri(locationName: "id"))
]
public let id: String
public init(id: String) {
self.id = id
}
private enum CodingKeys: CodingKey {}
}
public struct DescribeHarvestJobResponse: AWSDecodableShape {
public let arn: String?
public let channelId: String?
public let createdAt: String?
public let endTime: String?
public let id: String?
public let originEndpointId: String?
public let s3Destination: S3Destination?
public let startTime: String?
public let status: Status?
public init(arn: String? = nil, channelId: String? = nil, createdAt: String? = nil, endTime: String? = nil, id: String? = nil, originEndpointId: String? = nil, s3Destination: S3Destination? = nil, startTime: String? = nil, status: Status? = nil) {
self.arn = arn
self.channelId = channelId
self.createdAt = createdAt
self.endTime = endTime
self.id = id
self.originEndpointId = originEndpointId
self.s3Destination = s3Destination
self.startTime = startTime
self.status = status
}
private enum CodingKeys: String, CodingKey {
case arn
case channelId
case createdAt
case endTime
case id
case originEndpointId
case s3Destination
case startTime
case status
}
}
public struct DescribeOriginEndpointRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "id", location: .uri(locationName: "id"))
]
public let id: String
public init(id: String) {
self.id = id
}
private enum CodingKeys: CodingKey {}
}
public struct DescribeOriginEndpointResponse: AWSDecodableShape {
public let arn: String?
public let authorization: Authorization?
public let channelId: String?
public let cmafPackage: CmafPackage?
public let dashPackage: DashPackage?
public let description: String?
public let hlsPackage: HlsPackage?
public let id: String?
public let manifestName: String?
public let mssPackage: MssPackage?
public let origination: Origination?
public let startoverWindowSeconds: Int?
public let tags: [String: String]?
public let timeDelaySeconds: Int?
public let url: String?
public let whitelist: [String]?
public init(arn: String? = nil, authorization: Authorization? = nil, channelId: String? = nil, cmafPackage: CmafPackage? = nil, dashPackage: DashPackage? = nil, description: String? = nil, hlsPackage: HlsPackage? = nil, id: String? = nil, manifestName: String? = nil, mssPackage: MssPackage? = nil, origination: Origination? = nil, startoverWindowSeconds: Int? = nil, tags: [String: String]? = nil, timeDelaySeconds: Int? = nil, url: String? = nil, whitelist: [String]? = nil) {
self.arn = arn
self.authorization = authorization
self.channelId = channelId
self.cmafPackage = cmafPackage
self.dashPackage = dashPackage
self.description = description
self.hlsPackage = hlsPackage
self.id = id
self.manifestName = manifestName
self.mssPackage = mssPackage
self.origination = origination
self.startoverWindowSeconds = startoverWindowSeconds
self.tags = tags
self.timeDelaySeconds = timeDelaySeconds
self.url = url
self.whitelist = whitelist
}
private enum CodingKeys: String, CodingKey {
case arn
case authorization
case channelId
case cmafPackage
case dashPackage
case description
case hlsPackage
case id
case manifestName
case mssPackage
case origination
case startoverWindowSeconds
case tags
case timeDelaySeconds
case url
case whitelist
}
}
public struct EgressAccessLogs: AWSEncodableShape & AWSDecodableShape {
/// Customize the log group name.
public let logGroupName: String?
public init(logGroupName: String? = nil) {
self.logGroupName = logGroupName
}
private enum CodingKeys: String, CodingKey {
case logGroupName
}
}
public struct HarvestJob: AWSDecodableShape {
/// The Amazon Resource Name (ARN) assigned to the HarvestJob.
public let arn: String?
/// The ID of the Channel that the HarvestJob will harvest from.
public let channelId: String?
/// The time the HarvestJob was submitted
public let createdAt: String?
/// The end of the time-window which will be harvested.
public let endTime: String?
/// The ID of the HarvestJob. The ID must be unique within the region
/// and it cannot be changed after the HarvestJob is submitted.
public let id: String?
/// The ID of the OriginEndpoint that the HarvestJob will harvest from.
/// This cannot be changed after the HarvestJob is submitted.
public let originEndpointId: String?
public let s3Destination: S3Destination?
/// The start of the time-window which will be harvested.
public let startTime: String?
/// The current status of the HarvestJob. Consider setting up a CloudWatch Event to listen for
/// HarvestJobs as they succeed or fail. In the event of failure, the CloudWatch Event will
/// include an explanation of why the HarvestJob failed.
public let status: Status?
public init(arn: String? = nil, channelId: String? = nil, createdAt: String? = nil, endTime: String? = nil, id: String? = nil, originEndpointId: String? = nil, s3Destination: S3Destination? = nil, startTime: String? = nil, status: Status? = nil) {
self.arn = arn
self.channelId = channelId
self.createdAt = createdAt
self.endTime = endTime
self.id = id
self.originEndpointId = originEndpointId
self.s3Destination = s3Destination
self.startTime = startTime
self.status = status
}
private enum CodingKeys: String, CodingKey {
case arn
case channelId
case createdAt
case endTime
case id
case originEndpointId
case s3Destination
case startTime
case status
}
}
public struct HlsEncryption: AWSEncodableShape & AWSDecodableShape {
/// A constant initialization vector for encryption (optional).
/// When not specified the initialization vector will be periodically rotated.
public let constantInitializationVector: String?
/// The encryption method to use.
public let encryptionMethod: EncryptionMethod?
/// Interval (in seconds) between each encryption key rotation.
public let keyRotationIntervalSeconds: Int?
/// When enabled, the EXT-X-KEY tag will be repeated in output manifests.
public let repeatExtXKey: Bool?
public let spekeKeyProvider: SpekeKeyProvider
public init(constantInitializationVector: String? = nil, encryptionMethod: EncryptionMethod? = nil, keyRotationIntervalSeconds: Int? = nil, repeatExtXKey: Bool? = nil, spekeKeyProvider: SpekeKeyProvider) {
self.constantInitializationVector = constantInitializationVector
self.encryptionMethod = encryptionMethod
self.keyRotationIntervalSeconds = keyRotationIntervalSeconds
self.repeatExtXKey = repeatExtXKey
self.spekeKeyProvider = spekeKeyProvider
}
private enum CodingKeys: String, CodingKey {
case constantInitializationVector
case encryptionMethod
case keyRotationIntervalSeconds
case repeatExtXKey
case spekeKeyProvider
}
}
public struct HlsIngest: AWSDecodableShape {
/// A list of endpoints to which the source stream should be sent.
public let ingestEndpoints: [IngestEndpoint]?
public init(ingestEndpoints: [IngestEndpoint]? = nil) {
self.ingestEndpoints = ingestEndpoints
}
private enum CodingKeys: String, CodingKey {
case ingestEndpoints
}
}
public struct HlsManifest: AWSDecodableShape {
/// This setting controls how ad markers are included in the packaged OriginEndpoint.
/// "NONE" will omit all SCTE-35 ad markers from the output.
/// "PASSTHROUGH" causes the manifest to contain a copy of the SCTE-35 ad
/// markers (comments) taken directly from the input HTTP Live Streaming (HLS) manifest.
/// "SCTE35_ENHANCED" generates ad markers and blackout tags based on SCTE-35
/// messages in the input source.
/// "DATERANGE" inserts EXT-X-DATERANGE tags to signal ad and program transition events
/// in HLS and CMAF manifests. For this option, you must set a programDateTimeIntervalSeconds value
/// that is greater than 0.
public let adMarkers: AdMarkers?
/// The ID of the manifest. The ID must be unique within the OriginEndpoint and it cannot be changed after it is created.
public let id: String
/// When enabled, an I-Frame only stream will be included in the output.
public let includeIframeOnlyStream: Bool?
/// An optional short string appended to the end of the OriginEndpoint URL. If not specified, defaults to the manifestName for the OriginEndpoint.
public let manifestName: String?
/// The HTTP Live Streaming (HLS) playlist type.
/// When either "EVENT" or "VOD" is specified, a corresponding EXT-X-PLAYLIST-TYPE
/// entry will be included in the media playlist.
public let playlistType: PlaylistType?
/// Time window (in seconds) contained in each parent manifest.
public let playlistWindowSeconds: Int?
/// The interval (in seconds) between each EXT-X-PROGRAM-DATE-TIME tag
/// inserted into manifests. Additionally, when an interval is specified
/// ID3Timed Metadata messages will be generated every 5 seconds using the
/// ingest time of the content.
/// If the interval is not specified, or set to 0, then
/// no EXT-X-PROGRAM-DATE-TIME tags will be inserted into manifests and no
/// ID3Timed Metadata messages will be generated. Note that irrespective
/// of this parameter, if any ID3 Timed Metadata is found in HTTP Live Streaming (HLS) input,
/// it will be passed through to HLS output.
public let programDateTimeIntervalSeconds: Int?
/// The URL of the packaged OriginEndpoint for consumption.
public let url: String?
public init(adMarkers: AdMarkers? = nil, id: String, includeIframeOnlyStream: Bool? = nil, manifestName: String? = nil, playlistType: PlaylistType? = nil, playlistWindowSeconds: Int? = nil, programDateTimeIntervalSeconds: Int? = nil, url: String? = nil) {
self.adMarkers = adMarkers
self.id = id
self.includeIframeOnlyStream = includeIframeOnlyStream
self.manifestName = manifestName
self.playlistType = playlistType
self.playlistWindowSeconds = playlistWindowSeconds
self.programDateTimeIntervalSeconds = programDateTimeIntervalSeconds
self.url = url
}
private enum CodingKeys: String, CodingKey {
case adMarkers
case id
case includeIframeOnlyStream
case manifestName
case playlistType
case playlistWindowSeconds
case programDateTimeIntervalSeconds
case url
}
}
public struct HlsManifestCreateOrUpdateParameters: AWSEncodableShape {
/// This setting controls how ad markers are included in the packaged OriginEndpoint.
/// "NONE" will omit all SCTE-35 ad markers from the output.
/// "PASSTHROUGH" causes the manifest to contain a copy of the SCTE-35 ad
/// markers (comments) taken directly from the input HTTP Live Streaming (HLS) manifest.
/// "SCTE35_ENHANCED" generates ad markers and blackout tags based on SCTE-35
/// messages in the input source.
/// "DATERANGE" inserts EXT-X-DATERANGE tags to signal ad and program transition events
/// in HLS and CMAF manifests. For this option, you must set a programDateTimeIntervalSeconds value
/// that is greater than 0.
public let adMarkers: AdMarkers?
public let adsOnDeliveryRestrictions: AdsOnDeliveryRestrictions?
public let adTriggers: [Adtriggerselement]?
/// The ID of the manifest. The ID must be unique within the OriginEndpoint and it cannot be changed after it is created.
public let id: String
/// When enabled, an I-Frame only stream will be included in the output.
public let includeIframeOnlyStream: Bool?
/// An optional short string appended to the end of the OriginEndpoint URL. If not specified, defaults to the manifestName for the OriginEndpoint.
public let manifestName: String?
/// The HTTP Live Streaming (HLS) playlist type.
/// When either "EVENT" or "VOD" is specified, a corresponding EXT-X-PLAYLIST-TYPE
/// entry will be included in the media playlist.
public let playlistType: PlaylistType?
/// Time window (in seconds) contained in each parent manifest.
public let playlistWindowSeconds: Int?
/// The interval (in seconds) between each EXT-X-PROGRAM-DATE-TIME tag
/// inserted into manifests. Additionally, when an interval is specified
/// ID3Timed Metadata messages will be generated every 5 seconds using the
/// ingest time of the content.
/// If the interval is not specified, or set to 0, then
/// no EXT-X-PROGRAM-DATE-TIME tags will be inserted into manifests and no
/// ID3Timed Metadata messages will be generated. Note that irrespective
/// of this parameter, if any ID3 Timed Metadata is found in HTTP Live Streaming (HLS) input,
/// it will be passed through to HLS output.
public let programDateTimeIntervalSeconds: Int?
public init(adMarkers: AdMarkers? = nil, adsOnDeliveryRestrictions: AdsOnDeliveryRestrictions? = nil, adTriggers: [Adtriggerselement]? = nil, id: String, includeIframeOnlyStream: Bool? = nil, manifestName: String? = nil, playlistType: PlaylistType? = nil, playlistWindowSeconds: Int? = nil, programDateTimeIntervalSeconds: Int? = nil) {
self.adMarkers = adMarkers
self.adsOnDeliveryRestrictions = adsOnDeliveryRestrictions
self.adTriggers = adTriggers
self.id = id
self.includeIframeOnlyStream = includeIframeOnlyStream
self.manifestName = manifestName
self.playlistType = playlistType
self.playlistWindowSeconds = playlistWindowSeconds
self.programDateTimeIntervalSeconds = programDateTimeIntervalSeconds
}
private enum CodingKeys: String, CodingKey {
case adMarkers
case adsOnDeliveryRestrictions
case adTriggers
case id
case includeIframeOnlyStream
case manifestName
case playlistType
case playlistWindowSeconds
case programDateTimeIntervalSeconds
}
}
public struct HlsPackage: AWSEncodableShape & AWSDecodableShape {
/// This setting controls how ad markers are included in the packaged OriginEndpoint.
/// "NONE" will omit all SCTE-35 ad markers from the output.
/// "PASSTHROUGH" causes the manifest to contain a copy of the SCTE-35 ad
/// markers (comments) taken directly from the input HTTP Live Streaming (HLS) manifest.
/// "SCTE35_ENHANCED" generates ad markers and blackout tags based on SCTE-35
/// messages in the input source.
/// "DATERANGE" inserts EXT-X-DATERANGE tags to signal ad and program transition events
/// in HLS and CMAF manifests. For this option, you must set a programDateTimeIntervalSeconds value
/// that is greater than 0.
public let adMarkers: AdMarkers?
public let adsOnDeliveryRestrictions: AdsOnDeliveryRestrictions?
public let adTriggers: [Adtriggerselement]?
public let encryption: HlsEncryption?
/// When enabled, an I-Frame only stream will be included in the output.
public let includeIframeOnlyStream: Bool?
/// The HTTP Live Streaming (HLS) playlist type.
/// When either "EVENT" or "VOD" is specified, a corresponding EXT-X-PLAYLIST-TYPE
/// entry will be included in the media playlist.
public let playlistType: PlaylistType?
/// Time window (in seconds) contained in each parent manifest.
public let playlistWindowSeconds: Int?
/// The interval (in seconds) between each EXT-X-PROGRAM-DATE-TIME tag
/// inserted into manifests. Additionally, when an interval is specified
/// ID3Timed Metadata messages will be generated every 5 seconds using the
/// ingest time of the content.
/// If the interval is not specified, or set to 0, then
/// no EXT-X-PROGRAM-DATE-TIME tags will be inserted into manifests and no
/// ID3Timed Metadata messages will be generated. Note that irrespective
/// of this parameter, if any ID3 Timed Metadata is found in HTTP Live Streaming (HLS) input,
/// it will be passed through to HLS output.
public let programDateTimeIntervalSeconds: Int?
/// Duration (in seconds) of each fragment. Actual fragments will be
/// rounded to the nearest multiple of the source fragment duration.
public let segmentDurationSeconds: Int?
public let streamSelection: StreamSelection?
/// When enabled, audio streams will be placed in rendition groups in the output.
public let useAudioRenditionGroup: Bool?
public init(adMarkers: AdMarkers? = nil, adsOnDeliveryRestrictions: AdsOnDeliveryRestrictions? = nil, adTriggers: [Adtriggerselement]? = nil, encryption: HlsEncryption? = nil, includeIframeOnlyStream: Bool? = nil, playlistType: PlaylistType? = nil, playlistWindowSeconds: Int? = nil, programDateTimeIntervalSeconds: Int? = nil, segmentDurationSeconds: Int? = nil, streamSelection: StreamSelection? = nil, useAudioRenditionGroup: Bool? = nil) {
self.adMarkers = adMarkers
self.adsOnDeliveryRestrictions = adsOnDeliveryRestrictions
self.adTriggers = adTriggers
self.encryption = encryption
self.includeIframeOnlyStream = includeIframeOnlyStream
self.playlistType = playlistType
self.playlistWindowSeconds = playlistWindowSeconds
self.programDateTimeIntervalSeconds = programDateTimeIntervalSeconds
self.segmentDurationSeconds = segmentDurationSeconds
self.streamSelection = streamSelection
self.useAudioRenditionGroup = useAudioRenditionGroup
}
private enum CodingKeys: String, CodingKey {
case adMarkers
case adsOnDeliveryRestrictions
case adTriggers
case encryption
case includeIframeOnlyStream
case playlistType
case playlistWindowSeconds
case programDateTimeIntervalSeconds
case segmentDurationSeconds
case streamSelection
case useAudioRenditionGroup
}
}
public struct IngestEndpoint: AWSDecodableShape {
/// The system generated unique identifier for the IngestEndpoint
public let id: String?
/// The system generated password for ingest authentication.
public let password: String?
/// The ingest URL to which the source stream should be sent.
public let url: String?
/// The system generated username for ingest authentication.
public let username: String?
public init(id: String? = nil, password: String? = nil, url: String? = nil, username: String? = nil) {
self.id = id
self.password = password
self.url = url
self.username = username
}
private enum CodingKeys: String, CodingKey {
case id
case password
case url
case username
}
}
public struct IngressAccessLogs: AWSEncodableShape & AWSDecodableShape {
/// Customize the log group name.
public let logGroupName: String?
public init(logGroupName: String? = nil) {
self.logGroupName = logGroupName
}
private enum CodingKeys: String, CodingKey {
case logGroupName
}
}
public struct ListChannelsRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "maxResults", location: .querystring(locationName: "maxResults")),
AWSMemberEncoding(label: "nextToken", location: .querystring(locationName: "nextToken"))
]
public let maxResults: Int?
public let nextToken: String?
public init(maxResults: Int? = nil, nextToken: String? = nil) {
self.maxResults = maxResults
self.nextToken = nextToken
}
public func validate(name: String) throws {
try self.validate(self.maxResults, name: "maxResults", parent: name, max: 1000)
try self.validate(self.maxResults, name: "maxResults", parent: name, min: 1)
}
private enum CodingKeys: CodingKey {}
}
public struct ListChannelsResponse: AWSDecodableShape {
public let channels: [Channel]?
public let nextToken: String?
public init(channels: [Channel]? = nil, nextToken: String? = nil) {
self.channels = channels
self.nextToken = nextToken
}
private enum CodingKeys: String, CodingKey {
case channels
case nextToken
}
}
public struct ListHarvestJobsRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "includeChannelId", location: .querystring(locationName: "includeChannelId")),
AWSMemberEncoding(label: "includeStatus", location: .querystring(locationName: "includeStatus")),
AWSMemberEncoding(label: "maxResults", location: .querystring(locationName: "maxResults")),
AWSMemberEncoding(label: "nextToken", location: .querystring(locationName: "nextToken"))
]
public let includeChannelId: String?
public let includeStatus: String?
public let maxResults: Int?
public let nextToken: String?
public init(includeChannelId: String? = nil, includeStatus: String? = nil, maxResults: Int? = nil, nextToken: String? = nil) {
self.includeChannelId = includeChannelId
self.includeStatus = includeStatus
self.maxResults = maxResults
self.nextToken = nextToken
}
public func validate(name: String) throws {
try self.validate(self.maxResults, name: "maxResults", parent: name, max: 1000)
try self.validate(self.maxResults, name: "maxResults", parent: name, min: 1)
}
private enum CodingKeys: CodingKey {}
}
public struct ListHarvestJobsResponse: AWSDecodableShape {
public let harvestJobs: [HarvestJob]?
public let nextToken: String?
public init(harvestJobs: [HarvestJob]? = nil, nextToken: String? = nil) {
self.harvestJobs = harvestJobs
self.nextToken = nextToken
}
private enum CodingKeys: String, CodingKey {
case harvestJobs
case nextToken
}
}
public struct ListOriginEndpointsRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "channelId", location: .querystring(locationName: "channelId")),
AWSMemberEncoding(label: "maxResults", location: .querystring(locationName: "maxResults")),
AWSMemberEncoding(label: "nextToken", location: .querystring(locationName: "nextToken"))
]
public let channelId: String?
public let maxResults: Int?
public let nextToken: String?
public init(channelId: String? = nil, maxResults: Int? = nil, nextToken: String? = nil) {
self.channelId = channelId
self.maxResults = maxResults
self.nextToken = nextToken
}
public func validate(name: String) throws {
try self.validate(self.maxResults, name: "maxResults", parent: name, max: 1000)
try self.validate(self.maxResults, name: "maxResults", parent: name, min: 1)
}
private enum CodingKeys: CodingKey {}
}
public struct ListOriginEndpointsResponse: AWSDecodableShape {
public let nextToken: String?
public let originEndpoints: [OriginEndpoint]?
public init(nextToken: String? = nil, originEndpoints: [OriginEndpoint]? = nil) {
self.nextToken = nextToken
self.originEndpoints = originEndpoints
}
private enum CodingKeys: String, CodingKey {
case nextToken
case originEndpoints
}
}
public struct ListTagsForResourceRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "resourceArn", location: .uri(locationName: "resource-arn"))
]
public let resourceArn: String
public init(resourceArn: String) {
self.resourceArn = resourceArn
}
private enum CodingKeys: CodingKey {}
}
public struct ListTagsForResourceResponse: AWSDecodableShape {
public let tags: [String: String]?
public init(tags: [String: String]? = nil) {
self.tags = tags
}
private enum CodingKeys: String, CodingKey {
case tags
}
}
public struct MssEncryption: AWSEncodableShape & AWSDecodableShape {
public let spekeKeyProvider: SpekeKeyProvider
public init(spekeKeyProvider: SpekeKeyProvider) {
self.spekeKeyProvider = spekeKeyProvider
}
private enum CodingKeys: String, CodingKey {
case spekeKeyProvider
}
}
public struct MssPackage: AWSEncodableShape & AWSDecodableShape {
public let encryption: MssEncryption?
/// The time window (in seconds) contained in each manifest.
public let manifestWindowSeconds: Int?
/// The duration (in seconds) of each segment.
public let segmentDurationSeconds: Int?
public let streamSelection: StreamSelection?
public init(encryption: MssEncryption? = nil, manifestWindowSeconds: Int? = nil, segmentDurationSeconds: Int? = nil, streamSelection: StreamSelection? = nil) {
self.encryption = encryption
self.manifestWindowSeconds = manifestWindowSeconds
self.segmentDurationSeconds = segmentDurationSeconds
self.streamSelection = streamSelection
}
private enum CodingKeys: String, CodingKey {
case encryption
case manifestWindowSeconds
case segmentDurationSeconds
case streamSelection
}
}
public struct OriginEndpoint: AWSDecodableShape {
/// The Amazon Resource Name (ARN) assigned to the OriginEndpoint.
public let arn: String?
public let authorization: Authorization?
/// The ID of the Channel the OriginEndpoint is associated with.
public let channelId: String?
public let cmafPackage: CmafPackage?
public let dashPackage: DashPackage?
/// A short text description of the OriginEndpoint.
public let description: String?
public let hlsPackage: HlsPackage?
/// The ID of the OriginEndpoint.
public let id: String?
/// A short string appended to the end of the OriginEndpoint URL.
public let manifestName: String?
public let mssPackage: MssPackage?
/// Control whether origination of video is allowed for this OriginEndpoint. If set to ALLOW, the OriginEndpoint
/// may by requested, pursuant to any other form of access control. If set to DENY, the OriginEndpoint may not be
/// requested. This can be helpful for Live to VOD harvesting, or for temporarily disabling origination
public let origination: Origination?
/// Maximum duration (seconds) of content to retain for startover playback.
/// If not specified, startover playback will be disabled for the OriginEndpoint.
public let startoverWindowSeconds: Int?
public let tags: [String: String]?
/// Amount of delay (seconds) to enforce on the playback of live content.
/// If not specified, there will be no time delay in effect for the OriginEndpoint.
public let timeDelaySeconds: Int?
/// The URL of the packaged OriginEndpoint for consumption.
public let url: String?
/// A list of source IP CIDR blocks that will be allowed to access the OriginEndpoint.
public let whitelist: [String]?
public init(arn: String? = nil, authorization: Authorization? = nil, channelId: String? = nil, cmafPackage: CmafPackage? = nil, dashPackage: DashPackage? = nil, description: String? = nil, hlsPackage: HlsPackage? = nil, id: String? = nil, manifestName: String? = nil, mssPackage: MssPackage? = nil, origination: Origination? = nil, startoverWindowSeconds: Int? = nil, tags: [String: String]? = nil, timeDelaySeconds: Int? = nil, url: String? = nil, whitelist: [String]? = nil) {
self.arn = arn
self.authorization = authorization
self.channelId = channelId
self.cmafPackage = cmafPackage
self.dashPackage = dashPackage
self.description = description
self.hlsPackage = hlsPackage
self.id = id
self.manifestName = manifestName
self.mssPackage = mssPackage
self.origination = origination
self.startoverWindowSeconds = startoverWindowSeconds
self.tags = tags
self.timeDelaySeconds = timeDelaySeconds
self.url = url
self.whitelist = whitelist
}
private enum CodingKeys: String, CodingKey {
case arn
case authorization
case channelId
case cmafPackage
case dashPackage
case description
case hlsPackage
case id
case manifestName
case mssPackage
case origination
case startoverWindowSeconds
case tags
case timeDelaySeconds
case url
case whitelist
}
}
public struct RotateChannelCredentialsRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "id", location: .uri(locationName: "id"))
]
public let id: String
public init(id: String) {
self.id = id
}
private enum CodingKeys: CodingKey {}
}
public struct RotateChannelCredentialsResponse: AWSDecodableShape {
public let arn: String?
public let description: String?
public let egressAccessLogs: EgressAccessLogs?
public let hlsIngest: HlsIngest?
public let id: String?
public let ingressAccessLogs: IngressAccessLogs?
public let tags: [String: String]?
public init(arn: String? = nil, description: String? = nil, egressAccessLogs: EgressAccessLogs? = nil, hlsIngest: HlsIngest? = nil, id: String? = nil, ingressAccessLogs: IngressAccessLogs? = nil, tags: [String: String]? = nil) {
self.arn = arn
self.description = description
self.egressAccessLogs = egressAccessLogs
self.hlsIngest = hlsIngest
self.id = id
self.ingressAccessLogs = ingressAccessLogs
self.tags = tags
}
private enum CodingKeys: String, CodingKey {
case arn
case description
case egressAccessLogs
case hlsIngest
case id
case ingressAccessLogs
case tags
}
}
public struct RotateIngestEndpointCredentialsRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "id", location: .uri(locationName: "id")),
AWSMemberEncoding(label: "ingestEndpointId", location: .uri(locationName: "ingest_endpoint_id"))
]
public let id: String
public let ingestEndpointId: String
public init(id: String, ingestEndpointId: String) {
self.id = id
self.ingestEndpointId = ingestEndpointId
}
private enum CodingKeys: CodingKey {}
}
public struct RotateIngestEndpointCredentialsResponse: AWSDecodableShape {
public let arn: String?
public let description: String?
public let egressAccessLogs: EgressAccessLogs?
public let hlsIngest: HlsIngest?
public let id: String?
public let ingressAccessLogs: IngressAccessLogs?
public let tags: [String: String]?
public init(arn: String? = nil, description: String? = nil, egressAccessLogs: EgressAccessLogs? = nil, hlsIngest: HlsIngest? = nil, id: String? = nil, ingressAccessLogs: IngressAccessLogs? = nil, tags: [String: String]? = nil) {
self.arn = arn
self.description = description
self.egressAccessLogs = egressAccessLogs
self.hlsIngest = hlsIngest
self.id = id
self.ingressAccessLogs = ingressAccessLogs
self.tags = tags
}
private enum CodingKeys: String, CodingKey {
case arn
case description
case egressAccessLogs
case hlsIngest
case id
case ingressAccessLogs
case tags
}
}
public struct S3Destination: AWSEncodableShape & AWSDecodableShape {
/// The name of an S3 bucket within which harvested content will be exported
public let bucketName: String
/// The key in the specified S3 bucket where the harvested top-level manifest will be placed.
public let manifestKey: String
/// The IAM role used to write to the specified S3 bucket
public let roleArn: String
public init(bucketName: String, manifestKey: String, roleArn: String) {
self.bucketName = bucketName
self.manifestKey = manifestKey
self.roleArn = roleArn
}
private enum CodingKeys: String, CodingKey {
case bucketName
case manifestKey
case roleArn
}
}
public struct SpekeKeyProvider: AWSEncodableShape & AWSDecodableShape {
/// An Amazon Resource Name (ARN) of a Certificate Manager certificate
/// that MediaPackage will use for enforcing secure end-to-end data
/// transfer with the key provider service.
public let certificateArn: String?
/// The resource ID to include in key requests.
public let resourceId: String
/// An Amazon Resource Name (ARN) of an IAM role that AWS Elemental
/// MediaPackage will assume when accessing the key provider service.
public let roleArn: String
/// The system IDs to include in key requests.
public let systemIds: [String]
/// The URL of the external key provider service.
public let url: String
public init(certificateArn: String? = nil, resourceId: String, roleArn: String, systemIds: [String], url: String) {
self.certificateArn = certificateArn
self.resourceId = resourceId
self.roleArn = roleArn
self.systemIds = systemIds
self.url = url
}
private enum CodingKeys: String, CodingKey {
case certificateArn
case resourceId
case roleArn
case systemIds
case url
}
}
public struct StreamSelection: AWSEncodableShape & AWSDecodableShape {
/// The maximum video bitrate (bps) to include in output.
public let maxVideoBitsPerSecond: Int?
/// The minimum video bitrate (bps) to include in output.
public let minVideoBitsPerSecond: Int?
/// A directive that determines the order of streams in the output.
public let streamOrder: StreamOrder?
public init(maxVideoBitsPerSecond: Int? = nil, minVideoBitsPerSecond: Int? = nil, streamOrder: StreamOrder? = nil) {
self.maxVideoBitsPerSecond = maxVideoBitsPerSecond
self.minVideoBitsPerSecond = minVideoBitsPerSecond
self.streamOrder = streamOrder
}
private enum CodingKeys: String, CodingKey {
case maxVideoBitsPerSecond
case minVideoBitsPerSecond
case streamOrder
}
}
public struct TagResourceRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "resourceArn", location: .uri(locationName: "resource-arn"))
]
public let resourceArn: String
public let tags: [String: String]
public init(resourceArn: String, tags: [String: String]) {
self.resourceArn = resourceArn
self.tags = tags
}
private enum CodingKeys: String, CodingKey {
case tags
}
}
public struct UntagResourceRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "resourceArn", location: .uri(locationName: "resource-arn")),
AWSMemberEncoding(label: "tagKeys", location: .querystring(locationName: "tagKeys"))
]
public let resourceArn: String
public let tagKeys: [String]
public init(resourceArn: String, tagKeys: [String]) {
self.resourceArn = resourceArn
self.tagKeys = tagKeys
}
private enum CodingKeys: CodingKey {}
}
public struct UpdateChannelRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "id", location: .uri(locationName: "id"))
]
public let description: String?
public let id: String
public init(description: String? = nil, id: String) {
self.description = description
self.id = id
}
private enum CodingKeys: String, CodingKey {
case description
}
}
public struct UpdateChannelResponse: AWSDecodableShape {
public let arn: String?
public let description: String?
public let egressAccessLogs: EgressAccessLogs?
public let hlsIngest: HlsIngest?
public let id: String?
public let ingressAccessLogs: IngressAccessLogs?
public let tags: [String: String]?
public init(arn: String? = nil, description: String? = nil, egressAccessLogs: EgressAccessLogs? = nil, hlsIngest: HlsIngest? = nil, id: String? = nil, ingressAccessLogs: IngressAccessLogs? = nil, tags: [String: String]? = nil) {
self.arn = arn
self.description = description
self.egressAccessLogs = egressAccessLogs
self.hlsIngest = hlsIngest
self.id = id
self.ingressAccessLogs = ingressAccessLogs
self.tags = tags
}
private enum CodingKeys: String, CodingKey {
case arn
case description
case egressAccessLogs
case hlsIngest
case id
case ingressAccessLogs
case tags
}
}
public struct UpdateOriginEndpointRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "id", location: .uri(locationName: "id"))
]
public let authorization: Authorization?
public let cmafPackage: CmafPackageCreateOrUpdateParameters?
public let dashPackage: DashPackage?
public let description: String?
public let hlsPackage: HlsPackage?
public let id: String
public let manifestName: String?
public let mssPackage: MssPackage?
public let origination: Origination?
public let startoverWindowSeconds: Int?
public let timeDelaySeconds: Int?
public let whitelist: [String]?
public init(authorization: Authorization? = nil, cmafPackage: CmafPackageCreateOrUpdateParameters? = nil, dashPackage: DashPackage? = nil, description: String? = nil, hlsPackage: HlsPackage? = nil, id: String, manifestName: String? = nil, mssPackage: MssPackage? = nil, origination: Origination? = nil, startoverWindowSeconds: Int? = nil, timeDelaySeconds: Int? = nil, whitelist: [String]? = nil) {
self.authorization = authorization
self.cmafPackage = cmafPackage
self.dashPackage = dashPackage
self.description = description
self.hlsPackage = hlsPackage
self.id = id
self.manifestName = manifestName
self.mssPackage = mssPackage
self.origination = origination
self.startoverWindowSeconds = startoverWindowSeconds
self.timeDelaySeconds = timeDelaySeconds
self.whitelist = whitelist
}
private enum CodingKeys: String, CodingKey {
case authorization
case cmafPackage
case dashPackage
case description
case hlsPackage
case manifestName
case mssPackage
case origination
case startoverWindowSeconds
case timeDelaySeconds
case whitelist
}
}
public struct UpdateOriginEndpointResponse: AWSDecodableShape {
public let arn: String?
public let authorization: Authorization?
public let channelId: String?
public let cmafPackage: CmafPackage?
public let dashPackage: DashPackage?
public let description: String?
public let hlsPackage: HlsPackage?
public let id: String?
public let manifestName: String?
public let mssPackage: MssPackage?
public let origination: Origination?
public let startoverWindowSeconds: Int?
public let tags: [String: String]?
public let timeDelaySeconds: Int?
public let url: String?
public let whitelist: [String]?
public init(arn: String? = nil, authorization: Authorization? = nil, channelId: String? = nil, cmafPackage: CmafPackage? = nil, dashPackage: DashPackage? = nil, description: String? = nil, hlsPackage: HlsPackage? = nil, id: String? = nil, manifestName: String? = nil, mssPackage: MssPackage? = nil, origination: Origination? = nil, startoverWindowSeconds: Int? = nil, tags: [String: String]? = nil, timeDelaySeconds: Int? = nil, url: String? = nil, whitelist: [String]? = nil) {
self.arn = arn
self.authorization = authorization
self.channelId = channelId
self.cmafPackage = cmafPackage
self.dashPackage = dashPackage
self.description = description
self.hlsPackage = hlsPackage
self.id = id
self.manifestName = manifestName
self.mssPackage = mssPackage
self.origination = origination
self.startoverWindowSeconds = startoverWindowSeconds
self.tags = tags
self.timeDelaySeconds = timeDelaySeconds
self.url = url
self.whitelist = whitelist
}
private enum CodingKeys: String, CodingKey {
case arn
case authorization
case channelId
case cmafPackage
case dashPackage
case description
case hlsPackage
case id
case manifestName
case mssPackage
case origination
case startoverWindowSeconds
case tags
case timeDelaySeconds
case url
case whitelist
}
}
}
|
apache-2.0
|
6dca9ddaf37dfe3b00ab76042d80df9c
| 41.412174 | 609 | 0.641817 | 4.935974 | false | false | false | false |
galacemiguel/bluehacks2017
|
Project Civ-1/Project Civ/TextCell.swift
|
1
|
1188
|
//
// TextCell.swift
// Project Civ
//
// Created by Carlos Arcenas on 2/18/17.
// Copyright © 2017 Rogue Three. All rights reserved.
//
import UIKit
class TextCell: UICollectionViewCell {
static let font = UIFont(name: "Tofino-Book", size: 14)!
static let inset = UIEdgeInsets(top: 5, left: 15, bottom: 0, right: 15)
static func cellSize(width: CGFloat, string: String) -> CGSize {
return TextSize.size(string, font: TextCell.font, width: width, insets: TextCell.inset).size
}
let label: UILabel = {
let label = UILabel()
label.backgroundColor = UIColor.white
label.numberOfLines = 0
label.font = TextCell.font
label.textColor = UIColor.black
return label
}()
override init(frame: CGRect) {
super.init(frame: frame)
contentView.addSubview(label)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
label.frame = UIEdgeInsetsInsetRect(bounds, TextCell.inset)
print("layoutSubviews \(label.frame)")
}
}
|
mit
|
edc79b5f73bf3b68a8d67efe42e247a7
| 27.261905 | 100 | 0.631003 | 4.164912 | false | false | false | false |
CoderXpert/Weather
|
Weather/CurrentWeatherForecastViewModelType.swift
|
1
|
1701
|
//
// CurrentWeatherForecastViewModelType.swift
// Weather
//
// Created by Adnan Aftab on 3/8/16.
// Copyright © 2016 CX. All rights reserved.
//
import Foundation
//: Notificaitons
enum ForecastViewModelNotificaitons : String {
case GotNewForecastData = "viewModelGotNewForecastData"
case GotNewCurrentWeatherData = "viewModelGotNewCurrentWeatherData"
case GotAnErrorWhileFetchingCurrentWeather = "viewModelFetchCurrentWeather"
case GotNoForecasts = "viewModelGotNoForecasts"
case GotNoCurrentWeatherData = "viewModelGotNoCurrentWeatherData"
case StartLoadingCurrentWeatherInfo = "viewModelStartLoadingCurrentWeatherInfo"
}
protocol CurrentWeatherForecastViewModelType {
//: Current Weather
var currentLocationName:String {get}
var lastUpdateDateAndTimeString:String {get}
var currentTemperatureString:String {get}
var currentMaxTemperatureString:String {get}
var currentMinTemperatureString:String {get}
var currentWeatherConditionIconText:String {get}
var currentWeatherConditionText:String {get}
//: Forecasts
var totalNumberOfTodaysForecasts:Int {get}
var totalNumberOfFutureForecastsExcludingToday:Int {get}
func todayForecastTemperatureStringForIndex(index:Int) -> String?
func todayForecastShortDateTimeStringForIndex(index:Int) -> String?
func todayForecastWeatherConditionIconTextForIndex(index:Int) -> String?
func futureForecastTemperatureStringForIndex(index:Int) -> String?
func futureForecastShortDateTimeStringForIndex(index:Int) -> String?
func futureForecastWeatherConditionIconTextForIndex(index:Int) -> String?
//: Update
func updateWeatherData()->Void
}
|
apache-2.0
|
59c9e0cd98f297bd4538454a45b20923
| 38.55814 | 83 | 0.784118 | 4.956268 | false | false | false | false |
kickstarter/ios-oss
|
KsApi/lib/HTML Parser/HTMLRawText.swift
|
1
|
709
|
import Foundation
public enum HTMLRawText {
enum Base: String {
case htmlClass = "class"
case height
case iframe
case div
case video
case audio
}
enum List: String {
case listItem = "li"
case unorderedList = "ul"
case orderedList = "ol"
}
enum Link: String {
case anchor = "a"
case link = "href"
case source = "src"
}
enum Image: String {
case dataCaption = "data-caption"
case dataSource = "data-src"
case dataImage = "data-image"
case gifExtension = ".gif"
}
enum Video: String {
case high
}
enum KSRSpecific: String {
case templateAsset = "template asset"
case templateOembed = "template oembed"
}
}
|
apache-2.0
|
b3d6b38d39f26171c8693f9a4b8d43b0
| 16.725 | 43 | 0.616361 | 3.731579 | false | false | false | false |
k-thorat/Dotzu
|
Framework/Dotzu/Dotzu/LogNavigationViewController.swift
|
1
|
1051
|
//
// LogNavigationViewController.swift
// exampleWindow
//
// Created by Remi Robert on 20/01/2017.
// Copyright © 2017 Remi Robert. All rights reserved.
//
import UIKit
class LogNavigationViewController: UINavigationController {
override func viewDidLoad() {
super.viewDidLoad()
navigationBar.tintColor = Color.mainGreen
navigationBar.titleTextAttributes = [NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 20),
NSAttributedString.Key.foregroundColor: Color.mainGreen]
let selector = #selector(LogNavigationViewController.exit)
let image = UIImage(named: "close", in: Bundle(for: LogNavigationViewController.self), compatibleWith: nil)
let leftButton = UIBarButtonItem(image: image,
style: .done, target: self, action: selector)
topViewController?.navigationItem.leftBarButtonItem = leftButton
}
@objc func exit() {
dismiss(animated: true, completion: nil)
}
}
|
mit
|
dbb56215d07beceb93dcc5bd36781a3b
| 32.870968 | 115 | 0.662857 | 5.172414 | false | false | false | false |
Acidburn0zzz/firefox-ios
|
WidgetKit/QuickLink.swift
|
1
|
3392
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import SwiftUI
// Enum file that holds the different cases for the Quick Actions small widget with their configurations (string, backgrounds, images) as selected by the user in edit mode. It maps the values of IntentQuickLink enum in the QuickLinkSelectionIntent to the designated values of each case.
enum QuickLink: Int {
case search = 1
case copiedLink
case privateSearch
case closePrivateTabs
public var imageName: String {
switch self {
case .search:
return "faviconFox"
case .privateSearch:
return "smallPrivateMask"
case .copiedLink:
return "copiedLinkIcon"
case .closePrivateTabs:
return "delete"
}
}
public var label: String {
switch self {
case .search:
return String.SearchInFirefoxV2
case .privateSearch:
return String.SearchInPrivateTabLabelV2
case .copiedLink:
return String.GoToCopiedLinkLabelV2
case .closePrivateTabs:
return String.ClosePrivateTabsLabelV2
}
}
public var smallWidgetUrl: URL {
switch self {
case .search:
return linkToContainingApp("?private=false", query: "widget-small-quicklink-open-url")
case .privateSearch:
return linkToContainingApp("?private=true", query: "widget-small-quicklink-open-url")
case .copiedLink:
return linkToContainingApp(query: "widget-small-quicklink-open-copied")
case .closePrivateTabs:
return linkToContainingApp(query: "widget-small-quicklink-close-private-tabs")
}
}
public var mediumWidgetUrl: URL {
switch self {
case .search:
return linkToContainingApp("?private=false", query: "widget-medium-quicklink-open-url")
case .privateSearch:
return linkToContainingApp("?private=true", query: "widget-medium-quicklink-open-url")
case .copiedLink:
return linkToContainingApp(query: "widget-medium-quicklink-open-copied")
case .closePrivateTabs:
return linkToContainingApp(query: "widget-medium-quicklink-close-private-tabs")
}
}
public var backgroundColors: [Color] {
switch self {
case .search:
return [Color("searchButtonColorTwo"), Color("searchButtonColorOne")]
case .privateSearch:
return [Color("privateGradientThree"), Color("privateGradientTwo"),Color("privateGradientOne")]
case .copiedLink:
return [Color("goToCopiedLinkSolid")]
case .closePrivateTabs:
return [Color("privateGradientThree"), Color("privateGradientTwo"),Color("privateGradientOne")]
}
}
static func from(_ configuration: QuickLinkSelectionIntent) -> Self {
switch configuration.quickLink {
case .search:
return .search
case .privateSearch:
return .privateSearch
case .closePrivateTabs:
return .closePrivateTabs
case .copiedLink:
return .copiedLink
default:
return .search
}
}
}
|
mpl-2.0
|
023af9c2b51d796d2397060ac08f6111
| 35.473118 | 286 | 0.636203 | 4.730823 | false | false | false | false |
nathawes/swift
|
stdlib/public/core/KeyValuePairs.swift
|
9
|
5768
|
//===--- KeyValuePairs.swift ----------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
/// A lightweight collection of key-value pairs.
///
/// Use a `KeyValuePairs` instance when you need an ordered collection of
/// key-value pairs and don't require the fast key lookup that the
/// `Dictionary` type provides. Unlike key-value pairs in a true dictionary,
/// neither the key nor the value of a `KeyValuePairs` instance must
/// conform to the `Hashable` protocol.
///
/// You initialize a `KeyValuePairs` instance using a Swift dictionary
/// literal. Besides maintaining the order of the original dictionary literal,
/// `KeyValuePairs` also allows duplicates keys. For example:
///
/// let recordTimes: KeyValuePairs = ["Florence Griffith-Joyner": 10.49,
/// "Evelyn Ashford": 10.76,
/// "Evelyn Ashford": 10.79,
/// "Marlies Gohr": 10.81]
/// print(recordTimes.first!)
/// // Prints "(key: "Florence Griffith-Joyner", value: 10.49)"
///
/// Some operations that are efficient on a dictionary are slower when using
/// `KeyValuePairs`. In particular, to find the value matching a key, you
/// must search through every element of the collection. The call to
/// `firstIndex(where:)` in the following example must traverse the whole
/// collection to find the element that matches the predicate:
///
/// let runner = "Marlies Gohr"
/// if let index = recordTimes.firstIndex(where: { $0.0 == runner }) {
/// let time = recordTimes[index].1
/// print("\(runner) set a 100m record of \(time) seconds.")
/// } else {
/// print("\(runner) couldn't be found in the records.")
/// }
/// // Prints "Marlies Gohr set a 100m record of 10.81 seconds."
///
/// Key-Value Pairs as a Function Parameter
/// ---------------------------------------
///
/// When calling a function with a `KeyValuePairs` parameter, you can pass
/// a Swift dictionary literal without causing a `Dictionary` to be created.
/// This capability can be especially important when the order of elements in
/// the literal is significant.
///
/// For example, you could create an `IntPairs` structure that holds a list of
/// two-integer tuples and use an initializer that accepts a
/// `KeyValuePairs` instance.
///
/// struct IntPairs {
/// var elements: [(Int, Int)]
///
/// init(_ elements: KeyValuePairs<Int, Int>) {
/// self.elements = Array(elements)
/// }
/// }
///
/// When you're ready to create a new `IntPairs` instance, use a dictionary
/// literal as the parameter to the `IntPairs` initializer. The
/// `KeyValuePairs` instance preserves the order of the elements as
/// passed.
///
/// let pairs = IntPairs([1: 2, 1: 1, 3: 4, 2: 1])
/// print(pairs.elements)
/// // Prints "[(1, 2), (1, 1), (3, 4), (2, 1)]"
@frozen // trivial-implementation
public struct KeyValuePairs<Key, Value>: ExpressibleByDictionaryLiteral {
@usableFromInline // trivial-implementation
internal let _elements: [(Key, Value)]
/// Creates a new `KeyValuePairs` instance from the given dictionary
/// literal.
///
/// The order of the key-value pairs is kept intact in the resulting
/// `KeyValuePairs` instance.
@inlinable // trivial-implementation
public init(dictionaryLiteral elements: (Key, Value)...) {
self._elements = elements
}
}
/// `Collection` conformance that allows `KeyValuePairs` to
/// interoperate with the rest of the standard library.
extension KeyValuePairs: RandomAccessCollection {
/// The element type of a `KeyValuePairs`: a tuple containing an
/// individual key-value pair.
public typealias Element = (key: Key, value: Value)
public typealias Index = Int
public typealias Indices = Range<Int>
public typealias SubSequence = Slice<KeyValuePairs>
/// The position of the first element in a nonempty collection.
///
/// If the `KeyValuePairs` instance is empty, `startIndex` is equal to
/// `endIndex`.
@inlinable // trivial-implementation
public var startIndex: Index { return 0 }
/// The collection's "past the end" position---that is, the position one
/// greater than the last valid subscript argument.
///
/// If the `KeyValuePairs` instance is empty, `endIndex` is equal to
/// `startIndex`.
@inlinable // trivial-implementation
public var endIndex: Index { return _elements.endIndex }
/// Accesses the element at the specified position.
///
/// - Parameter position: The position of the element to access. `position`
/// must be a valid index of the collection that is not equal to the
/// `endIndex` property.
/// - Returns: The key-value pair at position `position`.
@inlinable // trivial-implementation
public subscript(position: Index) -> Element {
return _elements[position]
}
}
extension KeyValuePairs: CustomStringConvertible {
/// A string that represents the contents of the dictionary.
public var description: String {
return _makeKeyValuePairDescription()
}
}
extension KeyValuePairs: CustomDebugStringConvertible {
/// A string that represents the contents of the dictionary, suitable for
/// debugging.
public var debugDescription: String {
return _makeKeyValuePairDescription()
}
}
|
apache-2.0
|
bfb24482ad037bfe7b380b5227f49c4a
| 39.907801 | 80 | 0.65586 | 4.534591 | false | false | false | false |
per-dalsgaard/20-apps-in-20-weeks
|
App 09 - RainyShinyCloudy/RainyShinyCloudy/Forecast.swift
|
1
|
1816
|
//
// Forecast.swift
// RainyShinyCloudy
//
// Created by Per Kristensen on 14/04/2017.
// Copyright © 2017 Per Dalsgaard. All rights reserved.
//
import UIKit
class Forecast {
private var _date: Date!
private var _weatherType: String!
private var _highTemp: Double!
private var _lowTemp: Double!
var date: Date {
if _date == nil {
_date = Date()
}
return _date
}
var weatherType: String {
if _weatherType == nil {
_weatherType = ""
}
return _weatherType
}
var formattedHighTemp: String {
return String(format: "%.1f", _highTemp)
}
var formattedLowTemp: String {
return String(format: "%.1f", _lowTemp)
}
var formattedDate: String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "EEEE"
dateFormatter.locale = Locale(identifier: "da_DK")
return dateFormatter.string(from: _date).capitalized
}
init(weatherDict: Dictionary<String, AnyObject>) {
if let temp = weatherDict["temp"] as? Dictionary<String, AnyObject> {
if let min = temp["min"] as? Double {
self._lowTemp = min - 273.15
}
if let max = temp["max"] as? Double {
self._highTemp = max - 273.15
}
}
if let weather = weatherDict["weather"] as? [Dictionary<String, AnyObject>] {
if let main = weather[0]["main"] as? String {
self._weatherType = main
}
}
if let timeIntervalSince1970 = weatherDict["dt"] as? Double {
self._date = Date(timeIntervalSince1970: timeIntervalSince1970)
}
}
}
|
mit
|
6940aa8d0313336e282b15c8d73598d9
| 24.56338 | 85 | 0.534435 | 4.459459 | false | false | false | false |
mastershadow/indecente-ios
|
Indecente/GameViewController.swift
|
1
|
7097
|
//
// GameViewController.swift
// Indecente
//
// Created by Eduard Roccatello on 06/10/14.
// Copyright (c) 2014 Roccatello Eduard. All rights reserved.
//
import UIKit
import AVFoundation
class GameViewController : UIViewController, UIAlertViewDelegate {
struct Settings {
var topMargin:Int = 20
var leftMargin:Int = 20
var xSpacing:Int = 20
var ySpacing:Int = 10
var xPills:Int = 0
var yPills:Int = 0
let width:Int = 31
let height:Int = 71
var pillsNumber:Int {
return xPills * yPills
}
var poppedPills:Int = 0
}
struct Pill {
let poppedImage: UIImage? = UIImage(named: "pill-off")
let unpoppedImage: UIImage? = UIImage(named: "pill-on")
var popped:Bool = false
var image:UIImage {
if popped {
return poppedImage!
}
return unpoppedImage!
}
}
var audioPlayer:FISoundEngine = FISoundEngine.sharedEngine() as FISoundEngine
var popSound:FISound? = nil;
//let popSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("pop", ofType: "wav")!)
var settings = Settings()
var grid: [Pill] = []
var gameLayer: CALayer = CALayer()
var startDate: NSDate?
override init() {
super.init(nibName: nil, bundle: nil)
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
func initGame() {
startDate = NSDate()
for var i = 0; i < grid.count; i++ {
grid[i].popped = false
}
gameLayer.setNeedsDisplay()
}
override func prefersStatusBarHidden() -> Bool {
return true
}
override func drawLayer(layer: CALayer!, inContext ctx: CGContext!) {
UIGraphicsPushContext(ctx);
// println("IDRIS")
for var i = 0; i < grid.count; i++ {
var ii = Int(i % settings.xPills)
var jj = Int(i / settings.xPills)
var xx = ii * (settings.width + settings.xSpacing) + settings.leftMargin
var yy = jj * (settings.height + settings.ySpacing) + settings.topMargin
grid[i].image.drawAtPoint(CGPoint(x: xx, y: yy))
}
UIGraphicsPopContext()
}
override func viewDidLoad() {
super.viewDidLoad()
self.title = "Diventa indecente";
view.backgroundColor = UIColor(white: 0.9, alpha: 1)
var topBarH = self.navigationController!.navigationBar.frame.size.height
var size = view.bounds.size
size.height -= topBarH
settings.xPills = Int((size.width + (CGFloat)(settings.xSpacing)) / CGFloat(settings.width + settings.xSpacing))
settings.yPills = Int((size.height + (CGFloat)(settings.ySpacing)) / CGFloat(settings.height + settings.ySpacing))
settings.leftMargin = (Int(size.width) - (settings.width + settings.xSpacing) * settings.xPills + settings.xSpacing) / 2
settings.topMargin = (Int(size.height) - (settings.height + settings.ySpacing) * settings.yPills + settings.ySpacing) / 2
settings.topMargin += Int(topBarH)
for _ in 1...settings.pillsNumber {
grid += [Pill()]
}
gameLayer.bounds = view.bounds
gameLayer.position = CGPoint(x: gameLayer.bounds.size.width / 2, y: gameLayer.bounds.size.height / 2)
gameLayer.delegate = self
view.layer.addSublayer(gameLayer)
var gesture = UITapGestureRecognizer(target: self, action: "onTap:")
gesture.numberOfTouchesRequired = 1
gesture.numberOfTapsRequired = 1
view.addGestureRecognizer(gesture)
var swipeBack = UISwipeGestureRecognizer(target: self, action: "onSwipeBack")
swipeBack.numberOfTouchesRequired = 1
swipeBack.direction = UISwipeGestureRecognizerDirection.Right
view.addGestureRecognizer(swipeBack)
/*
audioPlayer = AVAudioPlayer(contentsOfURL: popSound, error: nil)
audioPlayer?.numberOfLoops = 0;
audioPlayer?.prepareToPlay()
*/
popSound = audioPlayer.soundNamed("pop.wav", maxPolyphony: 4, error: nil)
// NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("pop", ofType: "wav")!)
}
func onSwipeBack() {
gameLayer.delegate = nil
navigationController?.popViewControllerAnimated(true)
}
func onTap(gesture: UIGestureRecognizer) -> Void {
var point = gesture.locationInView(view)
point.x -= CGFloat(settings.leftMargin)
point.y -= CGFloat(settings.topMargin)
println(point)
if point.x > 0 && point.y > 0 {
var i:Int = Int(point.x / CGFloat(settings.width + settings.xSpacing))
var j:Int = Int(point.y / CGFloat(settings.height + settings.ySpacing))
// hit check
if (point.x - CGFloat(i) * CGFloat(settings.width + settings.xSpacing)) > CGFloat(settings.width) {
return;
}
if (point.y - CGFloat(j) * CGFloat(settings.height + settings.ySpacing)) > CGFloat(settings.height) {
return;
}
if grid[j * settings.xPills + i].popped == false {
grid[j * settings.xPills + i].popped = true
settings.poppedPills++
//play pop
/*
if audioPlayer?.playing == true {
audioPlayer!.stop()
}
audioPlayer!.play()
*/
popSound!.play()
gameLayer.setNeedsDisplay()
// check
if settings.pillsNumber == settings.poppedPills {
// finished
var endDate = NSDate()
var duration = endDate.timeIntervalSinceDate(startDate!)
dispatch_async(dispatch_get_main_queue(), { () -> Void in
var alert = UIAlertView()
alert.title = "Complimenti!"
alert.message = "Hai raggiunto l'indecenza in soli " + String(format: "%d", Int(duration)) + " secondi..."
alert.delegate = self
alert.addButtonWithTitle("Ok")
alert.show()
})
}
}
}
}
func alertView(alertView: UIAlertView, didDismissWithButtonIndex buttonIndex: Int) {
initGame()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.navigationController?.navigationBarHidden = false;
initGame()
}
override func viewWillDisappear(animated: Bool) {
gameLayer.delegate = nil
super.viewWillDisappear(animated);
}
override func supportedInterfaceOrientations() -> Int {
return Int(UIInterfaceOrientationMask.Portrait.rawValue);
}
}
|
mit
|
74c460bab957747c82b320700ba35a37
| 34.485 | 130 | 0.57165 | 4.632507 | false | false | false | false |
tzef/BmoImageLoader
|
Example/BmoImageLoader/ViewController.swift
|
1
|
11767
|
//
// ViewController.swift
// BmoImageLoader
//
// Created by LEE ZHE YU on 08/11/2016.
// Copyright (c) 2016 LEE ZHE YU. All rights reserved.
//
import UIKit
import BmoImageLoader
extension UILabel {
func formatRead(_ text: String) {
let mutableAttributes = NSMutableAttributedString(string: text)
let textArray = text.components(separatedBy: CharacterSet.newlines)
if textArray.count == 2 {
let nsStr = NSString(string: text)
let rangeSearch = NSMakeRange(0, nsStr.length)
let rangeTitle = nsStr.range(of: textArray[0], options: .backwards, range: rangeSearch, locale: nil)
let rangeContent = nsStr.range(of: textArray[1], options: .backwards, range: rangeSearch, locale: nil)
mutableAttributes.addAttributes([NSFontAttributeName : UIFont.systemFont(ofSize: 18.0)], range: rangeTitle)
mutableAttributes.addAttributes([NSFontAttributeName : UIFont.systemFont(ofSize: 12.0)], range: rangeContent)
}
self.attributedText = mutableAttributes
}
}
enum DemoType: String {
case shapeImageView = "Shape ImageView\nBmoImageViewFactory.shape(UIImageView, shape: BmoImageViewShape)"
case setImageFromURL = "Set Image From URL\nUIImageView.bmo_setImageWithURL(NSURL, style: BmoImageViewProgressStyle)"
case controlProgress = "Control Progress Self\nProgress completionState, animationDuration, completedCount, completionBlock"
case updateImage = "Update Image\nPast new image to BmoImageViewFactory.progressAnimation()"
case styleDemoCirclePaint = "Multi Animatio Style\nCirclePaint"
case styleDemoCircleBrush = "Multi Animatio Style\nCircleBrush"
case styleDemoCircleFill = "Multi Animatio Style\nCircleFill"
case styleDemoCirclePie = "Multi Animatio Style\nCirclePie"
case styleDemoColorBar = "Multi Animatio Style\nColorBar"
case styleDemoPercentNumber = "Multi Animatio Style\nPercentNumber"
}
let demoShapes: [(BmoImageViewShape?, String)] = [
(nil, "Custom ImageView Mask"),
(.roundedRect(corner: 15), ".RoundedRect(corner: 15)"),
(.circle, ".Circle"),
(.heart, ".Heart"),
(.star, ".Star"),
(.triangle, ".Triangle"),
(.pentagon, ".Pentagon"),
(.ellipse, ".Ellipse"),
]
class ViewController: UIViewController, UITableViewDataSource, DemoImageCellProtocol {
@IBOutlet weak var readLabel: UILabel!
@IBOutlet weak var tableView: UITableView!
var demoStep = DemoType.shapeImageView
override func viewDidLoad() {
super.viewDidLoad()
//Auto Demo
goDemoType(.shapeImageView)
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(3 * NSEC_PER_SEC)) / Double(NSEC_PER_SEC)) {
self.goDemoType(.setImageFromURL)
}
}
func goDemoType(_ type: DemoType) {
demoStep = type
readLabel.formatRead(demoStep.rawValue)
tableView.reloadData()
}
// MARK: - TableDataSource
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return demoShapes.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let cell = tableView.dequeueReusableCell(withIdentifier: "demoCell") as? DemoImageCell {
cell.configureCell(demoStep, index: indexPath, delegate: self)
return cell
}
return UITableViewCell()
}
// MARK: - Cell Delegate
func loadURLfinished() {
//Local AutoDemo
self.goDemoType(.controlProgress)
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(3.0 * Float(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)) {
self.goDemoType(.updateImage)
}
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(7.0 * Float(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)) {
self.goDemoType(.styleDemoCirclePaint)
}
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(9.0 * Float(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)) {
self.goDemoType(.styleDemoCircleFill)
}
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(11.0 * Float(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)) {
self.goDemoType(.styleDemoCirclePie)
}
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(13.0 * Float(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)) {
self.goDemoType(.styleDemoCircleBrush)
}
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(15.0 * Float(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)) {
self.goDemoType(.styleDemoColorBar)
}
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(17.0 * Float(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)) {
self.goDemoType(.styleDemoPercentNumber)
}
//Repeat
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(19.0 * Float(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)) {
self.loadURLfinished()
}
}
}
protocol DemoImageCellProtocol {
func loadURLfinished()
}
class DemoImageCell: UITableViewCell {
@IBOutlet weak var demoImageView: UIImageView!
@IBOutlet weak var readLabel: UILabel!
var delegate: DemoImageCellProtocol?
func configureCell(_ type: DemoType, index: IndexPath, delegate: DemoImageCellProtocol?) {
self.delegate = delegate
readLabel.text = "\(demoShapes[index.row].1)"
demoImageView.backgroundColor = UIColor.gray
demoImageView.bmo_runAnimationIfCatched(true)
let tinyDelay = DispatchTime.now() + Double(Int64(0.001 * Float(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)
DispatchQueue.main.asyncAfter(deadline: tinyDelay) {
if let shape = demoShapes[index.row].0 {
BmoImageViewFactory.shape(self.demoImageView, shape: shape)
} else {
// Custom Mask Layer Path
let rect = self.demoImageView.bounds
let maskShapeLayer = CAShapeLayer()
let path = UIBezierPath.init()
path.move(to: CGPoint(x: rect.minX, y: rect.midY - rect.height / 8))
path.addLine(to: CGPoint(x: rect.midX, y: rect.midY - rect.height / 8))
path.addLine(to: CGPoint(x: rect.midX, y: rect.minY))
path.addLine(to: CGPoint(x: rect.maxX, y: rect.midY))
path.addLine(to: CGPoint(x: rect.midX, y: rect.maxY))
path.addLine(to: CGPoint(x: rect.midX, y: rect.midY + rect.height / 8))
path.addLine(to: CGPoint(x: rect.minX, y: rect.midY + rect.height / 8))
path.close()
maskShapeLayer.path = path.cgPath
self.demoImageView.layer.mask = maskShapeLayer
}
switch type {
case .setImageFromURL:
if let url = URL(string: "https://raw.githubusercontent.com/tzef/BmoImageLoader/master/DemoImage/beemo.png#\(index.row)") {
self.demoImageView.bmo_setImageWithURL(url, style: .circlePie(borderShape: true), placeholderImage: nil, completion: { (response) in
self.readLabel.text = "\(demoShapes[index.row].1) \n \(response.result)"
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1, execute: {
self.delegate?.loadURLfinished()
})
})
}
case .controlProgress:
let animator = BmoImageViewFactory
.progressAnimation(self.demoImageView, newImage: nil, style: .circleBrush(borderShape: false))
.setAnimationDuration(0.5)
.setCompletedUnitCount(60)
.setCompletionBlock({ (result) in
self.readLabel.text = "\(demoShapes[index.row].1) \n \(result.isSuccess)"
})
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(888 * NSEC_PER_MSEC)) / Double(NSEC_PER_SEC)) {
animator
.setAnimationDuration(0.5)
.setCompletedUnitCount(33)
.closure()
}
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(1400 * NSEC_PER_MSEC)) / Double(NSEC_PER_SEC)) {
animator
.setNewImage(UIImage(named: "pikachu")!)
.setCompletionState(.succeed)
.closure()
}
case .updateImage:
BmoImageViewFactory
.progressAnimation(self.demoImageView, newImage: UIImage(named: "beemo"), style: .circleBrush(borderShape: true))
.setMarginPercent(0.3)
.setAnimationDuration(2)
.setCompletionState(.succeed)
.setCompletionBlock({ (result) in
self.readLabel.text = "\(demoShapes[index.row].1) \n \(result.isSuccess)"
})
.closure()
case .styleDemoColorBar:
self.demoImageView?.image = nil
BmoImageViewFactory
.progressAnimation(self.demoImageView, newImage: nil, style: .colorProgress(position: .positionCenter))
.setAnimationDuration(1)
.setNewImage(UIImage(named: "beemo")!)
.setCompletionState(.succeed)
.closure()
case .styleDemoCirclePaint:
BmoImageViewFactory
.progressAnimation(self.demoImageView, newImage: nil, style: .circlePaint(borderShape: true))
.setAnimationDuration(1)
.setNewImage(UIImage(named: "pikachu")!)
.setCompletionState(.succeed)
.closure()
case .styleDemoCircleFill:
BmoImageViewFactory
.progressAnimation(self.demoImageView, newImage: UIImage(named: "beemo"), style: .circleFill(borderShape: true))
.setAnimationDuration(1)
.setCompletionState(.succeed)
.closure()
case .styleDemoCirclePie:
BmoImageViewFactory
.progressAnimation(self.demoImageView, newImage: UIImage(named: "pikachu"), style: .circlePie(borderShape: true))
.setAnimationDuration(1)
.setCompletionState(.succeed)
.closure()
case .styleDemoCircleBrush:
self.demoImageView?.image = nil
BmoImageViewFactory
.progressAnimation(self.demoImageView, newImage: nil, style: .circleBrush(borderShape: true))
.setAnimationDuration(1)
.setNewImage(UIImage(named: "beemo")!)
.setCompletionState(.succeed)
.closure()
case .styleDemoPercentNumber:
self.demoImageView?.image = nil
BmoImageViewFactory
.progressAnimation(self.demoImageView, newImage: nil, style: .percentNumber)
.setAnimationDuration(1)
.setNewImage(UIImage(named: "beemo")!)
.setCompletionState(.succeed)
.closure()
default:
break
}
}
}
}
|
mit
|
3b921fd5bbdd82dab3616b2ff8c4bec4
| 49.286325 | 152 | 0.596329 | 4.600078 | false | false | false | false |
iOSDevLog/iOSDevLog
|
MyLocations/MyLocations/MapViewController.swift
|
1
|
6004
|
//
// MapViewController.swift
// MyLocations
//
// Created by iosdevlog on 16/2/18.
// Copyright © 2016年 iosdevlog. All rights reserved.
//
import UIKit
import MapKit
import CoreData
class MapViewController: UIViewController {
// MARK: outlet
@IBOutlet weak var mapView: MKMapView!
// MARK: property
var managedObjectContext: NSManagedObjectContext! {
didSet {
NSNotificationCenter.defaultCenter().addObserverForName(NSManagedObjectContextObjectsDidChangeNotification, object: managedObjectContext, queue: NSOperationQueue.mainQueue()) { _ in
if self.isViewLoaded() {
self.updateLocations()
}
}
}
}
var locations = [Location]()
// MARK: - lifeCycle
override func viewDidLoad() { super.viewDidLoad()
updateLocations()
if !locations.isEmpty {
showLocations()
}
}
// MARK: - action
@IBAction func showUser() {
let region = MKCoordinateRegionMakeWithDistance(mapView.userLocation.coordinate, 1000, 1000)
mapView.setRegion(mapView.regionThatFits(region), animated: true)
}
@IBAction func showLocations() {
let region = regionForAnnotations(locations)
mapView.setRegion(region, animated: true)
}
// MARK: - helper
func updateLocations() {
mapView.removeAnnotations(locations)
let entity = NSEntityDescription.entityForName("Location", inManagedObjectContext: managedObjectContext)
let fetchRequest = NSFetchRequest()
fetchRequest.entity = entity
locations = try! managedObjectContext.executeFetchRequest(fetchRequest) as! [Location]
mapView.addAnnotations(locations)
}
func regionForAnnotations(annotations: [MKAnnotation]) -> MKCoordinateRegion {
var region: MKCoordinateRegion
switch annotations.count {
case 0:
region = MKCoordinateRegionMakeWithDistance(mapView.userLocation.coordinate, 1000, 1000)
case 1:
let annotation = annotations[annotations.count - 1]
region = MKCoordinateRegionMakeWithDistance(annotation.coordinate, 1000, 1000)
default:
var topLeftCoord = CLLocationCoordinate2D(latitude: -90, longitude: 180)
var bottomRightCoord = CLLocationCoordinate2D(latitude: 90, longitude: -180)
for annotation in annotations {
topLeftCoord.latitude = max(topLeftCoord.latitude, annotation.coordinate.latitude)
topLeftCoord.longitude = min(topLeftCoord.longitude, annotation.coordinate.longitude)
bottomRightCoord.latitude = min(bottomRightCoord.latitude, annotation.coordinate.latitude)
bottomRightCoord.longitude = max(bottomRightCoord.longitude, annotation.coordinate.longitude)
}
let center = CLLocationCoordinate2D(
latitude: topLeftCoord.latitude - (topLeftCoord.latitude - bottomRightCoord.latitude) / 2,
longitude: topLeftCoord.longitude - (topLeftCoord.longitude - bottomRightCoord.longitude) / 2)
let extraSpace = 1.1
let span = MKCoordinateSpan(
latitudeDelta: abs(topLeftCoord.latitude - bottomRightCoord.latitude) * extraSpace,
longitudeDelta: abs(topLeftCoord.longitude - bottomRightCoord.longitude) * extraSpace)
region = MKCoordinateRegion(center: center, span: span)
}
return mapView.regionThatFits(region)
}
func showLocationDetails(sender: UIButton) {
performSegueWithIdentifier("EditLocation", sender: sender)
}
// MARK: - prepareForSegue
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "EditLocation" {
let navigationController = segue.destinationViewController as! UINavigationController
let controller = navigationController.topViewController as! LocationDetailsViewController
controller.managedObjectContext = managedObjectContext
let button = sender as! UIButton
let location = locations[button.tag]
controller.locationToEdit = location
}
}
}
extension MapViewController: MKMapViewDelegate {
func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? {
guard annotation is Location else {
return nil
}
let identifier = "Location"
var annotationView = mapView.dequeueReusableAnnotationViewWithIdentifier(identifier) as! MKPinAnnotationView!
if annotationView == nil {
annotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: identifier)
annotationView.enabled = true
annotationView.canShowCallout = true
annotationView.animatesDrop = false
annotationView.pinTintColor = UIColor(red: 0.32, green: 0.82, blue: 0.4, alpha: 1)
annotationView.tintColor = UIColor(white: 0.0, alpha: 0.5)
let rightButton = UIButton(type: .DetailDisclosure)
rightButton.addTarget(self, action: Selector("showLocationDetails:"), forControlEvents: .TouchUpInside)
annotationView.rightCalloutAccessoryView = rightButton
} else {
annotationView.annotation = annotation
}
let button = annotationView.rightCalloutAccessoryView as! UIButton
if let index = locations.indexOf(annotation as! Location) {
button.tag = index
}
return annotationView
}
}
extension MapViewController: UINavigationBarDelegate {
func positionForBar(bar: UIBarPositioning) -> UIBarPosition {
return .TopAttached
}
}
|
mit
|
49476bbea411d0887dad211886e93c66
| 37.474359 | 193 | 0.650725 | 5.843233 | false | false | false | false |
s-aska/OAuthSwift
|
OAuthSwift/Utils.swift
|
1
|
1762
|
//
// Utils.swift
// OAuthSwift
//
// Created by Dongri Jin on 1/28/15.
// Copyright (c) 2015 Dongri Jin. All rights reserved.
//
import Foundation
func rotateLeft(v:UInt16, n:UInt16) -> UInt16 {
return ((v << n) & 0xFFFF) | (v >> (16 - n))
}
func rotateLeft(v:UInt32, n:UInt32) -> UInt32 {
return ((v << n) & 0xFFFFFFFF) | (v >> (32 - n))
}
func rotateLeft(x:UInt64, n:UInt64) -> UInt64 {
return (x << n) | (x >> (64 - n))
}
func rotateRight(x:UInt16, n:UInt16) -> UInt16 {
return (x >> n) | (x << (16 - n))
}
func rotateRight(x:UInt32, n:UInt32) -> UInt32 {
return (x >> n) | (x << (32 - n))
}
func rotateRight(x:UInt64, n:UInt64) -> UInt64 {
return ((x >> n) | (x << (64 - n)))
}
func reverseBytes(value: UInt32) -> UInt32 {
let tmp1 = ((value & 0x000000FF) << 24) | ((value & 0x0000FF00) << 8)
let tmp2 = ((value & 0x00FF0000) >> 8) | ((value & 0xFF000000) >> 24)
return tmp1 | tmp2
}
public func generateStateWithLength (len : Int) -> NSString {
let letters : NSString = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
let randomString : NSMutableString = NSMutableString(capacity: len)
for (var i=0; i < len; i++){
let length = UInt32 (letters.length)
let rand = arc4random_uniform(length)
randomString.appendFormat("%C", letters.characterAtIndex(Int(rand)))
}
return randomString
}
public extension Dictionary {
mutating func merge<K, V>(dictionaries: Dictionary<K, V>...) {
for dict in dictionaries {
for (key, value) in dict {
self.updateValue(value as! Value, forKey: key as! Key)
}
}
}
}
public func +=<K, V> (inout left: [K : V], right: [K : V]) { left.merge(right) }
|
mit
|
64b9465aac8e14b6d444ea41f8c2b0a1
| 26.968254 | 93 | 0.590806 | 3.174775 | false | false | false | false |
soapyigu/LeetCode_Swift
|
Tree/SameTree.swift
|
1
|
854
|
/**
* Question Link: https://leetcode.com/problems/same-tree/
* Primary idea: recursion
* Time Complexity: O(n), Space Complexity: O(n)
*
* Copyright © 2016 YiGu. All rights reserved.
*
* Definition for a binary tree node.
* public class TreeNode {
* public var val: Int
* public var left: TreeNode?
* public var right: TreeNode?
* public init(_ val: Int) {
* self.val = val
* self.left = nil
* self.right = nil
* }
* }
*/
class SameTree {
func isSameTree(_ p: TreeNode?, _ q: TreeNode?) -> Bool {
guard let p = p else {
return q == nil
}
guard let q = q else {
return p == nil
}
if p.val != q.val {
return false
}
return isSameTree(p.left, q.left) && isSameTree(p.right, q.right)
}
}
|
mit
|
c651600b18a57450f34343d559744a2f
| 22.722222 | 73 | 0.528722 | 3.584034 | false | false | false | false |
tlax/GaussSquad
|
GaussSquad/Model/Calculator/FunctionsItems/MCalculatorFunctionsItemCubeRoot.swift
|
1
|
886
|
import UIKit
class MCalculatorFunctionsItemCubeRoot:MCalculatorFunctionsItem
{
init()
{
let icon:UIImage = #imageLiteral(resourceName: "assetFunctionCubeRoot")
let title:String = NSLocalizedString("MCalculatorFunctionsItemCubeRoot_title", comment:"")
super.init(
icon:icon,
title:title)
}
override func processFunction(
currentValue:Double,
currentString:String,
modelKeyboard:MKeyboard,
view:UITextView)
{
let cbrtValue:Double = cbrt(currentValue)
let cbrtString:String = modelKeyboard.numberAsString(scalar:cbrtValue)
let descr:String = "cube root(\(currentString)) = \(cbrtString)"
applyUpdate(
modelKeyboard:modelKeyboard,
view:view,
newEditing:cbrtString,
descr:descr)
}
}
|
mit
|
37410a7961f2bdb191994d27e304b5d0
| 27.580645 | 98 | 0.623025 | 4.763441 | false | false | false | false |
kenwilcox/ExchangeAGram
|
ExchangeAGram/FeedViewController.swift
|
1
|
7244
|
//
// FeedViewController.swift
// ExchangeAGram
//
// Created by Kenneth Wilcox on 1/31/15.
// Copyright (c) 2015 Kenneth Wilcox. All rights reserved.
//
import UIKit
import MobileCoreServices
import CoreData
import MapKit
class FeedViewController: UIViewController {
@IBOutlet weak var collectionView: UICollectionView!
var feedArray:[AnyObject] = []
var locationManager:CLLocationManager!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
let backgroundImage = UIImage(named: "OceanBackground")
self.view.backgroundColor = UIColor(patternImage: backgroundImage!)
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestAlwaysAuthorization()
//locationManager.requestWhenInUseAuthorization()
locationManager.distanceFilter = 100.0
locationManager.startUpdatingLocation()
}
override func viewDidAppear(animated: Bool) {
let request = NSFetchRequest(entityName: "FeedItem")
let appDelegate = (UIApplication.sharedApplication().delegate as AppDelegate)
let context = appDelegate.managedObjectContext!
feedArray = context.executeFetchRequest(request, error: nil)!
collectionView.reloadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func profileTapped(sender: UIBarButtonItem) {
self.performSegueWithIdentifier("profileSegue", sender: nil)
}
@IBAction func snapBarButtonItemTapped(sender: UIBarButtonItem) {
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera) {
var cameraController = UIImagePickerController()
cameraController.delegate = self
cameraController.sourceType = UIImagePickerControllerSourceType.Camera
let mediaTypes:[AnyObject] = [kUTTypeImage]
cameraController.mediaTypes = mediaTypes
cameraController.allowsEditing = false
self.presentViewController(cameraController, animated: true, completion: nil)
}
else if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.PhotoLibrary) {
var photoLibraryController = UIImagePickerController()
photoLibraryController.delegate = self
photoLibraryController.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
let mediaTypes:[AnyObject] = [kUTTypeImage]
photoLibraryController.mediaTypes = mediaTypes
photoLibraryController.allowsEditing = false
self.presentViewController(photoLibraryController, animated: true, completion: nil)
}
else {
var alertView = UIAlertController(title: "Alert", message: "Your device does not support the camera or photo Library", preferredStyle: UIAlertControllerStyle.Alert)
alertView.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alertView, animated: true, completion: nil)
}
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
// MARK: - UICollectionViewDataSource
extension FeedViewController: UICollectionViewDataSource {
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return feedArray.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
var cell:FeedCell = collectionView.dequeueReusableCellWithReuseIdentifier("feedCell", forIndexPath: indexPath) as FeedCell
let feedItem = feedArray[indexPath.row] as FeedItem
if feedItem.filtered == true {
let returnedImage = UIImage(data: feedItem.image)!
let image = UIImage(CGImage: returnedImage.CGImage, scale: 1.0, orientation: .Right)!
cell.imageView.image = image
} else {
cell.imageView.image = UIImage(data: feedItem.image)
}
cell.captionLabel.text = feedItem.caption
return cell
}
}
// MARK: - UICollectionViewDelegate
extension FeedViewController: UICollectionViewDelegate {
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
let thisItem = feedArray[indexPath.row] as FeedItem
var filterVC = FilterViewController()
filterVC.thisFeedItem = thisItem
self.navigationController?.pushViewController(filterVC, animated: false)
}
}
// MARK: - UIImagePickerControllerDelegate
extension FeedViewController: UIImagePickerControllerDelegate {
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) {
let image = info[UIImagePickerControllerOriginalImage] as UIImage
let imageData = UIImageJPEGRepresentation(image, 1.0)
// really make a thumbnail
let size = CGSizeApplyAffineTransform(image.size, CGAffineTransformMakeScale(300.0/image.size.width, 300.0/image.size.height))
let hasAlpha = false
let scale: CGFloat = 0.0 // automatically use scale factor of the main screen
UIGraphicsBeginImageContextWithOptions(size, !hasAlpha, scale)
image.drawInRect(CGRect(origin: CGPointZero, size: size))
let scaledImage = UIGraphicsGetImageFromCurrentImageContext()
let thumbnailData = UIImageJPEGRepresentation(scaledImage, 0.5)
let managedObjectContext = (UIApplication.sharedApplication().delegate as AppDelegate).managedObjectContext
let entityDescription = NSEntityDescription.entityForName("FeedItem", inManagedObjectContext: managedObjectContext!)
let feedItem = FeedItem(entity: entityDescription!, insertIntoManagedObjectContext: managedObjectContext!)
feedItem.image = imageData
feedItem.thumbnail = thumbnailData
feedItem.caption = "test caption"
if let location = locationManager.location? {
feedItem.latitude = location.coordinate.latitude
feedItem.longitude = location.coordinate.longitude
} else {
println("No location available")
}
let UUID = NSUUID().UUIDString
feedItem.uniqueID = UUID
feedItem.filtered = false
(UIApplication.sharedApplication().delegate as AppDelegate).saveContext()
feedArray.append(feedItem)
self.dismissViewControllerAnimated(true, completion: nil)
self.collectionView.reloadData()
}
}
// MARK: - UINavigationControllerDelegate
extension FeedViewController: UINavigationControllerDelegate {
}
// MARK: - CLLocationManagerDelegate
extension FeedViewController: CLLocationManagerDelegate {
func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
println("locations = \(locations)")
}
}
|
mit
|
eecd2502575df8a87ac0586f7f4f5050
| 36.533679 | 170 | 0.754279 | 5.776715 | false | false | false | false |
natecook1000/swift
|
test/SILGen/optional_lvalue.swift
|
2
|
7308
|
// RUN: %target-swift-emit-silgen -module-name optional_lvalue -enable-sil-ownership %s | %FileCheck %s
// CHECK-LABEL: sil hidden @$S15optional_lvalue07assign_a1_B0yySiSgz_SitF
// CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] %0 : $*Optional<Int>
// CHECK: [[FILESTR:%.*]] = string_literal utf8 "
// CHECK-NEXT: [[FILESIZ:%.*]] = integer_literal $Builtin.Word,
// CHECK-NEXT: [[FILEASC:%.*]] = integer_literal $Builtin.Int1,
// CHECK-NEXT: [[LINE:%.*]] = integer_literal $Builtin.Word,
// CHECK-NEXT: [[COLUMN:%.*]] = integer_literal $Builtin.Word,
// CHECK-NEXT: [[IMPLICIT:%.*]] = integer_literal $Builtin.Int1, 0
// CHECK: [[PRECOND:%.*]] = function_ref @$Ss30_diagnoseUnexpectedNilOptional{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[PRECOND]]([[FILESTR]], [[FILESIZ]], [[FILEASC]], [[LINE]], [[IMPLICIT]])
// CHECK: [[PAYLOAD:%.*]] = unchecked_take_enum_data_addr [[WRITE]] : $*Optional<Int>, #Optional.some!enumelt.1
// CHECK: assign {{%.*}} to [[PAYLOAD]]
func assign_optional_lvalue(_ x: inout Int?, _ y: Int) {
x! = y
}
// CHECK-LABEL: sil hidden @$S15optional_lvalue011assign_iuo_B0yySiSgz_SitF
// CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] %0 : $*Optional<Int>
// CHECK: [[FILESTR:%.*]] = string_literal utf8 "
// CHECK-NEXT: [[FILESIZ:%.*]] = integer_literal $Builtin.Word,
// CHECK-NEXT: [[FILEASC:%.*]] = integer_literal $Builtin.Int1,
// CHECK-NEXT: [[LINE:%.*]] = integer_literal $Builtin.Word,
// CHECK-NEXT: [[COLUMN:%.*]] = integer_literal $Builtin.Word,
// CHECK-NEXT: [[IMPLICIT:%.*]] = integer_literal $Builtin.Int1, 0
// CHECK: [[PRECOND:%.*]] = function_ref @$Ss30_diagnoseUnexpectedNilOptional{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[PRECOND]]([[FILESTR]], [[FILESIZ]], [[FILEASC]], [[LINE]], [[IMPLICIT]])
// CHECK: [[PAYLOAD:%.*]] = unchecked_take_enum_data_addr [[WRITE]] : $*Optional<Int>, #Optional.some!enumelt.1
// CHECK: assign {{%.*}} to [[PAYLOAD]]
func assign_iuo_lvalue(_ x: inout Int!, _ y: Int) {
x! = y
}
struct S {
var x: Int
var computed: Int {
get {}
set {}
}
}
// CHECK-LABEL: sil hidden @$S15optional_lvalue011assign_iuo_B9_implicityyAA1SVSgz_SitF
// CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] %0 : $*Optional<S>
// CHECK: [[FILESTR:%.*]] = string_literal utf8 "
// CHECK-NEXT: [[FILESIZ:%.*]] = integer_literal $Builtin.Word,
// CHECK-NEXT: [[FILEASC:%.*]] = integer_literal $Builtin.Int1,
// CHECK-NEXT: [[LINE:%.*]] = integer_literal $Builtin.Word,
// CHECK-NEXT: [[COLUMN:%.*]] = integer_literal $Builtin.Word,
// CHECK-NEXT: [[IMPLICIT:%.*]] = integer_literal $Builtin.Int1, -1
// CHECK: [[PRECOND:%.*]] = function_ref @$Ss30_diagnoseUnexpectedNilOptional{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[PRECOND]]([[FILESTR]], [[FILESIZ]], [[FILEASC]], [[LINE]], [[IMPLICIT]])
// CHECK: [[SOME:%.*]] = unchecked_take_enum_data_addr [[WRITE]]
// CHECK: [[X:%.*]] = struct_element_addr [[SOME]]
func assign_iuo_lvalue_implicit(_ s: inout S!, _ y: Int) {
s.x = y
}
struct Struct<T> {
var value: T?
}
// CHECK-LABEL: sil hidden @$S15optional_lvalue07assign_a1_B13_reabstractedyyAA6StructVyS2icGz_S2ictF
// CHECK: [[REABSTRACT:%.*]] = function_ref @$SS2iIegyd_S2iIegnr_TR
// CHECK: [[REABSTRACTED:%.*]] = partial_apply [callee_guaranteed] [[REABSTRACT]]
// CHECK: assign [[REABSTRACTED]] to {{%.*}} : $*@callee_guaranteed (@in_guaranteed Int) -> @out Int
func assign_optional_lvalue_reabstracted(_ x: inout Struct<(Int) -> Int>,
_ y: @escaping (Int) -> Int) {
x.value! = y
}
// CHECK-LABEL: sil hidden @$S15optional_lvalue07assign_a1_B9_computedySiAA1SVSgz_SitF
// CHECK: function_ref @$S15optional_lvalue1SV8computedSivs
// CHECK: function_ref @$S15optional_lvalue1SV8computedSivg
func assign_optional_lvalue_computed(_ x: inout S?, _ y: Int) -> Int {
x!.computed = y
return x!.computed
}
func generate_int() -> Int { return 0 }
// CHECK-LABEL: sil hidden @$S15optional_lvalue013assign_bound_a1_B0yySiSgzF
// CHECK: [[HASVALUE:%.*]] = select_enum_addr {{%.*}}
// CHECK: cond_br [[HASVALUE]], [[SOME:bb[0-9]+]], [[NONE:bb[0-9]+]]
//
// CHECK: [[SOME]]:
// CHECK: [[PAYLOAD:%.*]] = unchecked_take_enum_data_addr
// CHECK: [[FN:%.*]] = function_ref
// CHECK: [[T0:%.*]] = apply [[FN]]()
// CHECK: assign [[T0]] to [[PAYLOAD]]
func assign_bound_optional_lvalue(_ x: inout Int?) {
x? = generate_int()
}
struct ComputedOptional {
var computedOptional : Int? {
get {}
set {}
}
}
// CHECK-LABEL: sil hidden @$S15optional_lvalue013assign_bound_a10_computed_B0yyAA16ComputedOptionalVzF
// CHECK: [[SELF:%.*]] = begin_access [modify] [unknown] %0 : $*ComputedOptional
// CHECK: [[TEMP:%.*]] = alloc_stack $Optional<Int>
// CHECK: [[T0:%.*]] = load [trivial] [[SELF]] : $*ComputedOptional
// CHECK: [[GETTER:%.*]] = function_ref @$S15optional_lvalue16ComputedOptionalV08computedD0SiSgvg
// CHECK: [[VALUE:%.*]] = apply [[GETTER]]([[T0]])
// CHECK: store [[VALUE]] to [trivial] [[TEMP]] : $*Optional<Int>
// CHECK: select_enum_addr [[TEMP]] : $*Optional<Int>
// CHECK: cond_br
// CHECK: [[VALUE_ADDR:%.*]] = unchecked_take_enum_data_addr [[TEMP]] : $*Optional<Int>
// CHECK: [[GENERATOR:%.*]] = function_ref @$S15optional_lvalue12generate_intSiyF
// CHECK: [[VALUE:%.*]] = apply [[GENERATOR]]()
// CHECK: assign [[VALUE]] to [[VALUE_ADDR]] : $*Int
// CHECK: [[OPTVALUE:%.*]] = load [trivial] [[TEMP]] : $*Optional<Int>
// CHECK: [[SETTER:%.*]] = function_ref @$S15optional_lvalue16ComputedOptionalV08computedD0SiSgvs
// CHECK: apply [[SETTER]]([[OPTVALUE]], [[SELF]])
// CHECK: end_access [[SELF]]
// CHECK: dealloc_stack [[TEMP]]
func assign_bound_optional_computed_lvalue(_ co: inout ComputedOptional) {
co.computedOptional? = generate_int()
}
// CHECK-LABEL: sil hidden @$S15optional_lvalue014assign_forced_a10_computed_B0yyAA16ComputedOptionalVzF
// CHECK: [[GENERATOR:%.*]] = function_ref @$S15optional_lvalue12generate_intSiyF
// CHECK: [[VALUE:%.*]] = apply [[GENERATOR]]()
// CHECK: [[SELF:%.*]] = begin_access [modify] [unknown] %0 : $*ComputedOptional
// CHECK: [[TEMP:%.*]] = alloc_stack $Optional<Int>
// CHECK: [[T0:%.*]] = load [trivial] [[SELF]] : $*ComputedOptional
// CHECK: [[GETTER:%.*]] = function_ref @$S15optional_lvalue16ComputedOptionalV08computedD0SiSgvg
// CHECK: [[OPTVALUE:%.*]] = apply [[GETTER]]([[T0]])
// CHECK: store [[OPTVALUE]] to [trivial] [[TEMP]]
// CHECK: switch_enum_addr [[TEMP]]
// CHECK: [[VALUE_ADDR:%.*]] = unchecked_take_enum_data_addr [[TEMP]] : $*Optional<Int>
// CHECK: assign [[VALUE]] to [[VALUE_ADDR]] : $*Int
// CHECK: [[OPTVALUE:%.*]] = load [trivial] [[TEMP]] : $*Optional<Int>
// CHECK: [[SETTER:%.*]] = function_ref @$S15optional_lvalue16ComputedOptionalV08computedD0SiSgvs
// CHECK: apply [[SETTER]]([[OPTVALUE]], [[SELF]])
// CHECK: end_access [[SELF]]
// CHECK: dealloc_stack [[TEMP]]
func assign_forced_optional_computed_lvalue(_ co: inout ComputedOptional) {
co.computedOptional! = generate_int()
}
|
apache-2.0
|
9373ae6b4b6f44450c131c080e931762
| 49.4 | 119 | 0.602627 | 3.324841 | false | false | false | false |
drejkim/o-holy-night
|
ios/o-holy-night/o-holy-night/LightingControlPanelViewController.swift
|
1
|
3526
|
//
// LightingControlPanelViewController.swift
// o-holy-night
//
// Created by Esther Jun Kim on 12/21/16.
// Copyright © 2016 Esther Jun Kim. All rights reserved.
//
import UIKit
import ParticleSDK
// REPLACE WITH YOUR PARTICLE INFORMATION
let particleUsername = "USERNAME"
let particlePassword = "PASSWORD"
let particleDeviceName = "DEVICE NAME"
var myPhoton:SparkDevice?
class LightingControlPanelViewController: UITableViewController {
@IBOutlet weak var switchManger: UISwitch!
@IBOutlet weak var switchSky: UISwitch!
@IBOutlet weak var switchStar: UISwitch!
@IBOutlet weak var pulseBtnManger: UIButton!
@IBOutlet weak var pulseBtnSky: UIButton!
@IBOutlet weak var pulseBtnStar: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// Disable cell selection highlighting
tableView.allowsSelection = false
SparkCloud.sharedInstance().login(withUser: particleUsername, password: particlePassword) { (error:Error?) in
if let e = error {
print(e)
}
else {
print("Logged in!")
}
}
SparkCloud.sharedInstance().getDevices { (sparkDevices:[SparkDevice]?, error:Error?) in
if let e = error {
print(e)
}
else {
if let devices = sparkDevices as [SparkDevice]! {
for device in devices {
if device.name == particleDeviceName {
myPhoton = device
print(myPhoton!.id)
}
}
}
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func toggleMangerSwitch() {
let funcArgs=[getSwitchStateAsString(isOn:switchManger.isOn)]
callParticleFunction(name: "manger", args: funcArgs)
}
@IBAction func toggleSkySwitch() {
let funcArgs=[getSwitchStateAsString(isOn:switchSky.isOn)]
callParticleFunction(name: "sky", args: funcArgs)
}
@IBAction func toggleStarSwitch() {
let funcArgs=[getSwitchStateAsString(isOn:switchStar.isOn)]
callParticleFunction(name: "star", args: funcArgs)
}
@IBAction func pulseManger() {
if(pulseBtnManger.isTouchInside) {
let funcArgs=["pulse"]
callParticleFunction(name: "manger", args: funcArgs)
}
}
@IBAction func pulseSky() {
if(pulseBtnSky.isTouchInside) {
let funcArgs=["pulse"]
callParticleFunction(name: "sky", args: funcArgs)
}
}
@IBAction func pulseStar() {
if(pulseBtnStar.isTouchInside) {
let funcArgs=["pulse"]
callParticleFunction(name: "star", args: funcArgs)
}
}
func getSwitchStateAsString(isOn:Bool) -> String {
if(isOn) {
return "on"
}
else {
return "off"
}
}
func callParticleFunction(name:String, args:[Any]?) {
myPhoton!.callFunction(name, withArguments: args) { (resultCode:NSNumber?, error:Error?) in
if let e = error {
print(e)
}
else {
print(resultCode!)
}
}
}
}
|
mit
|
4b870aca1c0895adddff464499d0c5b8
| 27.427419 | 117 | 0.56 | 4.750674 | false | false | false | false |
mamaral/MAPageViewController
|
MAPageViewController/MAPageViewController.swift
|
1
|
3520
|
//
// MAPageViewController.swift
// MAPageViewController
//
// Created by Mike on 6/19/14.
// Copyright (c) 2014 Mike Amaral. All rights reserved.
//
import UIKit
class MAPageViewController: UIViewController, UIPageViewControllerDataSource, UIPageViewControllerDelegate {
let pageViewController: UIPageViewController = UIPageViewController(transitionStyle: UIPageViewControllerTransitionStyle.Scroll, navigationOrientation: UIPageViewControllerNavigationOrientation.Horizontal, options: nil)
let pageControl: UIPageControl = UIPageControl()
let pageControlHeight: CGFloat = 40
var viewControllers: UIViewController[] = []
init(viewControllers: UIViewController[]) {
self.viewControllers = viewControllers
super.init(nibName: nil, bundle: nil)
}
init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
override func viewDidLoad() {
super.viewDidLoad()
self.edgesForExtendedLayout = .None
setupPageViewController()
}
func setupPageViewController() {
pageViewController.delegate = self
pageViewController.dataSource = self;
pageViewController.view.frame = self.view.frame;
pageViewController.setViewControllers([viewControllers[0]], direction: UIPageViewControllerNavigationDirection.Forward, animated: false, completion: nil)
self.addChildViewController(pageViewController)
self.view.addSubview(pageViewController.view)
pageViewController.didMoveToParentViewController(self)
pageControl.frame = CGRectMake(0, CGRectGetMaxY(self.view.frame) - pageControlHeight, self.view.bounds.size.width, pageControlHeight)
pageControl.numberOfPages = viewControllers.count;
pageControl.autoresizingMask = .FlexibleWidth | .FlexibleTopMargin
self.view.addSubview(pageControl)
}
func indexOfViewController(viewController: UIViewController) -> Int {
var indexOfVC: Int = 0
for (index, element) in enumerate(viewControllers) {
if element == viewController {
indexOfVC = index
break
}
}
return indexOfVC
}
// PRAGMA: page view controller data source
func pageViewController(pageViewController: UIPageViewController!, viewControllerAfterViewController viewController: UIViewController!) -> UIViewController! {
let indexOfCurrentVC = indexOfViewController(viewController)
return indexOfCurrentVC < viewControllers.count - 1 ? viewControllers[indexOfCurrentVC + 1] : nil
}
func pageViewController(pageViewController: UIPageViewController!, viewControllerBeforeViewController viewController: UIViewController!) -> UIViewController! {
viewControllers.endIndex
let indexOfCurrentVC = indexOfViewController(viewController)
return indexOfCurrentVC > 0 ? viewControllers[indexOfCurrentVC - 1] : nil
}
// PRAGMA: page view controller delegate
func pageViewController(pageViewController: UIPageViewController!, didFinishAnimating finished: Bool, previousViewControllers: AnyObject[]!, transitionCompleted completed: Bool) {
if !completed {
return
}
let newViewController = pageViewController.viewControllers[0] as UIViewController
pageControl.currentPage = indexOfViewController(newViewController)
}
}
|
mit
|
d13387d994d16a14fe9334c890e00ed9
| 40.904762 | 223 | 0.720455 | 6.10052 | false | false | false | false |
BigZhanghan/DouYuLive
|
DouYuLive/DouYuLive/Classes/Home/Controller/HomeViewController.swift
|
1
|
3170
|
//
// HomeViewController.swift
// DouYuLive
//
// Created by zhanghan on 2017/9/28.
// Copyright © 2017年 zhanghan. All rights reserved.
//
import UIKit
private let titleViewH : CGFloat = 40;
class HomeViewController: UIViewController {
lazy var pageContentView : PageContentView = {[weak self] in
let contentH : CGFloat = Screen_height - StatusBarH - NavigationBarH - titleViewH - TabBarH
let contentFrame = CGRect(x: 0, y: StatusBarH + NavigationBarH + titleViewH, width: Screen_width, height: contentH)
var childVcs = [UIViewController]()
childVcs.append(RecommandViewController())
childVcs.append(GameViewController())
for _ in 0..<2 {
let vc = UIViewController()
vc.view.backgroundColor = UIColor(r: CGFloat(arc4random_uniform(255)), g: CGFloat(arc4random_uniform(255)), b: CGFloat(arc4random_uniform(255)))
childVcs.append(vc)
}
let contentView = PageContentView(frame: contentFrame, childVcs: childVcs, parentVc: self)
contentView.delegate = self
return contentView
}()
lazy var pageTitleView : PageTitleView = {[weak self] in
let titleFrame = CGRect(x: 0, y: 64, width: Screen_width, height: titleViewH);
let titles = ["推荐", "游戏", "娱乐", "趣玩"];
let titleView = PageTitleView(frame: titleFrame, titles: titles);
titleView.delegate = self
return titleView;
}()
override func viewDidLoad() {
super.viewDidLoad()
setupUI();
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
//mark - 设置UI界面
extension HomeViewController {
func setupUI() {
automaticallyAdjustsScrollViewInsets = false
setupNavigationBar();
view.addSubview(pageTitleView);
view.addSubview(pageContentView)
}
func setupNavigationBar () {
//leftBarButtonItem
navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: "logo");
//rightBarButtonItems
let size = CGSize.init(width: 35, height: 35);
let historyItem = UIBarButtonItem(imageName: "image_my_history", highImageName: "Image_my_history_click", size: size);
let searchItem = UIBarButtonItem(imageName: "btn_search", highImageName: "btn_search_clicked", size: size);
let qrcodeItem = UIBarButtonItem(imageName: "Image_scan", highImageName: "Image_scan_click", size: size);
navigationItem.rightBarButtonItems = [historyItem,searchItem,qrcodeItem];
}
}
extension HomeViewController : PageTitleViewDelegate {
func pageTitleView(titleView: PageTitleView, selectIndex index: Int) {
print(index)
pageContentView.setCurrentIndex(currentIndex: index)
}
}
extension HomeViewController : PageContentViewDelegate {
func pageContentView(pageContentView: PageContentView, progress: CGFloat, sourceIndex: Int, targetIndex: Int) {
pageTitleView.setTitleWithProgress(progress: progress, sourceIndex: sourceIndex, targetIndex: targetIndex)
}
}
|
mit
|
c1782105514f3bc319f80196d0d20daa
| 34.314607 | 156 | 0.665288 | 5.012759 | false | false | false | false |
cohix/MaterialKit
|
Source/SideNavigationViewController.swift
|
3
|
46942
|
//
// Copyright (C) 2015 GraphKit, Inc. <http://graphkit.io> and other GraphKit contributors.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program located at the root of the software package
// in a file called LICENSE. If not, see <http://www.gnu.org/licenses/>.
//
import UIKit
extension UIViewController {
/**
:name: sideNavigationViewController
*/
public var sideNavigationViewController: SideNavigationViewController? {
var viewController: UIViewController? = self
while nil != viewController {
if viewController is SideNavigationViewController {
return viewController as? SideNavigationViewController
}
viewController = viewController?.parentViewController
}
return nil
}
}
public enum SideNavigationViewState {
case Opened
case Closed
}
@objc(SideNavigationViewContainer)
public class SideNavigationViewContainer : Printable {
/**
:name: state
*/
public private(set) var state: SideNavigationViewState
/**
:name: point
*/
public private(set) var point: CGPoint
/**
:name: frame
*/
public private(set) var frame: CGRect
/**
:name: description
*/
public var description: String {
let s: String = .Opened == state ? "Opened" : "Closed"
return "(state: \(s), point: \(point), frame: \(frame))"
}
/**
:name: init
*/
public init(state: SideNavigationViewState, point: CGPoint, frame: CGRect) {
self.state = state
self.point = point
self.frame = frame
}
}
@objc(SideNavigationViewDelegate)
public protocol SideNavigationViewDelegate {
// left
optional func sideNavDidBeginLeftPan(nav: SideNavigationViewController, container: SideNavigationViewContainer)
optional func sideNavDidChangeLeftPan(nav: SideNavigationViewController, container: SideNavigationViewContainer)
optional func sideNavDidEndLeftPan(nav: SideNavigationViewController, container: SideNavigationViewContainer)
optional func sideNavDidOpenLeftViewContainer(nav: SideNavigationViewController, container: SideNavigationViewContainer)
optional func sideNavDidCloseLeftViewContainer(nav: SideNavigationViewController, container: SideNavigationViewContainer)
optional func sideNavDidTapLeft(nav: SideNavigationViewController, container: SideNavigationViewContainer)
// right
optional func sideNavDidBeginRightPan(nav: SideNavigationViewController, container: SideNavigationViewContainer)
optional func sideNavDidChangeRightPan(nav: SideNavigationViewController, container: SideNavigationViewContainer)
optional func sideNavDidEndRightPan(nav: SideNavigationViewController, container: SideNavigationViewContainer)
optional func sideNavDidOpenRightViewContainer(nav: SideNavigationViewController, container: SideNavigationViewContainer)
optional func sideNavDidCloseRightViewContainer(nav: SideNavigationViewController, container: SideNavigationViewContainer)
optional func sideNavDidTapRight(nav: SideNavigationViewController, container: SideNavigationViewContainer)
// bottom
optional func sideNavDidBeginBottomPan(nav: SideNavigationViewController, container: SideNavigationViewContainer)
optional func sideNavDidChangeBottomPan(nav: SideNavigationViewController, container: SideNavigationViewContainer)
optional func sideNavDidEndBottomPan(nav: SideNavigationViewController, container: SideNavigationViewContainer)
optional func sideNavDidOpenBottomViewContainer(nav: SideNavigationViewController, container: SideNavigationViewContainer)
optional func sideNavDidCloseBottomViewContainer(nav: SideNavigationViewController, container: SideNavigationViewContainer)
optional func sideNavDidTapBottom(nav: SideNavigationViewController, container: SideNavigationViewContainer)
// top
optional func sideNavDidBeginTopPan(nav: SideNavigationViewController, container: SideNavigationViewContainer)
optional func sideNavDidChangeTopPan(nav: SideNavigationViewController, container: SideNavigationViewContainer)
optional func sideNavDidEndTopPan(nav: SideNavigationViewController, container: SideNavigationViewContainer)
optional func sideNavDidOpenTopViewContainer(nav: SideNavigationViewController, container: SideNavigationViewContainer)
optional func sideNavDidCloseTopViewContainer(nav: SideNavigationViewController, container: SideNavigationViewContainer)
optional func sideNavDidTapTop(nav: SideNavigationViewController, container: SideNavigationViewContainer)
}
@objc(SideNavigationViewController)
public class SideNavigationViewController: UIViewController, UIGestureRecognizerDelegate {
/**
:name: default options
*/
public struct defaultOptions {
public static var bezelWidth: CGFloat = 48
public static var bezelHeight: CGFloat = 48
public static var containerWidth: CGFloat = 240
public static var containerHeight: CGFloat = 240
public static var defaultAnimationDuration: CGFloat = 0.3
public static var threshold: CGFloat = 48
public static var panningEnabled: Bool = true
}
/**
:name: options
*/
public struct options {
public static var shadowOpacity: Float = 0
public static var shadowRadius: CGFloat = 0
public static var shadowOffset: CGSize = CGSizeZero
public static var backdropScale: CGFloat = 1
public static var backdropOpacity: CGFloat = 0.5
public static var hideStatusBar: Bool = true
public static var horizontalThreshold: CGFloat = defaultOptions.threshold
public static var verticalThreshold: CGFloat = defaultOptions.threshold
public static var backdropBackgroundColor: UIColor = MaterialTheme.black.color
public static var animationDuration: CGFloat = defaultOptions.defaultAnimationDuration
public static var leftBezelWidth: CGFloat = defaultOptions.bezelWidth
public static var leftViewContainerWidth: CGFloat = defaultOptions.containerWidth
public static var leftPanFromBezel: Bool = defaultOptions.panningEnabled
public static var rightBezelWidth: CGFloat = defaultOptions.bezelWidth
public static var rightViewContainerWidth: CGFloat = defaultOptions.containerWidth
public static var rightPanFromBezel: Bool = defaultOptions.panningEnabled
public static var bottomBezelHeight: CGFloat = defaultOptions.bezelHeight
public static var bottomViewContainerHeight: CGFloat = defaultOptions.containerHeight
public static var bottomPanFromBezel: Bool = defaultOptions.panningEnabled
public static var topBezelHeight: CGFloat = defaultOptions.bezelHeight
public static var topViewContainerHeight: CGFloat = defaultOptions.containerHeight
public static var topPanFromBezel: Bool = defaultOptions.panningEnabled
}
/**
:name: delegate
*/
public weak var delegate: SideNavigationViewDelegate?
/**
:name: isViewBasedAppearance
*/
public var isViewBasedAppearance: Bool {
return 0 == NSBundle.mainBundle().objectForInfoDictionaryKey("UIViewControllerBasedStatusBarAppearance") as? Int
}
/**
:name: isLeftContainerOpened
*/
public var isLeftContainerOpened: Bool {
if let c = leftViewContainer {
return c.frame.origin.x != leftOriginX
}
return false
}
/**
:name: isRightContainerOpened
*/
public var isRightContainerOpened: Bool {
if let c = rightViewContainer {
return c.frame.origin.x != rightOriginX
}
return false
}
/**
:name: isBottomContainerOpened
*/
public var isBottomContainerOpened: Bool {
if let c = bottomViewContainer {
return c.frame.origin.y != bottomOriginY
}
return false
}
/**
:name: isTopContainerOpened
*/
public var isTopContainerOpened: Bool {
if let c = topViewContainer {
return c.frame.origin.y != topOriginY
}
return false
}
/**
:name: isUserInteractionEnabled
*/
public var isUserInteractionEnabled: Bool {
get {
return mainViewContainer!.userInteractionEnabled
}
set(value) {
mainViewContainer?.userInteractionEnabled = value
}
}
/**
:name: backdropViewContainer
*/
public private(set) var backdropViewContainer: UIView?
/**
:name: mainViewContainer
*/
public private(set) var mainViewContainer: UIView?
/**
:name: leftViewContainer
*/
public private(set) var leftViewContainer: UIView?
/**
:name: rightViewContainer
*/
public private(set) var rightViewContainer: UIView?
/**
:name: bottomViewContainer
*/
public private(set) var bottomViewContainer: UIView?
/**
:name: bottomViewContainer
*/
public private(set) var topViewContainer: UIView?
/**
:name: leftContainer
*/
public private(set) var leftContainer: SideNavigationViewContainer?
/**
:name: rightContainer
*/
public private(set) var rightContainer: SideNavigationViewContainer?
/**
:name: bottomContainer
*/
public private(set) var bottomContainer: SideNavigationViewContainer?
/**
:name: topContainer
*/
public private(set) var topContainer: SideNavigationViewContainer?
/**
:name: mainViewController
*/
public var mainViewController: UIViewController?
/**
:name: leftViewController
*/
public var leftViewController: UIViewController?
/**
:name: rightViewController
*/
public var rightViewController: UIViewController?
/**
:name: leftViewController
*/
public var bottomViewController: UIViewController?
/**
:name: topViewController
*/
public var topViewController: UIViewController?
/**
:name: leftPanGesture
*/
public var leftPanGesture: UIPanGestureRecognizer?
/**
:name: leftTapGesture
*/
public var leftTapGesture: UITapGestureRecognizer?
/**
:name: rightTapGesture
*/
public var rightTapGesture: UITapGestureRecognizer?
/**
:name: rightTapGesture
*/
public var bottomTapGesture: UITapGestureRecognizer?
/**
:name: topTapGesture
*/
public var topTapGesture: UITapGestureRecognizer?
/**
:name: rightPanGesture
*/
public var rightPanGesture: UIPanGestureRecognizer?
/**
:name: rightPanGesture
*/
public var bottomPanGesture: UIPanGestureRecognizer?
/**
:name: rightPanGesture
*/
public var topPanGesture: UIPanGestureRecognizer?
//
// :name: leftOriginX
//
private var leftOriginX: CGFloat {
return -options.leftViewContainerWidth
}
//
// :name: rightOriginX
//
private var rightOriginX: CGFloat {
return view.bounds.width
}
//
// :name: bottomOriginY
//
private var bottomOriginY: CGFloat {
return view.bounds.height
}
//
// :name: topOriginY
//
private var topOriginY: CGFloat {
return -options.topViewContainerHeight
}
/**
:name: init
*/
public required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
/**
:name: init
*/
public override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
/**
:name: init
*/
public convenience init(mainViewController: UIViewController, leftViewController: UIViewController) {
self.init()
self.mainViewController = mainViewController
self.leftViewController = leftViewController
prepareView()
prepareLeftView()
}
/**
:name: init
*/
public convenience init(mainViewController: UIViewController, rightViewController: UIViewController) {
self.init()
self.mainViewController = mainViewController
self.rightViewController = rightViewController
prepareView()
prepareRightView()
}
/**
:name: init
*/
public convenience init(mainViewController: UIViewController, bottomViewController: UIViewController) {
self.init()
self.mainViewController = mainViewController
self.bottomViewController = bottomViewController
prepareView()
prepareBottomView()
}
/**
:name: init
*/
public convenience init(mainViewController: UIViewController, topViewController: UIViewController) {
self.init()
self.mainViewController = mainViewController
self.topViewController = topViewController
prepareView()
prepareTopView()
}
/**
:name: init
*/
public convenience init(mainViewController: UIViewController, leftViewController: UIViewController, rightViewController: UIViewController) {
self.init()
self.mainViewController = mainViewController
self.leftViewController = leftViewController
self.rightViewController = rightViewController
prepareView()
prepareLeftView()
prepareRightView()
}
/**
:name: init
*/
public convenience init(mainViewController: UIViewController, leftViewController: UIViewController, bottomViewController: UIViewController) {
self.init()
self.mainViewController = mainViewController
self.leftViewController = leftViewController
self.bottomViewController = bottomViewController
prepareView()
prepareLeftView()
prepareBottomView()
}
/**
:name: init
*/
public convenience init(mainViewController: UIViewController, leftViewController: UIViewController, bottomViewController: UIViewController, rightViewController: UIViewController) {
self.init()
self.mainViewController = mainViewController
self.leftViewController = leftViewController
self.bottomViewController = bottomViewController
self.rightViewController = rightViewController
prepareView()
prepareLeftView()
prepareBottomView()
prepareRightView()
}
/**
:name: init
*/
public convenience init(mainViewController: UIViewController, leftViewController: UIViewController, bottomViewController: UIViewController, rightViewController: UIViewController, topViewController: UIViewController) {
self.init()
self.mainViewController = mainViewController
self.leftViewController = leftViewController
self.bottomViewController = bottomViewController
self.rightViewController = rightViewController
self.topViewController = topViewController
prepareView()
prepareLeftView()
prepareBottomView()
prepareRightView()
prepareTopView()
}
/**
:name: init
*/
public convenience init(mainViewController: UIViewController, bottomViewController: UIViewController, rightViewController: UIViewController) {
self.init()
self.mainViewController = mainViewController
self.bottomViewController = bottomViewController
self.rightViewController = rightViewController
prepareView()
prepareBottomView()
prepareRightView()
}
/**
:name: init
*/
public convenience init(mainViewController: UIViewController, bottomViewController: UIViewController, topViewController: UIViewController) {
self.init()
self.mainViewController = mainViewController
self.bottomViewController = bottomViewController
self.topViewController = topViewController
prepareView()
prepareBottomView()
prepareTopView()
}
/**
:name: init
*/
public convenience init(mainViewController: UIViewController, rightViewController: UIViewController, topViewController: UIViewController) {
self.init()
self.mainViewController = mainViewController
self.rightViewController = rightViewController
self.topViewController = topViewController
prepareView()
prepareRightView()
prepareTopView()
}
//
// :name: viewDidLoad
//
public override func viewDidLoad() {
super.viewDidLoad()
edgesForExtendedLayout = .None
}
//
// :name: viewWillLayoutSubviews
//
public override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
if mainViewController != nil {
prepareContainedViewController(&mainViewContainer, viewController: &mainViewController)
}
if leftViewController != nil {
prepareContainedViewController(&leftViewContainer, viewController: &leftViewController)
}
if rightViewController != nil {
prepareContainedViewController(&rightViewContainer, viewController: &rightViewController)
}
if bottomViewController != nil {
prepareContainedViewController(&bottomViewContainer, viewController: &bottomViewController)
}
if topViewController != nil {
prepareContainedViewController(&topViewContainer, viewController: &topViewController)
}
}
/**
:name: toggleLeftViewContainer
*/
public func toggleLeftViewContainer(velocity: CGFloat = 0) {
isLeftContainerOpened ? closeLeftViewContainer(velocity: velocity) : openLeftViewContainer(velocity: velocity)
}
/**
:name: toggleRightViewContainer
*/
public func toggleRightViewContainer(velocity: CGFloat = 0) {
isRightContainerOpened ? closeRightViewContainer(velocity: velocity) : openRightViewContainer(velocity: velocity)
}
/**
:name: toggleBottomViewContainer
*/
public func toggleBottomViewContainer(velocity: CGFloat = 0) {
isBottomContainerOpened ? closeBottomViewContainer(velocity: velocity) : openBottomViewContainer(velocity: velocity)
}
/**
:name: toggleTopViewContainer
*/
public func toggleTopViewContainer(velocity: CGFloat = 0) {
isTopContainerOpened ? closeTopViewContainer(velocity: velocity) : openTopViewContainer(velocity: velocity)
}
/**
:name: openLeftViewContainer
*/
public func openLeftViewContainer(velocity: CGFloat = 0) {
if let vc = leftViewContainer {
if let c = leftContainer {
prepareContainerToOpen(&leftViewController, viewContainer: &leftViewContainer, state: c.state)
UIView.animateWithDuration(Double(0 == velocity ? options.animationDuration : fmax(0.1, fmin(1, Double(vc.frame.origin.x / velocity)))),
delay: 0,
options: .CurveEaseInOut,
animations: { _ in
vc.frame.origin.x = 0
self.backdropViewContainer?.layer.opacity = Float(options.backdropOpacity)
self.mainViewContainer?.transform = CGAffineTransformMakeScale(options.backdropScale, options.backdropScale)
}
) { _ in
self.isUserInteractionEnabled = false
}
c.state = .Opened
delegate?.sideNavDidOpenLeftViewContainer?(self, container: c)
}
}
}
/**
:name: openRightViewContainer
*/
public func openRightViewContainer(velocity: CGFloat = 0) {
if let vc = rightViewContainer {
if let c = rightContainer {
prepareContainerToOpen(&rightViewController, viewContainer: &rightViewContainer, state: c.state)
UIView.animateWithDuration(Double(0 == velocity ? options.animationDuration : fmax(0.1, fmin(1, Double(fabs(vc.frame.origin.x - rightOriginX) / velocity)))),
delay: 0,
options: .CurveEaseInOut,
animations: { _ in
vc.frame.origin.x = self.rightOriginX - vc.frame.size.width
self.backdropViewContainer?.layer.opacity = Float(options.backdropOpacity)
self.mainViewContainer?.transform = CGAffineTransformMakeScale(options.backdropScale, options.backdropScale)
}
) { _ in
self.isUserInteractionEnabled = false
}
c.state = .Opened
delegate?.sideNavDidOpenRightViewContainer?(self, container: c)
}
}
}
/**
:name: openBottomViewContainer
*/
public func openBottomViewContainer(velocity: CGFloat = 0) {
if let vc = bottomViewContainer {
if let c = bottomContainer {
prepareContainerToOpen(&bottomViewController, viewContainer: &bottomViewContainer, state: c.state)
UIView.animateWithDuration(Double(0 == velocity ? options.animationDuration : fmax(0.1, fmin(1, Double(fabs(vc.frame.origin.y - bottomOriginY) / velocity)))),
delay: 0,
options: .CurveEaseInOut,
animations: { _ in
vc.frame.origin.y = self.bottomOriginY - vc.frame.size.height
self.backdropViewContainer?.layer.opacity = Float(options.backdropOpacity)
self.mainViewContainer?.transform = CGAffineTransformMakeScale(options.backdropScale, options.backdropScale)
}
) { _ in
self.isUserInteractionEnabled = false
}
c.state = .Opened
delegate?.sideNavDidOpenRightViewContainer?(self, container: c)
}
}
}
/**
:name: openTopViewContainer
*/
public func openTopViewContainer(velocity: CGFloat = 0) {
if let vc = topViewContainer {
if let c = topContainer {
prepareContainerToOpen(&topViewController, viewContainer: &topViewContainer, state: c.state)
UIView.animateWithDuration(Double(0 == velocity ? options.animationDuration : fmax(0.1, fmin(1, Double(fabs(vc.frame.origin.y + topOriginY) / velocity)))),
delay: 0,
options: .CurveEaseInOut,
animations: { _ in
vc.frame.origin.y = self.topOriginY + vc.frame.size.height
self.backdropViewContainer?.layer.opacity = Float(options.backdropOpacity)
self.mainViewContainer?.transform = CGAffineTransformMakeScale(options.backdropScale, options.backdropScale)
}
) { _ in
self.isUserInteractionEnabled = false
}
c.state = .Opened
delegate?.sideNavDidOpenTopViewContainer?(self, container: c)
}
}
}
/**
:name: closeLeftViewContainer
*/
public func closeLeftViewContainer(velocity: CGFloat = 0) {
if let vc = leftViewContainer {
if let c = leftContainer {
prepareContainerToClose(&leftViewController, state: c.state)
UIView.animateWithDuration(Double(0 == velocity ? options.animationDuration : fmax(0.1, fmin(1, fabs(vc.frame.origin.x - leftOriginX) / velocity))),
delay: 0,
options: .CurveEaseInOut,
animations: { _ in
vc.frame.origin.x = self.leftOriginX
self.backdropViewContainer?.layer.opacity = 0
self.mainViewContainer?.transform = CGAffineTransformMakeScale(1, 1)
}
) { _ in
self.removeShadow(&self.leftViewContainer)
self.isUserInteractionEnabled = true
}
c.state = .Closed
delegate?.sideNavDidCloseLeftViewContainer?(self, container: c)
}
}
}
/**
:name: closeRightViewContainer
*/
public func closeRightViewContainer(velocity: CGFloat = 0) {
if let vc = rightViewContainer {
if let c = rightContainer {
prepareContainerToClose(&rightViewController, state: c.state)
UIView.animateWithDuration(Double(0 == velocity ? options.animationDuration : fmax(0.1, fmin(1, fabs(vc.frame.origin.x - rightOriginX) / velocity))),
delay: 0,
options: .CurveEaseInOut,
animations: { _ in
vc.frame.origin.x = self.rightOriginX
self.backdropViewContainer?.layer.opacity = 0
self.mainViewContainer?.transform = CGAffineTransformMakeScale(1, 1)
}
) { _ in
self.removeShadow(&self.rightViewContainer)
self.isUserInteractionEnabled = true
}
c.state = .Closed
delegate?.sideNavDidCloseRightViewContainer?(self, container: c)
}
}
}
/**
:name: closeBottomViewContainer
*/
public func closeBottomViewContainer(velocity: CGFloat = 0) {
if let vc = bottomViewContainer {
if let c = bottomContainer {
prepareContainerToClose(&bottomViewController, state: c.state)
UIView.animateWithDuration(Double(0 == velocity ? options.animationDuration : fmax(0.1, fmin(1, fabs(vc.frame.origin.y - bottomOriginY) / velocity))),
delay: 0,
options: .CurveEaseInOut,
animations: { _ in
vc.frame.origin.y = self.bottomOriginY
self.backdropViewContainer?.layer.opacity = 0
self.mainViewContainer?.transform = CGAffineTransformMakeScale(1, 1)
}
) { _ in
self.removeShadow(&self.bottomViewContainer)
self.isUserInteractionEnabled = true
}
c.state = .Closed
delegate?.sideNavDidCloseBottomViewContainer?(self, container: c)
}
}
}
/**
:name: closeBottomViewContainer
*/
public func closeTopViewContainer(velocity: CGFloat = 0) {
if let vc = topViewContainer {
if let c = topContainer {
prepareContainerToClose(&topViewController, state: c.state)
UIView.animateWithDuration(Double(0 == velocity ? options.animationDuration : fmax(0.1, fmin(1, fabs(vc.frame.origin.y - topOriginY) / velocity))),
delay: 0,
options: .CurveEaseInOut,
animations: { _ in
vc.frame.origin.y = self.topOriginY
self.backdropViewContainer?.layer.opacity = 0
self.mainViewContainer?.transform = CGAffineTransformMakeScale(1, 1)
}
) { _ in
self.removeShadow(&self.topViewContainer)
self.isUserInteractionEnabled = true
}
c.state = .Closed
delegate?.sideNavDidCloseBottomViewContainer?(self, container: c)
}
}
}
/**
:name: switchMainViewController
*/
public func switchMainViewController(viewController: UIViewController, closeViewContainers: Bool) {
removeViewController(&mainViewController)
mainViewController = viewController
prepareContainedViewController(&mainViewContainer, viewController: &mainViewController)
if closeViewContainers {
closeLeftViewContainer()
closeRightViewContainer()
}
}
/**
:name: switchLeftViewController
*/
public func switchLeftViewController(viewController: UIViewController, closeLeftViewContainerViewContainer: Bool) {
removeViewController(&leftViewController)
leftViewController = viewController
prepareContainedViewController(&leftViewContainer, viewController: &leftViewController)
if closeLeftViewContainerViewContainer {
closeLeftViewContainer()
}
}
/**
:name: switchRightViewController
*/
public func switchRightViewController(viewController: UIViewController, closeRightViewContainerViewContainer: Bool) {
removeViewController(&rightViewController)
rightViewController = viewController
prepareContainedViewController(&rightViewContainer, viewController: &rightViewController)
if closeRightViewContainerViewContainer {
closeRightViewContainer()
}
}
/**
:name: switchBottomViewController
*/
public func switchBottomViewController(viewController: UIViewController, closeBottomViewContainerViewContainer: Bool) {
removeViewController(&rightViewController)
rightViewController = viewController
prepareContainedViewController(&rightViewContainer, viewController: &rightViewController)
if closeBottomViewContainerViewContainer {
closeBottomViewContainer()
}
}
/**
:name: switchTopViewController
*/
public func switchTopViewController(viewController: UIViewController, closeTopViewContainerViewContainer: Bool) {
removeViewController(&topViewController)
topViewController = viewController
prepareContainedViewController(&topViewContainer, viewController: &topViewController)
if closeTopViewContainerViewContainer {
closeTopViewContainer()
}
}
//
// :name: gestureRecognizer
//
public func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldReceiveTouch touch: UITouch) -> Bool {
if gestureRecognizer == leftPanGesture {
return gesturePanLeftViewController(gestureRecognizer, withTouchPoint: touch.locationInView(view))
}
if gestureRecognizer == rightPanGesture {
return gesturePanRightViewController(gestureRecognizer, withTouchPoint: touch.locationInView(view))
}
if gestureRecognizer == bottomPanGesture {
return gesturePanBottomViewController(gestureRecognizer, withTouchPoint: touch.locationInView(view))
}
if gestureRecognizer == topPanGesture {
return gesturePanTopViewController(gestureRecognizer, withTouchPoint: touch.locationInView(view))
}
if gestureRecognizer == leftTapGesture {
return isLeftContainerOpened && !isPointContainedWithinViewController(&leftViewContainer, point: touch.locationInView(view))
}
if gestureRecognizer == rightTapGesture {
return isRightContainerOpened && !isPointContainedWithinViewController(&rightViewContainer, point: touch.locationInView(view))
}
if gestureRecognizer == bottomTapGesture {
return isBottomContainerOpened && !isPointContainedWithinViewController(&bottomViewContainer, point: touch.locationInView(view))
}
if gestureRecognizer == topTapGesture {
return isTopContainerOpened && !isPointContainedWithinViewController(&topViewContainer, point: touch.locationInView(view))
}
return true
}
//
// :name: prepareView
//
internal func prepareView() {
prepareMainContainer()
prepareBackdropContainer()
}
//
// :name: prepareLeftView
//
internal func prepareLeftView() {
prepareContainer(&leftContainer, viewContainer: &leftViewContainer, originX: leftOriginX, originY: 0, width: options.leftViewContainerWidth, height: view.bounds.size.height)
prepareLeftGestures()
}
//
// :name: prepareRightView
//
internal func prepareRightView() {
prepareContainer(&rightContainer, viewContainer: &rightViewContainer, originX: rightOriginX, originY: 0, width: options.rightViewContainerWidth, height: view.bounds.size.height)
prepareRightGestures()
}
//
// :name: prepareBottomView
//
internal func prepareBottomView() {
prepareContainer(&bottomContainer, viewContainer: &bottomViewContainer, originX: 0, originY: bottomOriginY, width: view.bounds.size.width, height: options.bottomViewContainerHeight)
prepareBottomGestures()
}
//
// :name: prepareBottomView
//
internal func prepareTopView() {
prepareContainer(&topContainer, viewContainer: &topViewContainer, originX: 0, originY: topOriginY, width: view.bounds.size.width, height: options.topViewContainerHeight)
prepareTopGestures()
}
//
// :name: addGestures
//
private func addGestures(inout pan: UIPanGestureRecognizer?, panSelector: Selector, inout tap: UITapGestureRecognizer?, tapSelector: Selector) {
if nil == pan {
pan = UIPanGestureRecognizer(target: self, action: panSelector)
pan!.delegate = self
view.addGestureRecognizer(pan!)
}
if nil == tap {
tap = UITapGestureRecognizer(target: self, action: tapSelector)
tap!.delegate = self
view.addGestureRecognizer(tap!)
}
}
//
// :name: removeGestures
//
private func removeGestures(inout pan: UIPanGestureRecognizer?, inout tap: UITapGestureRecognizer?) {
if let g = pan {
view.removeGestureRecognizer(g)
pan = nil
}
if let g = tap {
view.removeGestureRecognizer(g)
tap = nil
}
}
//
// :name: handleLeftPanGesture
//
internal func handleLeftPanGesture(gesture: UIPanGestureRecognizer) {
if isRightContainerOpened || isBottomContainerOpened || isTopContainerOpened { return }
if let vc = leftViewContainer {
if let c = leftContainer {
if .Began == gesture.state {
addShadow(&leftViewContainer)
toggleStatusBar(hide: true)
c.state = isLeftContainerOpened ? .Opened : .Closed
c.point = gesture.locationInView(view)
c.frame = vc.frame
delegate?.sideNavDidBeginLeftPan?(self, container: c)
} else if .Changed == gesture.state {
c.point = gesture.translationInView(gesture.view!)
let r = (vc.frame.origin.x - leftOriginX) / vc.frame.size.width
let s: CGFloat = 1 - (1 - options.backdropScale) * r
let x: CGFloat = c.frame.origin.x + c.point.x
vc.frame.origin.x = x < leftOriginX ? leftOriginX : x > 0 ? 0 : x
backdropViewContainer?.layer.opacity = Float(r * options.backdropOpacity)
mainViewContainer?.transform = CGAffineTransformMakeScale(s, s)
delegate?.sideNavDidChangeLeftPan?(self, container: c)
} else {
c.point = gesture.velocityInView(gesture.view)
let x: CGFloat = c.point.x >= 1000 || c.point.x <= -1000 ? c.point.x : 0
c.state = vc.frame.origin.x <= CGFloat(floor(leftOriginX)) + options.horizontalThreshold || c.point.x <= -1000 ? .Closed : .Opened
if .Closed == c.state {
closeLeftViewContainer(velocity: x)
} else {
openLeftViewContainer(velocity: x)
}
delegate?.sideNavDidEndLeftPan?(self, container: c)
}
}
}
}
//
// :name: handleLeftTapGesture
//
internal func handleLeftTapGesture(gesture: UIPanGestureRecognizer) {
if let c = leftContainer {
delegate?.sideNavDidTapLeft?(self, container: c)
closeLeftViewContainer()
}
}
//
// :name: handleRightPanGesture
//
internal func handleRightPanGesture(gesture: UIPanGestureRecognizer) {
if isLeftContainerOpened || isBottomContainerOpened || isTopContainerOpened { return }
if let vc = rightViewContainer {
if let c = rightContainer {
if .Began == gesture.state {
c.point = gesture.locationInView(view)
c.state = isRightContainerOpened ? .Opened : .Closed
c.frame = vc.frame
addShadow(&rightViewContainer)
toggleStatusBar(hide: true)
delegate?.sideNavDidBeginRightPan?(self, container: c)
} else if .Changed == gesture.state {
c.point = gesture.translationInView(gesture.view!)
let r = (rightOriginX - vc.frame.origin.x) / vc.frame.size.width
let m: CGFloat = rightOriginX - vc.frame.size.width
let x: CGFloat = c.frame.origin.x + c.point.x
vc.frame.origin.x = x > rightOriginX ? rightOriginX : x < m ? m : x
backdropViewContainer?.layer.opacity = Float(r * options.backdropOpacity)
delegate?.sideNavDidChangeRightPan?(self, container: c)
} else {
c.point = gesture.velocityInView(gesture.view)
let x: CGFloat = c.point.x <= -1000 || c.point.x >= 1000 ? c.point.x : 0
c.state = vc.frame.origin.x >= CGFloat(floor(rightOriginX) - options.horizontalThreshold) || c.point.x >= 1000 ? .Closed : .Opened
if .Closed == c.state {
closeRightViewContainer(velocity: x)
} else {
openRightViewContainer(velocity: x)
}
delegate?.sideNavDidEndRightPan?(self, container: c)
}
}
}
}
//
// :name: handleRightTapGesture
//
internal func handleRightTapGesture(gesture: UIPanGestureRecognizer) {
if let c = rightContainer {
delegate?.sideNavDidTapRight?(self, container: c)
closeRightViewContainer()
}
}
//
// :name: handleBottomPanGesture
//
internal func handleBottomPanGesture(gesture: UIPanGestureRecognizer) {
if isLeftContainerOpened || isRightContainerOpened || isTopContainerOpened { return }
if let vc = bottomViewContainer {
if let c = bottomContainer {
if .Began == gesture.state {
addShadow(&bottomViewContainer)
toggleStatusBar(hide: true)
c.state = isBottomContainerOpened ? .Opened : .Closed
c.point = gesture.locationInView(view)
c.frame = vc.frame
delegate?.sideNavDidBeginBottomPan?(self, container: c)
} else if .Changed == gesture.state {
c.point = gesture.translationInView(gesture.view!)
let r = (bottomOriginY - vc.frame.origin.y) / vc.frame.size.height
let m: CGFloat = bottomOriginY - vc.frame.size.height
let y: CGFloat = c.frame.origin.y + c.point.y
vc.frame.origin.y = y > bottomOriginY ? bottomOriginY : y < m ? m : y
backdropViewContainer?.layer.opacity = Float(r * options.backdropOpacity)
delegate?.sideNavDidChangeBottomPan?(self, container: c)
} else {
c.point = gesture.velocityInView(gesture.view)
let y: CGFloat = c.point.y <= -1000 || c.point.y >= 1000 ? c.point.y : 0
c.state = vc.frame.origin.y >= CGFloat(floor(bottomOriginY) - options.verticalThreshold) || c.point.y >= 1000 ? .Closed : .Opened
if .Closed == c.state {
closeBottomViewContainer(velocity: y)
} else {
openBottomViewContainer(velocity: y)
}
delegate?.sideNavDidEndBottomPan?(self, container: c)
}
}
}
}
//
// :name: handleRightTapGesture
//
internal func handleBottomTapGesture(gesture: UIPanGestureRecognizer) {
if let c = bottomContainer {
delegate?.sideNavDidTapBottom?(self, container: c)
closeBottomViewContainer()
}
}
//
// :name: handleTopPanGesture
//
internal func handleTopPanGesture(gesture: UIPanGestureRecognizer) {
if isLeftContainerOpened || isRightContainerOpened || isBottomContainerOpened { return }
if let vc = topViewContainer {
if let c = topContainer {
if .Began == gesture.state {
addShadow(&topViewContainer)
toggleStatusBar(hide: true)
c.state = isTopContainerOpened ? .Opened : .Closed
c.point = gesture.locationInView(view)
c.frame = vc.frame
delegate?.sideNavDidBeginTopPan?(self, container: c)
} else if .Changed == gesture.state {
c.point = gesture.translationInView(gesture.view!)
let r = (topOriginY - vc.frame.origin.y) / vc.frame.size.height
let m: CGFloat = topOriginY + vc.frame.size.height
let y: CGFloat = c.frame.origin.y + c.point.y // increase origin y
vc.frame.origin.y = y < topOriginY ? topOriginY : y < m ? y : m
backdropViewContainer?.layer.opacity = Float(abs(r) * options.backdropOpacity)
delegate?.sideNavDidChangeTopPan?(self, container: c)
} else {
c.point = gesture.velocityInView(gesture.view)
let y: CGFloat = c.point.y <= -1000 || c.point.y >= 1000 ? c.point.y : 0
c.state = vc.frame.origin.y >= CGFloat(floor(topOriginY) + options.verticalThreshold) || c.point.y >= 1000 ? .Opened : .Closed
if .Closed == c.state {
closeTopViewContainer(velocity: y)
} else {
openTopViewContainer(velocity: y)
}
delegate?.sideNavDidEndTopPan?(self, container: c)
}
}
}
}
//
// :name: handleRightTapGesture
//
internal func handleTopTapGesture(gesture: UIPanGestureRecognizer) {
if let c = topContainer {
delegate?.sideNavDidTapTop?(self, container: c)
closeTopViewContainer()
}
}
//
// :name: addShadow
//
private func addShadow(inout viewContainer: UIView?) {
if let vc = viewContainer {
vc.layer.shadowOffset = options.shadowOffset
vc.layer.shadowOpacity = options.shadowOpacity
vc.layer.shadowRadius = options.shadowRadius
vc.layer.shadowPath = UIBezierPath(rect: vc.bounds).CGPath
vc.layer.masksToBounds = false
}
}
//
// :name: removeShadow
//
private func removeShadow(inout viewContainer: UIView?) {
if let vc = viewContainer {
vc.layer.opacity = 1
vc.layer.masksToBounds = true
}
}
//
// :name: toggleStatusBar
//
private func toggleStatusBar(hide: Bool = false) {
if options.hideStatusBar {
if isViewBasedAppearance {
UIApplication.sharedApplication().setStatusBarHidden(hide, withAnimation: .Slide)
} else {
dispatch_async(dispatch_get_main_queue(), {
if let w = UIApplication.sharedApplication().keyWindow {
w.windowLevel = hide ? UIWindowLevelStatusBar + 1 : 0
}
})
}
}
}
//
// :name: removeViewController
//
private func removeViewController(inout viewController: UIViewController?) {
if let vc = viewController {
vc.willMoveToParentViewController(nil)
vc.view.removeFromSuperview()
vc.removeFromParentViewController()
}
}
//
// :name: gesturePanLeftViewController
//
private func gesturePanLeftViewController(gesture: UIGestureRecognizer, withTouchPoint point: CGPoint) -> Bool {
return isLeftContainerOpened || options.leftPanFromBezel && isLeftPointContainedWithinRect(point)
}
//
// :name: gesturePanRightViewController
//
private func gesturePanRightViewController(gesture: UIGestureRecognizer, withTouchPoint point: CGPoint) -> Bool {
return isRightContainerOpened || options.rightPanFromBezel && isRightPointContainedWithinRect(point)
}
//
// :name: gesturePanRightViewController
//
private func gesturePanBottomViewController(gesture: UIGestureRecognizer, withTouchPoint point: CGPoint) -> Bool {
return isBottomContainerOpened || options.bottomPanFromBezel && isBottomPointContainedWithinRect(point)
}
//
// :name: gesturePanTopViewController
//
private func gesturePanTopViewController(gesture: UIGestureRecognizer, withTouchPoint point: CGPoint) -> Bool {
return isTopContainerOpened || options.topPanFromBezel && isTopPointContainedWithinRect(point)
}
//
// :name: isLeftPointContainedWithinRect
//
private func isLeftPointContainedWithinRect(point: CGPoint) -> Bool {
return CGRectContainsPoint(CGRectMake(0, 0, options.leftBezelWidth, view.bounds.size.height), point)
}
//
// :name: isRightPointContainedWithinRect
//
private func isRightPointContainedWithinRect(point: CGPoint) -> Bool {
return CGRectContainsPoint(CGRectMake(CGRectGetMaxX(view.bounds) - options.rightBezelWidth, 0, options.rightBezelWidth, view.bounds.size.height), point)
}
//
// :name: isBottomPointContainedWithinRect
//
private func isBottomPointContainedWithinRect(point: CGPoint) -> Bool {
return CGRectContainsPoint(CGRectMake(0, CGRectGetMaxY(view.bounds) - options.bottomBezelHeight, view.bounds.size.width, options.bottomBezelHeight), point)
}
//
// :name: isTopPointContainedWithinRect
//
private func isTopPointContainedWithinRect(point: CGPoint) -> Bool {
return CGRectContainsPoint(CGRectMake(0, 0, view.bounds.size.width, options.topBezelHeight), point)
}
//
// :name: isPointContainedWithinViewController
//
private func isPointContainedWithinViewController(inout viewContainer: UIView?, point: CGPoint) -> Bool {
if let vc = viewContainer {
return CGRectContainsPoint(vc.frame, point)
}
return false
}
//
// :name: prepareMainContainer
//
private func prepareMainContainer() {
mainViewContainer = UIView(frame: view.bounds)
mainViewContainer!.backgroundColor = MaterialTheme.clear.color
mainViewContainer!.autoresizingMask = .FlexibleHeight | .FlexibleWidth
view.addSubview(mainViewContainer!)
}
//
// :name: prepareBackdropContainer
//
private func prepareBackdropContainer() {
backdropViewContainer = UIView(frame: view.bounds)
backdropViewContainer!.backgroundColor = options.backdropBackgroundColor
backdropViewContainer!.autoresizingMask = .FlexibleHeight | .FlexibleWidth
backdropViewContainer!.layer.opacity = 0
view.addSubview(backdropViewContainer!)
}
//
// :name: prepareLeftGestures
//
private func prepareLeftGestures() {
removeGestures(&leftPanGesture, tap: &leftTapGesture)
addGestures(&leftPanGesture, panSelector: "handleLeftPanGesture:", tap: &leftTapGesture, tapSelector: "handleLeftTapGesture:")
}
//
// :name: prepareRightGestures
//
private func prepareRightGestures() {
removeGestures(&rightPanGesture, tap: &rightTapGesture)
addGestures(&rightPanGesture, panSelector: "handleRightPanGesture:", tap: &rightTapGesture, tapSelector: "handleRightTapGesture:")
}
//
// :name: prepareBottomGestures
//
private func prepareBottomGestures() {
removeGestures(&bottomPanGesture, tap: &bottomTapGesture)
addGestures(&bottomPanGesture, panSelector: "handleBottomPanGesture:", tap: &bottomTapGesture, tapSelector: "handleBottomTapGesture:")
}
//
// :name: prepareBottomGestures
//
private func prepareTopGestures() {
removeGestures(&topPanGesture, tap: &topTapGesture)
addGestures(&topPanGesture, panSelector: "handleTopPanGesture:", tap: &topTapGesture, tapSelector: "handleTopTapGesture:")
}
//
// :name: prepareContainer
//
private func prepareContainer(inout container: SideNavigationViewContainer?, inout viewContainer: UIView?, originX: CGFloat, originY: CGFloat, width: CGFloat, height: CGFloat) {
container = SideNavigationViewContainer(state: .Closed, point: CGPointZero, frame: CGRectZero)
var b: CGRect = view.bounds
b.size.width = width
b.size.height = height
b.origin.x = originX
b.origin.y = originY
viewContainer = UIView(frame: b)
viewContainer!.backgroundColor = MaterialTheme.clear.color
viewContainer!.autoresizingMask = .FlexibleHeight
view.addSubview(viewContainer!)
}
//
// :name: prepareContainerToOpen
//
private func prepareContainerToOpen(inout viewController: UIViewController?, inout viewContainer: UIView?, state: SideNavigationViewState) {
addShadow(&viewContainer)
toggleStatusBar(hide: true)
}
//
// :name: prepareContainerToClose
//
private func prepareContainerToClose(inout viewController: UIViewController?, state: SideNavigationViewState) {
toggleStatusBar()
}
//
// :name: prepareContainedViewController
//
private func prepareContainedViewController(inout viewContainer: UIView?, inout viewController: UIViewController?) {
if let vc = viewController {
if let c = viewContainer {
vc.view.setTranslatesAutoresizingMaskIntoConstraints(false)
addChildViewController(vc)
c.addSubview(vc.view)
Layout.expandToParent(c, child: vc.view)
vc.didMoveToParentViewController(self)
}
}
}
}
|
agpl-3.0
|
990006219146095341ffd00ee3486895
| 34.083707 | 221 | 0.697222 | 4.569009 | false | false | false | false |
troystribling/FutureLocation
|
Examples/Location/Location/UIAlertControllerExtensions.swift
|
3
|
1347
|
//
// UIAlertViewExtensions.swift
// BlueCap
//
// Created by Troy Stribling on 7/6/14.
// Copyright (c) 2014 Troy Stribling. The MIT License (MIT).
//
import UIKit
extension UIAlertController {
class func alertOnError(_ error: Swift.Error, handler: ((UIAlertAction?) -> Void)? = nil) -> UIAlertController {
let alert = UIAlertController(title: "Error", message: error.localizedDescription, preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: handler))
return alert
}
class func alertOnErrorWithMessage(_ message: String, handler: ((UIAlertAction?) -> Void)? = nil) -> UIAlertController {
let alert = UIAlertController(title: "Error", message:message, preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler:handler))
return alert
}
class func alertWithMessage(_ message: String, handler: ((UIAlertAction?) -> Void)? = nil) -> UIAlertController {
let alert = UIAlertController(title: "Alert", message:message, preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler:handler))
return alert
}
}
|
mit
|
a3afd821565ae6f48108eeba622e0039
| 43.9 | 136 | 0.703044 | 4.810714 | false | false | false | false |
dev-gao/GYPageViewController
|
GYPageViewController/Classes/UIView+GYPauseAnimation.swift
|
1
|
727
|
//
// UIView+GYPauseAnimation.swift
// GYPageViewController
//
// Created by GaoYu on 16/6/13.
// Copyright © 2016年 GaoYu. All rights reserved.
//
import UIKit
extension UIView {
func pauseAnimations() {
let paused_time = self.layer.convertTime(CACurrentMediaTime(), toLayer: nil)
self.layer.speed = 0.0
self.layer.timeOffset = paused_time
}
func resumeAnimations() {
let paused_time = self.layer.timeOffset
self.layer.speed = 1.0
self.layer.timeOffset = 0.0
self.layer.beginTime = 0.0
let time_since_pause = self.layer.convertTime(CACurrentMediaTime(), toLayer: nil) - paused_time
self.layer.beginTime = time_since_pause
}
}
|
mit
|
81e09eed70a53a31c44b3ba9629d2756
| 26.884615 | 103 | 0.650552 | 3.770833 | false | false | false | false |
comcxx11/JHProgressHUD
|
JHProgressHUD.swift
|
1
|
8340
|
//
// JHProgressHUD.swift
// JHProgressHUD
//
// Created by Harikrishnan on 02/12/14.
// Copyright (c) 2014 Harikrishnan T. All rights reserved.
//
import UIKit
class JHProgressHUD: UIView
{
private var backGroundView : UIView?
private var progressIndicator : UIActivityIndicatorView?
private var titleLabel : UILabel?
private var footerLabel : UILabel?
var headerColor : UIColor
var footerColor : UIColor
var backGroundColor : UIColor
var loaderColor : UIColor
class var sharedHUD : JHProgressHUD {
struct Static {
static var instance : JHProgressHUD?
static var token : dispatch_once_t = 0
}
dispatch_once(&Static.token) {
Static.instance = JHProgressHUD()
}
return Static.instance!
}
init()
{
//Initialising Code
headerColor = UIColor.whiteColor()
footerColor = UIColor.whiteColor()
backGroundColor = UIColor.blackColor()
loaderColor = UIColor.whiteColor()
super.init(frame: CGRectZero)
}
required init(coder aDecoder: NSCoder)
{
headerColor = UIColor.whiteColor()
footerColor = UIColor.whiteColor()
backGroundColor = UIColor.blackColor()
loaderColor = UIColor.whiteColor()
super.init(coder: aDecoder)
}
override init(frame: CGRect)
{
headerColor = UIColor.whiteColor()
footerColor = UIColor.whiteColor()
backGroundColor = UIColor.blackColor()
loaderColor = UIColor.whiteColor()
super.init(frame: frame)
}
// MARK: -Public Methods
// Show the loader added to the mentioned view with the provided title and footer texts
func showInView(view : UIView, withHeader title : String?, andFooter footer : String?)
{
self.hide()
self.frame = view.frame
setIndicator()
if title != nil && title != ""
{
setTitleLabel(title!)
titleLabel!.frame = CGRectMake(0, 0, getLabelSize().width, getLabelSize().height)
}
if footer != nil && footer != ""
{
setFooterLabel(footer!)
footerLabel!.frame = CGRectMake(0, 0, getLabelSize().width, getLabelSize().height)
}
setBackGround(self)
if title != nil && title != ""
{
titleLabel!.frame.origin = getHeaderOrigin(backGroundView!)
titleLabel?.adjustsFontSizeToFitWidth = true
backGroundView?.addSubview(titleLabel!)
}
if footer != nil && footer != ""
{
footerLabel!.frame.origin = getFooterOrigin(backGroundView!)
footerLabel?.adjustsFontSizeToFitWidth = true
backGroundView?.addSubview(footerLabel!)
}
progressIndicator?.frame.origin = getIndicatorOrigin(backGroundView!, activityIndicatorView: progressIndicator!)
backGroundView?.addSubview(progressIndicator!)
view.addSubview(self)
}
// Show the loader added to the mentioned window with the provided title and footer texts
func showInWindow(window : UIWindow, withHeader title : String?, andFooter footer : String?)
{
self.showInView(window, withHeader: title, andFooter: footer)
}
// Show the loader added to the mentioned view with no title and footer texts
func showInView(view : UIView)
{
self.showInView(view, withHeader: nil, andFooter: nil)
}
// Show the loader added to the mentioned window with no title and footer texts
func showInWindow(window : UIWindow)
{
self.showInView(window, withHeader: nil, andFooter: nil)
}
// Removes the loader from its superview
func hide()
{
if self.superview != nil
{
self.removeFromSuperview()
progressIndicator?.stopAnimating()
}
}
// MARK: -Set view properties
private func setBackGround(view : UIView)
{
if backGroundView?.superview != nil
{
backGroundView?.removeFromSuperview()
var aView = backGroundView?.viewWithTag(1001) as UIView?
aView?.removeFromSuperview()
}
backGroundView = UIView(frame: getBackGroundFrame(self))
backGroundView?.backgroundColor = UIColor.clearColor()
var translucentView = UIView(frame: backGroundView!.bounds)
translucentView.backgroundColor = backGroundColor
translucentView.alpha = 0.85
translucentView.tag = 1001;
translucentView.layer.cornerRadius = 15.0
backGroundView?.addSubview(translucentView)
backGroundView?.layer.cornerRadius = 15.0
self.addSubview(backGroundView!)
}
private func setIndicator()
{
if progressIndicator?.superview != nil
{
progressIndicator?.removeFromSuperview()
}
progressIndicator = UIActivityIndicatorView(activityIndicatorStyle: .WhiteLarge)
progressIndicator?.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.WhiteLarge
progressIndicator?.color = loaderColor
progressIndicator?.backgroundColor = UIColor.clearColor()
progressIndicator?.startAnimating()
}
private func setTitleLabel(text : String)
{
if titleLabel?.superview != nil
{
titleLabel?.removeFromSuperview()
}
titleLabel = UILabel()
titleLabel?.text = text
titleLabel?.font = self.boldFontWithFont(titleLabel?.font)
titleLabel?.textColor = headerColor
titleLabel?.textAlignment = .Center
}
private func setFooterLabel(text : String)
{
if footerLabel?.superview != nil
{
footerLabel?.removeFromSuperview()
}
footerLabel = UILabel()
footerLabel?.text = text
footerLabel?.textColor = footerColor
footerLabel?.textAlignment = .Center
}
// MARK: -Get Frame
private func getBackGroundFrame(view : UIView) -> CGRect
{
let sideMargin:CGFloat = 20.0
var side = progressIndicator!.frame.height + sideMargin
if titleLabel?.text != nil && titleLabel?.text != ""
{
side = progressIndicator!.frame.height + titleLabel!.frame.width
}
else if (footerLabel?.text != nil && footerLabel?.text != "")
{
side = progressIndicator!.frame.height + footerLabel!.frame.width
}
var originX = view.center.x - (side/2)
var originY = view.center.y - (side/2)
return CGRectMake(originX, originY, side, side)
}
// MARK: Get Size
private func getLabelSize() -> CGSize
{
var width = progressIndicator!.frame.width * 3
var height = progressIndicator!.frame.height / 1.5
return CGSizeMake(width, height)
}
// MARK: -Get Origin
private func getIndicatorOrigin(view : UIView, activityIndicatorView indicator : UIActivityIndicatorView) -> CGPoint
{
var side = indicator.frame.size.height
var originX = (view.bounds.width/2) - (side/2)
var originY = (view.bounds.height/2) - (side/2)
return CGPointMake(originX, originY)
}
private func getHeaderOrigin(view : UIView) -> CGPoint
{
var width = titleLabel!.frame.size.width
var originX = (view.bounds.width/2) - (width/2)
return CGPointMake(originX, 1)
}
private func getFooterOrigin(view : UIView) -> CGPoint
{
var width = footerLabel!.frame.width
var height = footerLabel!.frame.height
var originX = (view.bounds.width/2) - (width/2)
var originY = view.frame.height - (height + 1)
return CGPointMake(originX, originY)
}
// MARK: -Set Font
func boldFontWithFont(font : UIFont?) -> UIFont
{
var fontDescriptor : UIFontDescriptor = font!.fontDescriptor().fontDescriptorWithSymbolicTraits(.TraitBold)!
return UIFont(descriptor: fontDescriptor, size: 0)
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func drawRect(rect: CGRect)
{
// Drawing code
}
*/
}
|
mit
|
35454e3fa8a11b909ffe05640dfcf7e8
| 31.325581 | 120 | 0.622062 | 5.036232 | false | false | false | false |
DSanzh/GuideMe-iOS
|
GuideMe/Controller/ThingsListVC.swift
|
1
|
1872
|
//
// ThingsListVC.swift
// GuideMe
//
// Created by Sanzhar on 9/29/17.
// Copyright © 2017 Sanzhar Dauylov. All rights reserved.
//
import UIKit
import EasyPeasy
class ThingsListVC: UIViewController {
lazy var tableView: UITableView = {
let _table = UITableView()
_table.delegate = self
_table.dataSource = self
_table.register(ThingsListCell.self, forCellReuseIdentifier: "ThingsListCell")
_table.tableFooterView = UIView()
_table.separatorStyle = .none
return _table
}()
override func viewDidLoad() {
super.viewDidLoad()
setupViews()
setupConstraints()
}
private func setupViews() {
view.addSubview(tableView)
}
private func setupConstraints() {
tableView.easy.layout([
Top().to(view),
Left().to(view),
Right().to(view),
Bottom().to(view)
])
}
}
extension ThingsListVC: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 5
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell: ThingsListCell = tableView.dequeueReusableCell(withIdentifier: "ThingsListCell", for: indexPath) as! ThingsListCell
cell.configureCell()
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
}
|
mit
|
b59001de256e519416a554c6127ab2ae
| 25.728571 | 133 | 0.635489 | 5.255618 | false | false | false | false |
seanooi/Yapper
|
Yapper/ViewController.swift
|
1
|
11359
|
//
// ViewController.swift
// Yapper
//
// Created by Sean Ooi on 7/26/15.
// Copyright (c) 2015 Sean Ooi. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
let buyerCellIdentifier = "BuyerCell"
let sellerCellIdentifier = "SellerCell"
let sectionInset: CGFloat = 4
let toolbarHeight: CGFloat = 43
let saleItemHeight: CGFloat = 64
var currentKeyboardHeight: CGFloat = 0
var toolbar: TextToolbar!
var saleItem: SaleItemView!
var chats = [[String: String]]()
var item = [String: String]()
// Activity indicator variables
var activityIndicatorBox: UIView!
var activityIndicator: UIActivityIndicatorView!
var activityLabel: UILabel!
@IBOutlet weak var collectionView: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
navigationController?.navigationBar.translucent = false
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillChangeFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)
collectionView.delegate = self
collectionView.dataSource = self
collectionView.keyboardDismissMode = .Interactive
collectionView.backgroundColor = .whiteColor()
inputAccessoryView.autoresizingMask = [.FlexibleHeight, .FlexibleWidth]
showIndicator()
getChatData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
deinit {
collectionView.delegate = nil
collectionView.dataSource = nil
NSNotificationCenter.defaultCenter().removeObserver(self)
}
override func canBecomeFirstResponder() -> Bool {
return true
}
override var inputAccessoryView: UIView {
get {
if toolbar == nil {
let screenWidth = UIScreen.mainScreen().bounds.width
toolbar = TextToolbar(frame: CGRect(x: 0, y: 0, width: screenWidth, height: toolbarHeight))
toolbar.delegate = self
}
return toolbar
}
}
override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator)
collectionView.collectionViewLayout.invalidateLayout()
collectionView.reloadData()
}
func keyboardWillChangeFrame(notification: NSNotification) {
if let userInfo = notification.userInfo {
let endFrame = (userInfo["UIKeyboardBoundsUserInfoKey"] as? NSValue)?.CGRectValue()
currentKeyboardHeight = endFrame?.size.height ?? 0
toggleSaleItemViewByKeyboardHeight()
scrollToBottomWithKeyboardEndHeight()
}
}
/**
Retrieves the chat data
*/
func getChatData() {
let manager = AFHTTPRequestOperationManager()
manager.responseSerializer = AFJSONResponseSerializer()
manager.GET("http://www.seanooi.com/chat/content.json", parameters: nil, success: { (operation, responseObject) -> Void in
if let response = responseObject as? [String: AnyObject] {
if let responseChats = response["chats"] as? [[String: String]] {
self.chats = responseChats
}
if let responseItem = response["offer"] as? [String: String] {
self.item = responseItem
self.setupSaleItemView()
}
self.hideIndicator()
self.collectionView.reloadSections(NSIndexSet(index: 0))
}
}, failure: { (operation, error) -> Void in
print("Error: " + error.localizedDescription)
})
}
/**
Sets up the top sale item bar view
*/
func setupSaleItemView() {
let screenWidth = UIScreen.mainScreen().bounds.width
saleItem = SaleItemView(frame: CGRect(x: 0, y: 0, width: screenWidth, height: saleItemHeight))
saleItem.itemNameLabel?.text = item["product_name"]
saleItem.itemPriceLabel?.text = item["product_price"]
saleItem.itemImageView?.sd_setImageWithURL(NSURL(string: item["product_image_url"]!), placeholderImage: UIImage(named: "Placeholder"))
saleItem.autoresizingMask = .FlexibleWidth
title = item["buyer_name"]
view.addSubview(saleItem)
}
/**
Toggles the visibility of the top sale item bar view
*/
func toggleSaleItemViewByKeyboardHeight() {
if saleItem != nil {
var toggleHide = CGAffineTransformIdentity
if isShowingKeyboard() {
toggleHide = CGAffineTransformMakeTranslation(0, -saleItemHeight)
}
UIView.animateWithDuration(0.3, delay: 0, options: .CurveEaseInOut, animations: { () -> Void in
self.saleItem.transform = toggleHide
}, completion: { (finish) -> Void in
//
})
}
}
/**
Scrolls the chat to the latest (bottom) entry
*/
func scrollToBottomWithKeyboardEndHeight() {
let topInset = isShowingKeyboard() ? sectionInset : saleItemHeight
collectionView.contentInset = UIEdgeInsets(top: topInset, left: 0, bottom: currentKeyboardHeight, right: 0)
collectionView.scrollIndicatorInsets = UIEdgeInsets(top: topInset, left: 0, bottom: currentKeyboardHeight, right: 0)
// Don't scroll to bottom when dismissing keyboard
if isShowingKeyboard() {
collectionView.scrollEnabled = false
collectionView.decelerationRate = UIScrollViewDecelerationRateFast
if chats.count > 0 {
let section = collectionView.numberOfSections() - 1
let numberOfItems = chats.count - 1
let indexPath = NSIndexPath(forItem: numberOfItems, inSection: section)
collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: .Bottom, animated: true)
}
collectionView.scrollEnabled = true
collectionView.decelerationRate = UIScrollViewDecelerationRateNormal
}
}
/**
Calculates the size of a given set of texts
- parameter text: The text to be used for calculating the size
- parameter width: The maximum width the text should fit into
- returns: The size of the box the given text can fit into
*/
func sizeForText(text:String, width: CGFloat) -> CGSize {
let temp = UILabel()
temp.numberOfLines = 0
temp.text = text
let newSize = temp.sizeThatFits(CGSize(width: width, height: CGFloat.max))
return newSize
}
/**
Checks to see if keyboard is currently visible
- returns: Boolean value whether keyboard is visible
*/
func isShowingKeyboard() -> Bool {
return currentKeyboardHeight > toolbarHeight
}
/**
Shows an activity indicator
*/
func showIndicator() {
view.userInteractionEnabled = false
inputAccessoryView.userInteractionEnabled = false
activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: .White)
activityIndicator.translatesAutoresizingMaskIntoConstraints = false
activityIndicator.startAnimating()
activityLabel = UILabel()
activityLabel.translatesAutoresizingMaskIntoConstraints = false
activityLabel.textColor = .whiteColor()
activityLabel.text = "Loading Chat"
activityLabel.adjustsFontSizeToFitWidth = true
activityLabel.minimumScaleFactor = 0.5
activityIndicatorBox = UIView()
activityIndicatorBox.translatesAutoresizingMaskIntoConstraints = false
activityIndicatorBox.backgroundColor = .blackColor()
activityIndicatorBox.alpha = 0
activityIndicatorBox.layer.cornerRadius = 8
activityIndicatorBox.addSubview(activityIndicator)
activityIndicatorBox.addSubview(activityLabel)
view.addSubview(activityIndicatorBox)
// Indicator constraints
let indicatorLead = NSLayoutConstraint(item: activityIndicator, attribute: .Leading, relatedBy: .Equal, toItem: activityIndicatorBox, attribute: .Leading, multiplier: 1, constant: 8)
let indicatorCenterY = NSLayoutConstraint(item: activityIndicator, attribute: .CenterY, relatedBy: .Equal, toItem: activityIndicatorBox, attribute: .CenterY, multiplier: 1, constant: 0)
// Label constraints
let labelLead = NSLayoutConstraint(item: activityLabel, attribute: .Leading, relatedBy: .GreaterThanOrEqual, toItem: activityIndicator, attribute: .Trailing, multiplier: 1, constant: 8)
let labelCenterY = NSLayoutConstraint(item: activityLabel, attribute: .CenterY, relatedBy: .Equal, toItem: activityIndicatorBox, attribute: .CenterY, multiplier: 1, constant: 0)
let labelTrail = NSLayoutConstraint(item: activityIndicatorBox, attribute: .Trailing, relatedBy: .Equal, toItem: activityLabel, attribute: .Trailing, multiplier: 1, constant: 8)
// Box constraints
let x = NSLayoutConstraint(item: activityIndicatorBox, attribute: .CenterX, relatedBy: .Equal, toItem: view, attribute: .CenterX, multiplier: 1, constant: 0)
let y = NSLayoutConstraint(item: activityIndicatorBox, attribute: .CenterY, relatedBy: .Equal, toItem: view, attribute: .CenterY, multiplier: 1, constant: -32)
let w = NSLayoutConstraint(item: activityIndicatorBox, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: 150)
let h = NSLayoutConstraint(item: activityIndicatorBox, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: 50)
activityIndicatorBox.addConstraint(indicatorLead)
activityIndicatorBox.addConstraint(indicatorCenterY)
activityIndicatorBox.addConstraint(labelLead)
activityIndicatorBox.addConstraint(labelCenterY)
activityIndicatorBox.addConstraint(labelTrail)
view.addConstraint(x)
view.addConstraint(y)
view.addConstraint(w)
view.addConstraint(h)
UIView.animateWithDuration(0.3, animations: { () -> Void in
self.activityIndicatorBox.alpha = 0.8
})
}
/**
Hides and removed the activity indicator
*/
func hideIndicator() {
UIView.animateWithDuration(0.3, animations: { () -> Void in
self.activityIndicatorBox.alpha = 0
}) { (finish) -> Void in
self.view.userInteractionEnabled = true
self.inputAccessoryView.userInteractionEnabled = true
self.activityIndicatorBox.removeFromSuperview()
self.activityLabel = nil
self.activityIndicator = nil
self.activityIndicatorBox = nil
}
}
}
|
mit
|
9bb58798abe79cd5d206a5527f1ad12d
| 39.280142 | 193 | 0.645039 | 5.637221 | false | false | false | false |
sourcebitsllc/Asset-Generator-Mac
|
XCAssetGenerator/ProgressLineView.swift
|
1
|
1517
|
//
// ProgressLineView.swift
// XCAssetGenerator
//
// Created by Bader on 6/11/15.
// Copyright (c) 2015 Bader Alabdulrazzaq. All rights reserved.
//
import Cocoa
class ProgressLineView: NSView {
private let line: NSView
var lineWidth: CGFloat = 3 {
didSet {
line.frame.size.height = lineWidth
}
}
var color: NSColor = NSColor.blackColor() {
didSet {
line.layer?.backgroundColor = color.CGColor
}
}
init(width: CGFloat) {
let frame = NSRect(x: 0, y: 0, width: width, height: lineWidth)
line = NSView(frame: NSRect(x: 0, y: 0, width: 0, height: lineWidth))
super.init(frame: frame)
line.wantsLayer = true
line.layer?.masksToBounds = true
line.layer?.backgroundColor = color.CGColor
addSubview(line)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func animateTo(#progress: Float) {
let width = bounds.size.width * (CGFloat(progress) / 100)
line.animator().frame.size.width = width
}
func forceAnimateFullProgress() {
line.animator().frame.size.width = bounds.size.width
}
func animateFadeOut() {
line.animator().alphaValue = 0
}
func resetProgress() {
line.animator().frame.size.width = 0
}
func initiateProgress() {
line.animator().frame.size.width = 0
line.alphaValue = 1
}
}
|
mit
|
9163edc82e65394cda79ec83653388a1
| 23.885246 | 77 | 0.586025 | 4.1 | false | false | false | false |
DrankoLQ/CustomAlertView
|
CustomAlertView/CustomAlertView/CustomAlertView.swift
|
1
|
2585
|
//
// CustomAlertView.swift
// CustomAlertView
//
// Created by Daniel Luque Quintana on 16/3/17.
// Copyright © 2017 dluque. All rights reserved.
//
import UIKit
class CustomAlertView: UIViewController {
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var messageLabel: UILabel!
@IBOutlet weak var alertTextField: UITextField!
@IBOutlet weak var alertView: UIView!
@IBOutlet weak var cancelButton: UIButton!
@IBOutlet weak var okButton: UIButton!
@IBOutlet weak var segmentedControl: UISegmentedControl!
var delegate: CustomAlertViewDelegate?
var selectedOption = "First"
let alertViewGrayColor = UIColor(red: 224.0/255.0, green: 224.0/255.0, blue: 224.0/255.0, alpha: 1)
override func viewDidLoad() {
super.viewDidLoad()
alertTextField.becomeFirstResponder()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
setupView()
animateView()
cancelButton.addBorder(side: .Top, color: alertViewGrayColor, width: 1)
cancelButton.addBorder(side: .Right, color: alertViewGrayColor, width: 1)
okButton.addBorder(side: .Top, color: alertViewGrayColor, width: 1)
}
func setupView() {
alertView.layer.cornerRadius = 15
self.view.backgroundColor = UIColor.black.withAlphaComponent(0.4)
}
func animateView() {
alertView.alpha = 0;
self.alertView.frame.origin.y = self.alertView.frame.origin.y + 50
UIView.animate(withDuration: 0.4, animations: { () -> Void in
self.alertView.alpha = 1.0;
self.alertView.frame.origin.y = self.alertView.frame.origin.y - 50
})
}
@IBAction func onTapCancelButton(_ sender: Any) {
alertTextField.resignFirstResponder()
delegate?.cancelButtonTapped()
self.dismiss(animated: true, completion: nil)
}
@IBAction func onTapOkButton(_ sender: Any) {
alertTextField.resignFirstResponder()
delegate?.okButtonTapped(selectedOption: selectedOption, textFieldValue: alertTextField.text!)
self.dismiss(animated: true, completion: nil)
}
@IBAction func onTapSegmentedControl(_ sender: UISegmentedControl) {
switch sender.selectedSegmentIndex {
case 0:
print("First option")
selectedOption = "First"
break
case 1:
print("Second option")
selectedOption = "Second"
break
default:
break
}
}
}
|
apache-2.0
|
738ddfee9b1eeebd5a441aa268fddb46
| 31.708861 | 103 | 0.643576 | 4.589698 | false | false | false | false |
david1mdavis/IOS-nRF-Toolbox
|
nRF Toolbox/HRS/NORHRMViewController.swift
|
1
|
22654
|
//
// NORHRMViewController.swift
// nRF Toolbox
//
// Created by Mostafa Berg on 04/05/16.
// Copyright © 2016 Nordic Semiconductor. All rights reserved.
//
import UIKit
import CoreBluetooth
import CorePlot
fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l < r
case (nil, _?):
return true
default:
return false
}
}
fileprivate func > <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l > r
default:
return rhs < lhs
}
}
fileprivate func >= <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l >= r
default:
return !(lhs < rhs)
}
}
class NORHRMViewController: NORBaseViewController, CBCentralManagerDelegate, CBPeripheralDelegate, NORScannerDelegate, CPTPlotDataSource, CPTPlotSpaceDelegate {
//MARK: - Properties
var bluetoothManager : CBCentralManager?
var hrValues : NSMutableArray?
var xValues : NSMutableArray?
var plotXMaxRange : Int?
var plotXMinRange : Int?
var plotYMaxRange : Int?
var plotYMinRange : Int?
var plotXInterval : Int?
var plotYInterval : Int?
var isBluetoothOn : Bool?
var isDeviceConnected : Bool?
var isBackButtonPressed : Bool?
var batteryServiceUUID : CBUUID
var batteryLevelCharacteristicUUID : CBUUID
var hrServiceUUID : CBUUID
var hrMeasurementCharacteristicUUID : CBUUID
var hrLocationCharacteristicUUID : CBUUID
var linePlot : CPTScatterPlot?
var graph : CPTGraph?
var peripheral : CBPeripheral?
//MARK: - UIVIewController Outlets
@IBOutlet weak var verticalLabel: UILabel!
@IBOutlet weak var battery: UIButton!
@IBOutlet weak var deviceName: UILabel!
@IBOutlet weak var connectionButton: UIButton!
@IBOutlet weak var hrLocation: UILabel!
@IBOutlet weak var hrValue: UILabel!
@IBOutlet weak var graphView: CPTGraphHostingView!
//MARK: - UIVIewController Actions
@IBAction func connectionButtonTapped(_ sender: AnyObject) {
if peripheral != nil
{
bluetoothManager?.cancelPeripheralConnection(peripheral!)
}
}
@IBAction func aboutButtonTapped(_ sender: AnyObject) {
self.showAbout(message: NORAppUtilities.getHelpTextForService(service: .hrm))
}
//MARK: - UIViewController delegate
required init?(coder aDecoder: NSCoder) {
hrServiceUUID = CBUUID(string: NORServiceIdentifiers.hrsServiceUUIDString)
hrMeasurementCharacteristicUUID = CBUUID(string: NORServiceIdentifiers.hrsHeartRateCharacteristicUUIDString)
hrLocationCharacteristicUUID = CBUUID(string: NORServiceIdentifiers.hrsSensorLocationCharacteristicUUIDString)
batteryServiceUUID = CBUUID(string: NORServiceIdentifiers.batteryServiceUUIDString)
batteryLevelCharacteristicUUID = CBUUID(string: NORServiceIdentifiers.batteryLevelCharacteristicUUIDString)
super.init(coder: aDecoder)
}
override func viewDidLoad() {
super.viewDidLoad()
// Rotate the vertical label
verticalLabel.transform = CGAffineTransform(translationX: -(verticalLabel.frame.width/2) + (verticalLabel.frame.height / 2), y: 0.0).rotated(by: CGFloat(-M_PI_2))
isBluetoothOn = false
isDeviceConnected = false
isBackButtonPressed = false
peripheral = nil
hrValues = NSMutableArray()
xValues = NSMutableArray()
initLinePlot()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
if peripheral != nil && isBackButtonPressed == true
{
bluetoothManager?.cancelPeripheralConnection(peripheral!)
}
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
isBackButtonPressed = true
}
//MARK: - CTPPlot Implementation
func initLinePlot() {
//Initialize and display Graph (x and y axis lines)
graph = CPTXYGraph(frame: graphView.bounds)
self.graphView.hostedGraph = self.graph;
//apply styling to Graph
graph?.apply(CPTTheme(named: CPTThemeName.plainWhiteTheme))
//set graph backgound area transparent
graph?.fill = CPTFill(color: CPTColor.clear())
graph?.plotAreaFrame?.fill = CPTFill(color: CPTColor.clear())
graph?.plotAreaFrame?.fill = CPTFill(color: CPTColor.clear())
//This removes top and right lines of graph
graph?.plotAreaFrame?.borderLineStyle = CPTLineStyle(style: nil)
//This shows x and y axis labels from 0 to 1
graph?.plotAreaFrame?.masksToBorder = false
// set padding for graph from Left and Bottom
graph?.paddingBottom = 30;
graph?.paddingLeft = 50;
graph?.paddingRight = 0;
graph?.paddingTop = 0;
//Define x and y axis range
// x-axis from 0 to 100
// y-axis from 0 to 300
let plotSpace = graph?.defaultPlotSpace
plotSpace?.allowsUserInteraction = true
plotSpace?.delegate = self;
self.resetPlotRange()
let axisSet = graph?.axisSet as! CPTXYAxisSet;
let axisLabelFormatter = NumberFormatter()
axisLabelFormatter.generatesDecimalNumbers = false
axisLabelFormatter.numberStyle = NumberFormatter.Style.decimal
//Define x-axis properties
//x-axis intermediate interval 2
let xAxis = axisSet.xAxis
xAxis?.majorIntervalLength = plotXInterval as NSNumber?
xAxis?.minorTicksPerInterval = 4;
xAxis?.minorTickLength = 5;
xAxis?.majorTickLength = 7;
xAxis?.title = "Time (s)"
xAxis?.titleOffset = 25;
xAxis?.labelFormatter = axisLabelFormatter
//Define y-axis properties
let yAxis = axisSet.yAxis
yAxis?.majorIntervalLength = plotYInterval as NSNumber?
yAxis?.minorTicksPerInterval = 4
yAxis?.minorTickLength = 5
yAxis?.majorTickLength = 7
yAxis?.title = "BPM"
yAxis?.titleOffset = 30
yAxis?.labelFormatter = axisLabelFormatter
//Define line plot and set line properties
linePlot = CPTScatterPlot()
linePlot?.dataSource = self
graph?.add(linePlot!, to: plotSpace)
//set line plot style
let lineStyle = linePlot?.dataLineStyle!.mutableCopy() as! CPTMutableLineStyle
lineStyle.lineWidth = 2
lineStyle.lineColor = CPTColor.black()
linePlot!.dataLineStyle = lineStyle;
let symbolLineStyle = CPTMutableLineStyle(style: lineStyle)
symbolLineStyle.lineColor = CPTColor.black()
let symbol = CPTPlotSymbol.ellipse()
symbol.fill = CPTFill(color: CPTColor.black())
symbol.lineStyle = symbolLineStyle
symbol.size = CGSize(width: 3.0, height: 3.0)
linePlot?.plotSymbol = symbol;
//set graph grid lines
let gridLineStyle = CPTMutableLineStyle()
gridLineStyle.lineColor = CPTColor.gray()
gridLineStyle.lineWidth = 0.5
xAxis?.majorGridLineStyle = gridLineStyle
yAxis?.majorGridLineStyle = gridLineStyle
}
func resetPlotRange() {
plotXMaxRange = 121
plotXMinRange = -1
plotYMaxRange = 310
plotYMinRange = -1
plotXInterval = 20
plotYInterval = 50
let plotSpace = graph?.defaultPlotSpace as! CPTXYPlotSpace
plotSpace.xRange = CPTPlotRange(location: NSNumber(value: plotXMinRange!), length: NSNumber(value: plotXMaxRange!))
plotSpace.yRange = CPTPlotRange(location: NSNumber(value: plotYMinRange!), length: NSNumber(value: plotYMaxRange!))
}
func clearUI() {
deviceName.text = "DEFAULT HRM";
battery.setTitle("N/A", for: UIControlState())
battery.tag = 0;
hrLocation.text = "n/a";
hrValue.text = "-";
// Clear and reset the graph
hrValues?.removeAllObjects()
xValues?.removeAllObjects()
resetPlotRange()
graph?.reloadData()
}
func addHRvalueToGraph(data value: Int) {
// In this method the new value is added to hrValues array
hrValues?.add(NSDecimalNumber(value: value as Int))
// Also, we save the time when the data was received
// 'Last' and 'previous' values are timestamps of those values. We calculate them to know whether we should automatically scroll the graph
var lastValue : NSDecimalNumber
var firstValue : NSDecimalNumber
if xValues?.count > 0 {
lastValue = xValues?.lastObject as! NSDecimalNumber
firstValue = xValues?.firstObject as! NSDecimalNumber
}else{
lastValue = 0
firstValue = 0
}
let previous : Double = lastValue.subtracting(firstValue).doubleValue
xValues?.add(NORHRMViewController.longUnixEpoch())
lastValue = xValues?.lastObject as! NSDecimalNumber
firstValue = xValues?.firstObject as! NSDecimalNumber
let last : Double = lastValue.subtracting(firstValue).doubleValue
// Here we calculate the max value visible on the graph
let plotSpace = graph!.defaultPlotSpace as! CPTXYPlotSpace
let max = plotSpace.xRange.locationDouble + plotSpace.xRange.lengthDouble
if last > max && previous <= max {
let location = Int(last) - plotXMaxRange! + 1
plotSpace.xRange = CPTPlotRange(location: NSNumber(value: (location)), length: NSNumber(value: plotXMaxRange!))
}
// Rescale Y axis to display higher values
if value >= plotYMaxRange {
while (value >= plotYMaxRange)
{
plotYMaxRange = plotYMaxRange! + 50
}
plotSpace.yRange = CPTPlotRange(location: NSNumber(value: plotYMinRange!), length: NSNumber(value: plotYMaxRange!))
}
graph?.reloadData()
}
//MARK: - NORScannerDelegate
func centralManagerDidSelectPeripheral(withManager aManager: CBCentralManager, andPeripheral aPeripheral: CBPeripheral){
// We may not use more than one Central Manager instance. Let's just take the one returned from Scanner View Controller
bluetoothManager = aManager;
bluetoothManager!.delegate = self;
// The sensor has been selected, connect to it
peripheral = aPeripheral;
aPeripheral.delegate = self;
let options = NSDictionary(object: NSNumber(value: true as Bool), forKey: CBConnectPeripheralOptionNotifyOnNotificationKey as NSCopying)
bluetoothManager!.connect(aPeripheral, options: options as? [String : AnyObject])
}
//MARK: - CPTPlotDataSource
func numberOfRecords(for plot :CPTPlot) -> UInt {
return UInt(hrValues!.count)
}
func number(for plot: CPTPlot, field fieldEnum: UInt, record idx: UInt) -> Any? {
let fieldVal = NSInteger(fieldEnum)
let scatterPlotField = CPTScatterPlotField(rawValue: fieldVal)
switch (scatterPlotField!) {
case .X:
// The xValues stores timestamps. To show them starting from 0 we have to subtract the first one.
return (xValues?.object(at: Int(idx)) as! NSDecimalNumber).subtracting(xValues?.firstObject as! NSDecimalNumber)
case .Y:
return hrValues?.object(at: Int(idx)) as AnyObject?
}
}
//MARK: - CPRPlotSpaceDelegate
func plotSpace(_ space: CPTPlotSpace, shouldScaleBy interactionScale: CGFloat, aboutPoint interactionPoint: CGPoint) -> Bool {
return false
}
func plotSpace(_ space: CPTPlotSpace, willDisplaceBy proposedDisplacementVector: CGPoint) -> CGPoint {
return CGPoint(x: proposedDisplacementVector.x, y: 0)
}
func plotSpace(_ space: CPTPlotSpace, willChangePlotRangeTo newRange: CPTPlotRange, for coordinate: CPTCoordinate) -> CPTPlotRange? {
// The Y range does not change here
if coordinate == CPTCoordinate.Y {
return newRange;
}
// Adjust axis on scrolling
let axisSet = space.graph?.axisSet as! CPTXYAxisSet
if newRange.location.intValue >= plotXMinRange! {
// Adjust axis to keep them in view at the left and bottom;
// adjust scale-labels to match the scroll.
axisSet.yAxis!.orthogonalPosition = NSNumber(value: newRange.locationDouble - Double(plotXMinRange!))
return newRange
}
axisSet.yAxis!.orthogonalPosition = 0
return CPTPlotRange(location: NSNumber(value: plotXMinRange!), length: NSNumber(value: plotXMaxRange!))
}
//MARK: - CBCentralManagerDelegate
func centralManagerDidUpdateState(_ central: CBCentralManager) {
if central.state == .poweredOff {
print("Bluetooth powered off")
} else {
print("Bluetooth powered on")
}
}
func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
// Scanner uses other queue to send events. We must edit UI in the main queue
DispatchQueue.main.async {
self.deviceName.text = peripheral.name
self.connectionButton.setTitle("DISCONNECT", for: UIControlState())
self.hrValues?.removeAllObjects()
self.xValues?.removeAllObjects()
self.resetPlotRange()
}
if UIApplication.instancesRespond(to: #selector(UIApplication.registerUserNotificationSettings(_:))){
UIApplication.shared.registerUserNotificationSettings(UIUserNotificationSettings(types: [.alert, .sound], categories: nil))
}
NotificationCenter.default.addObserver(self, selector: #selector(NORHRMViewController.appDidEnterBackgroundCallback), name: NSNotification.Name.UIApplicationDidEnterBackground, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(NORHRMViewController.appDidBecomeActiveCallback), name: NSNotification.Name.UIApplicationDidBecomeActive, object: nil)
// Peripheral has connected. Discover required services
peripheral.discoverServices([hrServiceUUID, batteryServiceUUID])
}
func centralManager(_ central: CBCentralManager, didFailToConnect peripheral: CBPeripheral, error: Error?) {
// Scanner uses other queue to send events. We must edit UI in the main queue
DispatchQueue.main.async(execute: {
NORAppUtilities.showAlert(title: "Error", andMessage: "Connecting to peripheral failed. Try again")
self.connectionButton.setTitle("CONNCECT", for: UIControlState())
self.peripheral = nil
self.clearUI()
});
}
func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?) {
// Scanner uses other queue to send events. We must edit UI in the main queue
DispatchQueue.main.async(execute: {
self.connectionButton.setTitle("CONNECT", for: UIControlState())
self.peripheral = nil;
self.clearUI()
if NORAppUtilities.isApplicationInactive() {
let name = peripheral.name ?? "Peripheral"
NORAppUtilities.showBackgroundNotification(message: "\(name) is disconnected.")
}
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIApplicationDidBecomeActive, object: nil)
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIApplicationDidEnterBackground, object: nil)
});
}
//MARK: - CBPeripheralDelegate
func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
guard error == nil else {
print("An error occured while discovering services: \(error!.localizedDescription)")
bluetoothManager!.cancelPeripheralConnection(peripheral)
return
}
for aService : CBService in peripheral.services! {
if aService.uuid.isEqual(hrServiceUUID){
print("HRM Service found")
peripheral.discoverCharacteristics(nil, for: aService)
} else if aService.uuid.isEqual(batteryServiceUUID) {
print("Battery service found")
peripheral.discoverCharacteristics(nil, for: aService)
}
}
}
func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
guard error == nil else {
print("Error occurred while discovering characteristic: \(error!.localizedDescription)")
bluetoothManager!.cancelPeripheralConnection(peripheral)
return
}
if service.uuid.isEqual(hrServiceUUID) {
for aCharactersistic : CBCharacteristic in service.characteristics! {
if aCharactersistic.uuid.isEqual(hrMeasurementCharacteristicUUID) {
print("Heart rate measurement characteristic found")
peripheral.setNotifyValue(true, for: aCharactersistic)
}else if aCharactersistic.uuid.isEqual(hrLocationCharacteristicUUID) {
print("Heart rate sensor location characteristic found")
peripheral.readValue(for: aCharactersistic)
}
}
} else if service.uuid.isEqual(batteryServiceUUID) {
for aCharacteristic : CBCharacteristic in service.characteristics! {
if aCharacteristic.uuid.isEqual(batteryLevelCharacteristicUUID) {
print("Battery level characteristic found")
peripheral.readValue(for: aCharacteristic)
}
}
}
}
func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
guard error == nil else {
print("Error occurred while updating characteristic value: \(error!.localizedDescription)")
return
}
DispatchQueue.main.async {
if characteristic.uuid.isEqual(self.hrMeasurementCharacteristicUUID) {
let value = self.decodeHRValue(withData: characteristic.value!)
self.addHRvalueToGraph(data: Int(value))
self.hrValue.text = "\(value)"
} else if characteristic.uuid.isEqual(self.hrLocationCharacteristicUUID) {
self.hrLocation.text = self.decodeHRLocation(withData: characteristic.value!)
} else if characteristic.uuid.isEqual(self.batteryLevelCharacteristicUUID) {
let data = characteristic.value as NSData?
let array : UnsafePointer<UInt8> = (data?.bytes)!.assumingMemoryBound(to: UInt8.self)
let batteryLevel : UInt8 = array[0]
let text = "\(batteryLevel)%"
self.battery.setTitle(text, for: UIControlState.disabled)
if self.battery.tag == 0 {
if characteristic.properties.rawValue & CBCharacteristicProperties.notify.rawValue > 0 {
self.battery.tag = 1 // Mark that we have enabled notifications
peripheral.setNotifyValue(true, for: characteristic)
}
}
}
}
}
//MARK: - UIApplicationDelegate callbacks
func appDidEnterBackgroundCallback() {
let name = peripheral?.name ?? "peripheral"
NORAppUtilities.showBackgroundNotification(message: "You are still connected to \(name). It will collect data also in background.")
}
func appDidBecomeActiveCallback() {
UIApplication.shared.cancelAllLocalNotifications()
}
//MARK: - Segue management
override func shouldPerformSegue(withIdentifier identifier: String, sender: Any?) -> Bool {
// The 'scan' seque will be performed only if connectedPeripheral == nil (if we are not connected already).
return identifier != "scan" || peripheral == nil
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "scan" {
// Set this contoller as scanner delegate
let nc = segue.destination as! UINavigationController
let controller = nc.childViewControllerForStatusBarHidden as! NORScannerViewController
controller.filterUUID = hrServiceUUID
controller.delegate = self
}
}
//MARK: - Helpers
static func longUnixEpoch() -> NSDecimalNumber {
return NSDecimalNumber(value: Date().timeIntervalSince1970 as Double)
}
func decodeHRValue(withData data: Data) -> Int {
let count = data.count / MemoryLayout<UInt8>.size
var array = [UInt8](repeating: 0, count: count)
(data as NSData).getBytes(&array, length:count * MemoryLayout<UInt8>.size)
var bpmValue : Int = 0;
if ((array[0] & 0x01) == 0) {
bpmValue = Int(array[1])
} else {
//Convert Endianess from Little to Big
bpmValue = Int(UInt16(array[2] * 0xFF) + UInt16(array[1]))
}
return bpmValue
}
func decodeHRLocation(withData data:Data) -> String {
let location = (data as NSData).bytes.bindMemory(to: UInt16.self, capacity: data.count)
switch (location[0]) {
case 0:
return "Other"
case 1:
return "Chest"
case 2:
return "Wrist"
case 3:
return "Finger"
case 4:
return "Hand";
case 5:
return "Ear Lobe"
case 6:
return "Foot"
default:
return "Invalid";
}
}
}
|
bsd-3-clause
|
da415efc01841c29e9dca5ce92ed008d
| 40.718232 | 197 | 0.625524 | 5.104326 | false | false | false | false |
robertbtown/BtownToolkit
|
BtownToolkit/Classes/Views/LoadingView/LoadingViewViewController.swift
|
1
|
5233
|
//
// LoadingViewViewController.swift
// Pods
//
// Created by Robert Magnusson on 2017-08-11.
//
//
// swiftlint:disable line_length
import UIKit
/// This protocol defines a LoadingView.
/// You can create your own LoadingViews by conforming to this LoadingViewProtocol
/// That way you can control yourself how the LoadingView will look.
/// Then you just need to pass your CustomLoadingView in when creating the LoadingViewController.
/// Like this:
/// let loadingView = LoadingViewController(loadingViewType: MyCustomLoadingView.self, loadingText: "Loading", completionText: "Completed", completionErrorText: "Error")
/// loadingView.startLoading()
public protocol LoadingViewProtocol {
typealias CompletionClosure = () -> Void
/// Use this to update how much of the loading that is currently completed.
/// It will default to zero on init.
var completionPercentage: Float? { get set }
/// Creates an instance of the LoadingView.
/// All parameters in are optional except for the view.
/// This view is where you can add your custom views to display loading.
/// The view covers the entire window.
///
/// - Parameters:
/// - view: The container view that you show your loading views in.
/// - loadingText: Optional loading text.
/// - completionSuccessText: A completion text to show when loading is done without errors
/// - completionErrorText: A error text to show when loading is done with errors
init(withView view: UIView, loadingText: String?, completionSuccessText: String?, completionErrorText: String?)
/// Every time the container view get a new layout this function is called.
/// Update the layout of your views in this function.
func viewChangedLayout()
/// When this function is called you should set your loading view in a loading state.
/// When this function gets called the container view will be presented and show your views.
func startLoading()
/// When this function is called you should stop your loading view from loading.
/// If withCompletionState is true then the loading view will not be dismissed directly.
/// Instead you should change it to display a completion state.
/// If withCompletionState is false then the loading view will be dismissed.
///
/// - Parameters:
/// - withCompletionState: Indicates if a completion state should be shown after loading has stopped
/// - autoDismissDelay: The delay until the loading view will be dismissed.
/// - withError: Indicates if the loading was stopped with an error, meaning you should show an error state
/// - completionClosure: This block must be called. Call it after you are done with any potential code to hide your view.
func stopLoading(withCompletionState: Bool, autoDismissDelay: TimeInterval, withError: Bool, completionClosure: @escaping CompletionClosure)
}
class LoadingViewViewController: UIViewController {
private let loadingViewType: LoadingViewProtocol.Type
fileprivate let loadingText: String?
fileprivate let completionSuccessText: String?
fileprivate let completionErrorText: String?
fileprivate var loadingView: LoadingViewProtocol?
var completionPercentage: Float? {
didSet {
loadingView?.completionPercentage = completionPercentage
}
}
init(loadingViewType: LoadingViewProtocol.Type, loadingText: String? = nil, completionSuccessText: String? = nil, completionErrorText: String? = nil) {
self.loadingViewType = loadingViewType
self.loadingText = loadingText
self.completionSuccessText = completionSuccessText
self.completionErrorText = completionErrorText
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func loadView() {
let view = UIView()
view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
view.backgroundColor = .clear
view.setNeedsUpdateConstraints()
self.view = view
}
override func viewDidLoad() {
super.viewDidLoad()
loadingView = loadingViewType.init(withView: view, loadingText: loadingText, completionSuccessText: completionSuccessText, completionErrorText: completionErrorText)
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
loadingView?.viewChangedLayout()
}
override var prefersStatusBarHidden: Bool {
return UIApplication.shared.isStatusBarHidden
}
}
// MARK: Public functions
extension LoadingViewViewController {
func startLoading() {
loadingView?.startLoading()
}
func stopLoading(withCompletionState: Bool, autoDismissDelay: TimeInterval, withError: Bool, completionClosure: @escaping LoadingViewProtocol.CompletionClosure) {
if let loadingView = loadingView {
loadingView.stopLoading(withCompletionState: withCompletionState, autoDismissDelay: autoDismissDelay, withError: withError, completionClosure: {
completionClosure()
})
} else {
completionClosure()
}
}
}
|
mit
|
9f74c9745b5eecc6ceed5e7bac534f14
| 39.565891 | 173 | 0.715077 | 5.196624 | false | false | false | false |
wuzzapcom/Fluffy-Book
|
FluffyBook/BookParserMetaInfoService.swift
|
1
|
903
|
//
// BookParserMediaInfoService.swift
// FluffyBook
//
// Created by Alexandr Tsukanov on 16.04.17.
// Copyright © 2017 wuzzapcom. All rights reserved.
//
import Foundation
// Name of fields are taken from something OPF file
struct Author {
var name: String!
var role: String!
var fileAs: String!
init(name: String, role: String, fileAs: String) {
self.name = name
self.role = role
self.fileAs = fileAs
}
}
struct Meta {
var name: String?
var content: String?
// var id: String?
// var property: String?
// var value: String?
// var refines: String?
init(name: String, content: String) {
self.name = name
self.content = content
}
}
class BookParserMetaInfoService {
var creators = [Author]()
var titles = [String]()
var descriptions = [String]()
var metaAttributes = [Meta]()
}
|
mit
|
912a9e4d4e622f05635cf0fbbf6465ca
| 19.5 | 54 | 0.616408 | 3.579365 | false | false | false | false |
dannagle/PacketSender-iOS
|
Packet Sender/AppDelegate.swift
|
1
|
6178
|
//
// AppDelegate.swift
// Packet Sender
//
// Created by Dan Nagle on 12/6/14.
// Copyright (c) 2014 Dan Nagle. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "com.packetsender.Packet_Sender" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1] as! NSURL
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("Packet_Sender", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
// The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("Packet_Sender.sqlite")
var error: NSError? = nil
var failureReason = "There was an error creating or loading the application's saved data."
if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil, error: &error) == nil {
coordinator = nil
// Report any error we got.
let dict = NSMutableDictionary()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error
error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict as [NSObject : AnyObject])
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext? = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
if coordinator == nil {
return nil
}
var managedObjectContext = NSManagedObjectContext()
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if let moc = self.managedObjectContext {
var error: NSError? = nil
if moc.hasChanges && !moc.save(&error) {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
}
}
}
|
mit
|
3ed20cd61e11159de9cc5aff74232acb
| 54.160714 | 290 | 0.71528 | 5.76306 | false | false | false | false |
adolfrank/Swift_practise
|
08-day/08-day/HomeViewController.swift
|
1
|
3870
|
//
// HomeViewController.swift
// 08-day
//
// Created by Adolfrank on 3/21/16.
// Copyright © 2016 FrankAdol. All rights reserved.
//
import UIKit
class HomeViewController: UITableViewController {
let cellIdentifer = "NewCellIdentifier"
let favoriteEmoji = ["🤗🤗🤗🤗🤗", "😅😅😅😅😅", "😆😆😆😆😆"]
let newFavoriteEmoji = ["🏃🏃🏃🏃🏃", "💩💩💩💩💩", "👸👸👸👸👸", "🤗🤗🤗🤗🤗", "😅😅😅😅😅", "😆😆😆😆😆" ]
var emojiData = [String]()
// var tableViewController = UITableViewController(style: .Plain)
// var refreshControl = UIRefreshControl()
@IBAction func showNav(sender: AnyObject) {
print("yyy")
}
override func viewDidLoad() {
super.viewDidLoad()
emojiData = favoriteEmoji
let emojiTableView = self.tableView
emojiTableView.backgroundColor = UIColor(red:0.092, green:0.096, blue:0.116, alpha:1)
emojiTableView.dataSource = self
emojiTableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: cellIdentifer)
emojiTableView.tableFooterView = UIView(frame: CGRectZero)
emojiTableView.separatorStyle = UITableViewCellSeparatorStyle.None
self.refreshControl = UIRefreshControl()
self.refreshControl?.addTarget(self, action: "didRoadEmoji", forControlEvents: UIControlEvents.ValueChanged)
self.refreshControl!.backgroundColor = UIColor(red:100/255/0
, green:0.113, blue:0.145, alpha:1)
let attributes = [NSForegroundColorAttributeName: UIColor.whiteColor()]
self.refreshControl!.attributedTitle = NSAttributedString(string: "Last updated on \(NSDate())", attributes: attributes)
self.refreshControl!.tintColor = UIColor.whiteColor()
// self.title = "emoji"
let titleLabel = UILabel(frame: CGRectMake(0, 0, 0 , 44))
titleLabel.textAlignment = NSTextAlignment.Center
titleLabel.text = "下拉刷新"
titleLabel.textColor = UIColor.whiteColor()
self.navigationItem.titleView = titleLabel
self.navigationController?.hidesBarsOnSwipe
self.navigationController?.navigationBar.setBackgroundImage(UIImage(named: "bg"), forBarMetrics: UIBarMetrics.Default)
self.navigationController?.navigationBar.shadowImage = UIImage(named: "bg")
emojiTableView.rowHeight = UITableViewAutomaticDimension
emojiTableView.estimatedRowHeight = 60.0
}
func didRoadEmoji() {
print("ttt")
self.emojiData = newFavoriteEmoji
self.tableView.reloadData()
self.refreshControl!.endRefreshing()
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return emojiData.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifer, forIndexPath: indexPath)
// let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifer)! as UITableViewCell
// Configure the cell...
cell.textLabel!.text = self.emojiData[indexPath.row]
cell.textLabel!.textAlignment = NSTextAlignment.Center
cell.textLabel!.font = UIFont.systemFontOfSize(50)
cell.backgroundColor = UIColor.clearColor()
cell.selectionStyle = UITableViewCellSelectionStyle.None
return cell
}
}
|
mit
|
fe7359a0051f867b4380e4d9ff0c13b5
| 37.8125 | 128 | 0.676329 | 5.069388 | false | false | false | false |
NunoAlexandre/broccoli_mobile
|
ios/Carthage/Checkouts/Eureka/Source/Rows/SegmentedRow.swift
|
2
|
8561
|
// SegmentedRow.swift
// Eureka ( https://github.com/xmartlabs/Eureka )
//
// Copyright (c) 2016 Xmartlabs SRL ( http://xmartlabs.com )
//
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
//MARK: SegmentedCell
open class SegmentedCell<T: Equatable> : Cell<T>, CellType {
open var titleLabel : UILabel? {
textLabel?.translatesAutoresizingMaskIntoConstraints = false
textLabel?.setContentHuggingPriority(500, for: .horizontal)
return textLabel
}
lazy open var segmentedControl : UISegmentedControl = {
let result = UISegmentedControl()
result.translatesAutoresizingMaskIntoConstraints = false
result.setContentHuggingPriority(250, for: .horizontal)
return result
}()
private var dynamicConstraints = [NSLayoutConstraint]()
fileprivate var observingTitleText: Bool = false
required public init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
NotificationCenter.default.addObserver(forName: Notification.Name.UIApplicationWillResignActive, object: nil, queue: nil){ [weak self] notification in
guard let me = self else { return }
guard me.observingTitleText else { return }
me.titleLabel?.removeObserver(me, forKeyPath: "text")
me.observingTitleText = false
}
NotificationCenter.default.addObserver(forName: Notification.Name.UIApplicationDidBecomeActive, object: nil, queue: nil){ [weak self] notification in
guard let me = self else { return }
guard !me.observingTitleText else { return }
me.titleLabel?.addObserver(me, forKeyPath: "text", options: NSKeyValueObservingOptions.old.union(.new), context: nil)
me.observingTitleText = true
}
NotificationCenter.default.addObserver(forName: Notification.Name.UIContentSizeCategoryDidChange, object: nil, queue: nil){ [weak self] notification in
self?.setNeedsUpdateConstraints()
}
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
segmentedControl.removeTarget(self, action: nil, for: .allEvents)
if observingTitleText {
titleLabel?.removeObserver(self, forKeyPath: "text")
}
imageView?.removeObserver(self, forKeyPath: "image")
NotificationCenter.default.removeObserver(self, name: Notification.Name.UIApplicationWillResignActive, object: nil)
NotificationCenter.default.removeObserver(self, name: Notification.Name.UIApplicationDidBecomeActive, object: nil)
NotificationCenter.default.removeObserver(self, name: Notification.Name.UIContentSizeCategoryDidChange, object: nil)
}
open override func setup() {
super.setup()
height = { BaseRow.estimatedRowHeight }
selectionStyle = .none
contentView.addSubview(titleLabel!)
contentView.addSubview(segmentedControl)
titleLabel?.addObserver(self, forKeyPath: "text", options: [.old, .new], context: nil)
observingTitleText = true
imageView?.addObserver(self, forKeyPath: "image", options: [.old, .new], context: nil)
segmentedControl.addTarget(self, action: #selector(SegmentedCell.valueChanged), for: .valueChanged)
contentView.addConstraint(NSLayoutConstraint(item: segmentedControl, attribute: .centerY, relatedBy: .equal, toItem: contentView, attribute: .centerY, multiplier: 1, constant: 0))
}
open override func update() {
super.update()
detailTextLabel?.text = nil
updateSegmentedControl()
segmentedControl.selectedSegmentIndex = selectedIndex() ?? UISegmentedControlNoSegment
segmentedControl.isEnabled = !row.isDisabled
}
func valueChanged() {
row.value = (row as! SegmentedRow<T>).options[segmentedControl.selectedSegmentIndex]
}
open override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
let obj = object as AnyObject?
if let changeType = change, let _ = keyPath, ((obj === titleLabel && keyPath == "text") || (obj === imageView && keyPath == "image")) && (changeType[NSKeyValueChangeKey.kindKey] as? NSNumber)?.uintValue == NSKeyValueChange.setting.rawValue{
setNeedsUpdateConstraints()
updateConstraintsIfNeeded()
}
}
func updateSegmentedControl() {
segmentedControl.removeAllSegments()
items().enumerated().forEach { segmentedControl.insertSegment(withTitle: $0.element, at: $0.offset, animated: false) }
}
open override func updateConstraints() {
contentView.removeConstraints(dynamicConstraints)
dynamicConstraints = []
var views : [String: AnyObject] = ["segmentedControl": segmentedControl]
var hasImageView = false
var hasTitleLabel = false
if let imageView = imageView, let _ = imageView.image {
views["imageView"] = imageView
hasImageView = true
}
if let titleLabel = titleLabel, let text = titleLabel.text, !text.isEmpty {
views["titleLabel"] = titleLabel
hasTitleLabel = true
dynamicConstraints.append(NSLayoutConstraint(item: titleLabel, attribute: .centerY, relatedBy: .equal, toItem: contentView, attribute: .centerY, multiplier: 1, constant: 0))
}
dynamicConstraints.append(NSLayoutConstraint(item: segmentedControl, attribute: .width, relatedBy: .greaterThanOrEqual, toItem: contentView, attribute: .width, multiplier: 0.3, constant: 0.0))
if hasImageView && hasTitleLabel {
dynamicConstraints += NSLayoutConstraint.constraints(withVisualFormat: "H:[imageView]-(15)-[titleLabel]-[segmentedControl]-|", options: [], metrics: nil, views: views)
}
else if hasImageView && !hasTitleLabel {
dynamicConstraints += NSLayoutConstraint.constraints(withVisualFormat: "H:[imageView]-[segmentedControl]-|", options: [], metrics: nil, views: views)
}
else if !hasImageView && hasTitleLabel {
dynamicConstraints = NSLayoutConstraint.constraints(withVisualFormat: "H:|-[titleLabel]-[segmentedControl]-|", options: .alignAllCenterY, metrics: nil, views: views)
}
else {
dynamicConstraints = NSLayoutConstraint.constraints(withVisualFormat: "H:|-[segmentedControl]-|", options: .alignAllCenterY, metrics: nil, views: views)
}
contentView.addConstraints(dynamicConstraints)
super.updateConstraints()
}
func items() -> [String] {// or create protocol for options
var result = [String]()
for object in (row as! SegmentedRow<T>).options {
result.append(row.displayValueFor?(object) ?? "")
}
return result
}
func selectedIndex() -> Int? {
guard let value = row.value else { return nil }
return (row as! SegmentedRow<T>).options.index(of: value)
}
}
//MARK: SegmentedRow
/// An options row where the user can select an option from an UISegmentedControl
public final class SegmentedRow<T: Equatable>: OptionsRow<SegmentedCell<T>>, RowType {
required public init(tag: String?) {
super.init(tag: tag)
}
}
|
mit
|
d2ae3c24887a8a9471626a43b0e8cd93
| 46.561111 | 248 | 0.681813 | 5.248927 | false | false | false | false |
KaushalElsewhere/AllHandsOn
|
IGListDemo/IGListDemo/FeedCell.swift
|
1
|
550
|
//
// FeedCell.swift
// IGListDemo
//
// Created by Kaushal Elsewhere on 17/03/2017.
// Copyright © 2017 Kaushal Elsewhere. All rights reserved.
//
import UIKit
class FeedCell: CollectionCell {
lazy var label: UILabel = {
let label = UILabel()
label.textAlignment = .Center
label.textColor = .blackColor()
return label
}()
override func setupViews() {
contentView.addSubview(label)
contentView.backgroundColor = .whiteColor()
label.center = contentView.center
}
}
|
mit
|
69f157a7f43f25ff93fdbc8cbaf20c21
| 20.115385 | 60 | 0.632058 | 4.5 | false | false | false | false |
moysklad/ios-remap-sdk
|
Sources/MoyskladiOSRemapSDK/Structs/MSDocument.swift
|
1
|
14301
|
//
// MSDocument.swift
// MoyskladiOSRemapSDK
//
// Created by Anton Efimenko on 28.08.17.
// Copyright © 2017 Andrey Parshakov. All rights reserved.
//
import Foundation
public class MSDocument: MSAttributedEntity, MSBaseDocumentType, MSGeneralDocument, MSCustomerOrderType, MSDemandType,
MSInvoiceOutType, MSInvoiceInType, MSMoneyDocumentType, MSCashInType, MSCashOutType,
MSPaymentInType, MSPaymentOutType, MSProcurementType, MSSupplyType, MSRetailShiftType, MSMoveType, MSInventoryType, MSRetailType {
// MSBaseDocumentType
public var id : MSID
public var meta : MSMeta
public var info : MSInfo
public var agent : MSEntity<MSAgent>?
public var contract : MSEntity<MSContract>?
/// Приходит в валюте документа
public var sum : Money
public var vatSum : Money
/// Приходит в валюте учета (валюта по умолчанию для учетной записи)
public var payedSum: Money
public var rate : MSRate?
public var moment : Date
public var project : MSEntity<MSProject>?
public var organization : MSEntity<MSAgent>?
public var owner : MSEntity<MSEmployee>?
public var group : MSEntity<MSGroup>
public var shared : Bool
public var applicable : Bool
public var state : MSEntity<MSState>?
public var originalApplicable: Bool
public var stateContractId: String?
// MSGeneralDocument
public var agentAccount : MSEntity<MSAccount>?
public var organizationAccount : MSEntity<MSAccount>?
public var vatIncluded : Bool
public var vatEnabled : Bool
public var store : MSEntity<MSStore>?
public var originalStoreId: UUID?
public var positions : [MSEntity<MSPosition>]
public var totalPositionsCount: Int
public var stock : [MSEntity<MSDocumentStock>]
public var positionsManager: ObjectManager<MSPosition>?
// MSCustomerOrderType
public var deliveryPlannedMoment : Date?
public var purchaseOrders : [MSEntity<MSDocument>]
public var demands : [MSDemandType]
public var payments : [MSEntity<MSDocument>]
public var invoicesOut : [MSInvoiceOutType]
// MSPurchaseOrderType
public var customerOrders : [MSEntity<MSDocument>]
public var supplies : [MSEntity<MSDocument>]
// MSDemandType
public var returns: [MSEntity<MSDocument>]
public var factureOut: MSEntity<MSDocument>?
public var overhead : MSOverhead?
public var customerOrder : MSCustomerOrderType?
public var consignee: MSEntity<MSAgent>?
public var carrier: MSEntity<MSAgent>?
public var transportFacilityNumber: String?
public var shippingInstructions: String?
public var cargoName: String?
public var transportFacility: String?
public var goodPackQuantity: Int?
// MSInvoiceOut
public var paymentPlannedMoment : Date?
// MSInvoiceIn
public var purchaseOrder: MSEntity<MSDocument>?
public var incomingNumber: String?
public var incomingDate: Date?
// MSMoneyDocumentType
public var paymentPurpose: String?
public var factureIn: MSEntity<MSDocument>?
public var operations: [MSEntity<MSDocument>]
/// Приходит в валюте связанного документа
public var linkedSum: Money
// MSCashOutType
public var expenseItem: MSEntity<MSExpenseItem>?
// MSProcurementType
public var invoicesIn: [MSEntity<MSDocument>]
// MSRetailShiftType
public var proceedsNoCash: Money
public var proceedsCash: Money
public var receivedNoCash: Money
public var receivedCash: Money
// commissionreport
public var commitentSum: Money
// MSMoveType
public var sourceStore: MSEntity<MSStore>?
public var targetStore: MSEntity<MSStore>?
public var internalOrder: MSEntity<MSDocument>?
public var targetStock: [MSEntity<MSDocumentStock>]
// MSInventoryType
public var enters: [MSEntity<MSDocument>]
public var losses: [MSEntity<MSDocument>]
// MSRetailType
public var retailShift: MSEntity<MSRetailShift>?
public var cashSum: Money?
public var noCashSum: Money?
public var demand: MSEntity<MSDocument>?
public func copy(with zone: NSZone? = nil) -> Any {
return copyDocument()
}
public func copyDocument() -> MSDocument {
let positionsCopy = positions.compactMap { $0.value() }.map { MSEntity.entity($0.copy()) }
let operationsCopy = operations.compactMap { $0.value() }.map { MSEntity.entity($0.copyDocument()) }
return MSDocument(id: id,
meta: meta,
info: info,
agent: agent,
contract: contract,
sum: sum,
vatSum: vatSum,
payedSum: payedSum,
rate: rate,
moment: moment,
project: project,
organization: organization,
owner: owner,
group: group,
shared: shared,
applicable: applicable,
state: state,
attributes: attributes,
originalApplicable: originalApplicable,
agentAccount: agentAccount,
organizationAccount: organizationAccount,
vatIncluded: vatIncluded,
vatEnabled: vatEnabled,
store: store,
originalStoreId: originalStoreId,
positions: positionsCopy,
totalPositionsCount: totalPositionsCount,
stock: stock,
deliveryPlannedMoment: deliveryPlannedMoment,
purchaseOrders: purchaseOrders,
demands: demands,
payments: payments,
invoicesOut: invoicesOut,
returns: returns,
factureOut: factureOut,
overhead: overhead,
customerOrder: customerOrder,
consignee: consignee,
carrier: carrier,
transportFacilityNumber: transportFacilityNumber,
shippingInstructions: shippingInstructions,
cargoName: cargoName,
transportFacility: transportFacility,
goodPackQuantity: goodPackQuantity,
paymentPlannedMoment: paymentPlannedMoment,
purchaseOrder: purchaseOrder,
incomingNumber: incomingNumber,
incomingDate: incomingDate,
paymentPurpose: paymentPurpose,
factureIn: factureIn,
expenseItem: expenseItem,
operations: operationsCopy,
linkedSum: linkedSum,
stateContractId: stateContractId,
invoicesIn: invoicesIn,
proceedsNoCash: proceedsNoCash,
proceedsCash: proceedsCash,
receivedNoCash: receivedNoCash,
receivedCash: receivedCash,
customerOrders: customerOrders,
supplies: supplies,
commitentSum: commitentSum,
sourceStore: sourceStore,
targetStore: targetStore,
internalOrder: internalOrder,
targetStock: targetStock,
enters: enters,
losses: losses,
retailShift: retailShift,
cashSum: cashSum,
noCashSum: noCashSum,
demand: demand,
positionsManager: positionsManager?.copy())
}
public init(id : MSID,
meta : MSMeta,
info : MSInfo,
agent : MSEntity<MSAgent>?,
contract : MSEntity<MSContract>?,
sum : Money,
vatSum : Money,
payedSum: Money,
rate : MSRate?,
moment : Date,
project : MSEntity<MSProject>?,
organization : MSEntity<MSAgent>?,
owner : MSEntity<MSEmployee>?,
group : MSEntity<MSGroup>,
shared : Bool,
applicable : Bool,
state : MSEntity<MSState>?,
attributes : [MSEntity<MSAttribute>]?,
originalApplicable: Bool,
agentAccount : MSEntity<MSAccount>?,
organizationAccount : MSEntity<MSAccount>?,
vatIncluded : Bool,
vatEnabled : Bool,
store : MSEntity<MSStore>?,
originalStoreId: UUID?,
positions : [MSEntity<MSPosition>],
totalPositionsCount: Int,
stock : [MSEntity<MSDocumentStock>],
deliveryPlannedMoment : Date?,
purchaseOrders : [MSEntity<MSDocument>],
demands : [MSDemandType],
payments : [MSEntity<MSDocument>],
invoicesOut : [MSInvoiceOutType],
returns: [MSEntity<MSDocument>],
factureOut: MSEntity<MSDocument>?,
overhead : MSOverhead?,
customerOrder : MSCustomerOrderType?,
consignee: MSEntity<MSAgent>?,
carrier: MSEntity<MSAgent>?,
transportFacilityNumber: String?,
shippingInstructions: String?,
cargoName: String?,
transportFacility: String?,
goodPackQuantity: Int?,
paymentPlannedMoment : Date?,
purchaseOrder: MSEntity<MSDocument>?,
incomingNumber: String?,
incomingDate: Date?,
paymentPurpose: String?,
factureIn: MSEntity<MSDocument>?,
expenseItem: MSEntity<MSExpenseItem>?,
operations: [MSEntity<MSDocument>],
linkedSum: Money,
stateContractId: String?,
invoicesIn: [MSEntity<MSDocument>],
proceedsNoCash: Money,
proceedsCash: Money,
receivedNoCash: Money,
receivedCash: Money,
customerOrders: [MSEntity<MSDocument>],
supplies: [MSEntity<MSDocument>],
commitentSum: Money,
sourceStore: MSEntity<MSStore>?,
targetStore: MSEntity<MSStore>?,
internalOrder: MSEntity<MSDocument>?,
targetStock: [MSEntity<MSDocumentStock>],
enters: [MSEntity<MSDocument>],
losses: [MSEntity<MSDocument>],
retailShift: MSEntity<MSRetailShift>?,
cashSum: Money?,
noCashSum: Money?,
demand: MSEntity<MSDocument>?,
positionsManager: ObjectManager<MSPosition>?) {
self.id = id
self.meta = meta
self.info = info
self.agent = agent
self.contract = contract
self.sum = sum
self.vatSum = vatSum
self.payedSum = payedSum
self.rate = rate
self.moment = moment
self.project = project
self.organization = organization
self.owner = owner
self.group = group
self.shared = shared
self.applicable = applicable
self.state = state
self.originalApplicable = originalApplicable
self.agentAccount = agentAccount
self.organizationAccount = organizationAccount
self.vatIncluded = vatIncluded
self.vatEnabled = vatEnabled
self.store = store
self.originalStoreId = originalStoreId
self.positions = positions
self.totalPositionsCount = totalPositionsCount
self.stock = stock
self.deliveryPlannedMoment = deliveryPlannedMoment
self.purchaseOrders = purchaseOrders
self.demands = demands
self.payments = payments
self.invoicesOut = invoicesOut
self.returns = returns
self.factureOut = factureOut
self.overhead = overhead
self.customerOrder = customerOrder
self.consignee = consignee
self.carrier = carrier
self.transportFacilityNumber = transportFacilityNumber
self.shippingInstructions = shippingInstructions
self.cargoName = cargoName
self.transportFacility = transportFacility
self.goodPackQuantity = goodPackQuantity
self.paymentPlannedMoment = paymentPlannedMoment
self.purchaseOrder = purchaseOrder
self.incomingNumber = incomingNumber
self.incomingDate = incomingDate
self.paymentPurpose = paymentPurpose
self.factureIn = factureIn
self.expenseItem = expenseItem
self.operations = operations
self.linkedSum = linkedSum
self.stateContractId = stateContractId
self.invoicesIn = invoicesIn
self.proceedsNoCash = proceedsNoCash
self.proceedsCash = proceedsCash
self.receivedNoCash = receivedNoCash
self.receivedCash = receivedCash
self.customerOrders = customerOrders
self.supplies = supplies
self.commitentSum = commitentSum
self.sourceStore = sourceStore
self.targetStore = targetStore
self.internalOrder = internalOrder
self.targetStock = targetStock
self.enters = enters
self.losses = losses
self.retailShift = retailShift
self.cashSum = cashSum
self.noCashSum = noCashSum
self.demand = demand
self.positionsManager = positionsManager
super.init(attributes: attributes)
}
}
|
mit
|
9104473c203764671aa9cdd2ee8a85ac
| 39.65616 | 130 | 0.577701 | 5.065691 | false | false | false | false |
CoderAlexChan/AlexCocoa
|
String/String+pinyin.swift
|
1
|
1771
|
//
// String+pinyin.swift
// Main
//
// Created by 陈文强 on 2017/5/17.
// Copyright © 2017年 陈文强. All rights reserved.
//
import Foundation
// MARK: - pinyin
extension String {
// //将NSString装换成NSMutableString
// NSMutableString *pinyin = [chinese mutableCopy];
// //将汉字转换为拼音(带音标)
// CFStringTransform((__bridge CFMutableStringRef)pinyin, NULL, kCFStringTransformMandarinLatin, NO);
// NSLog(@"%@", pinyin);
// //去掉拼音的音标
// CFStringTransform((__bridge CFMutableStringRef)pinyin, NULL, kCFStringTransformStripCombiningMarks, NO);
// NSLog(@"%@", pinyin);
// //返回最近结果
// return pinyin;
public func toPinyin() -> String {
let mutableString = NSMutableString(string: self)
CFStringTransform(mutableString, nil, kCFStringTransformToLatin, false)
CFStringTransform(mutableString, nil, kCFStringTransformStripDiacritics, false)
let string = String(mutableString)
return string.replacing(" ", with: "")
}
public func toHeaderCharactar() -> String {
return toPinyin().firstCharacter ?? ""
}
public func isChinese() -> Bool {
var contain = false
for c in self.characters.enumerated() {
if c.element <= "\u{9FA5}" && c.element >= "\u{4E00}" {
contain = true
}else {
return false
}
}
return contain
}
public func containChinese() -> Bool {
for c in self.characters.enumerated() {
if c.element <= "\u{9FA5}" && c.element >= "\u{4E00}" {
return true
}
}
return false
}
}
|
mit
|
2036e99d04dda825dcdf796ce2c0582b
| 28.310345 | 114 | 0.570588 | 4.271357 | false | false | false | false |
ShamylZakariya/Squizit
|
Squizit/Extensions/UIImage+Sizing.swift
|
1
|
2635
|
//
// UIImage_sizing.swift
// Squizit
//
// Created by Shamyl Zakariya on 8/28/14.
// Copyright (c) 2014 Shamyl Zakariya. All rights reserved.
//
import Foundation
import UIKit
extension UIImage {
func imageByScalingToSize( size:CGSize, scale:CGFloat = 0.0 ) -> UIImage {
if CGSizeEqualToSize(size, self.size) {
return self
}
UIGraphicsBeginImageContextWithOptions(size, false, scale)
let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
CGContextClearRect(UIGraphicsGetCurrentContext(), rect)
self.drawInRect(rect, blendMode: CGBlendMode.Normal, alpha: 1)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage;
}
func imageByScalingToSize( newSize:CGSize, contentMode:UIViewContentMode, scale:CGFloat = 0.0 ) -> UIImage {
if CGSizeEqualToSize(newSize, self.size) {
return self
}
UIGraphicsBeginImageContextWithOptions(newSize, false, scale)
let imageWidth = self.size.width
let imageHeight = self.size.height
switch contentMode {
case UIViewContentMode.ScaleToFill:
self.drawInRect(CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height), blendMode: CGBlendMode.Normal, alpha: 1)
case UIViewContentMode.ScaleAspectFit:
var scale = newSize.width / imageWidth
if ( imageHeight * scale > newSize.height )
{
scale *= newSize.height / (imageHeight*scale)
}
let center = CGPoint( x:newSize.width/2, y: newSize.height/2)
self.drawInRect(centeredRect( center, width: imageWidth*scale, height: imageHeight*scale), blendMode: CGBlendMode.Normal, alpha: 1)
case UIViewContentMode.ScaleAspectFill:
var scale = newSize.width / imageWidth
if ( imageHeight * scale < newSize.height )
{
scale *= newSize.height / (imageHeight*scale)
}
let center = CGPoint( x:newSize.width/2, y: newSize.height/2)
self.drawInRect(centeredRect( center, width: imageWidth*scale, height: imageHeight*scale), blendMode: CGBlendMode.Normal, alpha: 1)
case UIViewContentMode.Center:
let center = CGPoint( x:newSize.width/2, y: newSize.height/2)
self.drawInRect(centeredRect( center, width: newSize.width, height: newSize.height), blendMode: CGBlendMode.Normal, alpha: 1)
default:
assertionFailure("Unsupported contentMode, sorry")
break;
}
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage;
}
private func centeredRect( center:CGPoint, width:CGFloat, height:CGFloat ) -> CGRect {
return CGRect(x: center.x - width/2, y: center.y - height/2, width: width, height: height)
}
}
|
mit
|
edb6cdfab6cb31f4191b1b7cc5cdda90
| 30.011765 | 135 | 0.728273 | 3.79683 | false | false | false | false |
chromium/chromium
|
ios/chrome/browser/ui/popup_menu/overflow_menu/overflow_menu_destination_view.swift
|
6
|
10156
|
// Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import SwiftUI
import ios_chrome_common_ui_colors_swift
/// PreferenceKey to listen to visibility changes for a given destination.
struct DestinationVisibilityPreferenceKey: PreferenceKey {
static var defaultValue: Int = 0
static func reduce(value: inout Int, nextValue: () -> Int) {
value += nextValue()
}
}
/// Style based on state for an OverflowMenuDestinationView.
@available(iOS 15, *)
struct OverflowMenuDestinationButton: ButtonStyle {
enum Dimensions {
static let cornerRadius: CGFloat = 13
/// The padding on either side of the text in the vertical layout,
/// separating it from the next view.
static let verticalLayoutTextPadding: CGFloat = 3
/// The padding on either side of the view in the horizontal layout,
/// separating it from the next view.
static let horizontalLayoutViewPadding: CGFloat = 16
/// The padding around the icon and inside the background in horizontal
/// layout.
static let horizontalLayoutIconPadding: CGFloat = 3
/// The spacing between the icon and the text in horizontal layout.
static let horizontalLayoutIconSpacing: CGFloat = 14
/// The image width, which controls the width of the overall view.
static let imageWidth: CGFloat = 54
/// The size of the Symbol in the icon.
static let iconSymbolSize: CGFloat = 26
/// The width of the icon, used for positioning the unread badge over the
/// corner.
static let iconWidth: CGFloat = 30
/// The width of the badge circle.
static let badgeWidth: CGFloat = 10
/// The width of the new label badge.
static let newLabelBadgeWidth: CGFloat = 20
/// The width of the badge border.
static let badgeBorderWidth: CGFloat = 2
}
/// The destination for this view.
var destination: OverflowMenuDestination
/// The layout parameters for this view.
var layoutParameters: OverflowMenuDestinationView.LayoutParameters
/// Tracks if the destination icon is visible in the carousel.
@State var isIconVisible = false
/// Tracks if the destination name is visible in the carousel.
@State var isTextVisible = false
weak var metricsHandler: PopupMenuMetricsHandler?
func makeBody(configuration: Configuration) -> some View {
Group {
switch layoutParameters {
case .vertical(let iconSpacing, let iconPadding):
VStack {
icon(configuration: configuration)
text
}
.frame(width: Dimensions.imageWidth + 2 * iconSpacing + 2 * iconPadding)
case .horizontal(let itemWidth):
HStack {
icon(configuration: configuration)
Spacer().frame(width: Dimensions.horizontalLayoutIconSpacing)
text
}
.frame(width: itemWidth, alignment: .leading)
// In horizontal layout, the item itself has leading and trailing
// padding.
.padding([.leading, .trailing], Dimensions.horizontalLayoutViewPadding)
}
}
.contentShape(Rectangle())
.preference(
key: DestinationVisibilityPreferenceKey.self,
value: (isIconVisible || isTextVisible) ? 1 : 0
)
}
/// Background color for the icon.
func backgroundColor(configuration: Configuration) -> Color {
return configuration.isPressed ? Color(.systemGray4) : .groupedSecondaryBackground
}
/// View representing the background of the icon.
func iconBackground(configuration: Configuration) -> some View {
RoundedRectangle(cornerRadius: Dimensions.cornerRadius)
.foregroundColor(backgroundColor(configuration: configuration))
}
/// Icon for the destination.
func icon(configuration: Configuration) -> some View {
let interiorPadding: CGFloat
let spacing: CGFloat
switch layoutParameters {
case .vertical(let iconSpacing, let iconPadding):
spacing = iconSpacing
interiorPadding = iconPadding
case .horizontal:
spacing = 0
interiorPadding = Dimensions.horizontalLayoutIconPadding
}
let image: Image
if !destination.symbolName.isEmpty {
image =
(destination.systemSymbol
? Image(systemName: destination.symbolName) : Image(destination.symbolName)).renderingMode(
.template)
} else {
image = destination.image
}
return iconBuilder(
configuration: configuration, spacing: spacing, interiorPadding: interiorPadding, image: image
)
}
var newBadgeOffsetX: CGFloat {
return Dimensions.iconWidth - (Dimensions.newLabelBadgeWidth - 10)
}
var newBadgeOffsetY: CGFloat {
return -Dimensions.iconWidth + (Dimensions.newLabelBadgeWidth - 10)
}
var newLabelString: String {
if let newString = L10NUtils.string(forMessageId: IDS_IOS_TOOLS_MENU_CELL_NEW_FEATURE_BADGE) {
return String(newString.prefix(1))
}
return ""
}
/// Build the image to be displayed, based on the configuration of the item.
/// TODO(crbug.com/1315544): Remove this once only the symbols are present.
@ViewBuilder
func iconBuilder(
configuration: Configuration, spacing: CGFloat, interiorPadding: CGFloat, image: Image
) -> some View {
let configuredImage =
image
.overlay {
if destination.badge == .blueDot {
Circle()
.strokeBorder(
backgroundColor(configuration: configuration), lineWidth: Dimensions.badgeBorderWidth
)
// Pad the color circle by 0.5, otherwise the color shows up faintly
// around the border.
.background(Circle().foregroundColor(.blue600).padding(0.5))
.frame(width: Dimensions.badgeWidth, height: Dimensions.badgeWidth)
.offset(x: Dimensions.iconWidth / 2, y: -Dimensions.iconWidth / 2)
} else if destination.badge == .newLabel {
Image(systemName: "seal.fill")
.resizable()
.foregroundColor(.blue600)
.frame(width: Dimensions.newLabelBadgeWidth, height: Dimensions.newLabelBadgeWidth)
.offset(x: newBadgeOffsetX, y: newBadgeOffsetY)
.overlay {
if !newLabelString.isEmpty {
Text(newLabelString)
.font(.system(size: 10, weight: .bold, design: .rounded))
.offset(x: newBadgeOffsetX, y: newBadgeOffsetY)
.scaledToFit()
.foregroundColor(.primaryBackground)
}
}
}
}
.frame(width: Dimensions.imageWidth, height: Dimensions.imageWidth)
.padding(interiorPadding)
.background(iconBackground(configuration: configuration))
.padding([.leading, .trailing], spacing)
// Without explicitly removing the image from accessibility,
// VoiceOver will occasionally read out icons it thinks it can
// recognize.
.accessibilityHidden(true)
.onAppear {
isIconVisible = true
}
.onDisappear {
isIconVisible = false
}
if !destination.symbolName.isEmpty {
configuredImage
.foregroundColor(.blue600).imageScale(.medium).font(
Font.system(size: Dimensions.iconSymbolSize, weight: .medium))
} else {
configuredImage
}
}
/// Text view for the destination.
var text: some View {
// Only the vertical layout has extra spacing around the text
let textSpacing: CGFloat
let maximumLines: Int?
switch layoutParameters {
case .vertical:
textSpacing = Dimensions.verticalLayoutTextPadding
maximumLines = nil
case .horizontal:
textSpacing = 0
maximumLines = 1
}
return Text(destination.name)
.font(.caption2)
.padding([.leading, .trailing], textSpacing)
.multilineTextAlignment(.center)
.lineLimit(maximumLines)
.onAppear {
isTextVisible = true
}
.onDisappear {
isTextVisible = false
}
}
}
/// A view displaying a single destination.
@available(iOS 15, *)
struct OverflowMenuDestinationView: View {
/// Parameters providing any necessary data to layout the view.
enum LayoutParameters {
/// The destination has an icon on top and text below.
/// There is `iconSpacing` to either side of the icon, and `iconPadding`
/// around the icon and inside the background.
case vertical(iconSpacing: CGFloat, iconPadding: CGFloat)
/// The destination has an icon on the left and text on the right. Here
/// the view will have a fixed overall `itemWidth`.
case horizontal(itemWidth: CGFloat)
}
enum AccessibilityIdentifier {
/// The addition to the `accessibilityIdentfier` for this element if it
/// has a badge.
static let badgeAddition = "badge"
/// The addition to the `accessibilityIdentfier` for this element if it
/// has a "New" badge.
static let newBadgeAddition = "newBadge"
}
/// The destination for this view.
var destination: OverflowMenuDestination
/// The layout parameters for this view.
var layoutParameters: LayoutParameters
weak var metricsHandler: PopupMenuMetricsHandler?
var body: some View {
Button(
action: {
metricsHandler?.popupMenuTookAction()
destination.handler()
},
label: {
EmptyView()
}
)
.accessibilityIdentifier(accessibilityIdentifier)
.accessibilityLabel(Text(accessibilityLabel))
.buttonStyle(
OverflowMenuDestinationButton(destination: destination, layoutParameters: layoutParameters))
}
var accessibilityLabel: String {
return [
destination.name,
destination.badge != .none
? L10NUtils.stringWithFixup(forMessageId: IDS_IOS_TOOLS_MENU_CELL_NEW_FEATURE_BADGE) : nil,
].compactMap { $0 }.joined(separator: ", ")
}
var accessibilityIdentifier: String {
return [
destination.accessibilityIdentifier,
destination.badge == .blueDot ? AccessibilityIdentifier.badgeAddition : nil,
destination.badge == .newLabel ? AccessibilityIdentifier.newBadgeAddition : nil,
].compactMap { $0 }.joined(separator: "-")
}
}
|
bsd-3-clause
|
fa99a5a11c23bedddfb494e0880c5ff8
| 32.518152 | 100 | 0.675364 | 4.763602 | false | true | false | false |
SquidKit/SquidKit
|
SquidKit/EndpointMap.swift
|
1
|
12068
|
//
// EndpointMap.swift
// SquidKit
//
// Created by Mike Leavy on 8/27/14.
// Copyright © 2014-2019 Squid Store, LLC. All rights reserved.
//
import Foundation
private let _EndpointMapperSharedInstance = EndpointMapper()
public protocol HostMapCacheStorable {
func setEntry(_ entry:[String: AnyObject], key:String)
func getEntry(_ key:String) -> [String: AnyObject]?
func remove(_ key:String)
}
public struct ProtocolHostPair: CustomStringConvertible, CustomDebugStringConvertible {
public var hostProtocol:String?
public var host:String?
public init(_ hostProtocol:String?, _ host:String?) {
self.hostProtocol = hostProtocol
self.host = host
}
public var description: String {
return "ProtocolHostPair: protocol = \(String(describing: hostProtocol)); host = \(String(describing: host))"
}
public var debugDescription: String {
return self.description
}
}
func == (left:ProtocolHostPair, right:ProtocolHostPair) -> Bool {
return left.host == right.host && left.hostProtocol == right.hostProtocol
}
open class EndpointMapper {
fileprivate var mappedHosts = [String: ProtocolHostPair]()
fileprivate init() {
}
open class var sharedInstance: EndpointMapper {
return _EndpointMapperSharedInstance
}
open class func addProtocolHostMappedPair(_ mappedPair:ProtocolHostPair, canonicalHost:String) {
EndpointMapper.sharedInstance.mappedHosts[canonicalHost] = mappedPair
}
open class func removeProtocolHostMappedPair(_ canonicalHost:String) {
EndpointMapper.sharedInstance.mappedHosts[canonicalHost] = nil
}
open class func mappedPairForCanonicalHost(_ canonicalHost:String) -> (ProtocolHostPair?) {
return EndpointMapper.sharedInstance.mappedHosts[canonicalHost]
}
}
open class HostMap {
public static let editableHostAlphanumericPlaceholderExpression = "<@>"
public static let editableHostNnumericPlaceholderExpression = "<#>"
public let canonicalProtocolHost:ProtocolHostPair
open var releaseKey = ""
open var prereleaseKey = ""
open var mappedPairs = [String: ProtocolHostPair]()
open var sortedKeys = [String]()
open var editableKeys = [String]()
open var numericEditableKeys = [String]()
open var canonicalHost:String {
if let host = canonicalProtocolHost.host {
return host
}
return ""
}
public init(canonicalProtocolHostPair:ProtocolHostPair) {
self.canonicalProtocolHost = canonicalProtocolHostPair
}
open func pairWithKey(_ key:String) -> ProtocolHostPair? {
return mappedPairs[key]
}
open func isEditable(_ key:String) -> Bool {
return editableKeys.contains(key)
}
open func isNumericallyEditable(_ key:String) -> Bool {
return numericEditableKeys.contains(key)
}
}
open class HostMapManager {
open var hostMaps = [HostMap]()
fileprivate var hostMapCache:HostMapCache!
required public init(cacheStore:HostMapCacheStorable?) {
self.hostMapCache = HostMapCache(cacheStore: cacheStore)
}
open func loadConfigurationMapFromResourceFile(_ fileName:String, bundle: Bundle = Bundle.main) -> Bool {
let result = HostConfigurationsLoader.loadConfigurationsFromResourceFile(fileName, bundle: bundle, manager: self)
self.restoreFromCache()
return result
}
open func setReleaseConfigurations() {
for hostMap in self.hostMaps {
if let releasePair = hostMap.pairWithKey(hostMap.releaseKey) {
EndpointMapper.addProtocolHostMappedPair(releasePair, canonicalHost: hostMap.canonicalHost)
}
}
}
open func setPrereleaseConfigurations() {
for hostMap in self.hostMaps {
if let preReleasePair = hostMap.pairWithKey(hostMap.prereleaseKey) {
EndpointMapper.addProtocolHostMappedPair(preReleasePair, canonicalHost: hostMap.canonicalHost)
}
}
}
open func setConfigurationForCanonicalHost(_ configurationKey:String, mappedHost:String?, canonicalHost:String, withCaching:Bool = true) {
for hostMap in self.hostMaps {
if hostMap.canonicalProtocolHost.host == canonicalHost {
var runtimePair = hostMap.pairWithKey(configurationKey)
if runtimePair != nil {
if mappedHost != nil {
runtimePair!.host = mappedHost
hostMap.mappedPairs[configurationKey] = runtimePair
}
let empty:Bool = (runtimePair!.host == nil || runtimePair!.host!.isEmpty)
if !empty {
EndpointMapper.addProtocolHostMappedPair(runtimePair!, canonicalHost: canonicalHost)
}
else {
EndpointMapper.removeProtocolHostMappedPair(canonicalHost)
}
if withCaching {
if !empty {
self.hostMapCache.cacheKeyAndHost(configurationKey, mappedHost:runtimePair!.host!, forCanonicalHost: canonicalHost)
}
else {
self.hostMapCache.removeCachedKeyForCanonicalHost(canonicalHost)
}
}
}
break
}
}
}
fileprivate func restoreFromCache() {
for hostMap in self.hostMaps {
if let (key, host) = self.hostMapCache.retreiveCachedKeyAndHostForCanonicalHost(hostMap.canonicalHost) {
self.setConfigurationForCanonicalHost(key, mappedHost:host, canonicalHost: hostMap.canonicalHost, withCaching: false)
}
}
}
fileprivate class HostConfigurationsLoader {
fileprivate class func loadConfigurationsFromResourceFile(_ fileName: String, bundle: Bundle, manager:HostMapManager) -> Bool {
var result = false
if let hostDictionary = NSDictionary.dictionaryFromResourceFile(fileName, bundle: bundle) {
result = true
if let configurations:NSArray = hostDictionary.object(forKey: "configurations") as? NSArray {
for configuration in configurations {
HostConfigurationsLoader.handleConfiguration(configuration as AnyObject, manager: manager)
}
}
}
return result
}
fileprivate class func handleConfiguration(_ configuration:AnyObject, manager:HostMapManager) {
if let config:[String: AnyObject] = configuration as? [String: AnyObject] {
let canonicalHost:String? = config[HostConfigurationKey.CanonicalHost.rawValue] as? String
let canonicalProtocol:String? = config[HostConfigurationKey.CanonicalProtocol.rawValue] as? String
let releaseKey:String? = config[HostConfigurationKey.ReleaseKey.rawValue] as? String
let prereleaseKey:String? = config[HostConfigurationKey.PrereleaseKey.rawValue] as? String
if canonicalHost != nil && canonicalProtocol != nil {
let hostMap = HostMap(canonicalProtocolHostPair:ProtocolHostPair(canonicalProtocol, canonicalHost))
if let release = releaseKey {
hostMap.releaseKey = release
}
if let prerelease = prereleaseKey {
hostMap.prereleaseKey = prerelease
}
if let hostsArray:[[String: String]] = config[HostConfigurationKey.Hosts.rawValue] as? [[String: String]] {
for host in hostsArray {
let aKey:String? = host[.HostsKey] as? String
let aHost:String? = host[.HostsHost] as? String
let aProtocol:String? = host[.HostsProtocol] as? String
if let key = aKey {
let pair = ProtocolHostPair(aProtocol, aHost)
hostMap.mappedPairs[key] = pair
hostMap.sortedKeys.append(key)
// if there is no host, consider this item editable
if aHost == nil {
hostMap.editableKeys.append(key)
}
else if aHost!.contains(HostMap.editableHostAlphanumericPlaceholderExpression) {
hostMap.editableKeys.append(key)
}
else if aHost!.contains(HostMap.editableHostNnumericPlaceholderExpression) {
hostMap.editableKeys.append(key)
hostMap.numericEditableKeys.append(key)
}
}
}
}
manager.hostMaps.append(hostMap)
}
}
}
}
}
private enum HostConfigurationKey:String {
case CanonicalHost = "canonical_host"
case CanonicalProtocol = "canonical_protocol"
case ReleaseKey = "release_key"
case PrereleaseKey = "prerelease_key"
case Hosts = "hosts"
case HostsKey = "key"
case HostsHost = "host"
case HostsProtocol = "protocol"
}
private class NilMarker :NSObject {
}
extension Dictionary {
fileprivate subscript(key:HostConfigurationKey) -> NSObject {
for k in self.keys {
if let kstring = k as? String {
if kstring == key.rawValue {
return self[k]! as! NSObject
}
}
}
return NilMarker()
}
}
private class HostMapCache {
let squidKitHostMapCacheKey = "com.squidkit.hostMapCachePreferenceKey"
typealias CacheDictionary = [String: [String: String]]
var cacheStore:HostMapCacheStorable?
required init(cacheStore:HostMapCacheStorable?) {
self.cacheStore = cacheStore
}
func cacheKeyAndHost(_ key:String, mappedHost:String, forCanonicalHost canonicalHost:String) {
var mutableCache:[String: AnyObject]?
if let cache:[String: AnyObject] = cacheStore?.getEntry(squidKitHostMapCacheKey) {
mutableCache = cache
}
else {
mutableCache = [String: AnyObject]()
}
var dictionaryItem = [String: String]()
dictionaryItem["key"] = key
dictionaryItem["host"] = mappedHost
mutableCache![canonicalHost] = dictionaryItem as AnyObject?
cacheStore?.setEntry(mutableCache!, key: squidKitHostMapCacheKey)
}
func retreiveCachedKeyAndHostForCanonicalHost(_ canonicalHost:String) -> (String, String)? {
var result:(String, String)?
if let cache:[String: AnyObject] = cacheStore?.getEntry(squidKitHostMapCacheKey) {
if let hostDict:[String: String] = cache[canonicalHost] as? [String: String] {
result = (hostDict["key"]! , hostDict["host"]! )
}
}
return result
}
func removeCachedKeyForCanonicalHost(_ canonicalHost:String) {
if let cache:[String: AnyObject] = cacheStore?.getEntry(squidKitHostMapCacheKey) {
var mutableCache = cache
mutableCache.removeValue(forKey: canonicalHost)
cacheStore?.setEntry(mutableCache, key: squidKitHostMapCacheKey)
}
}
func removeAll() {
cacheStore?.remove(squidKitHostMapCacheKey)
}
}
|
mit
|
8c7874dae1acc53e3bade3da1f088eaa
| 36.015337 | 143 | 0.592359 | 5.106644 | false | true | false | false |
daviejaneway/OrbitFrontend
|
Sources/ParenthesisedExpressionsRule.swift
|
1
|
2144
|
//
// ParenthesisedExpressionsRule.swift
// OrbitFrontend
//
// Created by Davie Janeway on 06/09/2017.
//
//
import Foundation
import OrbitCompilerUtils
public class NonTerminalExpression<T> : AbstractExpression, ValueExpression {
public typealias ValueType = T
public let value: T
init(value: T, startToken: Token) {
self.value = value
super.init(startToken: startToken)
}
}
public class ParenthesisedExpressionsRule : ParseRule {
public let name = "Orb.Core.Grammar.ParenthesisedExpressions"
private let openParen: TokenType
private let closeParen: TokenType
private let delimiter: TokenType
private let innerRule: ParseRule
init(openParen: TokenType = .LParen, closeParen: TokenType = .RParen, delimiter: TokenType = .Comma, innerRule: ParseRule) {
self.openParen = openParen
self.closeParen = closeParen
self.innerRule = innerRule
self.delimiter = delimiter
}
public func trigger(tokens: [Token]) throws -> Bool {
guard let open = tokens.first, let close = tokens.last else { throw OrbitError.ranOutOfTokens() }
return open.type == self.openParen && close.type == self.closeParen
}
public func parse(context: ParseContext) throws -> AbstractExpression {
let start = try context.expect(type: self.openParen)
var next = try context.peek()
var expressions = [AbstractExpression]()
while next.type != self.closeParen {
let expression = try self.innerRule.parse(context: context)
expressions.append(expression)
next = try context.peek()
// No delimter found means either the list is fully parsed
// or there's a syntax error
guard next.type == self.delimiter else { break }
_ = try context.consume()
}
_ = try context.expect(type: self.closeParen)
return NonTerminalExpression<[AbstractExpression]>(value: expressions, startToken: start)
}
}
|
mit
|
f8bf32cf8fe9839a635b94d1967ca86c
| 30.072464 | 128 | 0.629198 | 4.62069 | false | false | false | false |
changjiashuai/AudioKit
|
Tests/Tests/AKCabasa.swift
|
14
|
1563
|
//
// main.swift
// AudioKit
//
// Created by Nick Arner and Aurelius Prochazka on 12/26/14.
// Copyright (c) 2014 Aurelius Prochazka. All rights reserved.
//
import Foundation
let testDuration: NSTimeInterval = 10.0
class Instrument : AKInstrument {
override init() {
super.init()
let note = CabasaNote()
let cabasa = AKCabasa()
cabasa.count = note.count
cabasa.dampingFactor = note.dampingFactor
enableParameterLog(
"Count = ",
parameter: cabasa.count,
timeInterval:2
)
enableParameterLog(
"Damping Factor = ",
parameter: cabasa.dampingFactor,
timeInterval:2
)
setAudioOutput(cabasa)
}
}
class CabasaNote: AKNote {
var count = AKNoteProperty()
var dampingFactor = AKNoteProperty()
override init() {
super.init()
addProperty(count)
addProperty(dampingFactor)
}
convenience init(count: Int, dampingFactor: Float) {
self.init()
self.count.floatValue = Float(count)
self.dampingFactor.floatValue = dampingFactor
}
}
AKOrchestra.testForDuration(testDuration)
let instrument = Instrument()
AKOrchestra.addInstrument(instrument)
let phrase = AKPhrase()
for i in 1...10 {
let note = CabasaNote(count: i*20, dampingFactor: 1.1-Float(i)/10.0)
note.duration.floatValue = 1.0
phrase.addNote(note, atTime: Float(i-1))
}
instrument.playPhrase(phrase)
NSThread.sleepForTimeInterval(NSTimeInterval(testDuration))
|
mit
|
38565f88360802bc980f8a2ea47db0ae
| 21.328571 | 72 | 0.640435 | 4.212938 | false | true | false | false |
KrishMunot/swift
|
validation-test/compiler_crashers_fixed/27194-swift-pattern-foreachvariable.swift
|
11
|
2254
|
// This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -parse
{
{
a {{
{{
( { {
{
{
{{:a
}}}let a{{
{
{ {d b{}}}}}b}}}}}}<T}}}class S<T{func a<h{func b<T where h.g=a
{
func a{
if true{
}
struct d<T where g
func
{init(
{ (( (( )
let f=A{
[:e
}}}protocol P{
{
let g{
{
[{A
{
{
func a{func {
{{
func x:
{ {
{{{
a{
struct d<T where g{
{
{ {
"
{ {
[ { ()a{let v:
{ (
{ (
a{
{protocol P{
"class c
{
if true{
{{
{
if true{
struct B<T where I:a{
"
{ {g:{(){
{
let v:d<T where I:a=g
[{func{ {d b{}}}}}b}}}}}}<T}}}class S<T{func a<h{func b<T where h.g=a
{
}let a<T where T{{
typealias b:a{{T:
{
func a{struct S<b{
struct d
{
func a{
a{g=F
func x:
{
{
{d b{}}}}}b}}}}}}<T}}}class S<T{func a<h{func b<T where h.g=a
class d<T where I:
[:a{
let(
{
func a{
{
a{
a{{let t=0
class b:C{
a typealias b:Int=i{
{ {struct B{
"
{
let h{{class c{func x
typealias F
{
{
}protocol a
var b:a{(
"class b{
protocol P{
{
}struct d
{
{{}}}}protocol P{{
{ :a{
{ {
{
func{ a{init()a{
{ (
{g
{{
{ (
{
protocol A{
{
{
{ {{
typealias e:a{
{{
"
{
{{
{ {struct d<b:
d
let v:a
{
{
if true{
{
{typealias e{
func f{
{ {
func a{protocol P{{T:
var b{typealias e{
{ a{typealias b{let a{
func a<b{{
[{
{protocol P{
a typealias b:a=F
{
{
{
if true{
let f{{
(({
{
{}let g{
protocol a<T where g{let h{{
""
{let h{{struct d<T where g
struct S
{( ){let t:
var b{
{ {
protocol{{
protocol P{
{
{
{ {
func
}}protocol A{{
let v:e
{
{ {protocol b:
{
{
struct S<T where T:a<b:
{
a typealias e{
{
{
{
{{typealias f{let v:(()
{:C{{{
{
{{{{
func a{
{
{
func a
{}}}enum S<b{
{
( : ( )
{( : ( : ( : ( { {
struct d
{
{
{
"
protocol P{
class b{((
a {
{
((x
{{
{typealias e
}
{{
{
{
[{
a {{
{ :d= .c{
{e a{}
}}}
{{
{ ({{func b{func a
[{(
(){A<T:
{ {:a{
{
{
{
[ { {
{
d
{ ({func x
{{:
class A<T where I:a{A{
{{A
{
{{
func a{{let t:C{
[ {
{
struct Q{
class b{func a{
class A
{
{{
{{func
{
{{let v:a
struct d<T where I:e:
struct d<h}}}protocol A<h{}enum S
let t=F=g:a{let a{
{(
:
{ {
let a{
|
apache-2.0
|
5e1fc96b74b22214c8ad5cd81e01194f
| 8.470588 | 78 | 0.534605 | 2.062214 | false | false | false | false |
tkremenek/swift
|
test/PlaygroundTransform/implicit_return_subscript_chain.swift
|
21
|
1738
|
// RUN: %empty-directory(%t)
// RUN: cp %s %t/main.swift
// RUN: %target-build-swift -whole-module-optimization -module-name PlaygroundSupport -emit-module-path %t/PlaygroundSupport.swiftmodule -parse-as-library -c -o %t/PlaygroundSupport.o %S/Inputs/SilentPCMacroRuntime.swift %S/Inputs/PlaygroundsRuntime.swift
// RUN: %target-build-swift -Xfrontend -playground -Xfrontend -debugger-support -o %t/main -I=%t %t/PlaygroundSupport.o %t/main.swift
// RUN: %target-codesign %t/main
// RUN: %target-run %t/main | %FileCheck %s
// RUN: %target-build-swift -Xfrontend -pc-macro -Xfrontend -playground -Xfrontend -debugger-support -o %t/main2 -I=%t %t/PlaygroundSupport.o %t/main.swift
// RUN: %target-codesign %t/main2
// RUN: %target-run %t/main2 | %FileCheck %s
// REQUIRES: executable_test
import PlaygroundSupport
struct S {
var dict: [Int : Int?]
subscript(_ int: Int) -> Int? {
get {
dict[int, default: Int(String(int))]
}
set {
dict[int] = newValue
}
}
init() {
dict = [:]
}
}
var s = S()
s[13] = 33
s[14]
s[13]
// CHECK: {{.*}} __builtin_log_scope_entry
// CHECK-NEXT: {{.*}} __builtin_log_scope_exit
// CHECK: {{.*}} __builtin_log_scope_entry
// CHECK-NEXT: {{.*}} __builtin_log[='Optional(Optional(33))']
// CHECK-NEXT: {{.*}} __builtin_log_scope_exit
// CHECK: {{.*}} __builtin_log_scope_entry
// CHECK-NEXT: {{.*}} __builtin_log[='Optional(14)']
// CHECK-NEXT: {{.*}} __builtin_log_scope_exit
// CHECK-NEXT: {{.*}} __builtin_log[='Optional(14)']
// CHECK: {{.*}} __builtin_log_scope_entry
// CHECK-NEXT: {{.*}} __builtin_log[='Optional(33)']
// CHECK-NEXT: {{.*}} __builtin_log_scope_exit
// CHECK-NEXT: {{.*}} __builtin_log[='Optional(33)']
|
apache-2.0
|
edac1a140cf78176e573c0aaffaaeb3b
| 35.978723 | 255 | 0.619678 | 3.188991 | false | false | false | false |
br1sk/brisk-ios
|
Brisk iOS/Model/APIController.swift
|
1
|
3199
|
import Foundation
import Sonar
import Alamofire
protocol APIDelegate: class {
func didStartLoading()
func didFail(with error: SonarError)
func didPostToAppleRadar()
func didPostToOpenRadar()
}
protocol TwoFactorAuthenticationHandler: class {
func askForCode(completion: @escaping (String) -> Void)
}
final class APIController {
// MARK: - Properties
weak var delegate: APIDelegate?
weak var twoFactorHandler: TwoFactorAuthenticationHandler?
// MARK: - Init/Deinit
init(delegate: APIDelegate? = nil, twoFactorHandler: TwoFactorAuthenticationHandler? = nil) {
self.delegate = delegate
self.twoFactorHandler = twoFactorHandler
}
// MARK: - Duping
// TODO: Use delegate
func search(forRadarWithId radarId: String, loading: @escaping (Bool) -> Void, success: @escaping (Radar) -> Void, failure: @escaping (String, String) -> Void) {
// Fetch existing radar
guard let url = URL(string: "https://openradar.appspot.com/api/radar?number=\(radarId)") else {
preconditionFailure()
}
loading(true)
Alamofire.request(url)
.validate()
.responseJSON { result in
loading(false)
if let error = result.error {
failure("Error", error.localizedDescription)
return
}
guard let json = result.value as? [String: Any], let result = json["result"] as? [String: Any], !result.isEmpty else {
failure("No OpenRadar found", "Couldn't find an OpenRadar with ID #\(radarId)")
return
}
guard let radar = try? Radar(openRadar: json) else {
failure("Invalid OpenRadar", "OpenRadar is missing required fields")
return
}
success(radar)
}
}
// MARK: - Filing
func file(radar: Radar) {
guard let (username, password) = Keychain.get(.radar) else {
preconditionFailure("Shouldn't be able to submit a radar without credentials")
}
delegate?.didStartLoading()
let handleTwoFactorAuth: (@escaping (String?) -> Void) -> Void = { [weak self] closure in
self?.twoFactorHandler?.askForCode(completion: closure)
}
var radar = radar
// Post to Apple Radar
let appleRadar = Sonar(service: .appleRadar(appleID: username, password: password))
appleRadar.loginThenCreate(radar: radar, getTwoFactorCode: handleTwoFactorAuth) { [weak self] result in
switch result {
case .success(let radarID):
// Don't post to OpenRadar if no token is present.
// TODO: Should we show a confirmation/login for OpenRadar?
guard let (_, token) = Keychain.get(.openRadar) else {
self?.delegate?.didPostToAppleRadar()
return
}
// Post to open radar
radar.ID = radarID
let openRadar = Sonar(service: .openRadar(token: token))
openRadar.loginThenCreate(radar: radar, getTwoFactorCode: handleTwoFactorAuth) { [weak self] result in
switch result {
case .success:
self?.delegate?.didPostToAppleRadar()
self?.delegate?.didPostToOpenRadar()
case .failure(let error):
self?.delegate?.didFail(with: error)
}
}
case .failure(let error):
self?.delegate?.didFail(with: error)
}
}
}
}
|
mit
|
d6e8116dcb5c88413589c061c4cfd214
| 25.658333 | 162 | 0.661457 | 3.799287 | false | false | false | false |
taolong001/PlayThePlane
|
PlayThePlane/PlayThePlane/Home/ViewController.swift
|
1
|
3760
|
//
// ViewController.swift
// Play the plane
//
// Created by Aiya on 15/8/20.
// Copyright © 2015年 aiya. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.layer.contents = UIImage(named: "icon_1")!.CGImage
setupUI()
}
@objc func solitaireGame() {
let main = MainController()
presentViewController(main, animated: true) { () -> Void in
main.pattern = 1
}
}
@objc func onlineGame() {
let main = MainController()
presentViewController(main, animated: true) { () -> Void in
main.pattern = 2
}
}
@objc func localAreaGame() {
let main = MainController()
presentViewController(main, animated: true) { () -> Void in
main.pattern = 2
}
}
private let MyiAd: iAdViewController = iAdViewController()
private func setupUI() {
// 1. 添加控件
view.addSubview(solitaire)
view.addSubview(online)
view.addSubview(localArea)
solitaire.translatesAutoresizingMaskIntoConstraints = false
view.addConstraint(NSLayoutConstraint(item: solitaire, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.CenterX, multiplier: 1.0, constant: 0))
view.addConstraint(NSLayoutConstraint(item: solitaire, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.CenterY, multiplier: 1.0, constant: 0))
online.translatesAutoresizingMaskIntoConstraints = false
view.addConstraint(NSLayoutConstraint(item: online, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: solitaire, attribute: NSLayoutAttribute.CenterX, multiplier: 1.0, constant: 0))
view.addConstraint(NSLayoutConstraint(item: online, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: solitaire, attribute: NSLayoutAttribute.CenterY, multiplier: 1.0, constant: 40))
localArea.translatesAutoresizingMaskIntoConstraints = false
view.addConstraint(NSLayoutConstraint(item: localArea, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: online, attribute: NSLayoutAttribute.CenterX, multiplier: 1.0, constant: 0))
view.addConstraint(NSLayoutConstraint(item: localArea, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: online, attribute: NSLayoutAttribute.CenterY, multiplier: 1.0, constant: 40))
solitaire.addTarget(self, action: "solitaireGame", forControlEvents: UIControlEvents.TouchUpInside)
online.addTarget(self, action: "onlineGame", forControlEvents: UIControlEvents.TouchUpInside)
localArea.addTarget(self, action: "localAreaGame", forControlEvents: UIControlEvents.TouchUpInside)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: 懒加载控件
private lazy var solitaire: UIButton = UIButton(title: "单人游戏", imageName: "btn", fontSize: 20, width: 5 , height: 5, color: UIColor.whiteColor())
private lazy var online: UIButton = UIButton(title: "网络游戏", imageName: "btn", fontSize: 20, width: 5 , height: 5, color: UIColor.whiteColor())
private lazy var localArea: UIButton = UIButton(title: "局域对战", imageName: "btn", fontSize: 20, width: 5 , height: 5, color: UIColor.whiteColor())
}
|
apache-2.0
|
d4014fed4ad63123894cf209c07e1d1c
| 42.705882 | 221 | 0.683445 | 4.843546 | false | false | false | false |
C4Framework/C4iOS
|
C4/UI/ShapeLayer.swift
|
2
|
6443
|
// Copyright © 2015 C4
//
// 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 QuartzCore
/// Extension for CAShapeLayer that allows overriding the actions for specific properties.
public class ShapeLayer: CAShapeLayer {
/// A boolean value that, when true, prevents the animation of a shape's properties.
///
/// ````
/// ShapeLayer.disableActions = true
/// circle.fillColor = red
/// ShapeLayer.disableActions = false
///
/// This value can be set globally, after which changes to any shape's properties will be immediate.
public static var disableActions = true
/// This method searches for the given action object of the layer. Actions define dynamic behaviors for a layer. For example, the animatable properties of a layer typically have corresponding action objects to initiate the actual animations. When that property changes, the layer looks for the action object associated with the property name and executes it. You can also associate custom action objects with your layer to implement app-specific actions.
///
/// - parameter key: The identifier of the action.
///
/// - returns: the action object assigned to the specified key.
public override func action(forKey key: String) -> CAAction? {
if ShapeLayer.disableActions == true {
return nil
}
let animatableProperties = ["lineWidth", "strokeEnd", "strokeStart", "strokeColor", "path", "fillColor", "lineDashPhase", "contents", Layer.rotationKey, "shadowColor", "shadowRadius", "shadowOffset", "shadowOpacity", "shadowPath"]
if !animatableProperties.contains(key) {
return super.action(forKey: key)
}
let animation: CABasicAnimation
if let viewAnimation = ViewAnimation.stack.last as? ViewAnimation, viewAnimation.spring != nil {
animation = CASpringAnimation(keyPath: key)
} else {
animation = CABasicAnimation(keyPath: key)
}
animation.configureOptions()
animation.fromValue = value(forKey: key)
if key == Layer.rotationKey {
if let layer = presentation() {
animation.fromValue = layer.value(forKey: key)
}
}
return animation
}
private var _rotation = 0.0
/// The value of the receiver's current rotation state.
/// This value is cumulative, and can represent values beyong +/- π
@objc public dynamic var rotation: Double {
return _rotation
}
/// Initializes a new C4Layer
public override init() {
super.init()
}
/// Initializes a new C4Layer from a specified layer of any other type.
/// - parameter layer: Another CALayer
public override init(layer: Any) {
super.init(layer: layer)
if let layer = layer as? ShapeLayer {
_rotation = layer._rotation
}
}
/// Initializes a new C4Layer from data in a given unarchiver.
/// - parameter coder: An unarchiver object.
public required init?(coder: NSCoder) {
super.init(coder: coder)
}
/// Sets a value for a given key.
/// - parameter value: The value for the property identified by key.
/// - parameter key: The name of one of the receiver's properties
public override func setValue(_ value: Any?, forKey key: String) {
super.setValue(value, forKey: key)
if key == Layer.rotationKey {
_rotation = value as? Double ?? 0.0
}
}
/// Returns a Boolean indicating whether changes to the specified key require the layer to be redisplayed.
/// - parameter key: A string that specifies an attribute of the layer.
/// - returns: A Boolean indicating whether changes to the specified key require the layer to be redisplayed.
public override class func needsDisplay(forKey key: String) -> Bool {
if key == Layer.rotationKey {
return true
}
return super.needsDisplay(forKey: key)
}
/// Reloads the content of this layer.
/// Do not call this method directly.
public override func display() {
guard let presentation = presentation() else {
return
}
setValue(presentation._rotation, forKeyPath: "transform.rotation.z")
}
}
extension CABasicAnimation {
/// Configures basic options for a CABasicAnimation.
///
/// The options set in this method are favorable for the inner workings of C4's action behaviours.
@objc public func configureOptions() {
if let animation = ViewAnimation.currentAnimation {
self.autoreverses = animation.autoreverses
self.repeatCount = Float(animation.repeatCount)
}
self.fillMode = kCAFillModeBoth
self.isRemovedOnCompletion = false
}
}
extension CASpringAnimation {
/// Configures basic options for a CABasicAnimation.
///
/// The options set in this method are favorable for the inner workings of C4's animation behaviours.
public override func configureOptions() {
super.configureOptions()
if let animation = ViewAnimation.currentAnimation as? ViewAnimation, let spring = animation.spring {
mass = CGFloat(spring.mass)
damping = CGFloat(spring.damping)
stiffness = CGFloat(spring.stiffness)
initialVelocity = CGFloat(spring.initialVelocity)
}
}
}
|
mit
|
f8eb41227a1ae5aaf9b6f0cef5303288
| 41.098039 | 459 | 0.675671 | 4.901826 | false | false | false | false |
acort3255/Emby.ApiClient.Swift
|
Emby.ApiClient/apiinteraction/credentials/CredentialProvider.swift
|
2
|
1198
|
//
// CredentialProvider.swift
// Emby.ApiClient
//
// Created by Vedran Ozir on 02/11/15.
// Copyright © 2015 Vedran Ozir. All rights reserved.
//
import Foundation
/**
* Created by Luke on 4/5/2015.
*/
public class CredentialProvider: CredentialProviderProtocol { // ICredentialProvider {
private let jsonSerializer: IJsonSerializer
private let filePath: String
public init( jsonSerializer: IJsonSerializer, filePath: String) {
self.jsonSerializer = jsonSerializer
self.filePath = filePath
}
public func getCredentials() -> ServerCredentials {
if let data = UserDefaults.standard.object(forKey: "Emby Server Credentials") as? NSData,
let credentials = NSKeyedUnarchiver.unarchiveObject(with: data as Data) as? ServerCredentials
{
return credentials
}
return ServerCredentials(connectAccessToken: "", connectUserId: "")
}
public func saveCredentials(credentials: ServerCredentials) {
let data = NSKeyedArchiver.archivedData(withRootObject: credentials)
UserDefaults.standard.set(data, forKey: "Emby Server Credentials")
}
}
|
mit
|
b05d0c353264dc84654d3f4dab137c23
| 27.5 | 105 | 0.675856 | 5.008368 | false | false | false | false |
erichoracek/Motif
|
Examples/SwiftButtonsExample/UIView+Theming.swift
|
1
|
2168
|
//
// UIView+Theming.swift
// SwiftButtonsExample
//
// Created by Eric Horacek on 3/14/15.
// Copyright (c) 2015 Eric Horacek. All rights reserved.
//
import UIKit
import Motif
extension Themeable where ApplicantType == UIView {
static func registerProperties() {
ApplicantType.mtf_registerThemeProperty(
ThemeProperties.backgroundColor.rawValue,
requiringValueOf: UIColor.self,
applierBlock: { (color, view, _) -> Bool in
guard let view = view as? UIView else { return false }
guard let color = color as? UIColor else { return false }
view.backgroundColor = color
return true
})
ApplicantType.mtf_registerThemeProperty(
ThemeProperties.borderColor.rawValue,
requiringValueOf: UIColor.self,
applierBlock: { (color, view, _) -> Bool in
guard let view = view as? UIView else { return false }
guard let color = color as? UIColor else { return false }
view.layer.borderColor = color.cgColor
return true
})
ApplicantType.mtf_registerThemeProperty(
ThemeProperties.cornerRadius.rawValue,
requiringValueOf: NSNumber.self,
applierBlock: { (cornerRadius, view, _) -> Bool in
guard let view = view as? UIView else { return false }
guard let cornerRadius = cornerRadius as? NSNumber else { return false }
view.layer.cornerRadius = CGFloat(cornerRadius.floatValue)
return true
})
ApplicantType.mtf_registerThemeProperty(
ThemeProperties.borderWidth.rawValue,
requiringValueOf: NSNumber.self,
applierBlock: { (borderWidth, view, _) -> Bool in
guard let view = view as? UIView else { return false }
guard let borderWidth = borderWidth as? NSNumber else { return false }
view.layer.borderWidth = CGFloat(borderWidth.floatValue)
return true
})
}
}
|
mit
|
5e136699d5d1b90d79d190da2ab8cf81
| 32.875 | 88 | 0.583026 | 5.04186 | false | false | false | false |
eviathan/Salt
|
Pepper/Code Examples/Apple/AudioUnitV3ExampleABasicAudioUnitExtensionandHostImplementation/AUv3Host/iOS/HostViewController.swift
|
1
|
6635
|
/*
Copyright (C) 2016 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
View controller managing selection of an audio unit and presets, opening/closing an audio unit's view, and starting/stopping audio playback.
*/
import UIKit
import AVFoundation
import CoreAudioKit
class HostViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
// MARK: Properties
@IBOutlet var effectInstrumentSegmentedControl: UISegmentedControl!
@IBOutlet var playButton: UIButton!
@IBOutlet var audioUnitTableView: UITableView!
@IBOutlet var presetTableView: UITableView!
@IBOutlet var viewContainer: UIView!
@IBOutlet var noViewLabel: UILabel!
var childViewController: UIViewController?
var audioUnitView: UIView? {
return childViewController?.view
}
var playEngine: SimplePlayEngine!
// MARK: View Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
playEngine = SimplePlayEngine(componentType: kAudioUnitType_Effect) {
self.audioUnitTableView.reloadData()
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if tableView === audioUnitTableView {
return playEngine.availableAudioUnits.count + 1
}
if tableView === presetTableView {
return playEngine.presetList.count
}
return 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
if tableView === audioUnitTableView {
if (indexPath as NSIndexPath).row > 0 && (indexPath as NSIndexPath).row <= playEngine.availableAudioUnits.count {
let component = playEngine.availableAudioUnits[(indexPath as NSIndexPath).row - 1]
cell.textLabel!.text = "\(component.name) (\(component.manufacturerName))"
}
else {
if playEngine.isEffect() {
cell.textLabel!.text = "(No effect)"
} else {
cell.textLabel!.text = "(No instrument)"
}
}
return cell
}
if tableView === presetTableView {
cell.textLabel!.text = playEngine.presetList[(indexPath as NSIndexPath).row].name
return cell
}
fatalError("This index path doesn't make sense for this table view.")
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let row = (indexPath as NSIndexPath).row
if tableView === audioUnitTableView {
// We only want update the table view once the component is selected.
let completionHandler = presetTableView.reloadData
let component: AVAudioUnitComponent?
if row > 0 {
component = playEngine.availableAudioUnits[row - 1]
}
else {
component = nil
}
playEngine.selectAudioUnitComponent(component, completionHandler: completionHandler)
removeChildController()
noViewLabel.isHidden = true
}
else if tableView == presetTableView {
playEngine.selectPresetIndex(row)
}
}
// MARK: - IBActions
@IBAction func selectInstrumentOrEffect(_ sender: AnyObject?) {
let isInstrument = effectInstrumentSegmentedControl.selectedSegmentIndex == 0 ? false : true
audioUnitTableView.selectRow(at: IndexPath(row: 0, section: 0), animated: false, scrollPosition: UITableViewScrollPosition.top)
removeChildController()
if (isInstrument) {
// set the engine to show instrument types and refresh au list
playEngine.setInstrument()
} else {
// set the engine to show effect types and refresh au list
playEngine.setEffect()
}
noViewLabel.isHidden = true
playButton.setTitle("Play", for: UIControlState.normal)
self.audioUnitTableView.reloadData()
self.presetTableView.reloadData()
}
@IBAction func togglePlay(_ sender: AnyObject?) {
let isPlaying = playEngine.togglePlay()
let titleText = isPlaying ? "Stop" : "Play"
playButton.setTitle(titleText, for: UIControlState.normal)
}
@discardableResult
func removeChildController() -> Bool {
if let childViewController = childViewController, let audioUnitView = audioUnitView {
childViewController.willMove(toParentViewController: nil)
audioUnitView.removeFromSuperview()
childViewController.removeFromParentViewController()
self.childViewController = nil
return true
}
return false
}
@IBAction func toggleView(_ sender: AnyObject?) {
/*
This method is called when the view button is pressed.
If there is no view shown, and the AudioUnit has a UI, the view
controller is loaded from the AU and presented as a child view
controller.
If a pre-existing view is being shown, it is removed.
*/
let removedChildController = removeChildController()
guard !removedChildController else { return }
/*
Request the view controller asynchronously from the audio unit. This
only happens if the audio unit is non-nil.
*/
playEngine.testAudioUnit?.requestViewController { [weak self] viewController in
guard let strongSelf = self else { return }
// Only update the view if the view controller has one.
guard let viewController = viewController, let view = viewController.view else {
/*
Show placeholder text that tells the user the audio unit has
no view.
*/
strongSelf.noViewLabel.isHidden = false
return
}
strongSelf.addChildViewController(viewController)
view.frame = strongSelf.viewContainer.bounds
strongSelf.viewContainer.addSubview(view)
strongSelf.childViewController = viewController
viewController.didMove(toParentViewController: self)
strongSelf.noViewLabel.isHidden = true
}
}
}
|
apache-2.0
|
031dbd4ab82ec77b07481abe77b139d3
| 32.165 | 141 | 0.621137 | 5.597468 | false | false | false | false |
JakubMazur/FMBMParallaxView
|
FMBMParallaxView/ContentManager.swift
|
1
|
1495
|
//
// ContentManager.swift
// FMBMParallaxView
//
// Created by Pawel on 05.07.2014.
// Copyright (c) 2014 Kettu Jakub Mazur. All rights reserved.
//
import UIKit
class ContentManager {
struct Static {
static var token : dispatch_once_t = 0
static var instance : ContentManager?
}
class var instance: ContentManager {
dispatch_once(&Static.token) { Static.instance = ContentManager() }
return Static.instance!
}
init(){
assert(Static.instance == nil, "Singleton already initialized!")
}
func getDataUrls() -> (urls: String[]) {
var urls:String[]
urls = String[]()
for val in 1..10
{
urls.append("http://lorempixel.com/320/400/sports/\(val)/")
println("http://lorempixel.com/400/400/sports/\(val)/")
}
return urls;
}
func downloadDataWithUrlString (urlString: String, completionClosure: (data :NSData) ->()){
let session = NSURLSession.sharedSession()
let url:NSURL = NSURL.URLWithString(urlString)
let urlRequest = NSURLRequest(URL:url)
session.dataTaskWithRequest(urlRequest,
completionHandler: {(data: NSData!,
response: NSURLResponse!,
error: NSError!) in
println(data)
println(response)
println(error)
completionClosure(data: data)
}).resume()
}
}
|
mit
|
cdbdfac43b89b9a96d92ac16a988df0d
| 28.313725 | 95 | 0.570569 | 4.571865 | false | false | false | false |
hankbao/socket.io-client-swift
|
SocketIOClientSwift/SocketPacket.swift
|
1
|
7638
|
//
// SocketPacket.swift
// Socket.IO-Swift
//
// Created by Erik Little on 1/18/15.
//
// 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
final class SocketPacket: Printable {
var binary = ContiguousArray<NSData>()
var currentPlace = 0
var data:[AnyObject]?
var description:String {
var better = "SocketPacket {type: ~~0; data: ~~1; " +
"id: ~~2; placeholders: ~~3;}"
better = better["~~0"] ~= (self.type != nil ? String(self.type!.rawValue) : "nil")
better = better["~~1"] ~= (self.data != nil ? "\(self.data!)" : "nil")
better = better["~~2"] ~= (self.id != nil ? String(self.id!) : "nil")
better = better["~~3"] ~= (self.placeholders != nil ? String(self.placeholders!) : "nil")
return better
}
var id:Int?
var justAck = false
var nsp = ""
var placeholders:Int?
var type:PacketType?
enum PacketType:Int {
case CONNECT = 0
case DISCONNECT = 1
case EVENT = 2
case ACK = 3
case ERROR = 4
case BINARY_EVENT = 5
case BINARY_ACK = 6
init?(str:String) {
if let int = str.toInt(), let raw = PacketType(rawValue: int) {
self = raw
} else {
return nil
}
}
}
init(type:PacketType?, data:[AnyObject]? = nil, nsp:String = "",
placeholders:Int? = nil, id:Int? = nil) {
self.type = type
self.data = data
self.nsp = nsp
self.placeholders = placeholders
self.id = id
}
func getEvent() -> String {
return data?.removeAtIndex(0) as! String
}
func addData(data:NSData) -> Bool {
if self.placeholders == self.currentPlace {
return true
}
self.binary.append(data)
self.currentPlace++
if self.placeholders == self.currentPlace {
self.currentPlace = 0
return true
} else {
return false
}
}
func createMessageForEvent(event:String) -> String {
let message:String
var jsonSendError:NSError?
if self.binary.count == 0 {
self.type = PacketType.EVENT
if self.nsp == "/" {
if self.id == nil {
message = "2[\"\(event)\""
} else {
message = "2\(self.id!)[\"\(event)\""
}
} else {
if self.id == nil {
message = "2/\(self.nsp),[\"\(event)\""
} else {
message = "2/\(self.nsp),\(self.id!)[\"\(event)\""
}
}
} else {
self.type = PacketType.BINARY_EVENT
if self.nsp == "/" {
if self.id == nil {
message = "5\(self.binary.count)-[\"\(event)\""
} else {
message = "5\(self.binary.count)-\(self.id!)[\"\(event)\""
}
} else {
if self.id == nil {
message = "5\(self.binary.count)-/\(self.nsp),[\"\(event)\""
} else {
message = "5\(self.binary.count)-/\(self.nsp),\(self.id!)[\"\(event)\""
}
}
}
return self.completeMessage(message)
}
func createAck() -> String {
var msg:String
if self.binary.count == 0 {
self.type = PacketType.ACK
if nsp == "/" {
msg = "3\(self.id!)["
} else {
msg = "3/\(self.nsp),\(self.id!)["
}
} else {
self.type = PacketType.BINARY_ACK
if nsp == "/" {
msg = "6\(self.binary.count)-\(self.id!)["
} else {
msg = "6\(self.binary.count)-/\(self.nsp),\(self.id!)["
}
}
return self.completeMessage(msg, ack: true)
}
func completeMessage(var message:String, ack:Bool = false) -> String {
var err:NSError?
if self.data == nil || self.data!.count == 0 {
return message + "]"
} else if !ack {
message += ","
}
for arg in self.data! {
if arg is NSDictionary || arg is [AnyObject] {
let jsonSend = NSJSONSerialization.dataWithJSONObject(arg,
options: NSJSONWritingOptions(0), error: &err)
let jsonString = NSString(data: jsonSend!, encoding: NSUTF8StringEncoding)
message += jsonString! as String + ","
} else if arg is String {
message += "\"\(arg)\","
} else if arg is NSNull {
message += "null,"
} else {
message += "\(arg),"
}
}
if message != "" {
message.removeAtIndex(message.endIndex.predecessor())
}
return message + "]"
}
func fillInPlaceholders() {
var newArr = NSMutableArray(array: self.data!)
for i in 0..<self.data!.count {
if let str = self.data?[i] as? String, num = str["~~(\\d)"].groups() {
newArr[i] = self.binary[num[1].toInt()!]
} else if self.data?[i] is NSDictionary || self.data?[i] is NSArray {
newArr[i] = self._fillInPlaceholders(self.data![i])
}
}
self.data = newArr as [AnyObject]
}
private func _fillInPlaceholders(data:AnyObject) -> AnyObject {
if let str = data as? String {
if let num = str["~~(\\d)"].groups() {
return self.binary[num[1].toInt()!]
} else {
return str
}
} else if let dict = data as? NSDictionary {
var newDict = NSMutableDictionary(dictionary: dict)
for (key, value) in dict {
newDict[key as! NSCopying] = _fillInPlaceholders(value)
}
return newDict
} else if let arr = data as? NSArray {
var newArr = NSMutableArray(array: arr)
for i in 0..<arr.count {
newArr[i] = _fillInPlaceholders(arr[i])
}
return newArr
} else {
return data
}
}
}
|
apache-2.0
|
89382ff0f7b7ccfe4c7de49fbcde26c2
| 31.781116 | 97 | 0.487169 | 4.535629 | false | false | false | false |
apple/swift-nio
|
Sources/NIOFoundationCompat/JSONSerialization+ByteBuffer.swift
|
1
|
1257
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2021 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import NIOCore
import Foundation
extension JSONSerialization {
/// Attempts to derive a Foundation object from a ByteBuffer and return it as `T`.
///
/// - parameters:
/// - buffer: The ByteBuffer being used to derive the Foundation type.
/// - options: The reading option used when the parser derives the Foundation type from the ByteBuffer.
/// - returns: The Foundation value if successful or `nil` if there was an issue creating the Foundation type.
@inlinable
public static func jsonObject(with buffer: ByteBuffer,
options opt: JSONSerialization.ReadingOptions = []) throws -> Any {
return try JSONSerialization.jsonObject(with: Data(buffer: buffer), options: opt)
}
}
|
apache-2.0
|
98ccd1a6679d011d529ee43e12563c17
| 39.548387 | 114 | 0.604614 | 5.326271 | false | false | false | false |
antonio081014/LeeCode-CodeBase
|
Swift/power-of-two.swift
|
2
|
265
|
/**
* https://leetcode.com/problems/power-of-two/
*
*
*/
class Solution {
func isPowerOfTwo(_ n: Int) -> Bool {
var n = n
while n > 1 {
if n % 2 != 0 { return false }
n /= 2
}
return n == 1
}
}
|
mit
|
a9dd4b7c60590d04f89074f1866eaf44
| 16.666667 | 46 | 0.411321 | 3.397436 | false | false | false | false |
DominikBucher12/BEExtension
|
BEExtension/SourceEditorCommand.swift
|
1
|
3171
|
//
// SourceEditorCommand.swift
// BEExtension
//
// Created by Dominik Bucher on 21/05/2017.
// Copyright © 2017 Dominik Bucher. All rights reserved.
//
import Foundation
import XcodeKit
//TODO: Do some refactoring later when adding new features.
class SourceEditorCommand: NSObject, XCSourceEditorCommand {
func perform(with invocation: XCSourceEditorCommandInvocation, completionHandler: @escaping (Error?) -> Void ) -> Void {
// Implement your command here, invoking the completion handler when done. Pass it nil on success, and an NSError on failure.
guard invocation.buffer.contentUTI == Identifiers.ContentUTIs.swiftSource.rawValue else {
let errorWithUTI = create(error: .wrongUTI)
completionHandler(errorWithUTI)
return
}
// Select the text, get the identifier chosen, if something fails return without error...
guard let selectedText = try? getSelectedLinesText(withBuffer: invocation.buffer),
let commandIdentifier = Identifiers.Commands(rawValue: invocation.commandIdentifier)
else { completionHandler(nil); return; }
// Prepare the text from the buffer to be parsed.
let words = TextHelper.getPreparedWords(fromText: selectedText)
// We need to get the last selected line to insert our variable / switch below
guard let lastSelectedLine = lastSelectedLine(fromBuffer: invocation.buffer) else { completionHandler(nil); return; }
// Create the code snippet
let pieceOfCode = codeSnippet(
withCommandIdentifier: commandIdentifier,
withWords: words,
withTabWidth: invocation.buffer.tabWidth
)
// Get the lines ahead of the selection.
let linesAhead = self.linesAhead(lastSelectedline: lastSelectedLine, withBuffer: invocation.buffer)
invocation.buffer.lines.insert("\n", at: lastSelectedLine + linesAhead )
invocation.buffer.lines.insert(pieceOfCode, at: lastSelectedLine + linesAhead + 1)
completionHandler(nil)
}
func codeSnippet(withCommandIdentifier identifier: Identifiers.Commands, withWords words: [String], withTabWidth tabWidth: Int ) -> String {
switch identifier {
case .makeJustSwitch:
return TextHelper.generateSwitch(fromCases: words, tabWidth: tabWidth)
case .makeVariable:
return TextHelper.generateVariable(withEnumCases: words, withTabWidth: tabWidth)
}
}
/// Generates our defined error
///
/// - Parameter error: error from possible errors that could occur during text selection
/// - Returns: NSError to pass to Xcode
private func create(error: Identifiers.PossibleErrors) -> NSError {
let userInfo: [AnyHashable : Any] = [
NSLocalizedDescriptionKey : NSLocalizedString(
error.errorDescription,
value: error.errorDescription,
comment: ""
)
]
let error = NSError(domain: "com.dominikbucher.xcodeKitError", code: 1, userInfo: userInfo as? [String : Any])
return error
}
}
|
mit
|
b442d3b3dfab52bb91920417f44fec38
| 38.135802 | 144 | 0.675394 | 4.976452 | false | false | false | false |
bmichotte/HSTracker
|
HSTracker/Core/Extensions/String.swift
|
1
|
1929
|
/*
* This file is part of the HSTracker package.
* (c) Benjamin Michotte <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* Created on 17/02/16.
*/
import Foundation
extension String {
func trim() -> String {
return trimmingCharacters(in: .whitespacesAndNewlines)
}
var isBlank: Bool {
return trim().isEmpty
}
}
extension Optional where Wrapped == String {
var isBlank: Bool {
return self?.isBlank ?? true
}
}
extension String {
func substringWithRange(_ start: Int, end: Int) -> String {
if start < 0 || start > self.characters.count {
print("start index \(start) out of bounds")
return ""
} else if end < 0 || end > self.characters.count {
print("end index \(end) out of bounds")
return ""
}
let range = self.characters.index(self.startIndex, offsetBy: start)
..< self.characters.index(self.startIndex, offsetBy: end)
return self.substring(with: range)
}
func substringWithRange(_ start: Int, location: Int) -> String {
if start < 0 || start > self.characters.count {
print("start index \(start) out of bounds")
return ""
} else if location < 0 || start + location > self.characters.count {
print("end index \(start + location) out of bounds")
return ""
}
let startPos = self.characters.index(self.startIndex, offsetBy: start)
let endPos = self.characters.index(self.startIndex, offsetBy: start + location)
let range = startPos ..< endPos
return self.substring(with: range)
}
func char(at: Int) -> String {
let c = (self as NSString).character(at: at)
let s = NSString(format: "%c", c)
return s as String
}
}
|
mit
|
4cf4c8a8916d656c6ae89e3c45a5fa11
| 29.619048 | 87 | 0.599274 | 4.267699 | false | false | false | false |
samtstern/google-services
|
ios/analytics/AnalyticsExampleSwift/PatternTabBarController.swift
|
3
|
1614
|
//
// Copyright (c) 2015 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
/**
* PatternTabBarController exists as a subclass of UITabBarConttroller that
* supports a 'share' action. This will trigger a custom event to Analytics and
* display a dialog.
*/
@objc(PatternTabBarController) // match the ObjC symbol name inside Storyboard
class PatternTabBarController: UITabBarController {
@IBAction func didTapShare(_ sender: AnyObject) {
// [START custom_event_swift]
guard let tracker = GAI.sharedInstance().defaultTracker else { return }
guard let event = GAIDictionaryBuilder.createEvent(withCategory: "Action", action: "Share", label: nil, value: nil) else { return }
tracker.send(event.build() as [NSObject : AnyObject])
// [END custom_event_swift]
let title = "Share: \(self.selectedViewController!.title!)"
let message = "Share event sent to Analytics; actual share not implemented in this quickstart"
let alert = UIAlertView(title: title, message: message, delegate: nil, cancelButtonTitle: "Ok")
alert.show()
}
}
|
apache-2.0
|
4ae969daf4225d2eee5e065c828c25b5
| 39.35 | 135 | 0.731722 | 4.203125 | false | false | false | false |
allenlinli/Wildlife-League
|
Wildlife League/GameScene+Touches.swift
|
1
|
3914
|
//
// GameScene+Touches.swift
// Wildlife League
//
// Created by allenlin on 7/21/14.
// Copyright (c) 2014 Raccoonism. All rights reserved.
//
import SpriteKit
extension GameScene {
override func touchesBegan(touches: NSSet!, withEvent event: UIEvent!) {
let touch = touches.anyObject() as UITouch
let location = touch.locationInNode(beedLayer)
let (success, column, row) = convertPointToBoardCoordinate(location)
if success {
if let beed = board[column, row] {
self.beedToMove = beed
beed.sprite!.alpha = 0.5
self.addCopyBeedOnBoard(beedToCopy: beed, location: location)
}
}
}
override func touchesMoved(touches: NSSet!, withEvent event: UIEvent!) {
let touch = touches.anyObject() as UITouch
let location = touch.locationInNode(beedLayer)
if let beedMoving = beedMoving {
if let sprite = beedMoving.sprite {
sprite.position = location
}
}
let (success, column, row) = convertPointToBoardCoordinate(location)
if success {
if(column==self.beedMoving!.column && row==self.beedMoving!.row){
return
}
self.beedMoving!.column = column
self.beedMoving!.row = row
beedSwapped = board[column, row]
self.swapTwoBeeds(beed1: self.beedToMove!, beed2: self.beedSwapped!)
board.insertBeed(self.beedToMove!)
board.insertBeed(self.beedSwapped!)
}
else{
beedMoving?.sprite!.runAction(SKAction.sequence([
SKAction.fadeOutWithDuration(0),
SKAction.removeFromParent(),
SKAction.runBlock({
()->() in
self.beedMoving!.sprite!.removeFromParent()
self.beedMoving = nil
self.beedToMove!.sprite!.alpha = 1
self.beedSwapped = nil
self.beedToMove = nil
})]
))
}
}
override func touchesCancelled(touches: NSSet!, withEvent event: UIEvent!) {
beedMoving!.sprite!.removeFromParent()
beedMoving = nil
beedToMove!.sprite!.alpha = 1
beedSwapped = nil
beedToMove = nil
}
override func touchesEnded(touches: NSSet!, withEvent event: UIEvent!) {
UIApplication.sharedApplication().beginIgnoringInteractionEvents()
beedMoving?.sprite!.runAction(SKAction.sequence([SKAction.fadeOutWithDuration(0),SKAction.removeFromParent()]))
if let bm = beedToMove {
bm.sprite!.alpha = 1
self.doErase()
}
beedMoving = nil
beedSwapped = nil
beedToMove = nil
}
func swapTwoBeeds(#beed1 :Beed, beed2 :Beed) {
var tempRow = beed1.row
var tempColumn = beed1.column
beed1.row = beed2.row
beed1.column = beed2.column
beed2.row = tempRow
beed2.column = tempColumn
let Duration: NSTimeInterval = 0.05
let moveA = SKAction.moveTo(self.pointAtColumn(beed1.column, row: beed1.row), duration: Duration)
moveA.timingMode = .Linear
if let existingAction = beed1.sprite!.actionForKey("move") {
let newAction = SKAction.sequence([existingAction, moveA])
beed1.sprite!.removeAllActions()
beed1.sprite!.runAction(newAction, withKey: "move")
} else {
beed1.sprite!.runAction(moveA, withKey: "move")
}
let moveB = SKAction.moveTo(self.pointAtColumn(beed2.column, row: beed2.row), duration: Duration)
moveB.timingMode = .EaseOut
beed2.sprite!.runAction(moveB)
}
}
|
apache-2.0
|
11fe861207d50658768c30ef1f2c8a08
| 33.043478 | 119 | 0.567195 | 4.530093 | false | false | false | false |
colemancda/Decodable
|
DecodableTests/Repository.swift
|
1
|
1320
|
//
// RepositoryExample.swift
// Decodable
//
// Created by Fran_DEV on 13/07/15.
// Copyright © 2015 anviking. All rights reserved.
//
import Foundation
@testable import Decodable
struct Owner {
let id: Int
let login: String
}
struct Repository {
let id: Int
let name: String
let description: String
let htmlUrlString : String
let owner: Owner // Struct conforming to Decodable
let coverage: Double
let files: Array<String>
let optional: String?
}
extension Owner : Decodable {
static func decode(j: AnyObject) throws -> Owner {
return try Owner(
id: j => "id",
login: j => "login"
)
}
}
extension Repository : Decodable {
static func decode(j: AnyObject) throws -> Repository {
return try Repository(
id: j => "id",
name: j => "name",
description: j => "description",
htmlUrlString : j => "html_url",
owner: j => "owner",
coverage: j => "coverage",
files: j => "files",
optional: j => "optional"
)
}
}
// MARK: Equatable
func == (lhs: Owner, rhs: Owner) -> Bool {
return lhs.id == rhs.id && lhs.login == rhs.login
}
extension Owner: Equatable {
var hashValue: Int { return id.hashValue }
}
|
mit
|
3fff56fef76b2565c415bca7b5545aaa
| 21 | 59 | 0.571645 | 3.972892 | false | false | false | false |
nessBautista/iOSBackup
|
DataStructsSwift/DataStructsSwift/Sort.swift
|
1
|
2349
|
//
// Sort.swift
// DataStructsSwift
//
// Created by Nestor Javier Hernandez Bautista on 4/29/17.
// Copyright © 2017 Ness. All rights reserved.
//
import UIKit
class Sort: NSObject
{
var array: [Int]?
//MARK: QUICK SORT
public func quickSort()
{
guard let array = self.array else {
return
}
self.quickSortHelper(0, array.count - 1)
}
private func quickSortHelper(_ left:Int, _ right: Int)
{
guard let array = self.array else {
return
}
if left >= right
{
return
}
let pivotIdx : Int = (left + right) / 2
let pivot = array[pivotIdx]
//This is going to be the division point of the array
let index = self.partition(left, right, pivot)
//Perform recursion
quickSortHelper(left, index - 1)
quickSortHelper(index, right)
}
private func partition(_ l:Int, _ r: Int, _ pivot: Int) -> Int
{
var right = r
var left = l
guard let array = self.array else {
return -1
}
while(left <= right)
{
while array[left] < pivot
{
left += 1
}
while array[right] > pivot
{
right -= 1
}
if left <= right
{
self.swap(array, left, right)
left += 1
right -= 1
}
}
return left
}
func swap(_ array:[Int],_ a:Int, _ b: Int)
{
let tempA = array[a]
let tempB = array[b]
self.array?[a] = tempB
self.array?[b] = tempA
}
//MARK: INSERTION SORT
func insertionSort()
{
guard var array = self.array else {
return
}
for j in 1...array.count - 1
{
let key = array[j]
var i = j - 1
while(i >= 0 && array[i] > key)
{
array[i + 1] = array[i]
i -= 1
}
array[i + 1] = key
}
self.array = array
}
}
|
cc0-1.0
|
86aea77daec398107b27c38a30180e35
| 20.153153 | 66 | 0.409284 | 4.472381 | false | false | false | false |
pankcuf/DataContext
|
DataContext/Classes/DataContext.swift
|
1
|
1237
|
//
// DataContext.swift
// DataContext
//
// Created by Vladimir Pirogov on 17/10/16.
// Copyright © 2016 Vladimir Pirogov. All rights reserved.
//
import Foundation
open class DataContext: NSObject {
public typealias ViewCallback = ((ViewUpdateContext?) -> ())
open var transport: DataTransport?
open var isUpdating: Bool = false
public override init() {
super.init()
}
public init(transport: DataTransport?) {
super.init()
self.transport = transport
}
open func requestUpdate(with request: DataRequestContext<DataResponseContext>, callback: @escaping ViewCallback) {
self.isUpdating = true
self.transport?.doAction(requestContext: request) { (response:DataResponseContext?) in
let result = response?.parse()
DispatchQueue.main.async {
self.isUpdating = false
let updateContext = self.update(result)
callback(updateContext)
}
}
}
open func requestUpdate(with request: DataRequestContext<DataResponseContext>, for view: UIView) {
self.requestUpdate(with: request) { (updateContext: ViewUpdateContext?) in
view.update(with: updateContext)
}
}
open func update(_ response: Any?) -> ViewUpdateContext? {
return ViewUpdateContext()
}
}
|
mit
|
6c8dbe1802606941f868bd7f51ced203
| 19.949153 | 115 | 0.706311 | 3.814815 | false | false | false | false |
hikelee/hotel
|
Sources/Common/Controllers/IndexController.swift
|
1
|
736
|
import Vapor
import HTTP
import RandomKit
import CryptoSwift
final class IndexAdminController: Controller {
let path = "/admin"
func render(_ data:[String:Node]) throws ->ResponseRepresentable{
return try droplet.view.make("\(path)Login",data)
}
override func makeRouter(){
routerGroup.group(path){group in
group.get("/",handler: index)
}
}
func index(_ request: Request) throws -> ResponseRepresentable {
let user = request.user
let loginTitle = user?.title ?? request.channel?.title ?? ""
let isAdmin = user != nil
return try droplet.view.make(
"/admin/main/index",
["login_title":loginTitle,"is_admin":isAdmin])
}
}
|
mit
|
74eae20fc6518ca19b8cd1a18c1ffc7e
| 29.666667 | 69 | 0.625 | 4.35503 | false | false | false | false |
joeldom/PageMenu
|
Demos/Demo 4/PageMenuDemoTabbar/PageMenuDemoTabbar/ContactsTableViewController.swift
|
28
|
3595
|
//
// ContactsTableViewController.swift
// PageMenuDemoTabbar
//
// Created by Niklas Fahl on 1/9/15.
// Copyright (c) 2015 Niklas Fahl. All rights reserved.
//
import UIKit
class ContactsTableViewController: UITableViewController {
var namesArray : [String] = ["David Fletcher", "Charles Gray", "Zachary Hecker", "Anna Hunt", "Timothy Jones", "William Pearl", "George Porter", "Nicholas Ray", "Lauren Richard", "Juan Rodriguez", "Marie Turner", "Sarah Underwood", "Kim White"]
var photoNameArray : [String] = ["man8.jpg", "man2.jpg", "man7.jpg", "woman3.jpg", "man3.jpg", "man4.jpg", "man1.jpg", "man6.jpg", "woman5.jpg", "man5.jpg", "woman4.jpg", "woman2.jpg", "woman1.jpg"]
var staredArray : [Bool] = [true, true, false, false, true, false, false, false, false, false, true, false, true]
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.registerNib(UINib(nibName: "ContactTableViewCell", bundle: nil), forCellReuseIdentifier: "ContactTableViewCell")
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
println("\(self.title) page: viewWillAppear")
}
override func viewDidAppear(animated: Bool) {
// println("contacts page: viewDidAppear")
self.tableView.showsVerticalScrollIndicator = false
super.viewDidAppear(animated)
self.tableView.showsVerticalScrollIndicator = true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Potentially incomplete method implementation.
// Return the number of sections.
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete method implementation.
// Return the number of rows in the section.
return 13
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell : ContactTableViewCell = tableView.dequeueReusableCellWithIdentifier("ContactTableViewCell") as! ContactTableViewCell
// Configure the cell...
cell.nameLabel.text = namesArray[indexPath.row]
cell.photoImageView.image = UIImage(named: photoNameArray[indexPath.row])
if staredArray[indexPath.row] {
cell.starButton.imageView?.image = UIImage(named: "stared")
} else {
cell.starButton.imageView?.image = UIImage(named: "unstared")
}
return cell
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 94.0
}
override func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 0.001
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
println("did select contact row")
let contactPrompt = UIAlertController(title: "Contact Selected", message: "You have selected a contact.", preferredStyle: UIAlertControllerStyle.Alert)
contactPrompt.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Default, handler: nil))
presentViewController(contactPrompt, animated: true, completion: nil)
}
}
|
bsd-3-clause
|
68733846c2633f36c414ba948109476b
| 41.294118 | 248 | 0.676217 | 4.799733 | false | false | false | false |
abeschneider/stem
|
Sources/Op/optimize.swift
|
1
|
1817
|
//
// optimize.swift
// stem
//
// Created by Schneider, Abraham R. on 6/5/16.
// Copyright © 2016 none. All rights reserved.
//
import Foundation
import Tensor
protocol Optimizer {
associatedtype StorageType:Storage
func optimize() -> Op<StorageType>
}
open class GradientDescentOptimizer<S:Storage>: Op<S> where S.ElementType:FloatNumericType {
var alpha:ConstantOp<S>
var forward:Op<S>
var backward:Op<S>
var params:[Tensor<S>]
var gradParams:[Tensor<S>]
// NB: With current version of swift, constraints cannot be placed on
// Op s.t. its differentiable. Until this is changed, this code can fail a
// at runtime if non-differentiable op is used
public init(_ op:Op<S>, alpha:ConstantOp<S>) {
self.alpha = alpha
forward = op
backward = (op as! Differentiable).gradient() as! Op<S>
params = forward.params()
gradParams = backward.params()
// super.init(inputs: [("alpha", InputType(alpha))],
// outputs: forward.outputs)
// super.init()
super.init(inputs: ["alpha"], outputs: [])
connect(from: alpha, "output", to: self, "alpha")
let forwardOutputs:[Tensor<S>] = forward.outputs["output"]!
outputs["output"] = forwardOutputs
}
required public init(op: Op<S>, shared: Bool) {
fatalError("init(op:shared:) has not been implemented")
}
open override func apply() {
(backward as! GradientType).reset()
forward.apply()
backward.apply()
// this is a place where having a TensorScalar class might be nice
let a:S.ElementType = alpha.output[0]
for (param, gradParam) in zip(params, gradParams) {
param -= a*gradParam
}
}
}
|
mit
|
cb53d75505cafd87314d953e13ed9d1a
| 29.266667 | 92 | 0.606828 | 4.017699 | false | false | false | false |
VirgilSecurity/virgil-sdk-keys-ios
|
Source/Utils/Operation/GenericOperation+Dependencies.swift
|
1
|
2949
|
//
// Copyright (C) 2015-2020 Virgil Security Inc.
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// (1) Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// (2) Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in
// the documentation and/or other materials provided with the
// distribution.
//
// (3) Neither the name of the copyright holder nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''AS IS'' AND ANY EXPRESS OR
// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
// IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
// Lead Maintainer: Virgil Security Inc. <[email protected]>
//
import Foundation
// MARK: - Dependency-related operations
public extension GenericOperation {
/// Finds first dependency with Result of correct type and returns its result,
/// if operation has succeeded
///
/// - Returns: Dependency Result
/// - Throws: GenericOperationError.missingDependencies, if no dependency with correct type was found
/// GenericOperationError.dependencyFailed, if dependency has failed
func findDependencyResult<T>() throws -> T {
guard let operation = self.dependencies
.first(where: { ($0 as? GenericOperation<T>)?.result != nil }) as? GenericOperation<T>,
let operationResult = operation.result else {
throw GenericOperationError.missingDependencies
}
guard case let .success(result) = operationResult else {
throw GenericOperationError.dependencyFailed
}
return result
}
/// Finds dependency error
///
/// - Returns: Dependency error
func findDependencyError() -> Error? {
for dependency in self.dependencies {
if let dependency = dependency as? AsyncOperation,
let error = dependency.error {
return error
}
}
return nil
}
}
|
bsd-3-clause
|
c202b2f9d72b0bd9190b5653d3dd5245
| 38.851351 | 105 | 0.693116 | 4.939698 | false | false | false | false |
mattiabugossi/Swifter
|
Swifter/SwifterTweets.swift
|
1
|
17196
|
//
// SwifterTweets.swift
// Swifter
//
// Copyright (c) 2014 Matt Donnelly.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
public extension Swifter {
/*
GET statuses/retweets/:id
Returns up to 100 of the first retweets of a given tweet.
*/
public func getStatusesRetweetsWithID(id: String, count: Int? = nil, trimUser: Bool? = nil, success: ((statuses: [JSONValue]?) -> Void)? = nil, failure: FailureHandler? = nil) {
let path = "statuses/retweets/\(id).json"
var parameters = Dictionary<String, Any>()
if count != nil {
parameters["count"] = count!
}
if trimUser != nil {
parameters["trim_user"] = trimUser!
}
self.getJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: {
json, response in
success?(statuses: json.array)
return
}, failure: failure)
}
/*
GET statuses/show/:id
Returns a single Tweet, specified by the id parameter. The Tweet's author will also be embedded within the tweet.
See Embeddable Timelines, Embeddable Tweets, and GET statuses/oembed for tools to render Tweets according to Display Requirements.
# About Geo
If there is no geotag for a status, then there will be an empty <geo/> or "geo" : {}. This can only be populated if the user has used the Geotagging API to send a statuses/update.
The JSON response mostly uses conventions laid out in GeoJSON. Unfortunately, the coordinates that Twitter renders are reversed from the GeoJSON specification (GeoJSON specifies a longitude then a latitude, whereas we are currently representing it as a latitude then a longitude). Our JSON renders as: "geo": { "type":"Point", "coordinates":[37.78029, -122.39697] }
# Contributors
If there are no contributors for a Tweet, then there will be an empty or "contributors" : {}. This field will only be populated if the user has contributors enabled on his or her account -- this is a beta feature that is not yet generally available to all.
This object contains an array of user IDs for users who have contributed to this status (an example of a status that has been contributed to is this one). In practice, there is usually only one ID in this array. The JSON renders as such "contributors":[8285392].
*/
public func getStatusesShowWithID(id: String, count: Int? = nil, trimUser: Bool? = nil, includeMyRetweet: Bool? = nil, includeEntities: Bool? = nil, success: ((status: Dictionary<String, JSONValue>?) -> Void)? = nil, failure: FailureHandler? = nil) {
let path = "statuses/show.json"
var parameters = Dictionary<String, Any>()
parameters["id"] = id
if count != nil {
parameters["count"] = count!
}
if trimUser != nil {
parameters["trim_user"] = trimUser!
}
if includeMyRetweet != nil {
parameters["include_my_retweet"] = includeMyRetweet!
}
if includeEntities != nil {
parameters["include_entities"] = includeEntities!
}
self.getJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: {
json, response in
success?(status: json.object)
return
}, failure: failure)
}
/*
POST statuses/destroy/:id
Destroys the status specified by the required ID parameter. The authenticating user must be the author of the specified status. Returns the destroyed status if successful.
*/
public func postStatusesDestroyWithID(id: String, trimUser: Bool? = nil, success: ((status: Dictionary<String, JSONValue>?) -> Void)? = nil, failure: FailureHandler? = nil) {
let path = "statuses/destroy/\(id).json"
var parameters = Dictionary<String, Any>()
if trimUser != nil {
parameters["trim_user"] = trimUser!
}
self.postJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: {
json, response in
success?(status: json.object)
return
}, failure: failure)
}
/*
POST statuses/update
Updates the authenticating user's current status, also known as tweeting. To upload an image to accompany the tweet, use POST statuses/update_with_media.
For each update attempt, the update text is compared with the authenticating user's recent tweets. Any attempt that would result in duplication will be blocked, resulting in a 403 error. Therefore, a user cannot submit the same status twice in a row.
While not rate limited by the API a user is limited in the number of tweets they can create at a time. If the number of updates posted by the user reaches the current allowed limit this method will return an HTTP 403 error.
- Any geo-tagging parameters in the update will be ignored if geo_enabled for the user is false (this is the default setting for all users unless the user has enabled geolocation in their settings)
- The number of digits passed the decimal separator passed to lat, up to 8, will be tracked so that the lat is returned in a status object it will have the same number of digits after the decimal separator.
- Please make sure to use to use a decimal point as the separator (and not the decimal comma) for the latitude and the longitude - usage of the decimal comma will cause the geo-tagged portion of the status update to be dropped.
- For JSON, the response mostly uses conventions described in GeoJSON. Unfortunately, the geo object has coordinates that Twitter renderers are reversed from the GeoJSON specification (GeoJSON specifies a longitude then a latitude, whereas we are currently representing it as a latitude then a longitude. Our JSON renders as: "geo": { "type":"Point", "coordinates":[37.78217, -122.40062] }
- The coordinates object is replacing the geo object (no deprecation date has been set for the geo object yet) -- the difference is that the coordinates object, in JSON, is now rendered correctly in GeoJSON.
- If a place_id is passed into the status update, then that place will be attached to the status. If no place_id was explicitly provided, but latitude and longitude are, we attempt to implicitly provide a place by calling geo/reverse_geocode.
- Users will have the ability, from their settings page, to remove all the geotags from all their tweets en masse. Currently we are not doing any automatic scrubbing nor providing a method to remove geotags from individual tweets.
See:
- https://dev.twitter.com/notifications/multiple-media-entities-in-tweets
- https://dev.twitter.com/docs/api/multiple-media-extended-entities
*/
public func postStatusUpdate(status: String, inReplyToStatusID: String? = nil, lat: Double? = nil, long: Double? = nil, placeID: Double? = nil, displayCoordinates: Bool? = nil, trimUser: Bool? = nil, success: ((status: Dictionary<String, JSONValue>?) -> Void)? = nil, failure: FailureHandler? = nil) {
let path: String = "statuses/update.json"
var parameters = Dictionary<String, Any>()
parameters["status"] = status
if inReplyToStatusID != nil {
parameters["in_reply_to_status_id"] = inReplyToStatusID!
}
if placeID != nil {
parameters["place_id"] = placeID!
parameters["display_coordinates"] = true
}
else if lat != nil && long != nil {
parameters["lat"] = lat!
parameters["long"] = long!
parameters["display_coordinates"] = true
}
if trimUser != nil {
parameters["trim_user"] = trimUser!
}
self.postJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: {
json, response in
success?(status: json.object)
return
}, failure: failure)
}
public func postStatusUpdate(status: String, media: NSData, inReplyToStatusID: String? = nil, lat: Double? = nil, long: Double? = nil, placeID: Double? = nil, displayCoordinates: Bool? = nil, trimUser: Bool? = nil, success: ((status: Dictionary<String, JSONValue>?) -> Void)? = nil, failure: FailureHandler? = nil) {
var path: String = "statuses/update_with_media.json"
var parameters = Dictionary<String, Any>()
parameters["status"] = status
parameters["media[]"] = media
parameters[Swifter.DataParameters.dataKey] = "media[]"
if inReplyToStatusID != nil {
parameters["in_reply_to_status_id"] = inReplyToStatusID!
}
if placeID != nil {
parameters["place_id"] = placeID!
parameters["display_coordinates"] = true
}
else if lat != nil && long != nil {
parameters["lat"] = lat!
parameters["long"] = long!
parameters["display_coordinates"] = true
}
if trimUser != nil {
parameters["trim_user"] = trimUser!
}
self.postJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: {
json, response in
success?(status: json.object)
return
}, failure: failure)
}
/*
POST statuses/retweet/:id
Retweets a tweet. Returns the original tweet with retweet details embedded.
- This method is subject to update limits. A HTTP 403 will be returned if this limit as been hit.
- Twitter will ignore attempts to perform duplicate retweets.
- The retweet_count will be current as of when the payload is generated and may not reflect the exact count. It is intended as an approximation.
Returns Tweets (1: the new tweet)
*/
public func postStatusRetweetWithID(id: String, trimUser: Bool? = nil, success: ((status: Dictionary<String, JSONValue>?) -> Void)? = nil, failure: FailureHandler? = nil) {
let path = "statuses/retweet/\(id).json"
var parameters = Dictionary<String, Any>()
if trimUser != nil {
parameters["trim_user"] = trimUser!
}
self.postJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: {
json, response in
success?(status: json.object)
return
}, failure: failure)
}
/*
GET statuses/oembed
Returns information allowing the creation of an embedded representation of a Tweet on third party sites. See the oEmbed specification for information about the response format.
While this endpoint allows a bit of customization for the final appearance of the embedded Tweet, be aware that the appearance of the rendered Tweet may change over time to be consistent with Twitter's Display Requirements. Do not rely on any class or id parameters to stay constant in the returned markup.
*/
public func getStatusesOEmbedWithID(id: String, maxWidth: Int? = nil, hideMedia: Bool? = nil, hideThread: Bool? = nil, omitScript: Bool? = nil, align: String? = nil, related: String? = nil, lang: String? = nil, success: ((status: Dictionary<String, JSONValue>?) -> Void)? = nil, failure: FailureHandler? = nil) {
let path = "statuses/oembed.json"
var parameters = Dictionary<String, Any>()
parameters["id"] = id
if maxWidth != nil {
parameters["max_width"] = maxWidth!
}
if hideMedia != nil {
parameters["hide_media"] = hideMedia!
}
if hideThread != nil {
parameters["hide_thread"] = hideThread!
}
if omitScript != nil {
parameters["omit_scipt"] = omitScript!
}
if align != nil {
parameters["align"] = align!
}
if related != nil {
parameters["related"] = related!
}
if lang != nil {
parameters["lang"] = lang!
}
self.getJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: {
json, response in
success?(status: json.object)
return
}, failure: failure)
}
public func getStatusesOEmbedWithURL(url: NSURL, maxWidth: Int? = nil, hideMedia: Bool? = nil, hideThread: Bool? = nil, omitScript: Bool? = nil, align: String? = nil, related: String? = nil, lang: String? = nil, success: ((status: Dictionary<String, JSONValue>?) -> Void)? = nil, failure: FailureHandler? = nil) {
let path = "statuses/oembed.json"
var parameters = Dictionary<String, Any>()
parameters["url"] = url.absoluteString
if maxWidth != nil {
parameters["max_width"] = maxWidth!
}
if hideMedia != nil {
parameters["hide_media"] = hideMedia!
}
if hideThread != nil {
parameters["hide_thread"] = hideThread!
}
if omitScript != nil {
parameters["omit_scipt"] = omitScript!
}
if align != nil {
parameters["align"] = align!
}
if related != nil {
parameters["related"] = related!
}
if lang != nil {
parameters["lang"] = lang!
}
self.getJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: {
json, response in
success?(status: json.object)
return
}, failure: failure)
}
/*
GET statuses/retweeters/ids
Returns a collection of up to 100 user IDs belonging to users who have retweeted the tweet specified by the id parameter.
This method offers similar data to GET statuses/retweets/:id and replaces API v1's GET statuses/:id/retweeted_by/ids method.
*/
public func getStatusesRetweetersWithID(id: String, cursor: Int? = nil, stringifyIDs: Bool? = nil, success: ((ids: [JSONValue]?, previousCursor: Int?, nextCursor: Int?) -> Void)? = nil, failure: FailureHandler? = nil) {
let path = "statuses/retweeters/ids.json"
var parameters = Dictionary<String, Any>()
parameters["id"] = id
if cursor != nil {
parameters["cursor"] = cursor!
}
if stringifyIDs != nil {
parameters["stringify_ids"] = cursor!
}
self.getJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: {
json, response in
success?(ids: json["ids"].array, previousCursor: json["previous_cursor"].integer, nextCursor: json["next_cursor"].integer)
}, failure: failure)
}
/*
GET statuses/lookup
Returns fully-hydrated tweet objects for up to 100 tweets per request, as specified by comma-separated values passed to the id parameter. This method is especially useful to get the details (hydrate) a collection of Tweet IDs. GET statuses/show/:id is used to retrieve a single tweet object.
*/
public func getStatusesLookupTweetIDs(tweetIDs: [String], includeEntities: Bool? = nil, map: Bool? = nil, success: ((statuses: [JSONValue]?) -> Void)? = nil, failure: FailureHandler? = nil) {
let path = "statuses/lookup.json"
var parameters = Dictionary<String, AnyObject>()
parameters["id"] = tweetIDs.joinWithSeparator(",")
if includeEntities != nil {
parameters["include_entities"] = includeEntities!
}
if map != nil {
parameters["map"] = map!
}
self.getJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: {
json, response in
success?(statuses: json.array)
return
}, failure: failure)
}
}
|
mit
|
f93a9e47c857146010accf461bd8bbbf
| 45.101877 | 393 | 0.651431 | 4.577056 | false | false | false | false |
groue/GRDB.swift
|
GRDB/Utils/Pool.swift
|
1
|
6397
|
import Dispatch
/// A Pool maintains a set of elements that are built them on demand. A pool has
/// a maximum number of elements.
///
/// // A pool of 3 integers
/// var number = 0
/// let pool = Pool<Int>(maximumCount: 3, makeElement: {
/// number = number + 1
/// return number
/// })
///
/// The function get() dequeues an available element and gives this element to
/// the block argument. During the block execution, the element is not
/// available. When the block is ended, the element is available again.
///
/// // got 1
/// pool.get { n in
/// print("got \(n)")
/// }
///
/// If there is no available element, the pool builds a new element, unless the
/// maximum number of elements is reached. In this case, the get() method
/// blocks the current thread, until an element eventually turns available again.
///
/// DispatchQueue.concurrentPerform(iterations: 6) { _ in
/// pool.get { n in
/// print("got \(n)")
/// }
/// }
///
/// got 1
/// got 2
/// got 3
/// got 2
/// got 1
/// got 3
final class Pool<T> {
private class Item {
let element: T
var isAvailable: Bool
init(element: T, isAvailable: Bool) {
self.element = element
self.isAvailable = isAvailable
}
}
private let makeElement: () throws -> T
@ReadWriteBox private var items: [Item] = []
private let itemsSemaphore: DispatchSemaphore // limits the number of elements
private let itemsGroup: DispatchGroup // knows when no element is used
private let barrierQueue: DispatchQueue
private let semaphoreWaitingQueue: DispatchQueue // Inspired by https://khanlou.com/2016/04/the-GCD-handbook/
/// Creates a Pool.
///
/// - parameters:
/// - maximumCount: The maximum number of elements.
/// - qos: The quality of service of asynchronous accesses.
/// - makeElement: A function that creates an element. It is called
/// on demand.
init(
maximumCount: Int,
qos: DispatchQoS = .unspecified,
makeElement: @escaping () throws -> T)
{
GRDBPrecondition(maximumCount > 0, "Pool size must be at least 1")
self.makeElement = makeElement
self.itemsSemaphore = DispatchSemaphore(value: maximumCount)
self.itemsGroup = DispatchGroup()
self.barrierQueue = DispatchQueue(label: "GRDB.Pool.barrier", qos: qos, attributes: [.concurrent])
self.semaphoreWaitingQueue = DispatchQueue(label: "GRDB.Pool.wait", qos: qos)
}
/// Returns a tuple (element, release)
/// Client must call release(), only once, after the element has been used.
func get() throws -> (element: T, release: () -> Void) {
try barrierQueue.sync {
itemsSemaphore.wait()
itemsGroup.enter()
do {
let item = try $items.update { items -> Item in
if let item = items.first(where: \.isAvailable) {
item.isAvailable = false
return item
} else {
let element = try makeElement()
let item = Item(element: element, isAvailable: false)
items.append(item)
return item
}
}
return (element: item.element, release: { self.release(item) })
} catch {
itemsSemaphore.signal()
itemsGroup.leave()
throw error
}
}
}
/// Eventually produces a tuple (element, release), where element is
/// intended to be used asynchronously.
///
/// Client must call release(), only once, after the element has been used.
///
/// - important: The `execute` argument is executed in a serial dispatch
/// queue, so make sure you use the element asynchronously.
func asyncGet(_ execute: @escaping (Result<(element: T, release: () -> Void), Error>) -> Void) {
// Inspired by https://khanlou.com/2016/04/the-GCD-handbook/
// > We wait on the semaphore in the serial queue, which means that
// > we’ll have at most one blocked thread when we reach maximum
// > executing blocks on the concurrent queue. Any other tasks the user
// > enqueues will sit inertly on the serial queue waiting to be
// > executed, and won’t cause new threads to be started.
semaphoreWaitingQueue.async {
execute(Result { try self.get() })
}
}
/// Performs a synchronous block with an element. The element turns
/// available after the block has executed.
func get<U>(block: (T) throws -> U) throws -> U {
let (element, release) = try get()
defer { release() }
return try block(element)
}
private func release(_ item: Item) {
$items.update { _ in
// This is why Item is a class, not a struct: so that we can
// release it without having to find in it the items array.
item.isAvailable = true
}
itemsSemaphore.signal()
itemsGroup.leave()
}
/// Performs a block on each pool element, available or not.
/// The block is run is some arbitrary dispatch queue.
func forEach(_ body: (T) throws -> Void) rethrows {
try $items.read { items in
for item in items {
try body(item.element)
}
}
}
/// Removes all elements from the pool.
/// Currently used elements won't be reused.
func removeAll() {
items = []
}
/// Blocks until no element is used, and runs the `barrier` function before
/// any other element is dequeued.
func barrier<T>(execute barrier: () throws -> T) rethrows -> T {
try barrierQueue.sync(flags: [.barrier]) {
itemsGroup.wait()
return try barrier()
}
}
/// Asynchronously runs the `barrier` function when no element is used, and
/// before any other element is dequeued.
func asyncBarrier(execute barrier: @escaping () -> Void) {
barrierQueue.async(flags: [.barrier]) {
self.itemsGroup.wait()
barrier()
}
}
}
|
mit
|
b4d63b2a10a770891fb73e821d16e5eb
| 35.953757 | 113 | 0.573283 | 4.546942 | false | false | false | false |
vincentherrmann/multilinear-math
|
MultilinearMathTests/TensorOperationsTests.swift
|
1
|
11167
|
//
// TensorOperationsTests.swift
// MultilinearMath
//
// Created by Vincent Herrmann on 09.04.16.
// Copyright © 2016 Vincent Herrmann. All rights reserved.
//
import XCTest
import MultilinearMath
class TensorOperationsTests: XCTestCase {
var tensor1: Tensor<Float> = Tensor<Float>(scalar: 0)
var tensor2: Tensor<Float> = Tensor<Float>(scalar: 0)
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
// 0 1 2 3 12 13 14 15
// 4 5 6 7 16 17 18 19
// 8 9 10 11 20 21 22 23
tensor1 = Tensor<Float>(modeSizes: [2, 3, 4], values: Array(0..<24).map({return Float($0)}))
tensor2 = Tensor<Float>(modeSizes: [4, 5, 3], values: Array(0..<60).map({return Float($0)}))
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testTensorMultiplication() {
var t1 = Tensor<Float>(modeSizes: [2, 3], values: Array(0..<6).map({return Float($0)}))
var t2 = Tensor<Float>(modeSizes: [3, 4], values: Array(0..<12).map({return Float($0)}))
t1.indices = [.a, .b]
t2.indices = [.b, .c]
var product = t1*t2
var expectedProduct: [Float] = [20, 23, 26, 29, 56, 68, 80, 92]
XCTAssertEqual(product.values, expectedProduct, "product 2x3 * 3x4")
t1 = Tensor<Float>(modeSizes: [2, 2, 2], values: Array(0..<8).map({return Float($0)}))
t2 = Tensor<Float>(modeSizes: [2, 2, 2], values: Array(0..<8).map({return Float($0)}))
t1.indices = [.a, .b, .c]
t2.indices = [.c, .d, .e]
product = t1*t2
expectedProduct = [Float](repeating: 0, count: product.elementCount)
for a in 0...1 {
for b in 0...1 {
for d in 0...1 {
for e in 0...1 {
var sum: Float = 0
for c in 0...1 {
sum += t1[a, b, c] * t2[c, d, e]
}
expectedProduct[product.flatIndex([a, b, d, e])] = sum
}
}
}
}
XCTAssertEqual(product.values, expectedProduct, "product 2x2x2 * 2x2x2")
t1 = Tensor<Float>(modeSizes: [3, 3, 3], values: Array(0..<27).map({return Float($0)}))
t2 = Tensor<Float>(modeSizes: [3, 3, 3], values: Array(0..<27).map({return Float($0)}))
t1.indices = [.a, .b, .c]
t2.indices = [.b, .c, .d]
product = t1*t2
expectedProduct = [Float](repeating: 0, count: product.elementCount)
for a in 0...2 {
for d in 0...2 {
var sum: Float = 0
for b in 0...2 {
for c in 0...2 {
sum += t1[a, b, c] * t2[b, c, d]
}
}
expectedProduct[product.flatIndex([a, d])] = sum
}
}
XCTAssertEqual(product.values, expectedProduct, "product 3x3x3 * 3x3x3")
t1 = Tensor<Float>(modeSizes: [3, 3, 3], values: Array(0..<27).map({return Float($0)}))
t2 = Tensor<Float>(modeSizes: [3, 3, 3], values: Array(0..<27).map({return Float($0)}))
t1.indices = [.a, .b, .c]
t2.indices = [.c, .b, .d]
expectedProduct = [Float](repeating: 0, count: product.elementCount)
for a in 0...2 {
for d in 0...2 {
var sum: Float = 0
for b in 0...2 {
for c in 0...2 {
sum += t1[a, b, c] * t2[c, b, d]
}
}
expectedProduct[product.flatIndex([a, d])] = sum
}
}
product = t1*t2
XCTAssertEqual(product.values, expectedProduct, "product 3x3x3 * 3x3x3")
t1 = Tensor<Float>(modeSizes: [3, 3, 3], values: Array(0..<27).map({return Float($0)}))
t2 = Tensor<Float>(modeSizes: [3, 3, 3], values: Array(0..<27).map({return Float($0)}))
t1.indices = [.a, .b, .c]
t2.indices = [.d, .c, .b]
expectedProduct = [Float](repeating: 0, count: product.elementCount)
for a in 0...2 {
for d in 0...2 {
var sum: Float = 0
for b in 0...2 {
for c in 0...2 {
sum += t1[a, b, c] * t2[d, c, b]
}
}
expectedProduct[product.flatIndex([a, d])] = sum
}
}
product = t1*t2
XCTAssertEqual(product.values, expectedProduct, "product 3x3x3 * 3x3x3")
t1 = Tensor<Float>(modeSizes: [3, 3, 3], values: Array(0..<27).map({return Float($0)}))
t2 = Tensor<Float>(modeSizes: [3, 3, 3], values: Array(0..<27).map({return Float($0)}))
t1.indices = [.a, .b, .c]
t2.indices = [.c, .d, .b]
expectedProduct = [Float](repeating: 0, count: product.elementCount)
for a in 0...2 {
for d in 0...2 {
var sum: Float = 0
for b in 0...2 {
for c in 0...2 {
sum += t1[a, b, c] * t2[c, d, b]
}
}
expectedProduct[product.flatIndex([a, d])] = sum
}
}
product = t1*t2
XCTAssertEqual(product.values, expectedProduct, "product 3x3x3 * 3x3x3")
t1 = Tensor<Float>(modeSizes: [3, 3, 3, 3], values: Array(0..<81).map({return Float($0)}))
t2 = Tensor<Float>(modeSizes: [3, 3, 3, 3], values: Array(0..<81).map({return Float($0)}))
t1.indices = [.a, .b, .c, .d]
t2.indices = [.c, .d, .a, .e]
product = t1*t2
// t1 = Tensor<Float>(modeSizes: [3, 3, 3, 3], values: Array(0..<81).map({return Float($0)}))
// t2 = Tensor<Float>(modeSizes: [3, 3, 3, 3], values: Array(0..<81).map({return Float($0)}))
// t1.indexAs([.a, .b, .c, .d])
// t2.indexAs([.c, .d, .a, .e])
expectedProduct = [Float](repeating: 0, count: product.elementCount)
for b in 0...2 {
for e in 0...2 {
var sum: Float = 0
for a in 0...2 {
for c in 0...2 {
for d in 0...2 {
sum += t1[a, b, c, d] * t2[c, d, a, e]
}
}
}
expectedProduct[product.flatIndex([b, e])] = sum
}
}
XCTAssertEqual(product.values, expectedProduct, "product 3x3x3x3 * 3x3x3x3")
t1 = Tensor<Float>(modeSizes: [3, 3, 3, 3], values: Array(0..<81).map({return Float($0)}))
t2 = Tensor<Float>(modeSizes: [3, 3], values: Array(0..<9).map({return Float($0)}))
t1.indices = [.a, .b, .c, .d]
t2.indices = [.b, .e]
product = t1*t2
expectedProduct = [Float](repeating: 0, count: product.elementCount)
for a in 0...2 {
for c in 0...2 {
for d in 0...2 {
for e in 0...2 {
var sum: Float = 0
for b in 0...2 {
sum += t1[a, b, c, d] * t2[b, e]
}
expectedProduct[product.flatIndex([a, c, d, e])] = sum
}
}
}
}
XCTAssertEqual(product.values, expectedProduct, "product 3x3x3x3 * 3x3")
}
// func testTensorNormalization() {
// let originalValues = Array(0..<60).map({return Float($0)})
// var tensor = Tensor<Float>(modeSizes: [3, 4, 5], values: originalValues)
// tensor.indices = [.a, .b, .c]
//// let normalized1 = normalize(tensor, overModes: [1])
////
//// tensor = normalized1.normalizedTensor °* normalized1.standardDeviation
//// tensor = tensor + normalized1.mean
//// XCTAssert(squaredDistance(tensor.values, b: originalValues) < 50*0.001, "normalization over mode 1")
//
// tensor = Tensor<Float>(modeSizes: [3, 4, 5], values: originalValues)
// tensor.indices = [.a, .b, .c]
// let normalized = normalize(tensor, overModes: [0, 1, 2])
//
// tensor = normalized.normalizedTensor °* normalized.standardDeviation
// tensor = tensor + normalized.mean
// XCTAssert(squaredDistance(tensor.values, b: originalValues) < 50*0.001, "normalization over modes 0, 1 and 2")
// print("normalized: \(tensor.values)")
//
//// let normalizedConcurrent = normalizeConcurrent(tensor, overModes: [0, 1, 2])
////
//// tensor = normalizedConcurrent.normalizedTensor °* normalizedConcurrent.standardDeviation
//// tensor = tensor + normalized.mean
//// XCTAssert(squaredDistance(tensor.values, b: originalValues) < 50*0.001, "concurrent normalization over modes 0, 1 and 2")
//// print("normalizedConcurrent: \(tensor.values)")
// }
func testTensorModeSizesChange() {
let t1 = ones(5, 9)
let r1 = changeModeSizes(t1, targetSizes: [7, 10])
print("r1: \(r1.values)")
let r2 = changeModeSizes(t1, targetSizes: [4, 4])
print("r2: \(r2.values)")
let r3 = changeModeSizes(t1, targetSizes: [6, 2])
print("r3: \(r3.values)")
}
func testTensorSum() {
let sum1 = sum(tensor1, overModes: [0, 1, 2])
XCTAssertEqual(sum1.values, [276.0], "sum tensor1 over all modes")
let sum2 = sum(tensor1, overModes: [0, 2])
XCTAssertEqual(sum2.values, [60.0, 92.0, 124.0], "sum tensor1 over modes 0 and 2")
let sum3 = sum(tensor1, overModes: [1])
XCTAssertEqual(sum3.values, [12.0, 15.0, 18.0, 21.0, 48.0, 51.0, 54.0, 57.0], "sum tensor1 over mode 1")
}
func testTensorNormalization() {
let normalization1 = normalize(tensor1, overModes: [0, 1, 2])
let sum1 = sum(normalization1.normalizedTensor, overModes: [0, 1, 2])
XCTAssert(abs(sum1.values[0]) < 0.001, "normalize tensor1 over all modes")
}
func testTensorInverse() {
}
func testTensorOrdering() {
let reorderedMode0 = changeOrderOfModeIn(tensor1, mode: 0, newOrder: [1, 0])
XCTAssertEqual(reorderedMode0.values[2], 14.0, "reordered mode 0")
print("reordered values in mode 0: \(reorderedMode0.values)")
let reorderedMode1 = changeOrderOfModeIn(tensor1, mode: 1, newOrder: [2, 0, 1])
XCTAssertEqual(reorderedMode1.values[2], 10.0, "reordered mode 1")
print("reordered values in mode 1: \(reorderedMode1.values)")
let reorderedMode2 = changeOrderOfModeIn(tensor1, mode: 2, newOrder: [2, 0, 1, 3])
XCTAssertEqual(reorderedMode2.values[2], 1.0, "reordered mode 2")
print("reordered values in mode 2: \(reorderedMode2.values)")
}
}
|
apache-2.0
|
ef9f5be5945f495646f4b669ec31d6e1
| 41.60687 | 133 | 0.503986 | 3.496085 | false | false | false | false |
onevcat/CotEditor
|
CotEditor/Sources/FindPanelFieldViewController.swift
|
1
|
11102
|
//
// FindPanelFieldViewController.swift
//
// CotEditor
// https://coteditor.com
//
// Created by 1024jp on 2016-06-26.
//
// ---------------------------------------------------------------------------
//
// © 2014-2022 1024jp
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Combine
import Cocoa
import SwiftUI
final class FindPanelFieldViewController: NSViewController, NSTextViewDelegate {
// MARK: Private Properties
private lazy var regularExpressionReferenceViewController: NSViewController = {
let controller = DetachablePopoverViewController()
controller.view = NSHostingView(rootView: RegularExpressionReferenceView())
return controller
}()
@objc private dynamic let textFinder = TextFinder.shared
private var scrollerStyleObserver: AnyCancellable?
private var defaultsObservers: Set<AnyCancellable> = []
private var resultClosingTrigerObserver: AnyCancellable?
@IBOutlet private weak var findTextView: RegexFindPanelTextView?
@IBOutlet private weak var replacementTextView: RegexFindPanelTextView?
@IBOutlet private weak var findHistoryMenu: NSMenu?
@IBOutlet private weak var replaceHistoryMenu: NSMenu?
@IBOutlet private weak var findResultField: NSTextField?
@IBOutlet private weak var replacementResultField: NSTextField?
@IBOutlet private weak var findClearButtonConstraint: NSLayoutConstraint?
@IBOutlet private weak var replacementClearButtonConstraint: NSLayoutConstraint?
// MARK: -
// MARK: View Controller Methods
/// setup UI
override func viewDidLoad() {
super.viewDidLoad()
// adjust clear button position according to the visiblity of scroller area
let scroller = self.findTextView?.enclosingScrollView?.verticalScroller
self.scrollerStyleObserver = scroller?.publisher(for: \.scrollerStyle, options: .initial)
.sink { [weak self, weak scroller] (scrollerStyle) in
var inset = 5.0
if scrollerStyle == .legacy, let scroller = scroller {
inset += scroller.thickness
}
self?.findClearButtonConstraint?.constant = -inset
self?.replacementClearButtonConstraint?.constant = -inset
}
self.defaultsObservers = [
// sync history menus with user default
UserDefaults.standard.publisher(for: .findHistory, initial: true)
.sink { [unowned self] _ in self.updateFindHistoryMenu() },
UserDefaults.standard.publisher(for: .replaceHistory, initial: true)
.sink { [unowned self] _ in self.updateReplaceHistoryMenu() },
// sync text view states with user default
UserDefaults.standard.publisher(for: .findUsesRegularExpression, initial: true)
.sink { [unowned self] (value) in
self.findTextView?.isRegularExpressionMode = value
self.replacementTextView?.isRegularExpressionMode = value
},
UserDefaults.standard.publisher(for: .findRegexUnescapesReplacementString, initial: true)
.sink { [unowned self] (value) in
self.replacementTextView?.parseMode = .replacement(unescapes: value)
}
]
}
/// make find field initial first responder
override func viewWillAppear() {
super.viewWillAppear()
// make find text view the initial first responder to focus it on showWindow(_:)
self.view.window?.initialFirstResponder = self.findTextView
}
// MARK: Text View Delegate
/// find string did change
func textDidChange(_ notification: Notification) {
guard let textView = notification.object as? NSTextView else { return assertionFailure() }
switch textView {
case self.findTextView!:
self.clearNumberOfReplaced()
self.clearNumberOfFound()
case self.replacementTextView!:
self.clearNumberOfReplaced()
default:
break
}
}
// MARK: Action Messages
/// set selected history string to find field
@IBAction func selectFindHistory(_ sender: NSMenuItem?) {
guard
let string = sender?.representedObject as? String,
let textView = self.findTextView,
textView.shouldChangeText(in: textView.string.nsRange, replacementString: string)
else { return }
textView.string = string
textView.didChangeText()
}
/// set selected history string to replacement field
@IBAction func selectReplaceHistory(_ sender: NSMenuItem?) {
guard
let string = sender?.representedObject as? String,
let textView = self.replacementTextView,
textView.shouldChangeText(in: textView.string.nsRange, replacementString: string)
else { return }
textView.string = string
textView.didChangeText()
}
/// restore find history via UI
@IBAction func clearFindHistory(_ sender: Any?) {
self.view.window?.makeKeyAndOrderFront(self)
UserDefaults.standard.removeObject(forKey: DefaultKeys.findHistory.rawValue)
self.updateFindHistoryMenu()
}
/// restore replace history via UI
@IBAction func clearReplaceHistory(_ sender: Any?) {
self.view.window?.makeKeyAndOrderFront(self)
UserDefaults.standard.removeObject(forKey: DefaultKeys.replaceHistory.rawValue)
self.updateReplaceHistoryMenu()
}
@IBAction func showRegularExpressionReference(_ sender: NSButton) {
guard self.regularExpressionReferenceViewController.presentingViewController == nil else { return }
self.present(self.regularExpressionReferenceViewController, asPopoverRelativeTo: sender.bounds, of: sender, preferredEdge: .maxY, behavior: .transient)
}
// MARK: Public Methods
/// receive number of found
func updateResultCount(_ numberOfFound: Int, target: NSTextView) {
self.clearNumberOfFound()
let message: String = {
switch numberOfFound {
case ..<0:
return "Not Found".localized
default:
return String(format: "%i found".localized, locale: .current, numberOfFound)
}
}()
self.applyResult(message: message, textField: self.findResultField!, textView: self.findTextView!)
self.resultClosingTrigerObserver = Publishers.Merge(
NotificationCenter.default.publisher(for: NSTextStorage.didProcessEditingNotification, object: target.textStorage),
NotificationCenter.default.publisher(for: NSWindow.willCloseNotification, object: target.window))
.sink { [weak self] _ in self?.clearNumberOfFound() }
}
/// receive number of replaced
func updateReplacedCount(_ numberOfReplaced: Int, target: NSTextView) {
self.clearNumberOfReplaced()
let message: String = {
switch numberOfReplaced {
case ..<0:
return "Not Replaced".localized
default:
return String(format: "%i replaced".localized, locale: .current, numberOfReplaced)
}
}()
self.applyResult(message: message, textField: self.replacementResultField!, textView: self.replacementTextView!)
// feedback for VoiceOver
if let window = NSApp.mainWindow {
NSAccessibility.post(element: window, notification: .announcementRequested, userInfo: [.announcement: message])
}
}
// MARK: Private Methods
/// update find history menu
private func updateFindHistoryMenu() {
self.buildHistoryMenu(self.findHistoryMenu!, defaultsKey: .findHistory, action: #selector(selectFindHistory))
}
/// update replace history menu
private func updateReplaceHistoryMenu() {
self.buildHistoryMenu(self.replaceHistoryMenu!, defaultsKey: .replaceHistory, action: #selector(selectReplaceHistory))
}
/// apply history to UI
private func buildHistoryMenu(_ menu: NSMenu, defaultsKey key: DefaultKey<[String]>, action: Selector) {
assert(Thread.isMainThread)
// clear current history items
menu.items
.filter { $0.action == action || $0.isSeparatorItem }
.forEach { menu.removeItem($0) }
let history = UserDefaults.standard[key]
guard !history.isEmpty else { return }
menu.insertItem(NSMenuItem.separator(), at: 2) // the first item is invisible dummy
for string in history {
let title = (string.count <= 64) ? string : (String(string.prefix(64)) + "…")
let item = NSMenuItem(title: title, action: action, keyEquivalent: "")
item.representedObject = string
item.toolTip = string
item.target = self
menu.insertItem(item, at: 2)
}
}
/// number of found in find string field becomes no more valid
private func clearNumberOfFound() {
self.applyResult(message: nil, textField: self.findResultField!, textView: self.findTextView!)
self.resultClosingTrigerObserver = nil
}
/// number of replaced in replacement string field becomes no more valid
private func clearNumberOfReplaced(_ notification: Notification? = nil) {
self.applyResult(message: nil, textField: self.replacementResultField!, textView: self.replacementTextView!)
}
/// apply message to UI
private func applyResult(message: String?, textField: NSTextField, textView: NSTextView) {
textField.isHidden = (message == nil)
textField.stringValue = message ?? ""
textField.sizeToFit()
// add extra scroll margin to the right side of the textView, so that entire input can be read
textView.enclosingScrollView?.contentView.contentInsets.right = textField.frame.width
}
}
|
apache-2.0
|
aedf884a6029254352f180e9b0b783c6
| 35.035714 | 159 | 0.625011 | 5.361836 | false | false | false | false |
Piwigo/Piwigo-Mobile
|
piwigo/Settings/Albums/DefaultAlbumThumbnailSizeViewController.swift
|
1
|
13521
|
//
// DefaultAlbumThumbnailSizeViewController.swift
// piwigo
//
// Created by Eddy Lelièvre-Berna on 14/08/2019.
// Copyright © 2019 Piwigo.org. All rights reserved.
//
// Converted to Swift 5 by Eddy Lelièvre-Berna on 07/04/2020.
//
import UIKit
import piwigoKit
protocol DefaultAlbumThumbnailSizeDelegate: NSObjectProtocol {
func didSelectAlbumDefaultThumbnailSize(_ thumbnailSize: kPiwigoImageSize)
}
class DefaultAlbumThumbnailSizeViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
weak var delegate: DefaultAlbumThumbnailSizeDelegate?
private var currentThumbnailSize = kPiwigoImageSize(AlbumVars.shared.defaultAlbumThumbnailSize)
@IBOutlet var tableView: UITableView!
// MARK: - View Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
title = NSLocalizedString("tabBar_albums", comment: "Albums")
// Set colors, fonts, etc.
applyColorPalette()
}
@objc func applyColorPalette() {
// Background color of the view
view.backgroundColor = .piwigoColorBackground()
// Navigation bar
let attributes = [
NSAttributedString.Key.foregroundColor: UIColor.piwigoColorWhiteCream(),
NSAttributedString.Key.font: UIFont.piwigoFontNormal()
]
navigationController?.navigationBar.titleTextAttributes = attributes
if #available(iOS 11.0, *) {
navigationController?.navigationBar.prefersLargeTitles = false
}
navigationController?.navigationBar.barStyle = AppVars.shared.isDarkPaletteActive ? .black : .default
navigationController?.navigationBar.tintColor = .piwigoColorOrange()
navigationController?.navigationBar.barTintColor = .piwigoColorBackground()
navigationController?.navigationBar.backgroundColor = .piwigoColorBackground()
if #available(iOS 15.0, *) {
/// In iOS 15, UIKit has extended the usage of the scrollEdgeAppearance,
/// which by default produces a transparent background, to all navigation bars.
let barAppearance = UINavigationBarAppearance()
barAppearance.configureWithOpaqueBackground()
barAppearance.backgroundColor = .piwigoColorBackground()
navigationController?.navigationBar.standardAppearance = barAppearance
navigationController?.navigationBar.scrollEdgeAppearance = navigationController?.navigationBar.standardAppearance
}
// Table view
tableView.separatorColor = .piwigoColorSeparator()
tableView.indicatorStyle = AppVars.shared.isDarkPaletteActive ? .white : .black
tableView.reloadData()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// Register palette changes
NotificationCenter.default.addObserver(self, selector: #selector(applyColorPalette),
name: .pwgPaletteChanged, object: nil)
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
// Return selected album thumbnail size
delegate?.didSelectAlbumDefaultThumbnailSize(currentThumbnailSize)
}
deinit {
// Unregister palette changes
NotificationCenter.default.removeObserver(self, name: .pwgPaletteChanged, object: nil)
}
// MARK: - UITableView - Header
private func getContentOfHeader() -> (String, String) {
let title = String(format: "%@\n", NSLocalizedString("defaultAlbumThumbnailFile>414px", comment: "Albums Thumbnail File"))
let text = NSLocalizedString("defaultAlbumThumbnailSizeHeader", comment: "Please select an album thumbnail size")
return (title, text)
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
let (title, text) = getContentOfHeader()
return TableViewUtilities.shared.heightOfHeader(withTitle: title, text: text,
width: tableView.frame.size.width)
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let (title, text) = getContentOfHeader()
return TableViewUtilities.shared.viewOfHeader(withTitle: title, text: text)
}
// MARK: - UITableView - Rows
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return Int(kPiwigoImageSizeEnumCount.rawValue)
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 44.0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
let imageSize = kPiwigoImageSize(UInt32(indexPath.row))
// Name of the thumbnail size
cell.backgroundColor = .piwigoColorCellBackground()
cell.tintColor = .piwigoColorOrange()
cell.textLabel?.font = .piwigoFontNormal()
cell.textLabel?.textColor = .piwigoColorLeftLabel()
cell.textLabel?.adjustsFontSizeToFitWidth = false
// Add checkmark in front of selected item
if imageSize == currentThumbnailSize {
cell.accessoryType = .checkmark
} else {
cell.accessoryType = .none
}
// Disable unavailable and useless sizes
switch imageSize {
case kPiwigoImageSizeSquare:
if AlbumVars.shared.hasSquareSizeImages {
cell.isUserInteractionEnabled = true
cell.textLabel?.text = PiwigoImageData.name(forAlbumThumbnailSizeType: imageSize, withInfo: true)
} else {
cell.isUserInteractionEnabled = false
cell.textLabel?.textColor = .piwigoColorRightLabel()
cell.textLabel?.text = PiwigoImageData.name(forAlbumThumbnailSizeType: imageSize, withInfo: false)
cell.textLabel?.text = cell.textLabel?.text ?? "" + (NSLocalizedString("defaultSize_disabled", comment: " (disabled on server)"))
}
case kPiwigoImageSizeThumb:
if AlbumVars.shared.hasThumbSizeImages {
cell.isUserInteractionEnabled = true
cell.textLabel?.text = PiwigoImageData.name(forAlbumThumbnailSizeType: imageSize, withInfo: true)
} else {
cell.isUserInteractionEnabled = false
cell.textLabel?.textColor = .piwigoColorRightLabel()
cell.textLabel?.text = PiwigoImageData.name(forAlbumThumbnailSizeType: imageSize, withInfo: false)
cell.textLabel?.text = cell.textLabel?.text ?? "" + (NSLocalizedString("defaultSize_disabled", comment: " (disabled on server)"))
}
case kPiwigoImageSizeXXSmall:
if AlbumVars.shared.hasXXSmallSizeImages {
cell.isUserInteractionEnabled = true
cell.textLabel?.text = PiwigoImageData.name(forAlbumThumbnailSizeType: imageSize, withInfo: true)
} else {
cell.isUserInteractionEnabled = false
cell.textLabel?.textColor = .piwigoColorRightLabel()
cell.textLabel?.text = PiwigoImageData.name(forAlbumThumbnailSizeType: imageSize, withInfo: false)
cell.textLabel?.text = cell.textLabel?.text ?? "" + (NSLocalizedString("defaultSize_disabled", comment: " (disabled on server)"))
}
case kPiwigoImageSizeXSmall:
if AlbumVars.shared.hasXSmallSizeImages {
cell.isUserInteractionEnabled = true
cell.textLabel?.text = PiwigoImageData.name(forAlbumThumbnailSizeType: imageSize, withInfo: true)
} else {
cell.isUserInteractionEnabled = false
cell.textLabel?.textColor = .piwigoColorRightLabel()
cell.textLabel?.text = PiwigoImageData.name(forAlbumThumbnailSizeType: imageSize, withInfo: false)
cell.textLabel?.text = cell.textLabel?.text ?? "" + (NSLocalizedString("defaultSize_disabled", comment: " (disabled on server)"))
}
case kPiwigoImageSizeSmall:
if AlbumVars.shared.hasSmallSizeImages {
cell.isUserInteractionEnabled = true
cell.textLabel?.text = PiwigoImageData.name(forAlbumThumbnailSizeType: imageSize, withInfo: true)
} else {
cell.isUserInteractionEnabled = false
cell.textLabel?.textColor = .piwigoColorRightLabel()
cell.textLabel?.text = PiwigoImageData.name(forAlbumThumbnailSizeType: imageSize, withInfo: false)
cell.textLabel?.text = cell.textLabel?.text ?? "" + (NSLocalizedString("defaultSize_disabled", comment: " (disabled on server)"))
}
case kPiwigoImageSizeMedium:
if AlbumVars.shared.hasMediumSizeImages {
cell.isUserInteractionEnabled = true
cell.textLabel?.text = PiwigoImageData.name(forAlbumThumbnailSizeType: imageSize, withInfo: true)
} else {
cell.isUserInteractionEnabled = false
cell.textLabel?.textColor = .piwigoColorRightLabel()
cell.textLabel?.text = PiwigoImageData.name(forAlbumThumbnailSizeType: imageSize, withInfo: false)
cell.textLabel?.text = cell.textLabel?.text ?? "" + (NSLocalizedString("defaultSize_disabled", comment: " (disabled on server)"))
}
case kPiwigoImageSizeLarge:
cell.isUserInteractionEnabled = false
cell.textLabel?.textColor = .piwigoColorRightLabel()
if !AlbumVars.shared.hasLargeSizeImages {
cell.textLabel?.text = PiwigoImageData.name(forAlbumThumbnailSizeType: imageSize, withInfo: false)
cell.textLabel?.text = cell.textLabel?.text ?? "" + (NSLocalizedString("defaultSize_disabled", comment: " (disabled on server)"))
} else {
cell.textLabel?.text = PiwigoImageData.name(forAlbumThumbnailSizeType: imageSize, withInfo: true)
}
case kPiwigoImageSizeXLarge:
cell.isUserInteractionEnabled = false
cell.textLabel?.textColor = .piwigoColorRightLabel()
if !AlbumVars.shared.hasXLargeSizeImages {
cell.textLabel?.text = PiwigoImageData.name(forAlbumThumbnailSizeType: imageSize, withInfo: false)
cell.textLabel?.text = cell.textLabel?.text ?? "" + (NSLocalizedString("defaultSize_disabled", comment: " (disabled on server)"))
} else {
cell.textLabel?.text = PiwigoImageData.name(forAlbumThumbnailSizeType: imageSize, withInfo: true)
}
case kPiwigoImageSizeXXLarge:
cell.isUserInteractionEnabled = false
cell.textLabel?.textColor = .piwigoColorRightLabel()
if !AlbumVars.shared.hasXXLargeSizeImages {
cell.textLabel?.text = PiwigoImageData.name(forAlbumThumbnailSizeType: imageSize, withInfo: false)
cell.textLabel?.text = cell.textLabel?.text ?? "" + (NSLocalizedString("defaultSize_disabled", comment: " (disabled on server)"))
} else {
cell.textLabel?.text = PiwigoImageData.name(forAlbumThumbnailSizeType: imageSize, withInfo: true)
}
case kPiwigoImageSizeFullRes:
cell.isUserInteractionEnabled = false
cell.textLabel?.textColor = .piwigoColorRightLabel()
cell.textLabel?.text = PiwigoImageData.name(forAlbumThumbnailSizeType: imageSize, withInfo: true)
default:
break
}
return cell
}
// MARK: - UITableView - Footer
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
let footer = NSLocalizedString("defaultSizeFooter", comment: "Greyed sizes are not advised or not available on Piwigo server.")
return TableViewUtilities.shared.heightOfFooter(withText: footer, width: tableView.frame.width)
}
func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
let footer = NSLocalizedString("defaultSizeFooter", comment: "Greyed sizes are not advised or not available on Piwigo server.")
return TableViewUtilities.shared.viewOfFooter(withText: footer, alignment: .center)
}
// MARK: - UITableViewDelegate Methods
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
// Did the user change of default size
if kPiwigoImageSize(UInt32(indexPath.row)) == currentThumbnailSize { return }
// Update default size
tableView.cellForRow(at: IndexPath(row: Int(currentThumbnailSize.rawValue), section: 0))?.accessoryType = .none
currentThumbnailSize = kPiwigoImageSize(UInt32(indexPath.row))
tableView.cellForRow(at: indexPath)?.accessoryType = .checkmark
}
}
|
mit
|
8d0f90341e46e8b75847dd082dd92dad
| 49.629213 | 149 | 0.647655 | 5.595199 | false | false | false | false |
toshiapp/toshi-ios-client
|
Toshi/Controllers/Settings/DepositMoney/DepositMoneyBulletPoint.swift
|
1
|
1857
|
// Copyright (c) 2018 Token Browser, Inc
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
import UIKit
import TinyConstraints
class DepositMoneyBulletPoint: UIView {
private lazy var titleLabel: UILabel = {
let view = UILabel()
view.font = Theme.preferredSemibold()
view.textColor = Theme.darkTextColor
view.numberOfLines = 0
view.adjustsFontForContentSizeCategory = true
return view
}()
private lazy var textLabel: UILabel = {
let view = UILabel()
view.font = Theme.preferredRegular()
view.textColor = Theme.darkTextColor
view.numberOfLines = 0
view.adjustsFontForContentSizeCategory = true
return view
}()
convenience init(title: String, text: String) {
self.init()
titleLabel.text = title
addSubview(titleLabel)
textLabel.text = text
addSubview(textLabel)
titleLabel.top(to: self, offset: 15)
titleLabel.left(to: self, offset: 15)
titleLabel.right(to: self, offset: -15)
textLabel.topToBottom(of: titleLabel, offset: 5)
textLabel.left(to: self, offset: 15)
textLabel.right(to: self, offset: -15)
textLabel.bottom(to: self)
}
}
|
gpl-3.0
|
e87617e2323fa4dd1220774ec9ac577f
| 30.474576 | 72 | 0.671513 | 4.496368 | false | false | false | false |
takebayashi/swiftra
|
Sources/Router.swift
|
1
|
2042
|
/*
The MIT License (MIT)
Copyright (c) 2015 Shun Takebayashi
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
public typealias Handler = (Request) -> (ResponseSource)
class Router {
static let sharedRouter = Router()
var patterns = [(String, Matcher, Handler)]()
func addPattern(method method: String, pattern: Matcher, handler: Handler) {
patterns.append((method, pattern, handler))
}
func dispatch(request: Request) -> Response? {
for entry in patterns {
if entry.0 == request.method {
if let result = entry.1.match(request.path) {
if result.params.count > 0 {
let wrapped = ParameterizedRequest(
underlying: request,
parameters: result.params
)
return entry.2(wrapped).response()
}
return entry.2(request).response()
}
}
}
return nil
}
}
|
mit
|
fe1295448b9af53a16df44728dac9612
| 37.528302 | 80 | 0.653771 | 4.992665 | false | false | false | false |
konanxu/WeiBoWithSwift
|
WeiBo/WeiBo/AppDelegate.swift
|
1
|
2592
|
//
// AppDelegate.swift
// WeiBo
//
// Created by Konan on 16/3/8.
// Copyright © 2016年 Konan. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// NSUserDefaults.standardUserDefaults().setValue((UserAccount.loadAccount()) != nil ? true : false, forKeyPath: "isLogin")
//
//
// NSUserDefaults.standardUserDefaults().synchronize()
//
window = UIWindow(frame: UIScreen.mainScreen().bounds)
window?.rootViewController = MainViewController()
window?.makeKeyAndVisible()
UINavigationBar.appearance().tintColor = UIColor.orangeColor()
UITabBar.appearance().tintColor = UIColor.orangeColor()
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
|
mit
|
75b24828e95d4d54f055aabda7218ec8
| 44.421053 | 285 | 0.73117 | 5.555794 | false | false | false | false |
mrchenhao/American-TV-Series-Calendar
|
American-tv-series-calendar/EKManager.swift
|
1
|
3990
|
//
// EKManager.swift
// American-tv-series-calendar
//
// Created by ChenHao on 10/26/15.
// Copyright © 2015 HarriesChen. All rights reserved.
//
import UIKit
import EventKit
class EKManager {
static let sharedInstance = EKManager()
var store: EKEventStore = EKEventStore()
private init() {}
func addEventToCalendar(event: EKEvent) {
do {
try store.saveEvent(event, span: EKSpan.ThisEvent, commit: true)
} catch {
}
}
func getCalendars() ->Array<EKCalendar> {
let calendars = store.calendarsForEntityType(EKEntityType.Event)
return calendars
}
func getDefaultCalendar() -> EKCalendar {
return store.defaultCalendarForNewEvents
}
func getCalendarByIdentifer(identifer: String) -> EKCalendar {
return store.calendarWithIdentifier(identifer)!
}
func addEventToDefauCalendarWithMovie(episode: Episode) -> Bool {
let event: EKEvent = EKEvent(eventStore: store)
event.title = String(format: "%@", arguments: [episode.name])
event.startDate = episode.startTime
event.endDate = episode.endTime
event.calendar = getDefaultCalendar()
do {
try store.saveEvent(event, span: EKSpan.ThisEvent, commit: true)
} catch {
return false
}
return true
}
func addAllEventsToDefaultCalendarWitMovies(movie: Movie) -> Bool {
for var i = 1;i <= movie.total.integerValue; i++ {
let dateOffet: NSTimeInterval = (Double(i-1)*7*60.0*60*24)
let date:NSDate = movie.startDate.dateByAddingTimeInterval(dateOffet)
let episode: Episode = Episode(name: String(format: "%@ S%02dE%02d", arguments: [movie.name, movie.season.integerValue, i]), date: date)
addEventToDefauCalendarWithMovie(episode)
}
return true
}
func addMovieEventWithTitle(title: String, date:NSDate) {
for calendar in getCalendars() {
if calendar.title == title {
let event: EKEvent = EKEvent(eventStore: store)
event.title = title
event.startDate = date.dateByAddingTimeInterval(300.0)
event.endDate = date.dateByAddingTimeInterval(600.0)
event.calendar = calendar
do {
try store.saveEvent(event, span: EKSpan.ThisEvent, commit: true)
} catch {
}
}
}
}
func removeEventWithEventIdentifer(identifer: String) {
if let event = store.eventWithIdentifier(identifer) {
do {
try store.removeEvent(event, span: .ThisEvent, commit: true)
} catch {
}
}
}
/**
从默认的日历中拉取所有事件
- parameter startDate: 开始时间
- parameter endDate: 结束时间
- returns: 事件数组
*/
func fetchEvevtFromDefaultCalendarsBetweenDates(startDate:NSDate, endDate:NSDate) -> [EKEvent] {
let predicate: NSPredicate = store.predicateForEventsWithStartDate(startDate, endDate: endDate, calendars: [getDefaultCalendar()])
return store.eventsMatchingPredicate(predicate)
}
/**
拉取特定日历特定时间范围内的的事件
- parameter calendarIdentifer: 日历名称
- parameter startDate: 开始时间
- parameter endDate: 结束时间
- returns: 事件数组
*/
func fetchEvevtFromCalendarsBetweenDates(calendarIdentifer: String, startDate:NSDate, endDate:NSDate) -> [EKEvent] {
let predicate: NSPredicate = store.predicateForEventsWithStartDate(startDate, endDate: endDate, calendars: [store.calendarWithIdentifier(calendarIdentifer)!])
return store.eventsMatchingPredicate(predicate)
}
}
|
mit
|
fc090fb310557409972349ed07400025
| 30.745902 | 166 | 0.604699 | 4.66065 | false | false | false | false |
iAugux/Weboot
|
Weboot/UITextView+Additions.swift
|
1
|
1687
|
//
// UITextView+Additions.swift
// iBBS
//
// Created by Augus on 9/8/15.
//
// http://iAugus.com
// https://github.com/iAugux
//
// Copyright © 2015 iAugus. All rights reserved.
//
import Foundation
extension UITextView {
/**
Methods to allow using HTML code with CoreText
*/
func ausAttributedText(data: String) {
do {
let formatedData = data.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
let text = try NSAttributedString(data: formatedData.dataUsingEncoding(NSUnicodeStringEncoding,allowLossyConversion: false)!,
options: [ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
documentAttributes: nil)
self.attributedText = text
}catch{
print("something error with NSAttributedString")
}
}
/**
calculate size of UITextView
:returns: CGSize
*/
func ausReturnFrameSizeAfterResizingTextView() -> CGSize{
let fixedWidth = self.frame.size.width
self.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat.max))
let newSize = self.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat.max))
var newFrame = self.frame
newFrame.size = CGSize(width: max(newSize.width, fixedWidth), height: newSize.height)
self.frame = newFrame
return self.frame.size
}
}
func AusTextViewSizeForAttributedText(text: String) -> CGSize {
let calculationView = UITextView()
calculationView.ausAttributedText(text)
let size = calculationView.sizeThatFits(CGSizeMake(CGFloat.max, CGFloat.max))
return size
}
|
mit
|
4033fdc9b3c8932c2bd59256f112db93
| 28.068966 | 137 | 0.66726 | 4.683333 | false | false | false | false |
VirgilSecurity/virgil-sdk-pfs-x
|
Source/Client/Networking/Requests/PFS/OtcCountHTTPRequest.swift
|
1
|
1035
|
//
// OtcCountHTTPRequest.swift
// VirgilSDKPFS
//
// Created by Oleksandr Deundiak on 6/15/17.
// Copyright © 2017 VirgilSecurity. All rights reserved.
//
import Foundation
import VirgilSDK
class OtcCountHTTPRequest: PFSBaseHTTPRequest {
let recipientId: String
private(set) var otcCountResponse: OtcCountResponse?
init(context: VSSHTTPRequestContext, recipientId: String) {
self.recipientId = recipientId
super.init(context: context)
}
override var methodPath: String {
return "recipient/" + self.recipientId + "/actions/count-otcs"
}
override func handleResponse(_ candidate: NSObject?) -> Error? {
guard let candidate = candidate else {
return nil
}
let error = super.handleResponse(candidate)
guard error == nil else {
return error
}
self.otcCountResponse = OtcCountResponse(dictionary: candidate)
return nil
}
}
|
bsd-3-clause
|
37b92a96bfb8c42395ba2b883897b50c
| 23.046512 | 71 | 0.616054 | 4.657658 | false | false | false | false |
thelukester92/swift-engine
|
swift-engine/Engine/Classes/LGTMXParser.swift
|
1
|
8416
|
//
// LGTMXParser.swift
// swift-engine
//
// Created by Luke Godfrey on 6/24/14.
// Copyright (c) 2014 Luke Godfrey. See LICENSE.
//
import UIKit
public class LGTMXParser: NSObject
{
let firstBackgroundLayer = -100
let firstForegroundLayer = 100
// Setup variables
var collisionLayerName = "collision"
var foregroundLayerName = "foreground"
// Variables that may be retrieved after parsing
public var map: LGTileMap!
public var collisionLayer: LGTileLayer!
public var objects = [LGTMXObject]()
// Variables for parsing
var currentLayer: LGTileLayer!
var currentObject: LGTMXObject!
var currentRenderLayer: Int
var currentElement = ""
var currentData = ""
var currentEncoding = ""
var currentCompression = ""
var currentPropName = ""
public override init()
{
currentRenderLayer = firstBackgroundLayer
}
public convenience init(filename: String, filetype: String = "tmx")
{
self.init()
parseFile(filename, filetype: filetype)
}
public func addMapToTileSystem(system: LGTileSystem)
{
if map != nil
{
system.map = map
}
}
public func addCollisionLayerToPhysicsSystem(system: LGPhysicsSystem)
{
if collisionLayer != nil
{
system.collisionLayer = collisionLayer
}
}
public func addObjectsToScene(scene: LGScene)
{
for object in objects
{
let entity = LGEntity.EntityFromTemplate(object.type)? ?? LGEntity()
entity.put(component: LGPosition(x: Double(object.x), y: Double(map.height * map.tileHeight) - Double(object.y + object.height)))
// Properties unique to the entity
for (type, serialized) in object.properties
{
if let component = LGDeserializer.deserialize(serialized, withType: type)
{
entity.put(component: component)
}
else
{
println("WARNING: Failed to deserialize a component of type '\(type)'")
}
}
// Trigger, if not already a physics object
if !entity.has(LGPhysicsBody) && object.width > 0 && object.height > 0
{
let body = LGPhysicsBody(width: Double(object.width), height: Double(object.height), dynamic: false)
body.trigger = true
entity.put(component: body)
}
scene.addEntity(entity, named: object.name)
}
}
public func parseFile(filename: String, filetype: String = "tmx")
{
let parser = NSXMLParser(contentsOfURL: NSBundle.mainBundle().URLForResource(filename, withExtension: filetype))!
parser.delegate = self
parser.parse()
}
private func parseString(string: String, encoding: String, compression: String) -> [[LGTile]]
{
assert(encoding == "csv" || encoding == "base64", "Encoding must be csv or base64!")
assert(encoding != "csv" || compression == "", "csv-encoded strings cannot be compressed!")
assert(compression == "", "Compression is not yet supported!")
// TODO: add support for compression (probably zlib)
if encoding == "csv"
{
// uncompressed csv
let arr = string.componentsSeparatedByString(",")
assert(arr.count == map.width * map.height)
return parseArray(arr)
}
/* else if compression == "zlib"
{
// zlib compressed base64
var uncompressedBuffer = [UInt8](count: Int(width * height * 4), repeatedValue: 0)
var uncompressedLength: Int!
let data = NSData(base64EncodedString: string, options: .Encoding64CharacterLineLength)
let result = uncompress(&uncompressedBuffer, &uncompressedLength, data.bytes, data.length)
assert(result == Z_OK)
assert(uncompressedLength == width * height * 4)
return parseData(uncompressedBuffer)
} */
else
{
// uncompressed base64
let data = NSData(base64EncodedString: string, options: .IgnoreUnknownCharacters)!
assert(data.length == map.width * map.height * 4)
var bytes = [UInt8](count: data.length, repeatedValue: 0)
data.getBytes(&bytes, length: data.length)
return parseData(bytes)
}
}
private func parseArray(data: [String]) -> [[LGTile]]
{
var output = [[LGTile]]()
for i in 0 ..< map.height
{
output.append([LGTile]())
for j in 0 ..< map.width
{
let globalIdString = data[i * map.width + j].stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
let globalId: UInt32 = NSNumberFormatter().numberFromString(globalIdString)!.unsignedIntValue
output[i].append(LGTile(gid: globalId))
}
}
return output
}
private func parseData(data: [UInt8]) -> [[LGTile]]
{
var output = [[LGTile]]()
var byteIndex = 0
for i in 0 ..< map.height
{
output.append([LGTile]())
for _ in 0 ..< map.width
{
let globalId = UInt32(data[byteIndex++] | data[byteIndex++] << 8 | data[byteIndex++] << 16 | data[byteIndex++] << 24)
output[i].append(LGTile(gid: globalId))
}
}
return output
}
}
extension LGTMXParser: NSXMLParserDelegate
{
public func parser(parser: NSXMLParser!, didStartElement elementName: String!, namespaceURI: String!, qualifiedName: String!, attributes: NSDictionary!)
{
switch elementName.lowercaseString
{
case "map":
map = LGTileMap(width: attributes["width"]!.integerValue, height: attributes["height"]!.integerValue, tileWidth: attributes["tilewidth"]!.integerValue, tileHeight: attributes["tileheight"]!.integerValue)
case "image":
// TODO: Allow multiple tilesets in a single map
map.spriteSheet = LGSpriteSheet(textureName: attributes["source"] as String, frameWidth: map.tileWidth, frameHeight: map.tileHeight)
case "layer":
currentLayer = LGTileLayer(tileWidth: map.tileWidth, tileHeight: map.tileHeight)
if let value = attributes["opacity"]?.doubleValue
{
currentLayer.opacity = value
}
if let value = attributes["visible"]?.boolValue
{
currentLayer.isVisible = value
}
if attributes["name"] as String == collisionLayerName
{
currentLayer.isCollision = true
currentLayer.isVisible = false
collisionLayer = currentLayer
}
if attributes["name"] as String == foregroundLayerName
{
currentRenderLayer = firstForegroundLayer
}
currentLayer.renderLayer = currentRenderLayer++
case "data":
if let value = attributes["encoding"] as? String
{
currentEncoding = value
}
if let value = attributes["compression"] as? String
{
currentCompression = value
}
case "object":
currentObject = LGTMXObject(x: attributes["x"]!.integerValue, y: attributes["y"]!.integerValue)
if let value = attributes["name"] as? String
{
currentObject.name = value
}
if let value = attributes["type"] as? String
{
currentObject.type = value
}
if let value = attributes["width"]?.integerValue
{
currentObject.width = value
}
if let value = attributes["height"]?.integerValue
{
currentObject.height = value
}
case "property":
// TODO: allow custom properties in map, tile, and layer
if currentObject != nil
{
let name = attributes["name"] as String
if let value = attributes["value"] as? String
{
currentObject.properties[name] = value
}
currentPropName = name
}
// TODO: add case "objectgroup" if multiple object layers are desired
default:
break
}
// Save the current element for the parser(: foundCharacters:) method
currentElement = elementName.lowercaseString
}
public func parser(parser: NSXMLParser!, foundCharacters string: String!)
{
if currentElement == "data"
{
currentData += string
}
if currentElement == "property"
{
currentData += string
}
}
public func parser(parser: NSXMLParser!, didEndElement elementName: String!, namespaceURI: String!, qualifiedName: String!)
{
switch elementName.lowercaseString
{
case "layer":
map.add(currentLayer)
currentLayer = nil
case "data":
// Reverse the rows for the right-handed coordinate system
currentLayer.data = parseString(currentData, encoding: currentEncoding, compression: currentCompression).reverse()
currentData = ""
currentEncoding = ""
currentCompression = ""
case "object":
objects.append(currentObject)
currentObject = nil
case "property":
currentObject.properties[currentPropName] = currentData
currentData = ""
currentPropName = ""
default:
break
}
}
}
|
mit
|
3c4997890a3d2bd4ee3d1eff681de7a5
| 24.737003 | 207 | 0.670033 | 3.727192 | false | false | false | false |
bitboylabs/selluv-ios
|
selluv-ios/selluv-ios/Classes/Base/Model/RealmModel/ClothingSizeConvert/MenShoesSizeConvertInfo.swift
|
1
|
1543
|
//
// MenShoesSizeConvertInfo.swift
// selluv-ios
//
// Created by 조백근 on 2016. 12. 8..
// Copyright © 2016년 BitBoy Labs. All rights reserved.
//
import RealmSwift
class MenShoesSizeConvertInfo: Object {
dynamic var std = ""
dynamic var us = ""
dynamic var uk = ""
dynamic var eu = ""
dynamic var kr = ""
public func setupIndexes() {
self.std.indexTag = 0
self.us.indexTag = 1
self.uk.indexTag = 2
self.eu.indexTag = 3
self.kr.indexTag = 4
}
public static func displayNamesByTag() -> [String] {
return [SIZE_US, SIZE_UK, SIZE_EU, SIZE_KR]
}
public static func propertyName(displayName: String) -> String {
if displayName == SIZE_US { return "us"}
else if displayName == SIZE_UK { return "uk"}
else if displayName == SIZE_EU { return "eu"}
else if displayName == SIZE_KR { return "kr"}
return ""
}
public static func propertyIndex(displayName: String) -> String {
if displayName == SIZE_US { return "2"}
else if displayName == SIZE_UK { return "3"}
else if displayName == SIZE_EU { return "1"}
else if displayName == SIZE_KR { return "0"}
return "99"
}
public func sizeValues() -> [String] {
return [(self.kr.copy() as! String), (self.eu.copy() as! String), (self.uk.copy() as! String), (self.us.copy() as! String)]
}
override static func primaryKey() -> String? {
return "std"
}
}
|
mit
|
fa1bc5119cc0013d2c5a8088f97c2688
| 27.407407 | 131 | 0.571708 | 3.883544 | false | false | false | false |
joninsky/JVNotifications
|
JVNotifications/JVNotification.swift
|
1
|
1289
|
//
// JVNotification.swift
// JVNotifications
//
// Created by Jon Vogel on 9/6/16.
// Copyright © 2016 Jon Vogel. All rights reserved.
//
import UIKit
import RealmSwift
open class JVNotification: Object {
//MARK: Properties
open dynamic var title: String?
open dynamic var explination: String?
open internal(set) dynamic var coalescedTitle: String?
open dynamic var image: String?
open dynamic var subImage: String?
open internal(set) dynamic var dateFired: Date!
open dynamic var debug = false
open dynamic var seen = false
public dynamic var generatedFromRemote = false
public convenience init(title t: String, explination e: String, imageName i: String, subImageName s: String) {
self.init()
self.title = t
self.explination = e
self.image = i
self.subImage = s
}
//MARK: Functions
open func delete() throws {
do{
try Realm().write {
try! Realm().delete(self)
}
}catch{
throw error
}
}
open func markAsSeen() throws {
do{
try Realm().write{
self.seen = true
}
}catch{
throw error
}
}
}
|
mit
|
91ee21a6034a9b35f331b1046fab07e0
| 21.206897 | 114 | 0.569876 | 4.366102 | false | false | false | false |
manavgabhawala/swift
|
test/DebugInfo/self.swift
|
1
|
1016
|
// RUN: %target-swift-frontend -Xllvm -new-mangling-for-tests -primary-file %s -emit-ir -g -o - | %FileCheck %s
public struct stuffStruct {
var a: Int64 = 6
var b: String = "Nothing"
}
public func f() {
var _: stuffStruct = stuffStruct()
}
// In the constructor, self has a type of "inout stuffStruct", but it
// is constructed in an alloca. The debug info for the alloca should not
// describe a reference type as we would normally do with inout arguments.
//
// CHECK: define {{.*}} @_T04self11stuffStructVACycfC(
// CHECK-NEXT: entry:
// CHECK-NEXT: %[[ALLOCA:.*]] = alloca %T4self11stuffStructV, align {{(4|8)}}
// CHECK: call void @llvm.dbg.declare(metadata %T4self11stuffStructV* %[[ALLOCA]],
// CHECK-SAME: metadata ![[SELF:.*]], metadata !{{[0-9]+}}), !dbg
// CHECK: ![[STUFFSTRUCT:.*]] = !DICompositeType(tag: DW_TAG_structure_type, name: "stuffStruct",{{.*}}identifier
// CHECK: ![[SELF]] = !DILocalVariable(name: "self", scope
// CHECK-SAME: type: ![[STUFFSTRUCT]]
|
apache-2.0
|
acc89454000e70bf631b46a39e283423
| 41.333333 | 113 | 0.650591 | 3.515571 | false | false | false | false |
jsslai/Action
|
Carthage/Checkouts/RxSwift/RxCocoa/Common/DelegateProxy.swift
|
1
|
10140
|
//
// DelegateProxy.swift
// RxCocoa
//
// Created by Krunoslav Zaher on 6/14/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
#if !RX_NO_MODULE
import RxSwift
#endif
var delegateAssociatedTag: UInt8 = 0
var dataSourceAssociatedTag: UInt8 = 0
/**
Base class for `DelegateProxyType` protocol.
This implementation is not thread safe and can be used only from one thread (Main thread).
*/
open class DelegateProxy : _RXDelegateProxy {
private var sentMessageForSelector = [Selector: PublishSubject<[Any]>]()
private var methodInvokedForSelector = [Selector: PublishSubject<[Any]>]()
/**
Parent object associated with delegate proxy.
*/
weak private(set) var parentObject: AnyObject?
/**
Initializes new instance.
- parameter parentObject: Optional parent object that owns `DelegateProxy` as associated object.
*/
public required init(parentObject: AnyObject) {
self.parentObject = parentObject
MainScheduler.ensureExecutingOnScheduler()
#if TRACE_RESOURCES
OSAtomicIncrement32(&resourceCount)
#endif
super.init()
}
/**
Returns observable sequence of invocations of delegate methods. Elements are sent *before method is invoked*.
Only methods that have `void` return value can be observed using this method because
those methods are used as a notification mechanism. It doesn't matter if they are optional
or not. Observing is performed by installing a hidden associated `PublishSubject` that is
used to dispatch messages to observers.
Delegate methods that have non `void` return value can't be observed directly using this method
because:
* those methods are not intended to be used as a notification mechanism, but as a behavior customization mechanism
* there is no sensible automatic way to determine a default return value
In case observing of delegate methods that have return type is required, it can be done by
manually installing a `PublishSubject` or `BehaviorSubject` and implementing delegate method.
e.g.
// delegate proxy part (RxScrollViewDelegateProxy)
let internalSubject = PublishSubject<CGPoint>
public func requiredDelegateMethod(scrollView: UIScrollView, arg1: CGPoint) -> Bool {
internalSubject.on(.next(arg1))
return self._forwardToDelegate?.requiredDelegateMethod?(scrollView, arg1: arg1) ?? defaultReturnValue
}
....
// reactive property implementation in a real class (`UIScrollView`)
public var property: Observable<CGPoint> {
let proxy = RxScrollViewDelegateProxy.proxyForObject(base)
return proxy.internalSubject.asObservable()
}
**In case calling this method prints "Delegate proxy is already implementing `\(selector)`,
a more performant way of registering might exist.", that means that manual observing method
is required analog to the example above because delegate method has already been implemented.**
- parameter selector: Selector used to filter observed invocations of delegate methods.
- returns: Observable sequence of arguments passed to `selector` method.
*/
open func sentMessage(_ selector: Selector) -> Observable<[Any]> {
checkSelectorIsObservable(selector)
let subject = sentMessageForSelector[selector]
if let subject = subject {
return subject
}
else {
let subject = PublishSubject<[Any]>()
sentMessageForSelector[selector] = subject
return subject
}
}
/**
Returns observable sequence of invoked delegate methods. Elements are sent *after method is invoked*.
Only methods that have `void` return value can be observed using this method because
those methods are used as a notification mechanism. It doesn't matter if they are optional
or not. Observing is performed by installing a hidden associated `PublishSubject` that is
used to dispatch messages to observers.
Delegate methods that have non `void` return value can't be observed directly using this method
because:
* those methods are not intended to be used as a notification mechanism, but as a behavior customization mechanism
* there is no sensible automatic way to determine a default return value
In case observing of delegate methods that have return type is required, it can be done by
manually installing a `PublishSubject` or `BehaviorSubject` and implementing delegate method.
e.g.
// delegate proxy part (RxScrollViewDelegateProxy)
let internalSubject = PublishSubject<CGPoint>
public func requiredDelegateMethod(scrollView: UIScrollView, arg1: CGPoint) -> Bool {
internalSubject.on(.next(arg1))
return self._forwardToDelegate?.requiredDelegateMethod?(scrollView, arg1: arg1) ?? defaultReturnValue
}
....
// reactive property implementation in a real class (`UIScrollView`)
public var property: Observable<CGPoint> {
let proxy = RxScrollViewDelegateProxy.proxyForObject(base)
return proxy.internalSubject.asObservable()
}
**In case calling this method prints "Delegate proxy is already implementing `\(selector)`,
a more performant way of registering might exist.", that means that manual observing method
is required analog to the example above because delegate method has already been implemented.**
- parameter selector: Selector used to filter observed invocations of delegate methods.
- returns: Observable sequence of arguments passed to `selector` method.
*/
open func methodInvoked(_ selector: Selector) -> Observable<[Any]> {
checkSelectorIsObservable(selector)
let subject = methodInvokedForSelector[selector]
if let subject = subject {
return subject
}
else {
let subject = PublishSubject<[Any]>()
methodInvokedForSelector[selector] = subject
return subject
}
}
private func checkSelectorIsObservable(_ selector: Selector) {
MainScheduler.ensureExecutingOnScheduler()
if hasWiredImplementation(for: selector) {
print("Delegate proxy is already implementing `\(selector)`, a more performant way of registering might exist.")
}
// It's important to see if super class reponds to selector and not self,
// because super class (_RxDelegateProxy) returns all methods delegate proxy
// can respond to.
// Because of https://github.com/ReactiveX/RxSwift/issues/907 , and possibly
// some other reasons, subclasses could overrride `responds(to:)`, but it shouldn't matter
// for this case.
if !super.responds(to: selector) {
rxFatalError("This class doesn't respond to selector \(selector)")
}
}
@available(*, deprecated, renamed: "methodInvoked")
open func observe(_ selector: Selector) -> Observable<[Any]> {
return sentMessage(selector)
}
// proxy
open override func _sentMessage(_ selector: Selector, withArguments arguments: [Any]) {
sentMessageForSelector[selector]?.on(.next(arguments))
}
open override func _methodInvoked(_ selector: Selector, withArguments arguments: [Any]) {
methodInvokedForSelector[selector]?.on(.next(arguments))
}
/**
Returns tag used to identify associated object.
- returns: Associated object tag.
*/
open class func delegateAssociatedObjectTag() -> UnsafeRawPointer {
return _pointer(&delegateAssociatedTag)
}
/**
Initializes new instance of delegate proxy.
- returns: Initialized instance of `self`.
*/
open class func createProxyForObject(_ object: AnyObject) -> AnyObject {
return self.init(parentObject: object)
}
/**
Returns assigned proxy for object.
- parameter object: Object that can have assigned delegate proxy.
- returns: Assigned delegate proxy or `nil` if no delegate proxy is assigned.
*/
open class func assignedProxyFor(_ object: AnyObject) -> AnyObject? {
let maybeDelegate = objc_getAssociatedObject(object, self.delegateAssociatedObjectTag())
return castOptionalOrFatalError(maybeDelegate.map { $0 as AnyObject })
}
/**
Assigns proxy to object.
- parameter object: Object that can have assigned delegate proxy.
- parameter proxy: Delegate proxy object to assign to `object`.
*/
open class func assignProxy(_ proxy: AnyObject, toObject object: AnyObject) {
precondition(proxy.isKind(of: self.classForCoder()))
objc_setAssociatedObject(object, self.delegateAssociatedObjectTag(), proxy, .OBJC_ASSOCIATION_RETAIN)
}
/**
Sets reference of normal delegate that receives all forwarded messages
through `self`.
- parameter forwardToDelegate: Reference of delegate that receives all messages through `self`.
- parameter retainDelegate: Should `self` retain `forwardToDelegate`.
*/
open func setForwardToDelegate(_ delegate: AnyObject?, retainDelegate: Bool) {
self._setForward(toDelegate: delegate, retainDelegate: retainDelegate)
}
/**
Returns reference of normal delegate that receives all forwarded messages
through `self`.
- returns: Value of reference if set or nil.
*/
open func forwardToDelegate() -> AnyObject? {
return self._forwardToDelegate
}
deinit {
for v in sentMessageForSelector.values {
v.on(.completed)
}
for v in methodInvokedForSelector.values {
v.on(.completed)
}
#if TRACE_RESOURCES
OSAtomicDecrement32(&resourceCount)
#endif
}
// MARK: Pointer
class func _pointer(_ p: UnsafeRawPointer) -> UnsafeRawPointer {
return p
}
}
|
mit
|
1ebaa48d6dfad80bbb6cd91423fa67b3
| 36.139194 | 124 | 0.681625 | 5.421925 | false | false | false | false |
apple/swift
|
test/SILOptimizer/inline_self.swift
|
5
|
2473
|
// RUN: %target-swift-frontend -Xllvm -sil-full-demangle -O -emit-sil -primary-file %s | %FileCheck %s
//
// This is a .swift test because the SIL parser does not support Self.
// Do not inline C.factory into main. Doing so would lose the ability
// to materialize local Self metadata.
class C {
required init() {}
}
class SubC : C {}
var g: AnyObject = SubC()
@inline(never)
func gen<R>() -> R {
return g as! R
}
extension C {
@inline(__always)
class func factory(_ z: Int) -> Self {
return gen()
}
}
// Call the function so it can be inlined.
var x = C()
var x2 = C.factory(1)
@inline(never)
func callIt(fn: () -> ()) {
fn()
}
protocol Use {
func use<T>(_ t: T)
}
var user: Use? = nil
class BaseZ {
final func baseCapturesSelf() -> Self {
let fn = { [weak self] in _ = self }
callIt(fn: fn)
return self
}
}
// Do not inline C.capturesSelf() into main either. Doing so would lose the ability
// to materialize local Self metadata.
class Z : BaseZ {
@inline(__always)
final func capturesSelf() -> Self {
let fn = { [weak self] in _ = self }
callIt(fn: fn)
user?.use(self)
return self
}
// Inline captureSelf into callCaptureSelf,
// because their respective Self types refer to the same type.
final func callCapturesSelf() -> Self {
return capturesSelf()
}
final func callBaseCapturesSelf() -> Self {
return baseCapturesSelf()
}
}
_ = Z().capturesSelf()
// CHECK-LABEL: sil {{.*}}@main : $@convention(c)
// CHECK: function_ref static inline_self.C.factory(Swift.Int) -> Self
// CHECK: [[F:%[0-9]+]] = function_ref @$s11inline_self1CC7factory{{[_0-9a-zA-Z]*}}FZ : $@convention(method) (Int, @thick C.Type) -> @owned C
// CHECK: apply [[F]](%{{.+}}, %{{.+}}) : $@convention(method) (Int, @thick C.Type) -> @owned C
// CHECK: [[Z:%.*]] = alloc_ref $Z
// CHECK: function_ref inline_self.Z.capturesSelf() -> Self
// CHECK: [[F:%[0-9]+]] = function_ref @$s11inline_self1ZC12capturesSelfACXDyF : $@convention(method) (@guaranteed Z) -> @owned Z
// CHECK: apply [[F]]([[Z]]) : $@convention(method) (@guaranteed Z) -> @owned
// CHECK: return
// CHECK-LABEL: sil hidden @$s11inline_self1ZC16callCapturesSelfACXDyF : $@convention(method)
// CHECK-NOT: function_ref @$s11inline_self1ZC12capturesSelfACXDyF :
// CHECK: }
// CHECK-LABEL: sil hidden {{.*}}@$s11inline_self1ZC20callBaseCapturesSelfACXDyF
// CHECK-NOT: function_ref @$s11inline_self5BaseZC16baseCapturesSelfACXDyF :
// CHECK: }
|
apache-2.0
|
9c56b6cf1c7d0907a5320ce9accf595a
| 26.175824 | 141 | 0.64537 | 3.19509 | false | false | false | false |
GitHubCha2016/ZLSwiftFM
|
ZLSwiftFM/ZLSwiftFM/Classes/Tools/Global/XLTextView.swift
|
1
|
1243
|
//
// XLTextView.swift
// TodayNews
//
// Created by ZXL on 2017/2/21.
// Copyright © 2017年 zxl. All rights reserved.
// 输入中文时限制字符长度
import UIKit
class XLTextView: UITextView {
}
extension XLTextView: UITextViewDelegate{
func textViewDidChange(_ textView: UITextView) {
let toBeString = textView.text
// 获取输入法
let lang = textView.textInputMode?.primaryLanguage
// 如果输入法为中文
if lang == "zh-Hans" {
// 这个range就是指输入的拼音还没有转化成中文是的range
// 如果没有,就表示已经转成中文
let selectedRange = textView.markedTextRange
if selectedRange == nil && (toBeString?.characters.count)! > 5 {
// 截取前5个字符
let index = toBeString?.index((toBeString?.startIndex)!, offsetBy: 5)
textView.text = toBeString?.substring(to: index!)
}
}
else if (toBeString?.characters.count)! > 5{
// 截取前5个字符
let index = toBeString?.index((toBeString?.startIndex)!, offsetBy: 5)
textView.text = toBeString?.substring(to: index!)
}
}
}
|
mit
|
9a6b69c48a89cc3160645f5ce32b98eb
| 28.72973 | 85 | 0.588182 | 4 | false | false | false | false |
alobanov/ALFormBuilder
|
Sources/FormBuilder/Values/TupleValue.swift
|
1
|
1295
|
//
// PickerValue.swift
// ALFormBuilder
//
// Created by Lobanov Aleksey on 30/10/2017.
// Copyright © 2017 Lobanov Aleksey. All rights reserved.
//
import Foundation
public typealias ALTitledTuple = (title: String?, value: Any?)
public class ALTitledValue: ALValueTransformable {
private var originalValue: Any?
public var initialValue: String?
public var wasModify: Bool = false
public init(value: ALTitledTuple?) {
self.originalValue = value
self.initialValue = transformForDisplay()
}
public func change(originalValue: Any?) {
self.originalValue = originalValue
if initialValue == nil, let newValue = transformForDisplay() {
wasModify = !newValue.isEmpty
} else {
wasModify = (initialValue != transformForDisplay())
}
}
public func retriveOriginalValue() -> Any? {
return originalValue
}
public func transformForDisplay() -> DisplayValueType? {
guard let tuple = self.originalValue as? ALTitledTuple,
let title = tuple.title
else {
return nil
}
return title
}
public func transformForJSON() -> JSONValueType {
guard let tuple = self.originalValue as? ALTitledTuple,
let value = tuple.value
else {
return NSNull()
}
return value
}
}
|
mit
|
593103b99891cb4299e809f09015951c
| 22.962963 | 66 | 0.670788 | 4.446735 | false | false | false | false |
Zewo/Mapper
|
Sources/Mapper/OutMapper/OutMapper.swift
|
2
|
11713
|
/// Object that maps strongly-typed instances to structured data instances.
public protocol OutMapperProtocol {
associatedtype Destination: OutMap
associatedtype IndexPath: IndexPathElement
/// Destination of mapping (output).
var destination: Destination { get set }
}
public protocol ContextualOutMapperProtocol : OutMapperProtocol {
associatedtype Context
var context: Context { get }
}
public enum OutMapperError : Error {
case wrongType(Any.Type)
case cannotRepresentArray
case cannotSet(Error)
}
fileprivate extension OutMapperProtocol {
func getMap<T>(from value: T) throws -> Destination {
if let map = Destination.from(value) {
return map
} else {
throw OutMapperError.wrongType(T.self)
}
}
func arrayMap(of array: [Destination]) throws -> Destination {
if let array = Destination.fromArray(array) {
return array
} else {
throw OutMapperError.cannotRepresentArray
}
}
func unwrap<T>(_ optional: T?) throws -> T {
if let value = optional {
return value
} else {
throw OutMapperError.wrongType(T.self)
}
}
mutating func set(_ map: Destination, at indexPath: [IndexPath]) throws {
let indexPathValues = indexPath.map({ $0.indexPathValue })
do {
try destination.set(map, at: indexPathValues)
} catch {
throw OutMapperError.cannotSet(error)
}
}
}
extension OutMapperProtocol {
/// Maps given value to `indexPath`.
///
/// - parameter value: value that needs to be mapped.
/// - parameter indexPath: path to set value to.
///
/// - throws: `OutMapperError`.
public mutating func unsafe_map<T>(_ value: T, to indexPath: IndexPath...) throws {
let map = try getMap(from: value)
try set(map, at: indexPath)
}
public mutating func map(_ int: Int, to indexPath: IndexPath...) throws {
let map = try unwrap(Destination.from(int))
try set(map, at: indexPath)
}
public mutating func map(_ double: Double, to indexPath: IndexPath...) throws {
let map = try unwrap(Destination.from(double))
try set(map, at: indexPath)
}
public mutating func map(_ bool: Bool, to indexPath: IndexPath...) throws {
let map = try unwrap(Destination.from(bool))
try set(map, at: indexPath)
}
public mutating func map(_ string: String, to indexPath: IndexPath...) throws {
let map = try unwrap(Destination.from(string))
try set(map, at: indexPath)
}
/// Maps given value to `indexPath`, where value is `OutMappable`.
///
/// - parameter value: `OutMappable` value that needs to be mapped.
/// - parameter indexPath: path to set value to.
///
/// - throws: `OutMapperError`.
public mutating func map<T : OutMappable>(_ value: T, to indexPath: IndexPath...) throws {
let new: Destination = try value.map()
try set(new, at: indexPath)
}
/// Maps given value to `indexPath`, where value is `ExternalOutMappable`.
///
/// - parameter value: `ExternalOutMappable` value that needs to be mapped.
/// - parameter indexPath: path to set value to.
///
/// - throws: `OutMapperError`.
public mutating func map<T : BasicOutMappable>(_ value: T, to indexPath: IndexPath...) throws {
let new: Destination = try value.map()
try set(new, at: indexPath)
}
/// Maps given value to `indexPath`, where value is `RawRepresentable` (in most cases - `enum` with raw type).
///
/// - parameter value: `RawRepresentable` value that needs to be mapped.
/// - parameter indexPath: path to set value to.
///
/// - throws: `OutMapperError`.
public mutating func map<T : RawRepresentable>(_ value: T, to indexPath: IndexPath...) throws {
let map = try getMap(from: value.rawValue)
try set(map, at: indexPath)
}
/// Maps given value to `indexPath` using the defined context of value.
///
/// - parameter value: `OutMappableWithContext` value that needs to be mapped.
/// - parameter indexPath: path to set value to.
/// - parameter context: value-specific context, used to describe the way of mapping.
///
/// - throws: `OutMapperError`.
public mutating func map<T : OutMappableWithContext>(_ value: T, to indexPath: IndexPath..., withContext context: T.MappingContext) throws {
let new = try value.map(withContext: context) as Destination
try set(new, at: indexPath)
}
/// Maps given array of values to `indexPath`.
///
/// - parameter array: values that needs to be mapped.
/// - parameter indexPath: path to set values to.
///
/// - throws: `OutMapperError`.
public mutating func unsafe_mapArray<T>(_ array: [T], to indexPath: IndexPath...) throws {
let maps = try array.map({ try self.getMap(from: $0) })
let map = try arrayMap(of: maps)
try set(map, at: indexPath)
}
public mutating func map(_ array: [Int], to indexPath: IndexPath...) throws {
let maps = try array.map({ try unwrap(Destination.from($0)) })
let map = try arrayMap(of: maps)
try set(map, at: indexPath)
}
public mutating func map(_ array: [Double], to indexPath: IndexPath...) throws {
let maps = try array.map({ try unwrap(Destination.from($0)) })
let map = try arrayMap(of: maps)
try set(map, at: indexPath)
}
public mutating func map(_ array: [Bool], to indexPath: IndexPath...) throws {
let maps = try array.map({ try unwrap(Destination.from($0)) })
let map = try arrayMap(of: maps)
try set(map, at: indexPath)
}
public mutating func map(_ array: [String], to indexPath: IndexPath...) throws {
let maps = try array.map({ try unwrap(Destination.from($0)) })
let map = try arrayMap(of: maps)
try set(map, at: indexPath)
}
/// Maps given array of `OutMappable` values to `indexPath`.
///
/// - parameter array: `OutMappable` values that needs to be mapped.
/// - parameter indexPath: path to set values to.
///
/// - throws: `OutMapperError`.
public mutating func map<T : OutMappable>(_ array: [T], to indexPath: IndexPath...) throws {
let maps: [Destination] = try array.map({ try $0.map() })
let map = try arrayMap(of: maps)
try set(map, at: indexPath)
}
/// Maps given array of `ExternalOutMappable` values to `indexPath`.
///
/// - parameter array: `ExternalOutMappable` values that needs to be mapped.
/// - parameter indexPath: path to set values to.
///
/// - throws: `OutMapperError`.
public mutating func map<T : BasicOutMappable>(_ array: [T], to indexPath: IndexPath...) throws {
let maps: [Destination] = try array.map({ try $0.map() })
let map = try arrayMap(of: maps)
try set(map, at: indexPath)
}
/// Maps given array of `RawRepresentable` values to `indexPath`.
///
/// - parameter array: `RawRepresentable` values that needs to be mapped.
/// - parameter indexPath: path to set values to.
///
/// - throws: `OutMapperError`.
public mutating func map<T : RawRepresentable>(_ array: [T], to indexPath: IndexPath...) throws {
let maps = try array.map({ try self.getMap(from: $0.rawValue) })
let map = try arrayMap(of: maps)
try set(map, at: indexPath)
}
/// Maps given array of values to `indexPath` using the value-defined context.
///
/// - parameter array: `OutMappableWithContext` values that needs to be mapped.
/// - parameter indexPath: path to set values to.
/// - parameter context: values-specific context, used to describe the way of mapping.
///
/// - throws: `OutMapperError`.
public mutating func map<T : OutMappableWithContext>(_ array: [T], to indexPath: IndexPath..., withContext context: T.MappingContext) throws {
let maps: [Destination] = try array.map({ try $0.map(withContext: context) })
let map = try arrayMap(of: maps)
try set(map, at: indexPath)
}
}
extension ContextualOutMapperProtocol {
/// Maps given value to `indexPath`, where value type has the same associated `Context`, automatically passing the context.
///
/// - parameter value: value that needs to be mapped.
/// - parameter indexPath: path to set values to.
///
/// - throws: `OutMapperError`.
public mutating func map<T : OutMappableWithContext>(_ value: T, to indexPath: IndexPath...) throws where T.MappingContext == Context {
let new: Destination = try value.map(withContext: self.context)
try set(new, at: indexPath)
}
/// Maps given array of values to `indexPath`, where value type has the same associated `Context`, automatically passing the context.
///
/// - parameter value: values that needs to be mapped.
/// - parameter indexPath: path to set values to.
///
/// - throws: `OutMapperError`.
public mutating func map<T : OutMappableWithContext>(_ array: [T], to indexPath: IndexPath...) throws where T.MappingContext == Context {
let maps: [Destination] = try array.map({ try $0.map(withContext: context) })
let map = try arrayMap(of: maps)
try set(map, at: indexPath)
}
}
/// Object that maps strongly-typed instances to structured data instances.
public struct OutMapper<Destination : OutMap, MappingKeys : IndexPathElement> : OutMapperProtocol {
public typealias IndexPath = MappingKeys
public var destination: Destination
/// Creates `OutMapper` instance of blank `Destination`.
public init() {
self.destination = .blank
}
/// Creates `OutMapper` of `destination`.
///
/// - parameter destination: `OutMap` to which data will be mapped.
public init(of destination: Destination) {
self.destination = destination
}
}
public struct BasicOutMapper<Destination : OutMap> : OutMapperProtocol {
public var destination: Destination
public typealias IndexPath = IndexPathValue
public init() {
self.destination = .blank
}
public init(of destination: Destination) {
self.destination = destination
}
}
/// Object that maps strongly-typed instances to structured data instances using type-specific context.
public struct ContextualOutMapper<Destination : OutMap, MappingKeys : IndexPathElement, Context> : ContextualOutMapperProtocol {
public typealias IndexPath = MappingKeys
public var destination: Destination
/// Context allows to map data in several different ways.
public let context: Context
/// Creates `OutMapper` of `destination` with `context`.
///
/// - parameter destination: `OutMap` to which data will be mapped.
/// - parameter context: value-specific context, used to describe the way of mapping.
public init(of destination: Destination = .blank, context: Context) {
self.destination = destination
self.context = context
}
}
/// Mapper for mapping without MappingKeys.
public typealias PlainOutMapper<Destination : OutMap> = OutMapper<Destination, NoKeys>
/// Contextual Mapper for mapping without MappingKeys.
public typealias PlainContextualOutMapper<Destination : OutMap, Context> = ContextualOutMapper<Destination, NoKeys, Context>
|
mit
|
ca8a170100f1b2f8d59daa329f7ee79c
| 36.541667 | 146 | 0.632204 | 4.386891 | false | false | false | false |
banxi1988/BXAppKit
|
BXForm/Controller/SelectPickerController.swift
|
1
|
2926
|
//
// SingleCompomentPickerController.swift
// Pods
//
// Created by Haizhen Lee on 15/12/23.
//
//
import UIKit
open class SelectPickerController<T:CustomStringConvertible>:PickerController,UIPickerViewDataSource,UIPickerViewDelegate where T:Equatable{
fileprivate var options:[T] = []
open var rowHeight:CGFloat = 36{
didSet{
picker.reloadAllComponents()
}
}
open var textColor = UIColor.darkText{
didSet{
picker.reloadAllComponents()
}
}
open var font = UIFont.systemFont(ofSize: 14){
didSet{
picker.reloadAllComponents()
}
}
open var onSelectOption:((T) -> Void)?
public init(options:[T]){
self.options = options
super.init(nibName: nil, bundle: nil)
}
public init(){
super.init(nibName: nil, bundle: nil)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
open override func viewDidLoad() {
super.viewDidLoad()
picker.delegate = self
picker.dataSource = self
picker.showsSelectionIndicator = true
}
open func selectOption(_ option:T){
let index = options.index { $0 == option }
if let row = index{
picker.selectRow(row, inComponent: 0, animated: true)
}
}
open func updateOptions(_ options:[T]){
self.options = options
if isViewLoaded{
picker.reloadAllComponents()
}
}
open func appendOptions(_ options:[T]){
self.options.append(contentsOf: options)
picker.reloadAllComponents()
}
open func appendOption(_ option:T){
self.options.append(option)
picker.reloadAllComponents()
}
func optionAtRow(_ row:Int) -> T?{
if options.count <= row || row < 0{
return nil
}
return options[row]
}
// MARK: UIPickerViewDataSource
open func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
open func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return component == 0 ? options.count : 0
}
// MARK: UIPickerViewDelegate
open func pickerView(_ pickerView: UIPickerView, rowHeightForComponent component: Int) -> CGFloat {
return rowHeight
}
open func pickerView(_ pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString? {
guard let option = optionAtRow(row) else{
return nil
}
let title = option.description
let attributedText = NSAttributedString(string: title, attributes: [
NSAttributedStringKey.foregroundColor:textColor,
NSAttributedStringKey.font:font
])
return attributedText
}
// MARK: Base Controller
override open func onPickDone() {
if options.isEmpty{
return
}
let selectedRow = picker.selectedRow(inComponent: 0)
if let option = optionAtRow(selectedRow){
onSelectOption?(option)
}
}
}
|
mit
|
6c22e6742e678b7c097484fc5d8fd56d
| 22.788618 | 140 | 0.668831 | 4.543478 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.