repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
202 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
darjeelingsteve/uistackview_adaptivity
Adaptivity/Scene Delegates/CountySceneDelegate.swift
1
1598
// // CountySceneDelegate.swift // Counties // // Created by Stephen Anthony on 18/12/2019. // Copyright © 2019 Darjeeling Apps. All rights reserved. // import UIKit import CountiesUI import CountiesModel /// The delegate of the scene used to show an individual county's details. class CountySceneDelegate: UIResponder { var window: UIWindow? } // MARK: UIWindowSceneDelegate extension CountySceneDelegate: UIWindowSceneDelegate { func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { scene.activationConditions.canActivateForTargetContentIdentifierPredicate = NSPredicate(value: false) guard let county = Country.unitedKingdom.countyFrom(userActivity: session.stateRestorationActivity ?? connectionOptions.userActivities.first), let countyViewController = window?.rootViewController as? CountyViewController else { return } countyViewController.county = county countyViewController.delegate = self scene.title = county.name } func stateRestorationActivity(for scene: UIScene) -> NSUserActivity? { return scene.userActivity } } // MARK: CountyViewControllerDelegate extension CountySceneDelegate: CountyViewControllerDelegate { func countyViewControllerDidFinish(_ countyViewController: CountyViewController) { guard let sceneSession = countyViewController.view.window?.windowScene?.session else { return } UIApplication.shared.requestSceneSessionDestruction(sceneSession, options: nil, errorHandler: nil) } }
mit
a73b5b178e95253f745266bad183a18d
38.925
150
0.766437
5.201954
false
false
false
false
chweihan/Weibo
Weibo/Weibo/Classes/Tools/Common.swift
1
706
// // Common.swift // Weibo // // Created by 陈伟涵 on 2016/10/20. // Copyright © 2016年 cweihan. All rights reserved. // import Foundation /// OAuth授权需要的key let WB_App_Key = "3090663153" /// OAuth授权需要的Secret let WB_App_Secret = "6ab4bbc298a13dc13a39360a4ff8f6ed" /// OAuth授权需要的重定向地址 let WB_Redirect_uri = "http://www.baidu.com" // MARK: - 本地通知 //自定义转场的展现 let WHPresentationManagerDidPresented = "WHPresentationManagerDidPresented" //自定义转场的消失 let WHPresentationManagerDidDismissed = "WHPresentationManagerDidDismissed" /// 切换根控制器的通知 let WHSwitchRootViewController = "WHSwitchRootViewController"
mit
0eb0ba57cee12c59c312d61e97a4f4fc
23.958333
75
0.767947
2.950739
false
false
false
false
LoopKit/LoopKit
LoopKitUI/Views/OverrideViewCell.swift
1
2517
// // OverrideViewCell.swift // LoopKitUI // // Created by Anna Quinlan on 8/1/20. // Copyright © 2020 LoopKit Authors. All rights reserved. // import SwiftUI public struct OverrideViewCell: View { @Environment(\.lightenedInsulinTintColor) private var lightInsulin @Environment(\.darkenedInsulinTintColor) private var darkInsulin static let symbolWidth: CGFloat = 40 var symbolLabel: Text var nameLabel: Text var targetRangeLabel: Text var durationLabel: Text var subtitleLabel: Text var insulinNeedsScaleFactor: Double? public init( symbol: Text, name: Text, targetRange: Text, duration: Text, subtitle: Text, insulinNeedsScaleFactor: Double? ) { self.symbolLabel = symbol self.nameLabel = name self.targetRangeLabel = targetRange self.durationLabel = duration self.subtitleLabel = subtitle self.insulinNeedsScaleFactor = insulinNeedsScaleFactor } public var body: some View { HStack { symbolLabel .font(.largeTitle) .frame(width: Self.symbolWidth) // for alignment VStack(alignment: .leading, spacing: 3) { nameLabel targetRangeLabel .font(.caption) .foregroundColor(Color.gray) if self.insulinNeedsScaleFactor != nil { insulinNeedsBar } } Spacer() VStack { HStack(spacing: 4) { timer durationLabel .font(.caption) } .foregroundColor(Color.gray) subtitleLabel .font(.caption) } } .frame(minHeight: 53) } private var insulinNeedsBar: some View { GeometryReader { geo in HStack { Group { if self.insulinNeedsScaleFactor != nil { SegmentedGaugeBar(insulinNeedsScaler: self.insulinNeedsScaleFactor!, startColor: lightInsulin, endColor: darkInsulin) .frame(minHeight: 12) } } Spacer(minLength: geo.size.width * 0.35) // Hack to fix spacing } } } var timer: some View { Image(systemName: "timer") .resizable() .frame(width: 12.0, height: 12.0) } }
mit
14784728f585ce47f3b2a214e06218a9
27.590909
141
0.538156
5.155738
false
false
false
false
Egibide-DAM/swift
02_ejemplos/10_varios/01_optional_chaining/05_llamada_metodos.playground/Contents.swift
1
1174
class Person { var residence: Residence? } class Room { let name: String init(name: String) { self.name = name } } class Address { var buildingName: String? var buildingNumber: String? var street: String? func buildingIdentifier() -> String? { if let buildingNumber = buildingNumber, let street = street { return "\(buildingNumber) \(street)" } else if buildingName != nil { return buildingName } else { return nil } } } class Residence { var rooms = [Room]() var numberOfRooms: Int { return rooms.count } subscript(i: Int) -> Room { get { return rooms[i] } set { rooms[i] = newValue } } func printNumberOfRooms() { print("The number of rooms is \(numberOfRooms)") } var address: Address? } let john = Person() // ----- if john.residence?.printNumberOfRooms() != nil { print("It was possible to print the number of rooms.") } else { print("It was not possible to print the number of rooms.") } // Prints "It was not possible to print the number of rooms."
apache-2.0
da015badbc76b2c17091552ed1f8b3cb
21.150943
69
0.573254
4.300366
false
false
false
false
rambler-ios/RamblerConferences
Carthage/Checkouts/rides-ios-sdk/examples/Swift SDK/Swift SDK/NativeLoginExampleViewController.swift
1
5413
// // NativeLoginExampleViewController.swift // Swift SDK // // Copyright © 2015 Uber Technologies, Inc. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit import UberRides import CoreLocation /// This class provides an example for using the LoginButton to do Native Login (SSO with the Uber App) public class NativeLoginExampleViewController: ButtonExampleViewController, LoginButtonDelegate { let scopes: [RidesScope] let loginManager: LoginManager let blackLoginButton: LoginButton let whiteLoginButton: LoginButton override public init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { scopes = [.Profile, .Places, .Request] loginManager = LoginManager(loginType: .Native) blackLoginButton = LoginButton(frame: CGRectZero, scopes: scopes, loginManager: loginManager) whiteLoginButton = LoginButton(frame: CGRectZero, scopes: scopes, loginManager: loginManager) whiteLoginButton.colorStyle = .White super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) blackLoginButton.presentingViewController = self whiteLoginButton.presentingViewController = self blackLoginButton.delegate = self whiteLoginButton.delegate = self } public required init?(coder aDecoder: NSCoder) { fatalError("init?(coder aDecoder: NSCoder) is not supported") } override public func viewDidLoad() { super.viewDidLoad() self.navigationItem.title = "SSO" topView.addSubview(blackLoginButton) bottomView.addSubview(whiteLoginButton) addBlackLoginButtonConstraints() addWhiteLoginButtonConstraints() } // Mark: Private Interface private func addBlackLoginButtonConstraints() { blackLoginButton.translatesAutoresizingMaskIntoConstraints = false let centerYConstraint = NSLayoutConstraint(item: blackLoginButton, attribute: .CenterY, relatedBy: .Equal, toItem: topView, attribute: .CenterY, multiplier: 1.0, constant: 0.0) let centerXConstraint = NSLayoutConstraint(item: blackLoginButton, attribute: .CenterX, relatedBy: .Equal, toItem: topView, attribute: .CenterX, multiplier: 1.0, constant: 0.0) let widthConstraint = NSLayoutConstraint(item: blackLoginButton, attribute: .Width, relatedBy: .Equal, toItem: topView, attribute: .Width, multiplier: 1.0, constant: -20.0) topView.addConstraints([centerYConstraint, centerXConstraint, widthConstraint]) } private func addWhiteLoginButtonConstraints() { whiteLoginButton.translatesAutoresizingMaskIntoConstraints = false let centerYConstraint = NSLayoutConstraint(item: whiteLoginButton, attribute: .CenterY, relatedBy: .Equal, toItem: bottomView, attribute: .CenterY, multiplier: 1.0, constant: 0.0) let centerXConstraint = NSLayoutConstraint(item: whiteLoginButton, attribute: .CenterX, relatedBy: .Equal, toItem: bottomView, attribute: .CenterX, multiplier: 1.0, constant: 0.0) let widthConstraint = NSLayoutConstraint(item: whiteLoginButton, attribute: .Width, relatedBy: .Equal, toItem: bottomView, attribute: .Width, multiplier: 1.0, constant: -20.0) bottomView.addConstraints([centerYConstraint, centerXConstraint, widthConstraint]) } private func showMessage(message: String) { let alert = UIAlertController(title: nil, message: message, preferredStyle: UIAlertControllerStyle.Alert) let okayAction = UIAlertAction(title: "Okay", style: UIAlertActionStyle.Default, handler: nil) alert.addAction(okayAction) self.presentViewController(alert, animated: true, completion: nil) } // Mark: LoginButtonDelegate public func loginButton(button: LoginButton, didLogoutWithSuccess success: Bool) { if success { showMessage("Logout") } } public func loginButton(button: LoginButton, didCompleteLoginWithToken accessToken: AccessToken?, error: NSError?) { if let _ = accessToken { showMessage("Saved access token!") } else if let error = error { showMessage(error.localizedDescription) } else { showMessage("Error") } } }
mit
5e386285c440953906f2528197c25eeb
45.25641
187
0.711752
5.173996
false
false
false
false
HIkaruSato/BorderPopoverExample
Popover View/SpeechBalloonArrowView.swift
1
1504
// // SpeechBalloonArrowView.swift // Popover View // // Created by grachro on 2016/06/11. // import UIKit class SpeechBalloonArrowView: UIView { var arrowWidth:CGFloat let arrowHeight:CGFloat let borderWidth:CGFloat init(width: CGFloat = 25, height: CGFloat = 10, borderWidth: CGFloat = 2) { self.arrowWidth = width self.arrowHeight = height self.borderWidth = borderWidth super.init(frame: CGRect(x: 0, y: 0, width: arrowWidth, height: arrowHeight)) self.backgroundColor = UIColor.clearColor() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func drawRect(rect: CGRect) { let x:CGFloat = arrowWidth / 2 let y:CGFloat = 0 let back = UIBezierPath(); back.moveToPoint(CGPointMake(x, y+borderWidth)); back.addLineToPoint(CGPointMake(x+arrowWidth / 2, y+arrowHeight)); back.addLineToPoint(CGPointMake(x-arrowWidth / 2, y+arrowHeight)); back.closePath() UIColor.whiteColor().setFill() back.fill(); let line = UIBezierPath(); line.moveToPoint(CGPointMake(x+arrowWidth / 2, y+arrowHeight)); line.addLineToPoint(CGPointMake(x, y+borderWidth)); line.addLineToPoint(CGPointMake(x-arrowWidth / 2, y+arrowHeight)); UIColor.redColor().setStroke() line.lineWidth = self.borderWidth line.stroke(); } }
mit
abbe451124e08e8fb3f2d72127d780db
29.08
85
0.632314
4.489552
false
false
false
false
modocache/Guanaco
Guanaco/HaveSucceeded.swift
1
2550
import Nimble import Result // MARK: Public /** A Nimble matcher that succeeds when the actual value is a successful result. */ public func haveSucceeded<T, U>() -> NonNilMatcherFunc<Result<T, U>> { return NonNilMatcherFunc { actualExpression, failureMessage in failureMessage.postfixMessage = "have succeeded" do { if let result = try actualExpression.evaluate(){ return result.analysis( ifSuccess: { value in return true }, ifFailure: { error in return false } ) } else { return false } } catch { return false } } } /** A Nimble matcher that succeeds when the actual value is a successful result, and the given matcher matches its value. :param: matcher The matcher to run against the successful value. */ public func haveSucceeded<T, U>(_ matcher: MatcherFunc<T>) -> NonNilMatcherFunc<Result<T, U>> { return haveSucceededMatcherFunc(MatcherClosure { try matcher.matches($0, failureMessage: $1) }) } /** A Nimble matcher that succeeds when the actual value is a successful result, and the given matcher matches its value. :param: matcher The matcher to run against the successful value. */ public func haveSucceeded<T, U>(_ matcher: NonNilMatcherFunc<T>) -> NonNilMatcherFunc<Result<T, U>> { return haveSucceededMatcherFunc(MatcherClosure { try matcher.matches($0, failureMessage: $1) }) } // MARK: Private private func haveSucceededMatcherFunc<T, U>(_ matcherClosure: MatcherClosure<T>) -> NonNilMatcherFunc<Result<T, U>> { return NonNilMatcherFunc { actualExpression, failureMessage in failureMessage.postfixMessage = "have succeeded" do { if let result = try actualExpression.evaluate() { return result.analysis( ifSuccess: { value in do { let successfulExpression = Expression(expression: { value }, location: actualExpression.location) let matched = try matcherClosure.closure(successfulExpression, failureMessage) failureMessage.to = "for" failureMessage.postfixMessage = "successful value to \(failureMessage.postfixMessage)" return matched! } catch{ return false } }, ifFailure: { error in return false } ) } else { return false } } catch { return false } } }
mit
dfc7ec1205bd63c6cf88e9e6b34c92ab
29.357143
117
0.621176
5
false
false
false
false
ipraba/EPShapes
Pod/Classes/Paths/UIBezierPath+Stars.swift
1
1918
// // UIBezierPath+Stars.swift // Pods // // Created by Prabaharan Elangovan on 04/02/16. // // import Foundation public extension UIBezierPath { func getStars(_ originalRect: CGRect, scale: Double, corners: Int, extrusion: Int) -> UIBezierPath { let scaledWidth = (originalRect.size.width * CGFloat(scale)) let scaledXValue = ((originalRect.size.width) - scaledWidth) / 2 let scaledHeight = (originalRect.size.height * CGFloat(scale)) let scaledYValue = ((originalRect.size.height) - scaledHeight) / 2 let scaledRect = CGRect(x: scaledXValue, y: scaledYValue, width: scaledWidth, height: scaledHeight) drawStars(originalRect, scaledRect: scaledRect, corners: corners, extrusion: extrusion) return self } func drawStars(_ originalRect: CGRect, scaledRect: CGRect, corners: Int, extrusion: Int) { // if extrusion > 100 { // extrusion = 100 // } let center = CGPoint(x: originalRect.width/2, y: originalRect.height/2) var angle = -CGFloat( Double.pi / 2.0 ) let angleCounter = CGFloat( Double.pi * 2.0 / Double(corners * 2) ) let radius = min(scaledRect.size.width/2, scaledRect.size.height/2) let extrusion = radius * CGFloat(extrusion) / 100 self.move(to: CGPoint(x: radius * cos(angle) + center.x, y: radius * sin(angle) + center.y)) for i in 1...(corners * 2) { if i % 2 != 0 { self.addLine(to: CGPoint(x: radius * cos(angle) + center.x, y: radius * sin(angle) + center.y)) } else { self.addLine(to: CGPoint(x: extrusion * cos(angle) + center.x, y: extrusion * sin(angle) + center.y)) } angle += angleCounter } self.close() } }
mit
27bd9891a218913f907a43ab305c4d16
32.649123
117
0.569343
3.890467
false
false
false
false
instacrate/Subber-api
Sources/App/Controllers/VendorController.swift
2
2219
// // VendorController.swift // subber-api // // Created by Hakon Hanesand on 11/15/16. // // import Foundation import Vapor import HTTP import Turnstile import Auth extension Vendor { func shouldAllow(request: Request) throws { guard let vendor = try? request.vendor() else { throw try Abort.custom(status: .forbidden, message: "Method \(request.method) is not allowed on resource Vendor(\(throwableId())) by this user. Must be logged in as Vendor(\(throwableId())).") } guard try vendor.throwableId() == throwableId() else { throw try Abort.custom(status: .forbidden, message: "This Vendor(\(vendor.throwableId()) does not have access to resource Vendor(\(throwableId()). Must be logged in as Vendor(\(throwableId()).") } } } final class VendorController: ResourceRepresentable { func index(_ request: Request) throws -> ResponseRepresentable { return try request.vendor().makeJSON() } func show(_ request: Request, vendor: Vendor) throws -> ResponseRepresentable { try vendor.shouldAllow(request: request) return try vendor.makeJSON() } func create(_ request: Request) throws -> ResponseRepresentable { var vendor: Vendor = try request.extractModel() try vendor.save() let node = try request.json().node let username: String = try node.extract("username") let password: String = try node.extract("password") let usernamePassword = UsernamePassword(username: username, password: password) try request.vendorSubject().login(credentials: usernamePassword, persist: true) return vendor } func modify(_ request: Request, vendor: Vendor) throws -> ResponseRepresentable { try vendor.shouldAllow(request: request) var vendor: Vendor = try request.patchModel(vendor) try vendor.save() return try Response(status: .ok, json: vendor.makeJSON()) } func makeResource() -> Resource<Vendor> { return Resource( index: index, store: create, show: show, modify: modify ) } }
mit
40af6c649c942adcdd096b661cd65a5f
30.7
206
0.633619
4.691332
false
false
false
false
FahimF/FloatLabelFields
FloatLabelExample/FloatLabelExample/ViewController.swift
1
1094
// // ViewController.swift // FloatLabelExample // // Created by Fahim Farook on 28/11/14. // Copyright (c) 2014 RookSoft Ltd. All rights reserved. // import UIKit class ViewController: UITableViewController { @IBOutlet var vwName:FloatLabelTextField! @IBOutlet var vwAddress:FloatLabelTextView! @IBOutlet var vwHolder:UIView! override func viewDidLoad() { super.viewDidLoad() // Set font for placeholder of a FloatLabelTextField if let fnt = UIFont(name:"Zapfino", size:12) { vwName.titleFont = fnt } // Set font for placeholder of a FloatLabelTextView if let fnt = UIFont(name:"Zapfino", size:12) { vwAddress.titleFont = fnt } // Set up a FloatLabelTextField via code let fld = FloatLabelTextField(frame:vwHolder.bounds) fld.placeholder = "Comments" // Set font for place holder (only displays in title mode) if let fnt = UIFont(name:"Zapfino", size:12) { fld.titleFont = fnt } vwHolder.addSubview(fld) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
f7659f19d4b19d07386b568dc7402cd0
25.682927
60
0.723949
3.575163
false
false
false
false
robertofrontado/OkDataSources
Library/OkSlidingTabs.swift
2
6403
// // OkSlidingTabs.swift // OkDataSources // // Created by Roberto Frontado on 3/22/16. // Copyright © 2016 Roberto Frontado. All rights reserved. // import UIKit @objc public protocol OkSlidingTabsDataSource { @objc func numberOfTabs() -> Int @objc func titleAtIndex(_ index: Int) -> String } @objc public protocol OkSlidingTabsDelegate { @objc func onTabSelected(_ index: Int) } @IBDesignable @objc open class OkSlidingTabs: UIView { fileprivate var scrollView: UIScrollView! fileprivate var indicatorView: UIView! fileprivate var tabs: UILabel! fileprivate var xOffset: CGFloat = 0 fileprivate var currentTabSelected = 0 fileprivate var labels: [UILabel]! @IBInspectable open var xPadding: CGFloat = 20 @IBInspectable open var xMargin: CGFloat = 0 @IBInspectable open var labelTextColor: UIColor = UIColor.black @IBInspectable open var labelBgColor: UIColor = UIColor.white @IBInspectable open var indicatorColor: UIColor = UIColor.black @IBInspectable open var indicatorHeight: CGFloat = 5 @IBInspectable open var distributeEvenly: Bool = false { didSet { reloadData() } } open var font: UIFont = UIFont.systemFont(ofSize: 14) open weak var dataSource: OkSlidingTabsDataSource? open weak var delegate: OkSlidingTabsDelegate? required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) initView() } override init(frame: CGRect) { super.init(frame: frame) initView() } // MARK: - Private methods fileprivate func initView() { addScrollView() addIndicatorView() } fileprivate func addScrollView() { scrollView = UIScrollView(frame: self.bounds) scrollView.backgroundColor = UIColor.clear scrollView.isScrollEnabled = true scrollView.showsHorizontalScrollIndicator = false self.addSubview(scrollView) } fileprivate func addIndicatorView() { if let firstLabelFrame = labels?.first?.frame { indicatorView?.removeFromSuperview() indicatorView = UIView(frame: CGRect(x: 0, y: firstLabelFrame.height - indicatorHeight, width: firstLabelFrame.width, height: indicatorHeight)) indicatorView.backgroundColor = indicatorColor scrollView.addSubview(indicatorView) } } fileprivate func addTabsView() { if let dataSource = dataSource { if dataSource.numberOfTabs() > 0 { labels?.forEach { $0.removeFromSuperview() } labels = [] for i in 0..<dataSource.numberOfTabs() { // Label let label = UILabel() label.text = dataSource.titleAtIndex(i) label.backgroundColor = labelBgColor label.font = font label.textAlignment = .center label.textColor = labelTextColor label.sizeToFit() if distributeEvenly { let screenSize = UIScreen.main.bounds let width = screenSize.width / CGFloat(dataSource.numberOfTabs()) label.frame = CGRect(x: xOffset, y: 0, width: width, height: self.frame.height) } else { label.frame = CGRect(x: xOffset, y: 0, width: label.frame.width + xPadding, height: self.frame.height) } scrollView.contentSize = CGSize(width: xOffset + label.frame.width, height: self.frame.height) scrollView.addSubview(label) labels.append(label) // Button let button = UIButton(frame: label.frame) button.tag = i button.addTarget(self, action: #selector(buttonPressed), for: .touchUpInside) scrollView.addSubview(button) xOffset += label.frame.width + xMargin } } } layoutIfNeeded() scrollView.frame = self.bounds } @objc internal func buttonPressed(_ sender: UIButton) { currentTabSelected = sender.tag delegate?.onTabSelected(currentTabSelected) animateIndicator(currentTabSelected) } // MARK: - Indicator view animations fileprivate func animateIndicator(_ index: Int) { if !(labels != nil && labels.count > 0 && labels.count > index) { return } let labelFrame = labels[index].frame UIView.animate(withDuration: 0.3, animations: { () -> Void in // Indicator animation let indicatorFrame = self.indicatorView.frame self.indicatorView.frame = CGRect(x: labelFrame.minX, y: indicatorFrame.minY, width: labelFrame.width, height: indicatorFrame.height) // Scroll animation if distributeEvenly is false if !self.distributeEvenly { if labelFrame.minX < self.frame.width/2 { // The first places self.scrollView.contentOffset = CGPoint(x: 0, y: 0) } else { // The rest // If the remaining space is smaller than a CGRectGetWidth(self.frame) let lastWidth = self.scrollView.contentSize.width - labelFrame.minX - (self.frame.width - labelFrame.width)/2 if lastWidth < self.frame.width/2 - labelFrame.width/2 { let xLastOffset = self.scrollView.contentSize.width - self.frame.width self.scrollView.contentOffset = CGPoint(x: xLastOffset, y: 0) } else { // If not let xOffset = (self.frame.width - labelFrame.width)/2 self.scrollView.contentOffset = CGPoint(x: labelFrame.minX - xOffset, y: 0) } } } }) } // MARK: - Public methods open func reloadData() { xOffset = 0 scrollView.subviews.forEach { $0.removeFromSuperview() } addTabsView() addIndicatorView() } open func setCurrentTab(_ index: Int) { currentTabSelected = index animateIndicator(index) } }
apache-2.0
def4f7b6fe16cd6da4e9ab4a4ec4b2b8
36.22093
155
0.584661
5.125701
false
false
false
false
julienbodet/wikipedia-ios
Wikipedia/Code/NSArray+WMFExtensions.swift
1
5189
import Foundation extension NSArray { /// @return The object at `index` if it's within range of the receiver, otherwise `nil`. @objc public func wmf_safeObjectAtIndex(_ index: Int) -> Any? { guard index > -1 && index < self.count else { return nil } return self[index] } /** * Used to find arrays that contain Nulls - returns: true if any objects are [NSNull null], otherwise false */ @objc public func wmf_containsNullObjects() -> Bool { var foundNull = false for (_, value) in self.enumerated() { if value is NSNull { foundNull = true } } return foundNull } /** Used to find arrays that contain Nulls or contain sub-dictionaries or arrays that contain Nulls - returns: true if any objects or sub-collection objects are [NSNull null], otherwise false */ @objc public func wmf_recursivelyContainsNullObjects() -> Bool { if self.wmf_containsNullObjects(){ return true } var foundNull = false for (_, value) in self.enumerated() { if let value = value as? NSDictionary { foundNull = value.wmf_recursivelyContainsNullObjects() } if let value = value as? NSArray { foundNull = value.wmf_recursivelyContainsNullObjects() } } return foundNull } /** Select the first `n` elements from an array. - parameter intLength: The max length - returns: A new array with the first `n` items in the receiver, or the receiver if `n` exceeds the number of items in the array. */ @objc public func wmf_arrayByTrimmingToLength(_ intLength: Int) -> NSArray { if (self.count == 0 || self.count < intLength) { return self; } return self.wmf_safeSubarrayWithRange(NSMakeRange(0, intLength)); } /** Select the last `n` elements from an array :param: length The max length :returns: A new array with the last `n` items in the receiver, or the receiver if `n` exceeds the number of items in the array. */ @objc public func wmf_arrayByTrimmingToLengthFromEnd(_ intLength: Int) -> NSArray { if (self.count == 0 || self.count < intLength || intLength < 0) { return self; } return self.wmf_safeSubarrayWithRange(NSMakeRange(self.count-intLength, intLength)); } /** Get all elements in an array except the first. - returns: All but the first element of the receiver, or an empty array if there was only one element. */ @objc public func wmf_arrayByRemovingFirstElement() -> NSArray { return wmf_safeSubarrayWithRange(NSMakeRange(1, self.count - 1)) } /** Returns a subarray from the receiver, limited to its bounds. - parameter range: The range of the desired items. - returns: A subarray with the desired items, constrained by the number of items in the receiver. */ @objc public func wmf_safeSubarrayWithRange(_ range: NSRange) -> NSArray { if range.location > self.count - 1 || WMFRangeIsNotFoundOrEmpty(range) { return NSArray() } let safeLength: Int = { if WMFRangeGetMaxIndex(range) <= UInt(self.count) { return range.length } else { let countMinusLocation = self.count - range.location guard countMinusLocation > 0 else { return 0 } return countMinusLocation } }() if safeLength == 0 { return NSArray() } let safeRange = NSMakeRange(range.location, safeLength) return self.subarray(with: safeRange) as NSArray } /// - returns: A reversed copy of the receiver. @objc public func wmf_reverseArray() -> AnyObject { return self.reverseObjectEnumerator().allObjects as AnyObject; } /** Return an new array by interleaving the receiver with otherArray. The first element in the receiver is always first. :param: otherArray The array whose lements to interleave :returns: The interleaved array */ @objc public func wmf_arrayByInterleavingElementsFromArray(_ otherArray: NSArray) -> NSArray { let newArray = self.mutableCopy() as! NSMutableArray; otherArray.enumerateObjects({ (object, index, stop) -> Void in /* When adding items in an array from the begining, you need to adjust the index of each subssequent item to account for the previous added items. Multipling the index by 2 does this. */ var newIndex = 2*index + 1; newIndex = newIndex > newArray.count ? newArray.count : newIndex; newArray.insert(object, at: newIndex); }) return newArray; } @objc public func wmf_hasDuplicateElements() -> Bool { return NSSet(array: self as [AnyObject]).count != count; } }
mit
5e961ad5ddbd057c37a2c01c03c695b8
33.138158
120
0.596261
4.712988
false
false
false
false
diejmon/SugarRecord
library/CoreData/Base/SugarRecordCDContext.swift
1
7918
// // SugarRecordCDContext.swift // SugarRecord // // Created by Pedro Piñera Buendía on 11/09/14. // Copyright (c) 2014 SugarRecord. All rights reserved. // import Foundation import CoreData public class SugarRecordCDContext: SugarRecordContext { /// NSManagedObjectContext context let contextCD: NSManagedObjectContext /** SugarRecordCDContext initializer passing the CoreData context :param: context NSManagedObjectContext linked to this SugarRecord context :returns: Initialized SugarRecordCDContext */ init (context: NSManagedObjectContext) { self.contextCD = context } /** Notifies the context that you're going to start an edition/removal/saving operation */ public func beginWriting() { // CD begin writing does nothing } /** Notifies the context that you've finished an edition/removal/saving operation */ public func endWriting() { var error: NSError? self.contextCD.save(&error) if error != nil { let exception: NSException = NSException(name: "Database operations", reason: "Couldn't perform your changes in the context", userInfo: ["error": error!]) SugarRecord.handle(exception) } } /** * Asks the context for writing cancellation */ public func cancelWriting() { self.contextCD.rollback() } /** Creates and object in the context (without saving) :param: objectClass Class of the created object :returns: The created object in the context */ public func createObject(objectClass: AnyClass) -> AnyObject? { let managedObjectClass: NSManagedObject.Type = objectClass as! NSManagedObject.Type var object: AnyObject = NSEntityDescription.insertNewObjectForEntityForName(managedObjectClass.modelName(), inManagedObjectContext: self.contextCD) return object } /** Insert an object in the context :param: object NSManagedObject to be inserted in the context */ public func insertObject(object: AnyObject) { moveObject(object as! NSManagedObject, inContext: self.contextCD) } /** Find NSManagedObject objects in the database using the passed finder :param: finder SugarRecordFinder usded for querying (filtering/sorting) :returns: Objects fetched */ public func find(finder: SugarRecordFinder) -> SugarRecordResults { let fetchRequest: NSFetchRequest = SugarRecordCDContext.fetchRequest(fromFinder: finder) var error: NSError? var objects: [NSManagedObject]? = self.contextCD.executeFetchRequest(fetchRequest, error: &error) as? [NSManagedObject] SugarRecordLogger.logLevelInfo.log("Found \((objects == nil) ? 0 : objects!.count) objects in database") if objects == nil { objects = [NSManagedObject]() } return SugarRecordResults(results: SugarRecordArray(array: objects!), finder: finder) } /** Returns the NSFetchRequest from a given Finder :param: finder SugarRecord finder with the information about the filtering and sorting :returns: Created NSFetchRequest */ public class func fetchRequest(fromFinder finder: SugarRecordFinder) -> NSFetchRequest { let objectClass: NSObject.Type = finder.objectClass! let managedObjectClass: NSManagedObject.Type = objectClass as! NSManagedObject.Type let fetchRequest: NSFetchRequest = NSFetchRequest(entityName: managedObjectClass.modelName()) fetchRequest.predicate = finder.predicate var sortDescriptors: [NSSortDescriptor] = finder.sortDescriptors switch finder.elements { case .first: fetchRequest.fetchLimit = 1 case .last: if !sortDescriptors.isEmpty{ sortDescriptors[0] = NSSortDescriptor(key: "key", ascending: true) let sortDescriptor: NSSortDescriptor = first(sortDescriptors)! let sortDescriptorKey = sortDescriptor.getKey() let ascending: Bool = sortDescriptor.ascending sortDescriptors[0] = NSSortDescriptor(key: sortDescriptorKey! as String, ascending: ascending) } fetchRequest.fetchLimit = 1 case .firsts(let number): fetchRequest.fetchLimit = number case .lasts(let number): if !sortDescriptors.isEmpty{ let sortDescriptor: NSSortDescriptor = first(sortDescriptors)! let sortDescriptorKey = sortDescriptor.getKey() let ascending: Bool = sortDescriptor.ascending sortDescriptors[0] = NSSortDescriptor(key: sortDescriptorKey! as String, ascending: ascending) } fetchRequest.fetchLimit = number case .all: break } fetchRequest.sortDescriptors = sortDescriptors return fetchRequest } /** Deletes a given object :param: object NSManagedObject to be deleted :returns: If the object has been properly deleted */ public func deleteObject(object: AnyObject) -> SugarRecordContext { let managedObject: NSManagedObject? = object as? NSManagedObject let objectInContext: NSManagedObject? = moveObject(managedObject!, inContext: contextCD) if objectInContext == nil { let exception: NSException = NSException(name: "Database operations", reason: "Imposible to remove object \(object)", userInfo: nil) SugarRecord.handle(exception) } SugarRecordLogger.logLevelInfo.log("Object removed from database") self.contextCD.deleteObject(managedObject!) return self } /** Deletes NSManagedObject objecs from an array :param: objects NSManagedObject objects to be dleeted :returns: If the deletion has been successful */ public func deleteObjects(objects: SugarRecordResults) -> () { var objectsDeleted: Int = 0 for (var index = 0; index < Int(objects.count) ; index++) { let object: AnyObject! = objects[index] if (object != nil) { let _ = deleteObject(object) } } SugarRecordLogger.logLevelInfo.log("Deleted \(objects.count) objects") } /** * Count the number of entities of the given type */ public func count(objectClass: AnyClass, predicate: NSPredicate? = nil) -> Int { let managedObjectClass: NSManagedObject.Type = objectClass as! NSManagedObject.Type let fetchRequest: NSFetchRequest = NSFetchRequest(entityName: managedObjectClass.modelName()) fetchRequest.predicate = predicate var error: NSError? var count = self.contextCD.countForFetchRequest(fetchRequest, error: &error) SugarRecordLogger.logLevelInfo.log("Found \(count) objects in database") return count } //MARK: - HELPER METHODS /** Moves an NSManagedObject from one context to another :param: object NSManagedObject to be moved :param: context NSManagedObjectContext where the object is going to be moved to :returns: NSManagedObject in the new context */ func moveObject(object: NSManagedObject, inContext context: NSManagedObjectContext) -> NSManagedObject? { var error: NSError? let objectInContext: NSManagedObject? = context.existingObjectWithID(object.objectID, error: &error) if error != nil { let exception: NSException = NSException(name: "Database operations", reason: "Couldn't move the object into the new context", userInfo: nil) SugarRecord.handle(exception) return nil } else { return objectInContext } } }
mit
9f46c31c551ba80e219a02481305187f
34.662162
166
0.656013
5.433082
false
false
false
false
eselkin/DirectionFieldiOS
DirectionField/GraphViewController.swift
1
62030
// // GraphViewController.swift // DirectionField // // Created by Eli Selkin on 12/31/15. // Copyright © 2015 DifferentialEq. All rights reserved. // import UIKit import TwitterKit class GraphViewController: UIViewController, UITextFieldDelegate { var tutorialCompleteTest:Bool = false var tutorialSection = 0 var tutorialOverlay:CAShapeLayer! var tutorialView:UIView! var tutorialComplete:DBtutorial! var translation:CGPoint = CGPoint.zero var totalScale:CGFloat = 1 var scaleEvents:Int = 0 var translationEvents:Int = 0 var lineLayer: CAShapeLayer! var drawingScreen: UIImageView! var matrix:TwoDimMatrix? var ev:TwoDimMatrix? var evec:[TwoDimMatrix]? var pointArray: [CGPoint]? // This has only the points we selected! var matrixObject:DBMatrix! var red:Float = 0.0 var green:Float = 0.0 var blue:Float = 0.0 var alpha:Float = 1.0 // default opaque black var solutionColor: UIColor { return UIColor(colorLiteralRed: red, green: green, blue: blue, alpha: alpha) } var vectorFieldColor: UIColor = UIColor(colorLiteralRed: 0.5, green: 0.5, blue: 0.5, alpha: 0.5) var vectorFieldWidth:CGFloat = 1.0 var scale:CGFloat = 1.0 var lineWidth:CGFloat = 1.0 var solutionWidth:CGFloat = 2.0 var numTicksPerQuadrant:CGFloat = 10 var offset:CGPoint = CGPoint.zero var tickValue:CGFloat = 0.1 var arrowLength:Float = 10.0 var arrowHeight:Float = 10.0 var showDots = false var showAxes = true var showBorder = true var showArrows = true var showNumbers = true var showTickmarks = true var solutions = [Solution]() var vectorField = [Solution]() var colorRedVal:Float = 0.0 var colorGreenVal:Float = 0.0 var colorBlueVal:Float = 0.0 var colorMix:UIColor { get { return UIColor(colorLiteralRed: colorRedVal, green: colorGreenVal, blue: colorBlueVal, alpha: 1.0) } } var arrowLengthVal:Float = 10.0 var arrowHeightVal:Float = 10.0 var showDotsVal:Bool = false var showAxesVal:Bool = true var showBorderVal:Bool = true var showArrowsVal:Bool = true var showNumbersVal:Bool = true var showTickmarksVal:Bool = true @IBOutlet weak var xInput:UITextField! @IBOutlet weak var yInput:UITextField! var colorRed:UISlider! var colorGreen:UISlider! var colorBlue:UISlider! var sliderArrowH:UISlider! var sliderArrowL:UISlider! var switchDots:UISwitch! var switchAxes:UISwitch! var switchBorder:UISwitch! var switchNumbers:UISwitch! var switchTickmarks:UISwitch! var switchArrows:UISwitch! var viewArrow:UIImageView! var colorView:UIView! var optionsView:UIView! var optionsDict = Dictionary<String, UIView>() override func viewWillAppear(animated: Bool) { // oops this occurs after viewDidLoad! Can't use this to get the info from the database } func startTutorial() { dfDBQueue.inDatabase { db in self.tutorialComplete = DBtutorial.fetchOne(db, "SELECT * from tutorial") if (self.tutorialComplete != nil && self.tutorialComplete!.tutorialcomplete == 1) { self.tutorialCompleteTest = true } } } func finishTutorial() { dfDBQueue.inDatabase { db in let tutorialComplete:DBtutorial = DBtutorial(complete: 1) do { try tutorialComplete.insert(db) } catch { tutorialComplete.tutorialcomplete = 1 try! tutorialComplete.update(db) } } } @IBAction func longPress(sender: UILongPressGestureRecognizer) { if (sender.state == UIGestureRecognizerState.Began) { addTrajectoryPoint(sender.locationOfTouch(0, inView: self.drawingScreen)) } } @IBAction func panMotion(recognizer: UIPanGestureRecognizer) { translation = recognizer.translationInView(self.drawingScreen) translationEvents++ if translationEvents == 3 { pan(translation) recognizer.setTranslation(CGPoint.zero, inView: drawingScreen) translationEvents = 0 } } func pan(distance: CGPoint) { // here CGpoint is a distance offset.x -= (round((90*distance.x / self.drawingScreen.frame.width)) * tickValue * scale) offset.x = offset.x.roundToPlaces(3) offset.y += (round((90*distance.y / self.drawingScreen.frame.height)) * tickValue * scale) offset.y = offset.y.roundToPlaces(3) if (offset.y < -100) { offset.y = -100; } if (offset.x < -100) { offset.x = -100; } if (offset.y > 100) { offset.y = 100; } if (offset.x > 100) { offset.x = 100; } for sol in solutions { sol.isDrawn = false } self.drawingScreen.subviews.forEach({ $0.removeFromSuperview() }) self.drawingScreen.image = UIImage() if (showBorder){ self.drawingScreen.image = drawBorder(self.drawingScreen) } if (showNumbers){ self.drawingScreen.image = drawNumbers(self.drawingScreen) } if (showTickmarks){ self.drawingScreen.image = drawTicks(self.drawingScreen) } if (showAxes){ self.drawingScreen.image = drawAxes(self.drawingScreen) } self.drawingScreen.image = drawSolutions(self.drawingScreen) } @IBAction func pinchzoomMotion(sender: UIPinchGestureRecognizer) { totalScale *= sender.scale scaleEvents++ if (scaleEvents == 3) { pinchZoom(totalScale) totalScale = 1 scaleEvents = 0 sender.scale = 1 } } func pinchZoom(ts: CGFloat){ scale /= ts scale = scale.roundToPlaces(2) if scale <= 0.01 { scale = 0.01 } if scale >= 50 { scale = 50 } for sol in solutions { sol.isDrawn = false } self.drawingScreen.subviews.forEach({ $0.removeFromSuperview() }) self.drawingScreen.image = UIImage() if (showBorder){ self.drawingScreen.image = drawBorder(self.drawingScreen) } if (showNumbers){ self.drawingScreen.image = drawNumbers(self.drawingScreen) } if (showTickmarks){ self.drawingScreen.image = drawTicks(self.drawingScreen) } if (showAxes){ self.drawingScreen.image = drawAxes(self.drawingScreen) } self.drawingScreen.image = drawSolutions(self.drawingScreen) } func drawBorder(image: UIImageView) -> UIImage { UIGraphicsBeginImageContext(image.frame.size) image.image?.drawInRect(CGRect(x: 0, y: 0, width: image.frame.width, height: image.frame.height)) let context = UIGraphicsGetCurrentContext() CGContextSetStrokeColorWithColor(context, UIColor.blackColor().CGColor) CGContextSetLineWidth(context, lineWidth) CGContextStrokeRect(context, CGRect(x: 0, y: 0, width: image.frame.width, height: image.frame.width)) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image } func drawAxes(image: UIImageView) -> UIImage { let centerX = image.frame.width / 2.0 let centerY = image.frame.height / 2.0 UIGraphicsBeginImageContext(image.frame.size) image.image?.drawInRect(CGRect(x: 0, y: 0, width: image.frame.width, height: image.frame.height)) let context = UIGraphicsGetCurrentContext() CGContextSetStrokeColorWithColor(context, UIColor.blueColor().CGColor) CGContextSetLineWidth(context, lineWidth) CGContextBeginPath(context) CGContextMoveToPoint(context, centerX, 0) CGContextAddLineToPoint(context, centerX, image.frame.height) CGContextMoveToPoint(context, 0, centerY) CGContextAddLineToPoint(context, image.frame.width, centerY) CGContextStrokePath(context) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image } func drawTicks(image: UIImageView) -> UIImage { UIGraphicsBeginImageContext(image.frame.size) image.image?.drawInRect(CGRect(x: 0, y: 0, width: image.frame.width, height: image.frame.height)) let context = UIGraphicsGetCurrentContext() CGContextSetStrokeColorWithColor(context, UIColor.blueColor().CGColor) CGContextSetLineCap(context, CGLineCap.Round) CGContextSetLineWidth(context, lineWidth) let centerX = image.frame.width / 2.0 let centerY = image.frame.height / 2.0 let tickSeparation = round(centerX / numTicksPerQuadrant) CGContextBeginPath(context) for (var i:CGFloat = 0; i < centerX; i += tickSeparation) { CGContextMoveToPoint(context, centerX + i, centerY-2) CGContextAddLineToPoint(context, centerX + i, centerY+2) CGContextMoveToPoint(context, centerX - i, centerY-2) CGContextAddLineToPoint(context, centerX - i, centerY+2) CGContextMoveToPoint(context, centerX - 2, centerY-i) CGContextAddLineToPoint(context, centerX + 2, centerY-i) CGContextMoveToPoint(context, centerX - 2, centerY+i) CGContextAddLineToPoint(context, centerX + 2, centerY+i) } CGContextStrokePath(context) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image } func drawNumbers(image: UIImageView) -> UIImage { UIGraphicsBeginImageContext(image.frame.size) image.image?.drawInRect(CGRect(x: 0, y: 0, width: image.frame.width, height: image.frame.height)) let context = UIGraphicsGetCurrentContext() CGContextSetStrokeColorWithColor(context, UIColor.blueColor().CGColor) CGContextSetLineCap(context, CGLineCap.Round) CGContextSetLineWidth(context, lineWidth) let textFont: UIFont = UIFont(name: "Helvetica", size: 7)! let textColor: UIColor = UIColor.blueColor() let textFontAttr = [ NSFontAttributeName: textFont, NSForegroundColorAttributeName: textColor ] let centerX = image.frame.width / 2.0 let centerY = image.frame.height / 2.0 let tickSeparation = round(centerX / numTicksPerQuadrant) CGContextBeginPath(context) var ticks:CGFloat = 1.0 for (var i:CGFloat = tickSeparation; i < centerX; i += 2*tickSeparation) { let pointPosX:NSString = NSString(string: (offset.x + (ticks * tickValue * scale)).roundToPlaces(3).description) let pointNegX:NSString = NSString(string: (offset.x - (ticks * tickValue * scale)).roundToPlaces(3).description) let pointPosY:NSString = NSString(string: (offset.y + (ticks * tickValue * scale)).roundToPlaces(3).description) let pointNegY:NSString = NSString(string: (offset.y - (ticks * tickValue * scale)).roundToPlaces(3).description) pointPosX.drawAtPoint(CGPoint(x: centerX+i, y: centerY+5), withAttributes: textFontAttr) pointNegY.drawAtPoint(CGPoint(x: centerX+5, y: centerY+i), withAttributes: textFontAttr) pointNegX.drawAtPoint(CGPoint(x: centerX-i, y: centerY+5), withAttributes: textFontAttr) pointPosY.drawAtPoint(CGPoint(x: centerX+5, y: centerY-i), withAttributes: textFontAttr) ticks += 2 } CGContextStrokePath(context) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image } func addTrajectoryPoint(XY:CGPoint) -> () { let coordPoint = convertTouchToCoordinate(XY) pointArray!.append(coordPoint) solutions = addPoint(solutions, point: coordPoint) writePointsToDB() self.drawingScreen.image = drawSolutions(self.drawingScreen) } func writePointsToDB() -> Bool { var listPoints:String = "" for (var i = 0; i < pointArray!.count - 1; i++) { listPoints.appendContentsOf("(" + pointArray![i].x.description + "," + pointArray![i].y.description + "),") } let xVal = pointArray![(pointArray?.count)!-1].x.description let yVal = pointArray![(pointArray?.count)!-1].y.description listPoints.appendContentsOf("(" + xVal + "," + yVal + ")") matrixObject.points = listPoints do { try dfDBQueue.inDatabase { db in try self.matrixObject.update(db) } } catch { } return true } func convertCoordinateToPhysical(XY: CGPoint) -> (CGPoint) { let screenHalfHeight = ((self.drawingScreen.image?.size.height )!) / 2.0 let screenHalfWidth = ((self.drawingScreen.image?.size.width )!) / 2.0 // let's do this by proportion let distanceOnHalfScreen = tickValue * numTicksPerQuadrant * scale let proportionOnScreenX = ((XY.x - offset.x) / distanceOnHalfScreen) // print ("X: " + XY.x.description + " is " + proportionOnScreenX.description + " of Distance: " + distanceOnHalfScreen.description) let proportionOnScreenY = ((XY.y - offset.y) / distanceOnHalfScreen) return CGPoint(x: screenHalfWidth + (proportionOnScreenX * screenHalfWidth), y: screenHalfHeight - (proportionOnScreenY * screenHalfHeight) ) } func convertTouchToCoordinate(XY: CGPoint) -> (CGPoint) { let screenHalfHeight = ((self.drawingScreen.image?.size.height )!) / 2.0 let screenHalfWidth = ((self.drawingScreen.image?.size.width )!) / 2.0 let proportionOfHalfX = ( abs(screenHalfWidth - XY.x) / screenHalfWidth ) * (XY.x < screenHalfWidth ? -1 : 1) let proportionOfHalfY = ( abs(screenHalfHeight - XY.y) / screenHalfHeight ) * (XY.y > screenHalfHeight ? -1 : 1) let xValue = scale * proportionOfHalfX + offset.x let yValue = scale * proportionOfHalfY + offset.y return CGPoint(x: xValue.roundToPlaces(5), y: yValue.roundToPlaces(5)) } func drawSolutions(image: UIImageView) -> UIImage { UIGraphicsBeginImageContext(image.frame.size) image.image?.drawInRect(CGRect(x: 0, y: 0, width: image.frame.width, height: image.frame.height)) image.clipsToBounds = true let context = UIGraphicsGetCurrentContext() CGContextSetStrokeColorWithColor(context, solutionColor.CGColor) CGContextSetLineCap(context, CGLineCap.Round) CGContextSetLineWidth(context, solutionWidth) let linePath = UIBezierPath() let beginPoints = UIBezierPath() let endPoints = UIBezierPath() for sol in solutions { let t0 = sol.getXY(0) var getNext = false var previous = CGPoint.zero if (!sol.isDrawn && sol.pointsAtT.count > 0) { sol.isDrawn = true let arrayStart = convertCoordinateToPhysical(sol.pointsAtT[0]) linePath.moveToPoint(arrayStart) for point in sol.pointsAtT { let newPoint = convertCoordinateToPhysical(point) if (newPoint.x < image.frame.width+500 && newPoint.x >= -500 && newPoint.y < image.frame.height + 500 && newPoint.y >= -500) { if approxEqual(point, RHS: t0, epsilon: 0.00001) { getNext = true previous = newPoint beginPoints.moveToPoint(newPoint) beginPoints.addLineToPoint(newPoint) } else if (getNext){ getNext = false endPoints.moveToPoint(newPoint) endPoints.addLineToPoint(newPoint) // make the arrowhead let dy = newPoint.y - previous.y let dx = newPoint.x - previous.x if (showArrows) { let blueArrow = UIImage(named: "blueArrow") let blueView = UIImageView(image: blueArrow) blueView.frame = CGRect(origin: newPoint, size: CGSize(width: CGFloat(arrowLength), height: CGFloat(arrowHeight))) blueView.center = previous image.addSubview(blueView) if (dx != 0){ blueView.transform = CGAffineTransformMakeRotation(atan(dy/dx)) if (dy >= 0 && dx <= 0) || (dy <= 0 && dx <= 0) { blueView.transform = CGAffineTransformRotate(blueView.transform, CGFloat(M_PI)) } } } } linePath.addLineToPoint(newPoint) linePath.moveToPoint(newPoint) } else { linePath.moveToPoint(newPoint) } } } } CGContextAddPath(context, linePath.CGPath) CGContextStrokePath(context) if (showDots) { CGContextAddPath(context, beginPoints.CGPath) CGContextSetStrokeColorWithColor(context, UIColor.greenColor().CGColor) CGContextSetLineCap(context, CGLineCap.Round) CGContextSetLineWidth(context, 5.0) CGContextStrokePath(context) CGContextAddPath(context, endPoints.CGPath) CGContextSetStrokeColorWithColor(context, UIColor.blueColor().CGColor) CGContextSetLineCap(context, CGLineCap.Round) CGContextSetLineWidth(context, 5.0) CGContextStrokePath(context) } let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image } func unitVectorFromPointSlope(point: CGPoint, dy: CGFloat, dx: CGFloat) -> CGPoint { var result:CGPoint = CGPoint() if dx == 0 { result.x = point.x if (dy > 0){ result.y = point.y + tickValue } else { result.y = point.y - tickValue } } else { let tanθ = dy/dx // slope == hypotenuse let secSqθ = 1 + tanθ * tanθ let cosSqθ = 1 / secSqθ let sinSqθ = 1 - cosSqθ var cosθ = sqrt(cosSqθ) var sinθ = sqrt(sinSqθ) if (dy <= 0) { sinθ *= -1 } if (dx <= 0) { cosθ *= -1 } result.x = point.x + cosθ * tickValue * scale result.y = point.y + sinθ * tickValue * scale } return result } // Add coordinate point on coordinate axes not touch axes func addPoint(var whichArray:[Solution], point: CGPoint) -> ([Solution]) { do { // test if matrix is imaginary so we need iSolution or just Solution let Rs = [(self.ev?.getValueAt(1, col: 1))!, (self.ev?.getValueAt(2, col: 1))!] let Pt = [point.x, point.y] if (self.ev?.getValueAt(1, col: 1).imaginary != 0.0) || (self.ev?.getValueAt(2, col: 1).imaginary != 0.0) { let Lambda0 = ev!.getValueAt(2, col: 1).real let Mu0 = self.ev!.getValueAt(2, col: 1).imaginary let A00 = self.evec![0].getValueAt(1, col: 1).real let B00 = self.evec![0].getValueAt(1, col: 1).imaginary let A01 = self.evec![0].getValueAt(2, col: 1).real let B01 = self.evec![0].getValueAt(2, col: 1).imaginary let imaginary = iSolution(x: Pt, Rs: Rs, EigVecs: self.evec!, As: [A00, A01], Bs: [B00, B01], mu: Mu0, lambda: Lambda0) try imaginary.determineCs() dispatch_sync(dispatch_get_global_queue(QOS_CLASS_USER_INTERACTIVE, 0)) { imaginary.isDrawn = true imaginary.generatePoints(); imaginary.generateDerivatives() imaginary.isDrawn = false // now we can draw it whichArray.append(imaginary) } return whichArray } else { let real = Solution(x: Pt, Rs: [(self.ev?.getValueAt(1, col: 1))!, (self.ev?.getValueAt(2, col: 1))!], EigVecs: self.evec!) try real.determineCs() dispatch_sync(dispatch_get_global_queue(QOS_CLASS_USER_INTERACTIVE, 0)) { real.isDrawn = true real.generatePoints() real.generateDerivatives() real.isDrawn = false // now we can draw it whichArray.append(real) } return whichArray } } catch { // could not add! return whichArray } } override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { xInput.resignFirstResponder() yInput.resignFirstResponder() } // MARK: - Taken from http://www.globalnerdy.com/2015/04/27/how-to-program-an-ios-text-field-that-takes-only-numeric-input-or-specific-characters-with-a-maximum-length/ func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool { let currentText = textField.text ?? "" let prospectiveText = (currentText as NSString).stringByReplacingCharactersInRange(range, withString: string) return prospectiveText.containsOnlyCharactersIn("0123456789.+-") } // get rid of keyboard func textFieldShouldReturn(textField: UITextField) -> Bool { textField.resignFirstResponder() return true; } override func viewDidLoad() { super.viewDidLoad() drawingScreen = self.view.viewWithTag(1) as! UIImageView drawingScreen.clipsToBounds = true let buttonOptions = self.view.viewWithTag(2) as! UIButton let xInput = self.view.viewWithTag(4) as! UITextField let yInput = self.view.viewWithTag(6) as! UITextField let buttonAddPoint = self.view.viewWithTag(7) as! UIButton let buttonDrawDirectionField = self.view.viewWithTag(8) as! UIButton let buttonScreenShot = self.view.viewWithTag(9) as! UIButton let buttonTweet = self.view.viewWithTag(10) as! UIButton buttonOptions.addTarget(self, action: "graphOptionsPressed:", forControlEvents: UIControlEvents.TouchUpInside) buttonAddPoint.addTarget(self, action: "addButtonPressed:", forControlEvents: UIControlEvents.TouchUpInside) buttonDrawDirectionField.addTarget(self, action: "generateVectorField:", forControlEvents: UIControlEvents.TouchUpInside) buttonScreenShot.addTarget(self, action: "takeScreenShot:", forControlEvents: UIControlEvents.TouchUpInside) buttonTweet.addTarget(self, action: "tweet:", forControlEvents: UIControlEvents.TouchUpInside) xInput.delegate = self yInput.delegate = self xInput.keyboardType = UIKeyboardType.NumbersAndPunctuation yInput.keyboardType = UIKeyboardType.NumbersAndPunctuation //let minWidthHeight = round(min(view.frame.width, view.frame.height)) self.drawingScreen.subviews.forEach({ $0.removeFromSuperview() }) self.drawingScreen.image = UIImage() if pointArray == nil { pointArray = [CGPoint]() } for point in pointArray! { solutions = addPoint(solutions, point: point) self.drawingScreen.image = drawSolutions(self.drawingScreen) } if (showBorder){ self.drawingScreen.image = drawBorder(self.drawingScreen) } if (showNumbers){ self.drawingScreen.image = drawNumbers(self.drawingScreen) } if (showTickmarks){ self.drawingScreen.image = drawTicks(self.drawingScreen) } if (showAxes){ self.drawingScreen.image = drawAxes(self.drawingScreen) } self.drawingScreen.image = drawSolutions(self.drawingScreen) // Do any additional setup after loading the view. startTutorial() if (!tutorialCompleteTest){ showTutorial(self.view) } } // take screen shot // - Mark - http://stackoverflow.com/questions/30696307/how-to-convert-a-uiview-to-a-image func screenShot() -> UIImage { UIGraphicsBeginImageContext(self.drawingScreen.bounds.size) self.drawingScreen.layer.renderInContext(UIGraphicsGetCurrentContext()!) let screenShotImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return screenShotImage } func image (image: UIImage, didFinishSavingWithError error: NSError?, contextInfo:UnsafePointer<Void>) { } @IBAction func takeScreenShot (sender: UIButton!) { let shot = screenShot() UIImageWriteToSavedPhotosAlbum(shot, self, "image:didFinishSavingWithError:contextInfo:", nil) } @IBAction func tweet (sender: UIButton!) { // taken into prepareforsegue because that was being done before this action! } @IBAction func showTutorial(sender: UIView!) { if tutorialSection == 0 { tutorialView = UIView(frame: CGRect(origin: (self.navigationController?.view.frame.origin)!, size: CGSize(width: (self.navigationController?.view.frame.width)!, height: (self.navigationController?.view.frame.height)!))) tutorialView.frame = (self.navigationController?.view.frame)! tutorialView.userInteractionEnabled = true self.navigationController?.view.addSubview(tutorialView) self.navigationController?.view.bringSubviewToFront(tutorialView) tutorialOverlay = CAShapeLayer() tutorialOverlay.frame = tutorialView.frame tutorialOverlay.hidden = false let tutorialButton1 = UIButton() tutorialButton1.frame = CGRect(origin: CGPoint.zero, size: CGSize(width: 400, height: 200)) tutorialButton1.addTarget(self, action: "showTutorial:", forControlEvents: UIControlEvents.TouchUpInside) let tutorialText1 = UILabel(frame: CGRect(x: 0, y: tutorialButton1.frame.height+5, width: 300, height: 240)) tutorialText1.numberOfLines = 0 tutorialText1.lineBreakMode = NSLineBreakMode.ByWordWrapping tutorialText1.font = UIFont.systemFontOfSize(16) tutorialText1.textColor = UIColor.whiteColor() tutorialText1.textAlignment = NSTextAlignment.Center tutorialText1.text = "This is the most major component of the application. On the drawing screen you can long press to add an initial value to your functions. You can pan up/down/left/right with your finger. You can pinch and zoom too." let tutorialPath1 = UIBezierPath(roundedRect: CGRect(x: 0, y: 0, width: (self.navigationController?.view.frame.width)!, height: (self.navigationController?.view.frame.height)!), cornerRadius: 0.0) let tutorialCircle1 = UIBezierPath(roundedRect: tutorialButton1.frame, cornerRadius: 20) tutorialPath1.appendPath(tutorialCircle1) tutorialPath1.usesEvenOddFillRule = true tutorialOverlay.path = tutorialPath1.CGPath tutorialOverlay.fillRule = kCAFillRuleEvenOdd tutorialOverlay.fillColor = UIColor.lightGrayColor().CGColor tutorialOverlay.opacity = 0.9 tutorialView.layer.addSublayer(tutorialOverlay) tutorialView.addSubview(tutorialButton1) tutorialView.addSubview(tutorialText1) tutorialSection++ } else if tutorialSection == 1 { tutorialView.subviews.forEach({$0.removeFromSuperview()}) tutorialOverlay.path = nil tutorialOverlay = CAShapeLayer() tutorialOverlay.frame = tutorialView.frame tutorialOverlay.hidden = false let tutorialButton1 = UIButton() let buttonAddPoint = self.view.viewWithTag(7) as! UIButton tutorialButton1.frame = CGRect(origin: CGPoint(x: drawingScreen.frame.origin.x, y: buttonAddPoint.frame.origin.y), size: CGSize(width: drawingScreen.frame.width, height: 40)) tutorialButton1.addTarget(self, action: "showTutorial:", forControlEvents: UIControlEvents.TouchUpInside) let tutorialText1 = UILabel(frame: CGRect(x: 20, y:60, width: 300, height: 150)) tutorialText1.numberOfLines = 0 tutorialText1.lineBreakMode = NSLineBreakMode.ByWordWrapping tutorialText1.font = UIFont.systemFontOfSize(16) tutorialText1.textColor = UIColor.whiteColor() tutorialText1.textAlignment = NSTextAlignment.Center tutorialText1.text = "This row of can add a specific point that you could not add by touch. It's practically impossible to add a specific point." let tutorialPath1 = UIBezierPath(roundedRect: CGRect(x: 0, y: 0, width: (self.navigationController?.view.frame.width)!, height: (self.navigationController?.view.frame.height)!), cornerRadius: 0.0) let tutorialCircle1 = UIBezierPath(roundedRect: tutorialButton1.frame, cornerRadius: 20) tutorialPath1.appendPath(tutorialCircle1) tutorialPath1.usesEvenOddFillRule = true tutorialOverlay.path = tutorialPath1.CGPath tutorialOverlay.fillRule = kCAFillRuleEvenOdd tutorialOverlay.fillColor = UIColor.lightGrayColor().CGColor tutorialOverlay.opacity = 0.9 tutorialView.layer.addSublayer(tutorialOverlay) tutorialView.addSubview(tutorialButton1) tutorialView.addSubview(tutorialText1) tutorialSection++ } else if tutorialSection == 2 { tutorialView.subviews.forEach({$0.removeFromSuperview()}) tutorialOverlay.path = nil tutorialOverlay = CAShapeLayer() tutorialOverlay.frame = tutorialView.frame tutorialOverlay.hidden = false let tutorialButton1 = UIButton() let buttonDrawDirectionField = self.view.viewWithTag(8) as! UIButton tutorialButton1.frame = buttonDrawDirectionField.frame tutorialButton1.addTarget(self, action: "showTutorial:", forControlEvents: UIControlEvents.TouchUpInside) let tutorialText1 = UILabel(frame: CGRect(x: 20, y:180, width: 300, height: 150)) tutorialText1.numberOfLines = 0 tutorialText1.lineBreakMode = NSLineBreakMode.ByWordWrapping tutorialText1.font = UIFont.systemFontOfSize(16) tutorialText1.textColor = UIColor.whiteColor() tutorialText1.textAlignment = NSTextAlignment.Center tutorialText1.text = "Here you can display the vector field of the functions you have inputted. You will see a general behavior of the curves." let tutorialPath1 = UIBezierPath(roundedRect: CGRect(x: 0, y: 0, width: (self.navigationController?.view.frame.width)!, height: (self.navigationController?.view.frame.height)!), cornerRadius: 0.0) let tutorialCircle1 = UIBezierPath(roundedRect: tutorialButton1.frame, cornerRadius: 20) tutorialPath1.appendPath(tutorialCircle1) tutorialPath1.usesEvenOddFillRule = true tutorialOverlay.path = tutorialPath1.CGPath tutorialOverlay.fillRule = kCAFillRuleEvenOdd tutorialOverlay.fillColor = UIColor.lightGrayColor().CGColor tutorialOverlay.opacity = 0.9 tutorialView.layer.addSublayer(tutorialOverlay) tutorialView.addSubview(tutorialButton1) tutorialView.addSubview(tutorialText1) tutorialSection++ } else if tutorialSection == 3 { tutorialView.subviews.forEach({$0.removeFromSuperview()}) tutorialOverlay.path = nil tutorialOverlay = CAShapeLayer() tutorialOverlay.frame = tutorialView.frame tutorialOverlay.hidden = false let tutorialButton1 = UIButton() let buttonOptions = self.view.viewWithTag(2) as! UIButton tutorialButton1.frame = buttonOptions.frame tutorialButton1.addTarget(self, action: "showTutorial:", forControlEvents: UIControlEvents.TouchUpInside) let tutorialText1 = UILabel(frame: CGRect(x: 20, y: 180, width: 300, height: 150)) tutorialText1.numberOfLines = 0 tutorialText1.lineBreakMode = NSLineBreakMode.ByWordWrapping tutorialText1.font = UIFont.systemFontOfSize(16) tutorialText1.textColor = UIColor.whiteColor() tutorialText1.textAlignment = NSTextAlignment.Center tutorialText1.text = "This will open a window of graph options, such as showing or not showing the arrows on the curves or the color of the solution curves." let tutorialPath1 = UIBezierPath(roundedRect: CGRect(x: 0, y: 0, width: (self.navigationController?.view.frame.width)!, height: (self.navigationController?.view.frame.height)!), cornerRadius: 0.0) let tutorialCircle1 = UIBezierPath(roundedRect: tutorialButton1.frame, cornerRadius: 20) tutorialPath1.appendPath(tutorialCircle1) tutorialPath1.usesEvenOddFillRule = true tutorialOverlay.path = tutorialPath1.CGPath tutorialOverlay.fillRule = kCAFillRuleEvenOdd tutorialOverlay.fillColor = UIColor.lightGrayColor().CGColor tutorialOverlay.opacity = 0.9 tutorialView.layer.addSublayer(tutorialOverlay) tutorialView.addSubview(tutorialButton1) tutorialView.addSubview(tutorialText1) tutorialSection++ } else { tutorialView.subviews.forEach({$0.removeFromSuperview()}) tutorialOverlay.path = nil tutorialOverlay = nil tutorialView.hidden = true finishTutorial() } } @IBAction func generateVectorField(sender:UIButton!) { let intervalWidth = drawingScreen.frame.width / 5 let intervalHeight = drawingScreen.frame.height / 5 for (var i:CGFloat = 0.0; i <= drawingScreen.frame.width; i += intervalWidth ) { for (var j:CGFloat = 0.0; j <= drawingScreen.frame.height; j += intervalHeight ) { let pointForVF = CGPoint(x: i,y: j) let realPoint = convertTouchToCoordinate(pointForVF) vectorField = addPoint(vectorField, point: realPoint) } } // a little loop to wait for all dispatched solutions to return var finished = false while !finished { for curve in vectorField { if curve.pointsAtT.count != 101 { finished = false break } if curve.derivativesAtT.count != 101 { finished = false break } } finished = true } // problem with the fact that addPoint is sending these things out on a side queue and therefore we'll have to wait // I can't find out if there's a particular, "wait until the queue is finished type of thing" let time = dispatch_time(dispatch_time_t(DISPATCH_TIME_NOW), Int64(NSEC_PER_SEC)/2) dispatch_after(time, dispatch_get_main_queue()) { self.drawingScreen.image = self.drawVectorField(self.drawingScreen) } } func drawVectorField(image: UIImageView) -> (UIImage) { UIGraphicsBeginImageContext(image.frame.size) image.image?.drawInRect(CGRect(x: 0, y: 0, width: image.frame.width, height: image.frame.height)) image.clipsToBounds = true let context = UIGraphicsGetCurrentContext() CGContextSetStrokeColorWithColor(context, vectorFieldColor.CGColor) CGContextSetLineCap(context, CGLineCap.Round) CGContextSetLineWidth(context, vectorFieldWidth) let linePath = UIBezierPath() for sol in vectorField { if (!sol.isDrawn && sol.pointsAtT.count > 0) { sol.isDrawn = true if (sol.derivativesAtT.count == sol.pointsAtT.count) { for (var i = 0; i < sol.derivativesAtT.count; i++) { let currentPoint = convertCoordinateToPhysical(sol.pointsAtT[i]) // we are a point in bounds linePath.moveToPoint(currentPoint) var unitEndPoint = unitVectorFromPointSlope(sol.pointsAtT[i], dy: sol.derivativesAtT[i], dx: 1.0) unitEndPoint = convertCoordinateToPhysical(unitEndPoint) linePath.addLineToPoint(unitEndPoint) } } } } // } CGContextAddPath(context, linePath.CGPath) CGContextStrokePath(context) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image } @IBAction func addButtonPressed(sender:UIButton!) { let formatString = "^([+-]?[0-9]*[.]?[0-9]+)$" if (xInput == nil || yInput == nil) { return } if !requiredFormat(xInput.text!, regex: formatString) { xInput.backgroundColor = UIColor.lightGrayColor() let time = dispatch_time(dispatch_time_t(DISPATCH_TIME_NOW), 4 * Int64(NSEC_PER_SEC)) dispatch_after(time, dispatch_get_main_queue()) { self.xInput.backgroundColor = UIColor.whiteColor() } return } if !requiredFormat(yInput.text!, regex: formatString) { yInput.backgroundColor = UIColor.lightGrayColor() let time = dispatch_time(dispatch_time_t(DISPATCH_TIME_NOW), 4 * Int64(NSEC_PER_SEC)) dispatch_after(time, dispatch_get_main_queue()) { self.yInput.backgroundColor = UIColor.whiteColor() } return } // strings are formatted correctly let xValue = (xInput.text! as NSString).floatValue let yValue = (yInput.text! as NSString).floatValue xInput.text! = "" yInput.text! = "" let coordPoint = CGPoint(x: CGFloat(xValue), y: CGFloat(yValue)) solutions = addPoint(solutions, point: coordPoint) pointArray!.append(coordPoint) writePointsToDB() self.drawingScreen.image = drawSolutions(self.drawingScreen) } @IBAction func graphOptionsPressed(sender:UIButton!) { optionsView = UIView() switchAxes = UISwitch() switchDots = UISwitch() switchBorder = UISwitch() switchArrows = UISwitch() switchNumbers = UISwitch() switchTickmarks = UISwitch() // popover a view overlay optionsView.backgroundColor = UIColor.whiteColor() optionsView.alpha = 0.9 optionsView.frame = self.view.frame optionsView.bounds = optionsView.frame optionsView.hidden = false self.view.addSubview(optionsView) // make changes let buttonMakeChanges = UIButton(type: UIButtonType.System) as UIButton buttonMakeChanges.setTitle("Save Changes", forState: UIControlState.Normal) buttonMakeChanges.translatesAutoresizingMaskIntoConstraints = false optionsView.addSubview(buttonMakeChanges) optionsDict["buttonMakeChanges"] = buttonMakeChanges buttonMakeChanges.addTarget(self, action: "getFinalStates:", forControlEvents: UIControlEvents.TouchUpInside) // cancel let cancelButton = UIButton(type: UIButtonType.System) as UIButton cancelButton.setTitle("Cancel Changes", forState: UIControlState.Normal) cancelButton.translatesAutoresizingMaskIntoConstraints = false optionsView.addSubview(cancelButton) optionsDict["cancelButton"] = cancelButton cancelButton.addTarget(self, action: "revertStates:", forControlEvents: UIControlEvents.TouchUpInside) // dots let labelDots = UILabel() labelDots.translatesAutoresizingMaskIntoConstraints = false labelDots.text = "Show Dots" switchDots.translatesAutoresizingMaskIntoConstraints = false switchDots.setOn(showDots, animated: true) switchDots.on = showDots switchDots.addTarget(self, action: "getStates:", forControlEvents: UIControlEvents.ValueChanged) optionsView.addSubview(labelDots) optionsView.addSubview(switchDots) optionsDict["labelDots"] = labelDots optionsDict["switchDots"] = switchDots // axes let labelAxes = UILabel() labelAxes.translatesAutoresizingMaskIntoConstraints = false labelAxes.text = "Show Axes" switchAxes.translatesAutoresizingMaskIntoConstraints = false switchAxes.setOn(showAxes, animated: true) switchAxes.on = showAxes switchAxes.addTarget(self, action: "getStates:", forControlEvents: UIControlEvents.ValueChanged) optionsView.addSubview(labelAxes) optionsView.addSubview(switchAxes) optionsDict["labelAxes"] = labelAxes optionsDict["switchAxes"] = switchAxes // Border let labelBorder = UILabel() labelBorder.translatesAutoresizingMaskIntoConstraints = false labelBorder.text = "Show Border" switchBorder.translatesAutoresizingMaskIntoConstraints = false switchBorder.setOn(showBorder, animated: true) switchBorder.on = showBorder switchBorder.addTarget(self, action: "getStates:", forControlEvents: UIControlEvents.ValueChanged) optionsView.addSubview(labelBorder) optionsView.addSubview(switchBorder) optionsDict["labelBorder"] = labelBorder optionsDict["switchBorder"] = switchBorder // Arrows let labelArrows = UILabel() labelArrows.translatesAutoresizingMaskIntoConstraints = false labelArrows.text = "Show Arrows" switchArrows.translatesAutoresizingMaskIntoConstraints = false switchArrows.setOn(showArrows, animated: true) switchArrows.on = showArrows switchArrows.addTarget(self, action: "getStates:", forControlEvents: UIControlEvents.ValueChanged) optionsView.addSubview(labelArrows) optionsView.addSubview(switchArrows) optionsDict["labelArrows"] = labelArrows optionsDict["switchArrows"] = switchArrows // Numbers let labelNumbers = UILabel() labelNumbers.translatesAutoresizingMaskIntoConstraints = false labelNumbers.text = "Show Numbers" switchNumbers.translatesAutoresizingMaskIntoConstraints = false switchNumbers.setOn(showNumbers, animated: true) switchNumbers.on = showNumbers switchNumbers.addTarget(self, action: "getStates:", forControlEvents: UIControlEvents.ValueChanged) optionsView.addSubview(labelNumbers) optionsView.addSubview(switchNumbers) optionsDict["labelNumbers"] = labelNumbers optionsDict["switchNumbers"] = switchNumbers // Tickmarks let labelTickmarks = UILabel() labelTickmarks.translatesAutoresizingMaskIntoConstraints = false labelTickmarks.text = "Show Tickmarks" switchTickmarks.translatesAutoresizingMaskIntoConstraints = false switchTickmarks.setOn(showTickmarks, animated: true) switchTickmarks.on = showTickmarks switchTickmarks.addTarget(self, action: "getStates:", forControlEvents: UIControlEvents.ValueChanged) optionsView.addSubview(labelTickmarks) optionsView.addSubview(switchTickmarks) optionsDict["labelTickmarks"] = labelTickmarks optionsDict["switchTickmarks"] = switchTickmarks // sliderArrowLength let labelArrowL = UILabel() labelArrowL.text = "Arrow Length" labelArrowL.translatesAutoresizingMaskIntoConstraints = false sliderArrowL = UISlider() sliderArrowL.maximumValue = 50.0 sliderArrowL.minimumValue = 0.0 sliderArrowL.value = arrowLength sliderArrowL.translatesAutoresizingMaskIntoConstraints = false optionsView.addSubview(sliderArrowL) optionsView.addSubview(labelArrowL) optionsDict["labelArrowL"] = labelArrowL optionsDict["sliderArrowL"] = sliderArrowL // sliderArrowHeight let labelArrowH = UILabel() labelArrowH.text = "Arrow Height" labelArrowH.translatesAutoresizingMaskIntoConstraints = false sliderArrowH = UISlider() sliderArrowH.maximumValue = 50.0 sliderArrowH.minimumValue = 0.0 sliderArrowH.value = arrowHeight sliderArrowH.translatesAutoresizingMaskIntoConstraints = false sliderArrowH.addTarget(self, action: "getStates:", forControlEvents: UIControlEvents.ValueChanged) sliderArrowL.addTarget(self, action: "getStates:", forControlEvents: UIControlEvents.ValueChanged) optionsView.addSubview(sliderArrowH) optionsView.addSubview(labelArrowH) optionsDict["labelArrowH"] = labelArrowH optionsDict["sliderArrowH"] = sliderArrowH // color picker let labelRed = UILabel() labelRed.text = "Solution line color Red:" labelRed.translatesAutoresizingMaskIntoConstraints = false colorRed = UISlider() colorRed.translatesAutoresizingMaskIntoConstraints = false colorRed.addTarget(self, action: "getStates:", forControlEvents: UIControlEvents.ValueChanged) colorRed.maximumValue = 1.0 colorRed.minimumValue = 0.0 colorRed.value = red optionsView.addSubview(labelRed) optionsView.addSubview(colorRed) optionsDict["colorRed"] = colorRed optionsDict["labelRed"] = labelRed let labelBlue = UILabel() labelBlue.text = "Blue:" labelBlue.translatesAutoresizingMaskIntoConstraints = false colorBlue = UISlider() colorBlue.maximumValue = 1.0 colorBlue.minimumValue = 0.0 colorBlue.value = blue colorBlue.translatesAutoresizingMaskIntoConstraints = false colorBlue.addTarget(self, action: "getStates:", forControlEvents: UIControlEvents.ValueChanged) optionsView.addSubview(labelBlue) optionsView.addSubview(colorBlue) optionsDict["colorBlue"] = colorBlue optionsDict["labelBlue"] = labelBlue let labelGreen = UILabel() labelGreen.text = "Green:" labelGreen.translatesAutoresizingMaskIntoConstraints = false colorGreen = UISlider() colorGreen.maximumValue = 1.0 colorGreen.minimumValue = 0.0 colorGreen.value = green colorGreen.translatesAutoresizingMaskIntoConstraints = false optionsView.addSubview(labelGreen) optionsView.addSubview(colorGreen) optionsDict["colorGreen"] = colorGreen optionsDict["labelGreen"] = labelGreen colorGreen.addTarget(self, action: "getStates:", forControlEvents: UIControlEvents.ValueChanged) colorView = UIView() colorView.backgroundColor = colorMix colorView.translatesAutoresizingMaskIntoConstraints = false optionsView.addSubview(colorView) optionsDict["colorView"] = colorView let hConstraintButton = NSLayoutConstraint.constraintsWithVisualFormat("H:|-(>=1)-[buttonMakeChanges(>=50)]-(<=10)-|", options: [], metrics: nil, views: optionsDict) let vConstraintButton = NSLayoutConstraint.constraintsWithVisualFormat("V:|-(<=50)-[buttonMakeChanges(50)]", options: [], metrics: nil, views: optionsDict) let hConstraintDots = NSLayoutConstraint.constraintsWithVisualFormat("H:|-(>=1)-[labelDots(<=100)]-(<=1)-[switchDots(>=30)]-(<=10)-|", options: [.AlignAllCenterY], metrics: nil, views: optionsDict) let vConstraintDots0 = NSLayoutConstraint.constraintsWithVisualFormat("V:[buttonMakeChanges]-(>=5)-[labelDots(>=20)]", options: [], metrics: nil, views: optionsDict) let vConstraintDots1 = NSLayoutConstraint.constraintsWithVisualFormat("V:[buttonMakeChanges]-(>=5)-[switchDots(>=20)]", options: [], metrics: nil, views: optionsDict) let hConstraintAxes = NSLayoutConstraint.constraintsWithVisualFormat("H:|-(>=1)-[labelAxes(<=100)]-(<=1)-[switchAxes(>=30)]-(<=10)-|", options: [.AlignAllCenterY], metrics: nil, views: optionsDict) let vConstraintAxes0 = NSLayoutConstraint.constraintsWithVisualFormat("V:[labelDots]-(>=5)-[labelAxes(>=20)]", options: [], metrics: nil, views: optionsDict) let vConstraintAxes1 = NSLayoutConstraint.constraintsWithVisualFormat("V:[switchDots]-(>=5)-[switchAxes(>=20)]", options: [], metrics: nil, views: optionsDict) let hConstraintBorder = NSLayoutConstraint.constraintsWithVisualFormat("H:|-(>=1)-[labelBorder(<=100)]-(<=1)-[switchBorder(>=30)]-(<=10)-|", options: [.AlignAllCenterY], metrics: nil, views: optionsDict) let vConstraintBorder0 = NSLayoutConstraint.constraintsWithVisualFormat("V:[labelAxes]-(>=5)-[labelBorder(>=20)]", options: [], metrics: nil, views: optionsDict) let vConstraintBorder1 = NSLayoutConstraint.constraintsWithVisualFormat("V:[switchAxes]-(>=5)-[switchBorder(>=20)]", options: [], metrics: nil, views: optionsDict) let hConstraintArrows = NSLayoutConstraint.constraintsWithVisualFormat("H:|-(>=1)-[labelArrows(<=150)]-(<=1)-[switchArrows(>=30)]-(<=10)-|", options: [.AlignAllCenterY], metrics: nil, views: optionsDict) let vConstraintArrows0 = NSLayoutConstraint.constraintsWithVisualFormat("V:[labelBorder]-(>=5)-[labelArrows(>=20)]", options: [], metrics: nil, views: optionsDict) let vConstraintArrows1 = NSLayoutConstraint.constraintsWithVisualFormat("V:[switchBorder]-(>=5)-[switchArrows(>=20)]", options: [], metrics: nil, views: optionsDict) let hConstraintNumbers = NSLayoutConstraint.constraintsWithVisualFormat("H:|-(>=1)-[labelNumbers(<=150)]-(<=1)-[switchNumbers(>=30)]-(<=10)-|", options: [.AlignAllCenterY], metrics: nil, views: optionsDict) let vConstraintNumbers0 = NSLayoutConstraint.constraintsWithVisualFormat("V:[labelArrows]-(>=5)-[labelNumbers(>=20)]", options: [], metrics: nil, views: optionsDict) let vConstraintNumbers1 = NSLayoutConstraint.constraintsWithVisualFormat("V:[switchArrows]-(>=5)-[switchNumbers(>=20)]", options: [], metrics: nil, views: optionsDict) let hConstraintTickmarks = NSLayoutConstraint.constraintsWithVisualFormat("H:|-(>=1)-[labelTickmarks(<=150)]-(<=1)-[switchTickmarks(>=30)]-(<=10)-|", options: [.AlignAllCenterY], metrics: nil, views: optionsDict) let vConstraintTickmarks0 = NSLayoutConstraint.constraintsWithVisualFormat("V:[labelNumbers]-(>=5)-[labelTickmarks(>=20)]", options: [], metrics: nil, views: optionsDict) let vConstraintTickmarks1 = NSLayoutConstraint.constraintsWithVisualFormat("V:[switchNumbers]-(>=5)-[switchTickmarks(>=20)]", options: [], metrics: nil, views: optionsDict) if (self.view.frame.height >= 600) { let hConstraintArrowL = NSLayoutConstraint.constraintsWithVisualFormat("H:|-(>=1)-[labelArrowL(<=150)]-(<=1)-[sliderArrowL(>=100)]-(<=10)-|", options: [.AlignAllCenterY], metrics: nil, views: optionsDict) let vConstraintArrowL0 = NSLayoutConstraint.constraintsWithVisualFormat("V:[labelTickmarks]-(>=5)-[labelArrowL(>=20)]", options: [], metrics: nil, views: optionsDict) let vConstraintArrowL1 = NSLayoutConstraint.constraintsWithVisualFormat("V:[switchTickmarks]-(>=5)-[sliderArrowL(>=20)]", options: [], metrics: nil, views: optionsDict) let hConstraintArrowH = NSLayoutConstraint.constraintsWithVisualFormat("H:|-(>=1)-[labelArrowH(<=150)]-(<=1)-[sliderArrowH(>=100)]-(<=10)-|", options: [.AlignAllCenterY], metrics: nil, views: optionsDict) let vConstraintArrowH0 = NSLayoutConstraint.constraintsWithVisualFormat("V:[labelArrowL]-(>=5)-[labelArrowH(>=20)]", options: [], metrics: nil, views: optionsDict) let vConstraintArrowH1 = NSLayoutConstraint.constraintsWithVisualFormat("V:[sliderArrowL]-(>=5)-[sliderArrowH(>=20)]", options: [], metrics: nil, views: optionsDict) optionsView.addConstraints(hConstraintArrowL) optionsView.addConstraints(vConstraintArrowL0) optionsView.addConstraints(vConstraintArrowL1) optionsView.addConstraints(hConstraintArrowH) optionsView.addConstraints(vConstraintArrowH0) optionsView.addConstraints(vConstraintArrowH1) } let hConstraintRed = NSLayoutConstraint.constraintsWithVisualFormat("H:|-(>=1)-[labelRed(>=50)]-(<=1)-[colorRed(>=100)]-(<=10)-|", options: [.AlignAllCenterY], metrics: nil, views: optionsDict) var vConstraintRed0 = NSLayoutConstraint.constraintsWithVisualFormat("V:[labelArrowH]-(>=5)-[labelRed(>=20)]", options: [], metrics: nil, views: optionsDict) var vConstraintRed1 = NSLayoutConstraint.constraintsWithVisualFormat("V:[sliderArrowH]-(>=5)-[colorRed(>=20)]", options: [], metrics: nil, views: optionsDict) if (self.view.frame.height < 600) { vConstraintRed0 = NSLayoutConstraint.constraintsWithVisualFormat("V:[labelTickmarks]-(>=5)-[labelRed(>=20)]", options: [], metrics: nil, views: optionsDict) vConstraintRed1 = NSLayoutConstraint.constraintsWithVisualFormat("V:[switchTickmarks]-(>=5)-[colorRed(>=20)]", options: [], metrics: nil, views: optionsDict) } let hConstraintGreen = NSLayoutConstraint.constraintsWithVisualFormat("H:|-(>=1)-[labelGreen(<=75)]-(<=1)-[colorGreen(>=100)]-(<=10)-|", options: [.AlignAllCenterY], metrics: nil, views: optionsDict) let vConstraintGreen0 = NSLayoutConstraint.constraintsWithVisualFormat("V:[labelRed]-(>=5)-[labelGreen(>=20)]", options: [], metrics: nil, views: optionsDict) let vConstraintGreen1 = NSLayoutConstraint.constraintsWithVisualFormat("V:[colorRed]-(>=5)-[colorGreen(>=20)]", options: [], metrics: nil, views: optionsDict) let hConstraintBlue = NSLayoutConstraint.constraintsWithVisualFormat("H:|-(>=1)-[labelBlue(<=50)]-(<=1)-[colorBlue(>=100)]-(<=10)-|", options: [.AlignAllCenterY], metrics: nil, views: optionsDict) let vConstraintBlue0 = NSLayoutConstraint.constraintsWithVisualFormat("V:[labelGreen]-(>=5)-[labelBlue(>=20)]", options: [], metrics: nil, views: optionsDict) let vConstraintBlue1 = NSLayoutConstraint.constraintsWithVisualFormat("V:[colorGreen]-(>=5)-[colorBlue(>=20)]", options: [], metrics: nil, views: optionsDict) let hConstraintMix = NSLayoutConstraint.constraintsWithVisualFormat("H:|-(>=1)-[colorView(>=30)]-(<=10)-|", options: [.AlignAllCenterY], metrics: nil, views: optionsDict) let vConstraintMix = NSLayoutConstraint.constraintsWithVisualFormat("V:[colorBlue]-(>=5)-[colorView(>=30)]", options: [], metrics: nil, views: optionsDict) let hConstraintCancel = NSLayoutConstraint.constraintsWithVisualFormat("H:|-(>=1)-[cancelButton(>=50)]-(<=10)-|", options: [.AlignAllCenterY], metrics: nil, views: optionsDict) let vConstraintCancel = NSLayoutConstraint.constraintsWithVisualFormat("V:[colorView]-(>=5)-[cancelButton(>=20)]", options: [], metrics: nil, views: optionsDict) optionsView.addConstraints(hConstraintButton) optionsView.addConstraints(vConstraintButton) optionsView.addConstraints(hConstraintDots) optionsView.addConstraints(vConstraintDots0) optionsView.addConstraints(vConstraintDots1) optionsView.addConstraints(hConstraintAxes) optionsView.addConstraints(vConstraintAxes0) optionsView.addConstraints(vConstraintAxes1) optionsView.addConstraints(hConstraintBorder) optionsView.addConstraints(vConstraintBorder0) optionsView.addConstraints(vConstraintBorder1) optionsView.addConstraints(hConstraintArrows) optionsView.addConstraints(vConstraintArrows0) optionsView.addConstraints(vConstraintArrows1) optionsView.addConstraints(hConstraintNumbers) optionsView.addConstraints(vConstraintNumbers0) optionsView.addConstraints(vConstraintNumbers1) optionsView.addConstraints(hConstraintTickmarks) optionsView.addConstraints(vConstraintTickmarks0) optionsView.addConstraints(vConstraintTickmarks1) optionsView.addConstraints(hConstraintRed) optionsView.addConstraints(vConstraintRed0) optionsView.addConstraints(vConstraintRed1) optionsView.addConstraints(hConstraintBlue) optionsView.addConstraints(vConstraintBlue0) optionsView.addConstraints(vConstraintBlue1) optionsView.addConstraints(hConstraintGreen) optionsView.addConstraints(vConstraintGreen0) optionsView.addConstraints(vConstraintGreen1) optionsView.addConstraints(hConstraintMix) optionsView.addConstraints(vConstraintMix) optionsView.addConstraints(hConstraintCancel) optionsView.addConstraints(vConstraintCancel) } @IBAction func getStates(sender: UIView!) -> () { colorRedVal = colorRed.value colorGreenVal = colorGreen.value colorBlueVal = colorBlue.value colorView.backgroundColor = colorMix arrowHeightVal = sliderArrowH.value arrowLengthVal = sliderArrowL.value showDotsVal = switchDots.on showAxesVal = switchAxes.on showBorderVal = switchBorder.on showArrowsVal = switchArrows.on showNumbersVal = switchNumbers.on showTickmarksVal = switchTickmarks.on if (!showArrowsVal) { sliderArrowH.enabled = false sliderArrowL.enabled = false } else { sliderArrowH.enabled = true sliderArrowL.enabled = true } } @IBAction func getFinalStates(sender: UIButton!) -> () { red = colorRedVal blue = colorBlueVal green = colorGreenVal arrowHeight = arrowHeightVal arrowLength = arrowLengthVal showDots = showDotsVal showAxes = showAxesVal showArrows = showArrowsVal showBorder = showBorderVal showNumbers = showNumbersVal showTickmarks = showTickmarksVal optionsView.hidden = true self.drawingScreen.subviews.forEach({ $0.removeFromSuperview() }) if (showBorder){ self.drawingScreen.image = drawBorder(self.drawingScreen) } if (showNumbers){ self.drawingScreen.image = drawNumbers(self.drawingScreen) } if (showTickmarks){ self.drawingScreen.image = drawTicks(self.drawingScreen) } if (showAxes){ self.drawingScreen.image = drawAxes(self.drawingScreen) } self.drawingScreen.image = drawSolutions(self.drawingScreen) } @IBAction func revertStates(sender: UIButton!) -> () { colorRedVal = red colorRed.value = 0.0 colorBlueVal = blue colorBlue.value = 0.0 colorGreenVal = green colorGreen.value = 0.0 arrowHeightVal = arrowHeight sliderArrowH.value = 10.0 arrowLengthVal = arrowLength sliderArrowL.value = 10.0 showDotsVal = showDots switchDots.on = showDots showAxesVal = showAxes switchAxes.on = showAxes showBorderVal = showBorder switchBorder.on = showBorder showNumbersVal = showNumbers switchNumbers.on = showNumbers showTickmarksVal = showTickmarks switchTickmarks.on = showTickmarks optionsView.hidden = true // don't redraw } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { let tweetImage = screenShot() UIImageWriteToSavedPhotosAlbum(tweetImage, self, "image:didFinishSavingWithError:contextInfo:", nil) let nextViewController = segue.destinationViewController as!TwitterViewController nextViewController.tweetImage = tweetImage nextViewController.tweetMatrix = matrix?.description } } // MARK - Credit - http://stackoverflow.com/questions/27338573/rounding-a-double-value-to-x-number-of-decimal-places-in-swift // Sebastian & Sandy extension Double { /// Rounds the double to decimal places value func roundToPlaces(places:Int) -> Double { let divisor = pow(10.0, Double(places)) return round(self * divisor) / divisor } } extension Float32 { /// Rounds the double to decimal places value func roundToPlaces(places:Int) -> Float32 { let divisor = powf(10.0, Float32(places)) return Float32(round(self * divisor) / divisor) } } extension CGFloat { /// Rounds the double to decimal places value func roundToPlaces(places:Int) -> CGFloat { let divisor = powf(10.0, Float32(places)) return CGFloat(round(self * CGFloat(divisor)) / CGFloat(divisor)) } }
gpl-3.0
f9760cad1064f3fe5fd2b332eb1b998a
49.955629
248
0.649686
4.844009
false
false
false
false
Tommy1990/swiftWibo
SwiftWibo/SwiftWibo/Classes/Tools/EPMSQLManager.swift
1
1749
// // EPMSQLManager.swift // SwiftWibo // // Created by 马继鵬 on 17/4/4. // Copyright © 2017年 7TH. All rights reserved. // import UIKit import FMDB private let dbName = "home.db" class EPMSQLManager { static let shearManger:EPMSQLManager = EPMSQLManager() let queue :FMDatabaseQueue init() { let path = ((NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).last!) as NSString).appendingPathComponent(dbName) queue = FMDatabaseQueue(path: path) } fileprivate func creatTable(){ //获取文件 let file = Bundle.main.path(forResource: "db.sql", ofType: nil) let sql = try! String(contentsOfFile:file!) queue.inDatabase { (db) in if db!.executeStatements(sql){ print("建表成功") }else{ print("建表失败") } } } func selectDataWith(sql:String) -> [[String: Any]]{ var tempArray: [[String: Any]] = [[String:Any]]() EPMSQLManager.shearManger.queue.inDatabase { (db) in guard let resSet = db?.executeQuery(sql, withArgumentsIn: nil) else{ return } while resSet.next(){ var dict: [String: Any] = [String: Any]() for i in 0..<resSet.columnCount() { let key = resSet.columnName(for: i) let value = resSet.object(forColumnIndex: i) dict[key!] = value } tempArray.append(dict) } } return tempArray; } }
mit
b9a042f57ed7871e10faa62fc2180615
27.131148
212
0.543706
4.42268
false
false
false
false
SereivoanYong/Charts
Source/Charts/Data/Implementations/Standard/CandleEntry.swift
1
1266
// // CandleEntry.swift // Charts // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/Charts // import Foundation open class CandleEntry: Entry { /// shadow-high value open var high: CGFloat /// shadow-low value open var low: CGFloat /// open value open var open: CGFloat /// close value open var close: CGFloat public init(x: CGFloat, shadowH: CGFloat, shadowL: CGFloat, open: CGFloat, close: CGFloat, icon: UIImage? = nil, data: Any? = nil) { self.high = shadowH self.low = shadowL self.open = open self.close = close super.init(x: x, y: (shadowH + shadowL) / 2.0, icon: icon, data: data) } /// - returns: The overall range (difference) between shadow-high and shadow-low. open var shadowRange: CGFloat { return abs(high - low) } /// - returns: The body size (difference between open and close). open var bodyRange: CGFloat { return abs(open - close) } /// the center value of the candle. (Middle value between high and low) open override var y: CGFloat { get { return super.y } set { super.y = (high + low) / 2.0 } } }
apache-2.0
be306947670ccff91105b1b5d7872240
21.607143
134
0.633491
3.669565
false
false
false
false
tavultesoft/keymanweb
ios/engine/KMEI/KeymanEngine/Classes/Resource Data/Keyboard.swift
1
3324
// // Keyboard.swift // KeymanEngine // // Created by Gabriel Wong on 2017-10-24. // Copyright © 2017 SIL International. All rights reserved. // import Foundation /// Keyboard object for Keyman Cloud API 4.0. public struct Keyboard: Codable { /// Name of the keyboard. public var name: String /// ID of the keyboard. Always matches the filename of the keyboard. public var id: String /// Name of the keyboard `.js` file. public var filename: String /// The keyboard is the recommended default for the language. public var isDefault: Bool /// Keyboard targets a right-to-left script. public var isRTL: Bool /// Date the keyboard was last updated. public var lastModified: Date /// Size of the keyboard file in bytes. public var fileSize: Int? /// Dot-decimal version number of the keyboard. public var version: String /// Language objects linked to the keyboard. public var languages: [Language]? /// Font for input fields (and OSK if `oskFont` is not present). public var font: Font? /// Font for the OSK. public var oskFont: Font? enum CodingKeys: String, CodingKey { case name case id case filename case isDefault = "default" case isRTL = "rtl" case lastModified case fileSize case version case languages case font case oskFont } public init(name: String, id: String, filename: String, isDefault: Bool?, isRTL: Bool?, lastModified: Date, fileSize: Int?, version: String, languages: [Language]?, font: Font?, oskFont: Font?) { self.name = name self.id = id self.filename = filename self.isDefault = isDefault ?? false self.isRTL = isRTL ?? false self.lastModified = lastModified self.fileSize = fileSize self.version = version self.languages = languages self.font = font self.oskFont = oskFont } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) let name = try container.decode(String.self, forKey: .name) let id = try container.decode(String.self, forKey: .id) let filename = try container.decode(String.self, forKey: .filename) let isDefault = try container.decodeIfPresent(Bool.self, forKey: .isDefault) let isRTL = try container.decodeIfPresent(Bool.self, forKey: .isRTL) // TODO: Handle both seconds and ISO 8601 let lastModified = try container.decode(Date.self, forKey: .lastModified) let fileSize = try container.decodeIfPresent(Int.self, forKey: .fileSize) let version = try container.decode(String.self, forKey: .version) let languages = try container.decodeIfPresent([Language].self, forKey: .languages) let font = try container.decodeIfPresent(Font.self, forKey: .font) let oskFont = try container.decodeIfPresent(Font.self, forKey: .oskFont) self.init(name: name, id: id, filename: filename, isDefault: isDefault, isRTL: isRTL, lastModified: lastModified, fileSize: fileSize, version: version, languages: languages, font: font, oskFont: oskFont) } }
apache-2.0
aba1112961beeb6ddd3e61e6ba0020eb
28.669643
86
0.644297
4.472409
false
false
false
false
ArnavChawla/InteliChat
Carthage/Checkouts/swift-sdk/Source/DiscoveryV1/Models/Histogram.swift
1
1566
/** * Copyright IBM Corporation 2018 * * 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 /** Histogram. */ public struct Histogram: Decodable { /// The type of aggregation command used. For example: term, filter, max, min, etc. public var type: String? public var results: [AggregationResult]? /// Number of matching results. public var matchingResults: Int? /// Aggregations returned by the Discovery service. public var aggregations: [QueryAggregation]? /// The field where the aggregation is located in the document. public var field: String? /// Interval of the aggregation. (For 'histogram' type). public var interval: Int? // Map each property name to the key that shall be used for encoding/decoding. private enum CodingKeys: String, CodingKey { case type = "type" case results = "results" case matchingResults = "matching_results" case aggregations = "aggregations" case field = "field" case interval = "interval" } }
mit
0984b37bee5daae586c6c8545128152a
30.959184
87
0.696041
4.512968
false
false
false
false
coderZsq/coderZsq.target.swift
StudyNotes/Foundation/Algorithm4Swift/Algorithm4Swift/Algorithm/Raywenderlich/QuickSort.swift
1
2972
// // QuickSort.swift // Algorithm // // Created by 朱双泉 on 2018/5/24. // Copyright © 2018 Castie!. All rights reserved. // import Foundation func quickSort<T: Comparable>(_ a: [T]) -> [T] { guard a.count > 1 else { return a } let pivot = a[a.count / 2] let less = a.filter { $0 < pivot } let equal = a.filter { $0 == pivot } let greater = a.filter { $0 > pivot } return quickSort(less) + equal + quickSort(greater) } func partitionLomuto<T: Comparable>(_ a: inout [T], low: Int, high: Int) -> Int { let pivot = a[high] var i = low for j in low..<high { if a[j] <= pivot { (a[i], a[j]) = (a[j], a[i]) i += 1 } } (a[i], a[high]) = (a[high], a[i]) return i } public func quickSortLomuto<T: Comparable>(_ a: inout [T], low: Int, high: Int) { if low < high { let p = partitionLomuto(&a, low: low, high: high) quickSortLomuto(&a, low: low, high: p - 1) quickSortLomuto(&a, low: p + 1, high: high) } } func partitionHoare<T: Comparable>(_ a: inout [T], low: Int, high: Int) -> Int { let pivot = a[low] var i = low - 1 var j = high + 1 while true { repeat { j -= 1 } while a[j] > pivot repeat { i += 1 } while a[i] < pivot if i < j { a.swapAt(i, j) } else { return j } } } func quickSortHoare<T: Comparable>(_ a: inout [T], low: Int, high: Int) { if low < high { let p = partitionHoare(&a, low: low, high: high) quickSortHoare(&a, low: low, high: p) quickSortHoare(&a, low: p + 1, high: high) } } func quickSortRandom<T: Comparable>(_ a: inout [T], low: Int, high: Int) { if low < high { let pivotIndex = random(min: low, max: high) (a[pivotIndex], a[high]) = (a[high], a[pivotIndex]) let p = partitionLomuto(&a, low: low, high: high) quickSortRandom(&a, low: low, high: p - 1) quickSortRandom(&a, low: p + 1, high: high) } } func partitionDutchFlag<T: Comparable>(_ a: inout [T], low: Int, high: Int, pivotIndex: Int) -> (Int, Int) { let pivot = a[pivotIndex] var smaller = low var equal = low var larger = high while equal <= larger { if a[equal] < pivot { a.swapAt(smaller, equal) smaller += 1 equal += 1 } else if a[equal] == pivot { equal += 1 } else { a.swapAt(equal, larger) larger -= 1 } } return (smaller, larger) } func quickSortDutchFlag<T: Comparable>(_ a: inout [T], low: Int, high: Int) { if low < high { let pivotIndex = random(min: low, max: high) let (p, q) = partitionDutchFlag(&a, low: low, high: high, pivotIndex: pivotIndex) quickSortDutchFlag(&a, low: low, high: p - 1) quickSortDutchFlag(&a, low: q + 1, high: high) } }
mit
c0410e6eb97f66df79d7267799bab5d1
25.008772
108
0.518381
3.212351
false
false
false
false
tensorflow/swift-models
Gym/DQN/main.swift
1
8263
// Copyright 2020 The TensorFlow Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import Foundation import PythonKit import TensorFlow // Initialize Python. This comment is a hook for internal use, do not remove. let np = Python.import("numpy") let gym = Python.import("gym") let plt = Python.import("matplotlib.pyplot") class TensorFlowEnvironmentWrapper { let originalEnv: PythonObject init(_ env: PythonObject) { self.originalEnv = env } func reset() -> Tensor<Float> { let state = self.originalEnv.reset() return Tensor<Float>(numpy: np.array(state, dtype: np.float32))! } func step(_ action: Tensor<Int32>) -> ( state: Tensor<Float>, reward: Tensor<Float>, isDone: Tensor<Bool>, info: PythonObject ) { let (state, reward, isDone, info) = originalEnv.step(action.scalarized()).tuple4 let tfState = Tensor<Float>(numpy: np.array(state, dtype: np.float32))! let tfReward = Tensor<Float>(numpy: np.array(reward, dtype: np.float32))! let tfIsDone = Tensor<Bool>(numpy: np.array(isDone, dtype: np.bool))! return (tfState, tfReward, tfIsDone, info) } } func evaluate(_ agent: DeepQNetworkAgent) -> Float { let evalEnv = TensorFlowEnvironmentWrapper(gym.make("CartPole-v0")) var evalEpisodeReturn: Float = 0 var state: Tensor<Float> = evalEnv.reset() var reward: Tensor<Float> var evalIsDone: Tensor<Bool> = Tensor<Bool>(false) while evalIsDone.scalarized() == false { let action = agent.getAction(state: state, epsilon: 0) (state, reward, evalIsDone, _) = evalEnv.step(action) evalEpisodeReturn += reward.scalarized() } return evalEpisodeReturn } // Hyperparameters /// The size of the hidden layer of the 2-layer Q-network. The network has the /// shape observationSize - hiddenSize - actionCount. let hiddenSize: Int = 100 /// Maximum number of episodes to train the agent. The training is terminated /// early if maximum score is achieved during evaluation. let maxEpisode: Int = 1000 /// The initial epsilon value. With probability epsilon, the agent chooses a /// random action instead of the action that it thinks is the best. let epsilonStart: Float = 1 /// The terminal epsilon value. let epsilonEnd: Float = 0.01 /// The decay rate of epsilon. let epsilonDecay: Float = 1000 /// The learning rate for the Q-network. let learningRate: Float = 0.001 /// The discount factor. This measures how much to "discount" the future rewards /// that the agent will receive. The discount factor must be from 0 to 1 /// (inclusive). Discount factor of 0 means that the agent only considers the /// immediate reward and disregards all future rewards. Discount factor of 1 /// means that the agent values all rewards equally, no matter how distant /// in the future they may be. let discount: Float = 0.99 /// If enabled, uses the Double DQN update equation instead of the original DQN /// equation. This mitigates the overestimation problem of DQN. For more /// information about Double DQN, check Deep Reinforcement Learning with Double /// Q-learning (Hasselt, Guez, and Silver, 2015). let useDoubleDQN: Bool = true /// The maximum size of the replay buffer. If the replay buffer is full, the new /// element replaces the oldest element. let replayBufferCapacity: Int = 100000 /// The minimum replay buffer size before the training starts. Must be at least /// the training batch size. let minBufferSize: Int = 64 /// The training batch size. let batchSize: Int = 64 /// If enabled, uses Combined Experience Replay (CER) sampling instead of the /// uniform random sampling in the original DQN paper. Original DQN samples /// batch uniformly randomly in the replay buffer. CER always includes the most /// recent element and samples the rest of the batch uniformly randomly. This /// makes the agent more robust to different replay buffer capacities. For more /// information about Combined Experience Replay, check A Deeper Look at /// Experience Replay (Zhang and Sutton, 2017). let useCombinedExperienceReplay: Bool = true /// The number of steps between target network updates. The target network is /// a copy of the Q-network that is updated less frequently to stabilize the /// training process. let targetNetUpdateRate: Int = 5 /// The update rate for target network. In the original DQN paper, the target /// network is updated to be the same as the Q-network. Soft target network /// only updates the target network slightly towards the direction of the /// Q-network. The softTargetUpdateRate of 0 means that the target network is /// not updated at all, and 1 means that soft target network update is disabled. let softTargetUpdateRate: Float = 0.05 // Setup device let device: Device = Device.default // Initialize environment let env = TensorFlowEnvironmentWrapper(gym.make("CartPole-v0")) // Initialize agent var qNet = DeepQNetwork(observationSize: 4, hiddenSize: hiddenSize, actionCount: 2) var targetQNet = DeepQNetwork(observationSize: 4, hiddenSize: hiddenSize, actionCount: 2) let optimizer = Adam(for: qNet, learningRate: learningRate) var replayBuffer = ReplayBuffer( capacity: replayBufferCapacity, combined: useCombinedExperienceReplay ) var agent = DeepQNetworkAgent( qNet: qNet, targetQNet: targetQNet, optimizer: optimizer, replayBuffer: replayBuffer, discount: discount, minBufferSize: minBufferSize, doubleDQN: useDoubleDQN, device: device ) // RL Loop var stepIndex = 0 var episodeIndex = 0 var episodeReturn: Float = 0 var episodeReturns: [Float] = [] var losses: [Float] = [] var state = env.reset() var bestReturn: Float = 0 while episodeIndex < maxEpisode { stepIndex += 1 // Interact with environment let epsilon: Float = epsilonEnd + (epsilonStart - epsilonEnd) * exp(-1.0 * Float(stepIndex) / epsilonDecay) let action = agent.getAction(state: state, epsilon: epsilon) let (nextState, reward, isDone, _) = env.step(action) episodeReturn += reward.scalarized() // Save interaction to replay buffer replayBuffer.append( state: state, action: action, reward: reward, nextState: nextState, isDone: isDone) // Train agent losses.append(agent.train(batchSize: batchSize)) // Periodically update Target Net if stepIndex % targetNetUpdateRate == 0 { agent.updateTargetQNet(tau: softTargetUpdateRate) } // End-of-episode if isDone.scalarized() == true { state = env.reset() episodeIndex += 1 let evalEpisodeReturn = evaluate(agent) episodeReturns.append(evalEpisodeReturn) if evalEpisodeReturn > bestReturn { print( String( format: "Episode: %4d | Step %6d | Epsilon: %.03f | Train: %3d | Eval: %3d", episodeIndex, stepIndex, epsilon, Int(episodeReturn), Int(evalEpisodeReturn))) bestReturn = evalEpisodeReturn } if evalEpisodeReturn > 199 { print("Solved in \(episodeIndex) episodes with \(stepIndex) steps!") break } episodeReturn = 0 } // End-of-step state = nextState } // Save learning curve plt.plot(episodeReturns) plt.title("Deep Q-Network on CartPole-v0") plt.xlabel("Episode") plt.ylabel("Episode Return") plt.savefig("/tmp/dqnEpisodeReturns.png") plt.clf() // Save smoothed learning curve let runningMeanWindow: Int = 10 let smoothedEpisodeReturns = np.convolve( episodeReturns, np.ones((runningMeanWindow)) / np.array(runningMeanWindow, dtype: np.int32), mode: "same") plt.plot(episodeReturns) plt.title("Deep Q-Network on CartPole-v0") plt.xlabel("Episode") plt.ylabel("Smoothed Episode Return") plt.savefig("/tmp/dqnSmoothedEpisodeReturns.png") plt.clf() // // Save TD loss curve plt.plot(losses) plt.title("Deep Q-Network on CartPole-v0") plt.xlabel("Step") plt.ylabel("TD Loss") plt.savefig("/tmp/dqnTDLoss.png") plt.clf()
apache-2.0
64cc08a8db4b725af8f3e43a8f350534
35.888393
100
0.733753
3.786893
false
false
false
false
Bartlebys/Bartleby
Bartleby.xOS/operations/TriggersForIndexes.swift
1
6945
// // TriggersForIndexes.swift // BartlebyKit // // Created by Benoit Pereira da silva on 29/05/2016. // // import Foundation #if !USE_EMBEDDED_MODULES import Alamofire #endif open class TriggersForIndexes { open static func execute( from documentUID: String, indexes: [Int], sucessHandler success:@escaping (_ triggers: [Trigger])->(), failureHandler failure:@escaping (_ context: HTTPContext)->()) { if let document=Bartleby.sharedInstance.getDocumentByUID(documentUID){ let pathURL=document.baseURL.appendingPathComponent("triggers") let dictionary:[String:AnyObject]=["indexes":indexes as AnyObject] let urlRequest=HTTPManager.requestWithToken(inDocumentWithUID:document.UID, withActionName:"TriggersForIndexes", forMethod:"GET", and: pathURL) do { let r=try URLEncoding().encode(urlRequest,with:dictionary) request(r).validate().responseString(completionHandler: { (response) in let request=response.request let result=response.result let timeline=response.timeline let statusCode=response.response?.statusCode ?? 0 let metrics=Metrics() metrics.operationName="TriggersForIndexes" metrics.latency=timeline.latency metrics.requestDuration=timeline.requestDuration metrics.serializationDuration=timeline.serializationDuration metrics.totalDuration=timeline.totalDuration let context = HTTPContext( code: 3054667497, caller: "TriggersForIndexes.execute", relatedURL:request?.url, httpStatusCode: statusCode) if let request=request{ context.request=HTTPRequest(urlRequest: request) } if let data = response.data, let utf8Text = String(data: data, encoding: .utf8) { context.responseString=utf8Text } metrics.httpContext=context document.report(metrics) var reactions = Array<Reaction> () reactions.append(Reaction.track(result: result.value, context: context)) // Tracking if result.isFailure { /* let failureReaction = Reaction.dispatchAdaptiveMessage( context: context, title: NSLocalizedString("Unsuccessfull attempt", comment: "Unsuccessfull attempt"), body:"\(result.value)\n\(#file)\n\(#function)\nhttp Status code: (\(statusCode)", transmit: { (selectedIndex) -> () in }) reactions.append(failureReaction) */ failure(context) } else { if 200...299 ~= statusCode { if let data = response.data{ if let instance = try? JSON.decoder.decode([Trigger].self,from:data){ success(instance) }else{ let failureReaction = Reaction.dispatchAdaptiveMessage( context: context, title: NSLocalizedString("Deserialization issue", comment: "Deserialization issue"), body:"\(String(describing: result.value))\n\(#file)\n\(#function)\nhttp Status code: (\(statusCode))", transmit:{ (selectedIndex) -> () in }) reactions.append(failureReaction) failure(context) } }else{ let failureReaction = Reaction.dispatchAdaptiveMessage( context: context, title: NSLocalizedString("No String Deserialization issue", comment: "No String Deserialization issue"), body:"\(String(describing: result.value))\n\(#file)\n\(#function)\nhttp Status code: (\(statusCode))", transmit: { (selectedIndex) -> () in }) reactions.append(failureReaction) failure(context) } } else { // Bartlby does not currenlty discriminate status codes 100 & 101 // and treats any status code >= 300 the same way // because we consider that failures differentiations could be done by the caller. let failureReaction = Reaction.dispatchAdaptiveMessage( context: context, title: NSLocalizedString("Unsuccessfull attempt", comment: "Unsuccessfull attempt"), body:"\(String(describing: result.value))\n\(#file)\n\(#function)\nhttp Status code: (\(statusCode))", transmit: { (selectedIndex) -> () in }) reactions.append(failureReaction) failure(context) } } //Let s react according to the context. document.perform(reactions, forContext: context) }) }catch{ let context = HTTPContext( code:2 , caller: "TriggersForIndexes.execute", relatedURL:nil, httpStatusCode:500) context.responseString = "{\"message\":\"\(error)}" failure(context) } }else{ let context = HTTPContext( code: 1, caller: "TriggersForIndexes.execute", relatedURL:nil, httpStatusCode: 417) context.responseString = "{\"message\":\"Unexisting document with documentUID \(documentUID)\"}" failure(context) } } }
apache-2.0
7ecaf60250153a58ce64d04a93c3be84
52.015267
155
0.459467
6.601711
false
false
false
false
Lollipop95/WeiBo
WeiBo/WeiBo/Classes/Tools/Emoticon/Model/WBEmoticon.swift
1
2471
// // WBEmoticon.swift // WeiBo // // Created by Ning Li on 2017/5/7. // Copyright © 2017年 Ning Li. All rights reserved. // import UIKit /// 表情模型 class WBEmoticon: NSObject { /// 表情类型 var type: Bool = false /// 本地图文混排的图片 var png: String? /// 发送给服务器的表情字符串 var chs: String? /// 表情使用次数 var times: Int = 0 /// emoji var code: String? { didSet { guard let code = code else { return } let scanner = Scanner(string: code) var result: UInt32 = 0 scanner.scanHexInt32(&result) let scalar = UnicodeScalar(result) let character = Character(scalar!) emoji = String(character) } } /// 表情所在目录 var directory: String? /// 表情图像 var image: UIImage? { if type { return nil } guard let path = Bundle.main.path(forResource: "HMEmoticon", ofType: "bundle"), let bundle = Bundle(path: path), let directory = directory, let png = png else { return nil } let imageName = "\(directory)/\(png)" let img = UIImage(named: imageName, in: bundle, compatibleWith: nil) return img } /// emoji 字符串 var emoji: String? /// 将图片转换成属性文本 /// /// - Parameter font: 字体 /// - Returns: 属性文本 func imageText(font: UIFont) -> NSAttributedString { if image == nil { let attrString: NSAttributedString = NSAttributedString(string: "") return attrString } let attachment: WBEmoticonAttachment = WBEmoticonAttachment() let height: CGFloat = font.lineHeight attachment.chs = chs attachment.image = image attachment.bounds = CGRect(x: 0, y: -4, width: height, height: height) let attrString: NSAttributedString = NSAttributedString(attachment: attachment) return attrString } override var description: String { return yy_modelDescription() } }
mit
b7b5a35116ffa5d4ef699b1e719394aa
22.4
87
0.490171
5.021459
false
false
false
false
aschwaighofer/swift
test/stdlib/UnsafePointerDiagnostics.swift
2
32017
// RUN: %target-typecheck-verify-swift -enable-invalid-ephemeralness-as-error // Test availability attributes on UnsafePointer initializers. // Assume the original source contains no UnsafeRawPointer types. func unsafePointerConversionAvailability( mrp: UnsafeMutableRawPointer, rp: UnsafeRawPointer, umpv: UnsafeMutablePointer<Void>, // expected-warning {{UnsafeMutablePointer<Void> has been replaced by UnsafeMutableRawPointer}} upv: UnsafePointer<Void>, // expected-warning {{UnsafePointer<Void> has been replaced by UnsafeRawPointer}} umpi: UnsafeMutablePointer<Int>, upi: UnsafePointer<Int>, umps: UnsafeMutablePointer<String>, ups: UnsafePointer<String>) { let omrp: UnsafeMutableRawPointer? = mrp let orp: UnsafeRawPointer? = rp let oumpv: UnsafeMutablePointer<Void> = umpv // expected-warning {{UnsafeMutablePointer<Void> has been replaced by UnsafeMutableRawPointer}} let oupv: UnsafePointer<Void>? = upv // expected-warning {{UnsafePointer<Void> has been replaced by UnsafeRawPointer}} let oumpi: UnsafeMutablePointer<Int>? = umpi let oupi: UnsafePointer<Int>? = upi let oumps: UnsafeMutablePointer<String>? = umps let oups: UnsafePointer<String>? = ups _ = UnsafeMutableRawPointer(mrp) _ = UnsafeMutableRawPointer(rp) // expected-error {{'init(_:)' has been renamed to 'init(mutating:)'}} _ = UnsafeMutableRawPointer(umpv) _ = UnsafeMutableRawPointer(upv) // expected-error {{'init(_:)' has been renamed to 'init(mutating:)'}} _ = UnsafeMutableRawPointer(umpi) _ = UnsafeMutableRawPointer(upi) // expected-error {{'init(_:)' has been renamed to 'init(mutating:)'}} _ = UnsafeMutableRawPointer(umps) _ = UnsafeMutableRawPointer(ups) // expected-error {{'init(_:)' has been renamed to 'init(mutating:)'}} _ = UnsafeMutableRawPointer(omrp) _ = UnsafeMutableRawPointer(orp) // expected-error {{'init(_:)' has been renamed to 'init(mutating:)'}} _ = UnsafeMutableRawPointer(oumpv) _ = UnsafeMutableRawPointer(oupv) // expected-error {{'init(_:)' has been renamed to 'init(mutating:)'}} _ = UnsafeMutableRawPointer(oumpi) _ = UnsafeMutableRawPointer(oupi) // expected-error {{'init(_:)' has been renamed to 'init(mutating:)'}} _ = UnsafeMutableRawPointer(oumps) _ = UnsafeMutableRawPointer(oups) // expected-error {{'init(_:)' has been renamed to 'init(mutating:)'}} // These all correctly pass with no error. _ = UnsafeRawPointer(mrp) _ = UnsafeRawPointer(rp) _ = UnsafeRawPointer(umpv) _ = UnsafeRawPointer(upv) _ = UnsafeRawPointer(umpi) _ = UnsafeRawPointer(upi) _ = UnsafeRawPointer(umps) _ = UnsafeRawPointer(ups) _ = UnsafeRawPointer(omrp) _ = UnsafeRawPointer(orp) _ = UnsafeRawPointer(oumpv) _ = UnsafeRawPointer(oupv) _ = UnsafeRawPointer(oumpi) _ = UnsafeRawPointer(oupi) _ = UnsafeRawPointer(oumps) _ = UnsafeRawPointer(oups) _ = UnsafePointer<Int>(upi) _ = UnsafePointer<Int>(oumpi) _ = UnsafePointer<Int>(oupi) _ = UnsafeMutablePointer<Int>(umpi) _ = UnsafeMutablePointer<Int>(oumpi) _ = UnsafeMutablePointer<Void>(rp) // expected-error {{no exact matches in call to initializer}} expected-warning {{UnsafeMutablePointer<Void> has been replaced by UnsafeMutableRawPointer}} _ = UnsafeMutablePointer<Void>(mrp) // expected-error {{no exact matches in call to initializer}} expected-warning {{UnsafeMutablePointer<Void> has been replaced by UnsafeMutableRawPointer}} _ = UnsafeMutablePointer<Void>(umpv) // expected-warning {{UnsafeMutablePointer<Void> has been replaced by UnsafeMutableRawPointer}} _ = UnsafeMutablePointer<Void>(umpi) // expected-warning {{UnsafeMutablePointer<Void> has been replaced by UnsafeMutableRawPointer}} _ = UnsafeMutablePointer<Void>(umps) // expected-warning {{UnsafeMutablePointer<Void> has been replaced by UnsafeMutableRawPointer}} _ = UnsafePointer<Void>(rp) // expected-error {{cannot convert value of type 'UnsafeRawPointer' to expected argument type 'Builtin.RawPointer'}} expected-warning {{UnsafePointer<Void> has been replaced by UnsafeRawPointer}} _ = UnsafePointer<Void>(mrp) // expected-error {{cannot convert value of type 'UnsafeMutableRawPointer' to expected argument type 'Builtin.RawPointer'}} expected-warning {{UnsafePointer<Void> has been replaced by UnsafeRawPointer}} _ = UnsafePointer<Void>(umpv) // expected-warning {{UnsafePointer<Void> has been replaced by UnsafeRawPointer}} _ = UnsafePointer<Void>(upv) // expected-warning {{UnsafePointer<Void> has been replaced by UnsafeRawPointer}} _ = UnsafePointer<Void>(umpi) // expected-warning {{UnsafePointer<Void> has been replaced by UnsafeRawPointer}} _ = UnsafePointer<Void>(upi) // expected-warning {{UnsafePointer<Void> has been replaced by UnsafeRawPointer}} _ = UnsafePointer<Void>(umps) // expected-warning {{UnsafePointer<Void> has been replaced by UnsafeRawPointer}} _ = UnsafePointer<Void>(ups) // expected-warning {{UnsafePointer<Void> has been replaced by UnsafeRawPointer}} _ = UnsafeMutablePointer<Int>(rp) // expected-error {{no exact matches in call to initializer}} _ = UnsafeMutablePointer<Int>(mrp) // expected-error {{no exact matches in call to initializer}} _ = UnsafeMutablePointer<Int>(orp) // expected-error {{no exact matches in call to initializer}} _ = UnsafeMutablePointer<Int>(omrp) // expected-error {{no exact matches in call to initializer}} _ = UnsafePointer<Int>(rp) // expected-error {{cannot convert value of type 'UnsafeRawPointer' to expected argument type 'Builtin.RawPointer'}} _ = UnsafePointer<Int>(mrp) // expected-error {{cannot convert value of type 'UnsafeMutableRawPointer' to expected argument type 'Builtin.RawPointer'}} _ = UnsafePointer<Int>(orp) // expected-error {{cannot convert value of type 'UnsafeRawPointer?' to expected argument type 'Builtin.RawPointer'}} _ = UnsafePointer<Int>(omrp) // expected-error {{cannot convert value of type 'UnsafeMutableRawPointer?' to expected argument type 'Builtin.RawPointer'}} _ = UnsafePointer<Int>(ups) // expected-error {{cannot convert value of type 'UnsafePointer<String>' to expected argument type 'UnsafePointer<Int>'}} // expected-note@-1 {{arguments to generic parameter 'Pointee' ('String' and 'Int') are expected to be equal}} _ = UnsafeMutablePointer<Int>(umps) // expected-error {{cannot convert value of type 'UnsafeMutablePointer<String>' to expected argument type 'UnsafeMutablePointer<Int>'}} // expected-note@-1 {{arguments to generic parameter 'Pointee' ('String' and 'Int') are expected to be equal}} _ = UnsafePointer<String>(upi) // expected-error {{cannot convert value of type 'UnsafePointer<Int>' to expected argument type 'UnsafePointer<String>'}} // expected-note@-1 {{arguments to generic parameter 'Pointee' ('Int' and 'String') are expected to be equal}} _ = UnsafeMutablePointer<String>(umpi) // expected-error {{cannot convert value of type 'UnsafeMutablePointer<Int>' to expected argument type 'UnsafeMutablePointer<String>'}} // expected-note@-1 {{arguments to generic parameter 'Pointee' ('Int' and 'String') are expected to be equal}} } func unsafeRawBufferPointerConversions( mrp: UnsafeMutableRawPointer, rp: UnsafeRawPointer, mrbp: UnsafeMutableRawBufferPointer, rbp: UnsafeRawBufferPointer, mbpi: UnsafeMutableBufferPointer<Int>, bpi: UnsafeBufferPointer<Int>) { let omrp: UnsafeMutableRawPointer? = mrp let orp: UnsafeRawPointer? = rp _ = UnsafeMutableRawBufferPointer(start: mrp, count: 1) _ = UnsafeRawBufferPointer(start: mrp, count: 1) _ = UnsafeMutableRawBufferPointer(start: rp, count: 1) // expected-error {{cannot convert value of type 'UnsafeRawPointer' to expected argument type 'UnsafeMutableRawPointer?'}} _ = UnsafeRawBufferPointer(start: rp, count: 1) _ = UnsafeMutableRawBufferPointer(mrbp) _ = UnsafeRawBufferPointer(mrbp) _ = UnsafeMutableRawBufferPointer(rbp) // expected-error {{missing argument label 'mutating:' in call}} _ = UnsafeRawBufferPointer(rbp) _ = UnsafeMutableRawBufferPointer(mbpi) _ = UnsafeRawBufferPointer(mbpi) _ = UnsafeMutableRawBufferPointer(bpi) // expected-error {{cannot convert value of type 'UnsafeBufferPointer<Int>' to expected argument type 'UnsafeMutableRawBufferPointer'}} _ = UnsafeRawBufferPointer(bpi) _ = UnsafeMutableRawBufferPointer(start: omrp, count: 1) _ = UnsafeRawBufferPointer(start: omrp, count: 1) _ = UnsafeMutableRawBufferPointer(start: orp, count: 1) // expected-error {{cannot convert value of type 'UnsafeRawPointer?' to expected argument type 'UnsafeMutableRawPointer?'}} _ = UnsafeRawBufferPointer(start: orp, count: 1) } struct SR9800 { func foo(_: UnsafePointer<CChar>) {} func foo(_: UnsafePointer<UInt8>) {} func ambiguityTest(buf: UnsafeMutablePointer<CChar>) { foo(UnsafePointer(buf)) // this call should be unambiguoius } } // Test that we get a custom diagnostic for an ephemeral conversion to non-ephemeral param for an Unsafe[Mutable][Raw][Buffer]Pointer init. func unsafePointerInitEphemeralConversions() { class C {} var foo = 0 var str = "" var arr = [0] var optionalArr: [Int]? = [0] var c: C? _ = UnsafePointer(&foo) // expected-error {{initialization of 'UnsafePointer<Int>' results in a dangling pointer}} // expected-note@-1 {{implicit argument conversion from 'Int' to 'UnsafePointer<Int>' produces a pointer valid only for the duration of the call to 'init(_:)'}} // expected-note@-2 {{use 'withUnsafePointer' in order to explicitly convert argument to pointer valid for a defined scope}} _ = UnsafePointer(&foo + 1) // expected-error {{cannot use inout expression here; argument #1 must be a pointer that outlives the call to '+'}} // expected-note@-1 {{implicit argument conversion from 'Int' to 'UnsafePointer<Int>' produces a pointer valid only for the duration of the call to '+'}} // expected-note@-2 {{use 'withUnsafePointer' in order to explicitly convert argument to pointer valid for a defined scope}} _ = UnsafePointer.init(&foo) // expected-error {{initialization of 'UnsafePointer<Int>' results in a dangling pointer}} // expected-note@-1 {{implicit argument conversion from 'Int' to 'UnsafePointer<Int>' produces a pointer valid only for the duration of the call to 'init(_:)'}} // expected-note@-2 {{use 'withUnsafePointer' in order to explicitly convert argument to pointer valid for a defined scope}} _ = UnsafePointer<Int8>("") // expected-error {{initialization of 'UnsafePointer<Int8>' results in a dangling pointer}} // expected-note@-1 {{implicit argument conversion from 'String' to 'UnsafePointer<Int8>' produces a pointer valid only for the duration of the call to 'init(_:)'}} // expected-note@-2 {{use the 'withCString' method on String in order to explicitly convert argument to pointer valid for a defined scope}} _ = UnsafePointer<Int8>.init("") // expected-error {{initialization of 'UnsafePointer<Int8>' results in a dangling pointer}} // expected-note@-1 {{implicit argument conversion from 'String' to 'UnsafePointer<Int8>' produces a pointer valid only for the duration of the call to 'init(_:)'}} // expected-note@-2 {{use the 'withCString' method on String in order to explicitly convert argument to pointer valid for a defined scope}} _ = UnsafePointer<Int8>(str) // expected-error {{initialization of 'UnsafePointer<Int8>' results in a dangling pointer}} // expected-note@-1 {{implicit argument conversion from 'String' to 'UnsafePointer<Int8>' produces a pointer valid only for the duration of the call to 'init(_:)'}} // expected-note@-2 {{use the 'withCString' method on String in order to explicitly convert argument to pointer valid for a defined scope}} _ = UnsafePointer([0]) // expected-error {{initialization of 'UnsafePointer<Int>' results in a dangling pointer}} // expected-note@-1 {{implicit argument conversion from '[Int]' to 'UnsafePointer<Int>' produces a pointer valid only for the duration of the call to 'init(_:)'}} // expected-note@-2 {{use the 'withUnsafeBufferPointer' method on Array in order to explicitly convert argument to buffer pointer valid for a defined scope}} _ = UnsafePointer(arr) // expected-error {{initialization of 'UnsafePointer<Int>' results in a dangling pointer}} // expected-note@-1 {{implicit argument conversion from '[Int]' to 'UnsafePointer<Int>' produces a pointer valid only for the duration of the call to 'init(_:)'}} // expected-note@-2 {{use the 'withUnsafeBufferPointer' method on Array in order to explicitly convert argument to buffer pointer valid for a defined scope}} _ = UnsafePointer(&arr) // expected-error {{initialization of 'UnsafePointer<Int>' results in a dangling pointer}} // expected-note@-1 {{implicit argument conversion from '[Int]' to 'UnsafePointer<Int>' produces a pointer valid only for the duration of the call to 'init(_:)'}} // expected-note@-2 {{use the 'withUnsafeBufferPointer' method on Array in order to explicitly convert argument to buffer pointer valid for a defined scope}} _ = UnsafePointer(optionalArr) // expected-error {{initialization of 'UnsafePointer<Int>' results in a dangling pointer}} // expected-note@-1 {{implicit argument conversion from '[Int]?' to 'UnsafePointer<Int>?' produces a pointer valid only for the duration of the call to 'init(_:)'}} _ = UnsafeMutablePointer(&foo) // expected-error {{initialization of 'UnsafeMutablePointer<Int>' results in a dangling pointer}} // expected-note@-1 {{implicit argument conversion from 'Int' to 'UnsafeMutablePointer<Int>' produces a pointer valid only for the duration of the call to 'init(_:)'}} // expected-note@-2 {{use 'withUnsafeMutablePointer' in order to explicitly convert argument to pointer valid for a defined scope}} _ = UnsafeMutablePointer(&arr) // expected-error {{initialization of 'UnsafeMutablePointer<Int>' results in a dangling pointer}} // expected-note@-1 {{implicit argument conversion from '[Int]' to 'UnsafeMutablePointer<Int>' produces a pointer valid only for the duration of the call to 'init(_:)'}} // expected-note@-2 {{use the 'withUnsafeMutableBufferPointer' method on Array in order to explicitly convert argument to buffer pointer valid for a defined scope}} _ = UnsafeMutablePointer(&arr + 2) // expected-error {{cannot use inout expression here; argument #1 must be a pointer that outlives the call to '+'}} // expected-note@-1 {{implicit argument conversion from '[Int]' to 'UnsafeMutablePointer<Int>' produces a pointer valid only for the duration of the call to '+'}} // expected-note@-2 {{use the 'withUnsafeMutableBufferPointer' method on Array in order to explicitly convert argument to buffer pointer valid for a defined scope}} _ = UnsafeMutablePointer(mutating: &foo) // expected-error {{initialization of 'UnsafeMutablePointer<Int>' results in a dangling pointer}} // expected-note@-1 {{implicit argument conversion from 'Int' to 'UnsafePointer<Int>' produces a pointer valid only for the duration of the call to 'init(mutating:)}} // expected-note@-2 {{use 'withUnsafePointer' in order to explicitly convert argument to pointer valid for a defined scope}} _ = UnsafeMutablePointer<Int8>(mutating: "") // expected-error {{initialization of 'UnsafeMutablePointer<Int8>' results in a dangling pointer}} // expected-note@-1 {{implicit argument conversion from 'String' to 'UnsafePointer<Int8>' produces a pointer valid only for the duration of the call to 'init(mutating:)}} // expected-note@-2 {{use the 'withCString' method on String in order to explicitly convert argument to pointer valid for a defined scope}} _ = UnsafeMutablePointer<Int8>(mutating: str) // expected-error {{initialization of 'UnsafeMutablePointer<Int8>' results in a dangling pointer}} // expected-note@-1 {{implicit argument conversion from 'String' to 'UnsafePointer<Int8>' produces a pointer valid only for the duration of the call to 'init(mutating:)}} // expected-note@-2 {{use the 'withCString' method on String in order to explicitly convert argument to pointer valid for a defined scope}} _ = UnsafeMutablePointer(mutating: [0]) // expected-error {{initialization of 'UnsafeMutablePointer<Int>' results in a dangling pointer}} // expected-note@-1 {{implicit argument conversion from '[Int]' to 'UnsafePointer<Int>' produces a pointer valid only for the duration of the call to 'init(mutating:)}} // expected-note@-2 {{use the 'withUnsafeBufferPointer' method on Array in order to explicitly convert argument to buffer pointer valid for a defined scope}} _ = UnsafeMutablePointer(mutating: arr) // expected-error {{initialization of 'UnsafeMutablePointer<Int>' results in a dangling pointer}} // expected-note@-1 {{implicit argument conversion from '[Int]' to 'UnsafePointer<Int>' produces a pointer valid only for the duration of the call to 'init(mutating:)}} // expected-note@-2 {{use the 'withUnsafeBufferPointer' method on Array in order to explicitly convert argument to buffer pointer valid for a defined scope}} _ = UnsafeMutablePointer(mutating: &arr) // expected-error {{initialization of 'UnsafeMutablePointer<Int>' results in a dangling pointer}} // expected-note@-1 {{implicit argument conversion from '[Int]' to 'UnsafePointer<Int>' produces a pointer valid only for the duration of the call to 'init(mutating:)}} // expected-note@-2 {{use the 'withUnsafeBufferPointer' method on Array in order to explicitly convert argument to buffer pointer valid for a defined scope}} _ = UnsafeMutablePointer(mutating: optionalArr) // expected-error {{initialization of 'UnsafeMutablePointer<Int>' results in a dangling pointer}} // expected-note@-1 {{implicit argument conversion from '[Int]?' to 'UnsafePointer<Int>?' produces a pointer valid only for the duration of the call to 'init(mutating:)}} _ = UnsafeRawPointer(&foo) // expected-error {{initialization of 'UnsafeRawPointer' results in a dangling pointer}} // expected-note@-1 {{implicit argument conversion from 'Int' to 'UnsafeMutableRawPointer' produces a pointer valid only for the duration of the call to 'init(_:)'}} // expected-note@-2 {{use 'withUnsafeMutableBytes' in order to explicitly convert argument to buffer pointer valid for a defined scope}} _ = UnsafeRawPointer(str) // expected-error {{initialization of 'UnsafeRawPointer' results in a dangling pointer}} // expected-note@-1 {{implicit argument conversion from 'String' to 'UnsafeRawPointer' produces a pointer valid only for the duration of the call to 'init(_:)'}} // expected-note@-2 {{use the 'withCString' method on String in order to explicitly convert argument to pointer valid for a defined scope}} _ = UnsafeRawPointer(arr) // expected-error {{initialization of 'UnsafeRawPointer' results in a dangling pointer}} // expected-note@-1 {{implicit argument conversion from '[Int]' to 'UnsafeRawPointer' produces a pointer valid only for the duration of the call to 'init(_:)'}} // expected-note@-2 {{use the 'withUnsafeBytes' method on Array in order to explicitly convert argument to buffer pointer valid for a defined scope}} _ = UnsafeRawPointer(&arr) // expected-error {{initialization of 'UnsafeRawPointer' results in a dangling pointer}} // expected-note@-1 {{implicit argument conversion from '[Int]' to 'UnsafeMutableRawPointer' produces a pointer valid only for the duration of the call to 'init(_:)'}} // expected-note@-2 {{use the 'withUnsafeMutableBytes' method on Array in order to explicitly convert argument to buffer pointer valid for a defined scope}} _ = UnsafeRawPointer(optionalArr) // expected-error {{initialization of 'UnsafeRawPointer' results in a dangling pointer}} // expected-note@-1 {{implicit argument conversion from '[Int]?' to 'UnsafeRawPointer?' produces a pointer valid only for the duration of the call to 'init(_:)'}} _ = UnsafeMutableRawPointer(&foo) // expected-error {{initialization of 'UnsafeMutableRawPointer' results in a dangling pointer}} // expected-note@-1 {{implicit argument conversion from 'Int' to 'UnsafeMutableRawPointer' produces a pointer valid only for the duration of the call to 'init(_:)'}} // expected-note@-2 {{use 'withUnsafeMutableBytes' in order to explicitly convert argument to buffer pointer valid for a defined scope}} _ = UnsafeMutableRawPointer(&arr) // expected-error {{initialization of 'UnsafeMutableRawPointer' results in a dangling pointer}} // expected-note@-1 {{implicit argument conversion from '[Int]' to 'UnsafeMutableRawPointer' produces a pointer valid only for the duration of the call to 'init(_:)'}} // expected-note@-2 {{use the 'withUnsafeMutableBytes' method on Array in order to explicitly convert argument to buffer pointer valid for a defined scope}} _ = UnsafeMutableRawPointer(mutating: &foo) // expected-error {{initialization of 'UnsafeMutableRawPointer' results in a dangling pointer}} // expected-note@-1 {{implicit argument conversion from 'Int' to 'UnsafeRawPointer' produces a pointer valid only for the duration of the call to 'init(mutating:)}} // expected-note@-2 {{use 'withUnsafeBytes' in order to explicitly convert argument to buffer pointer valid for a defined scope}} _ = UnsafeMutableRawPointer(mutating: str) // expected-error {{initialization of 'UnsafeMutableRawPointer' results in a dangling pointer}} // expected-note@-1 {{implicit argument conversion from 'String' to 'UnsafeRawPointer' produces a pointer valid only for the duration of the call to 'init(mutating:)}} // expected-note@-2 {{use the 'withCString' method on String in order to explicitly convert argument to pointer valid for a defined scope}} _ = UnsafeMutableRawPointer(mutating: arr) // expected-error {{initialization of 'UnsafeMutableRawPointer' results in a dangling pointer}} // expected-note@-1 {{implicit argument conversion from '[Int]' to 'UnsafeRawPointer' produces a pointer valid only for the duration of the call to 'init(mutating:)}} // expected-note@-2 {{use the 'withUnsafeBytes' method on Array in order to explicitly convert argument to buffer pointer valid for a defined scope}} _ = UnsafeMutableRawPointer(mutating: &arr) // expected-error {{initialization of 'UnsafeMutableRawPointer' results in a dangling pointer}} // expected-note@-1 {{implicit argument conversion from '[Int]' to 'UnsafeRawPointer' produces a pointer valid only for the duration of the call to 'init(mutating:)}} // expected-note@-2 {{use the 'withUnsafeBytes' method on Array in order to explicitly convert argument to buffer pointer valid for a defined scope}} _ = UnsafeMutableRawPointer(mutating: optionalArr) // expected-error {{initialization of 'UnsafeMutableRawPointer' results in a dangling pointer}} // expected-note@-1 {{implicit argument conversion from '[Int]?' to 'UnsafeRawPointer?' produces a pointer valid only for the duration of the call to 'init(mutating:)}} _ = UnsafeBufferPointer(start: &foo, count: 0) // expected-error {{initialization of 'UnsafeBufferPointer<Int>' results in a dangling buffer pointer}} // expected-note@-1 {{implicit argument conversion from 'Int' to 'UnsafePointer<Int>?' produces a pointer valid only for the duration of the call to 'init(start:count:)'}} // expected-note@-2 {{use 'withUnsafePointer' in order to explicitly convert argument to pointer valid for a defined scope}} _ = UnsafeBufferPointer.init(start: &foo, count: 0) // expected-error {{initialization of 'UnsafeBufferPointer<Int>' results in a dangling buffer pointer}} // expected-note@-1 {{implicit argument conversion from 'Int' to 'UnsafePointer<Int>?' produces a pointer valid only for the duration of the call to 'init(start:count:)'}} // expected-note@-2 {{use 'withUnsafePointer' in order to explicitly convert argument to pointer valid for a defined scope}} _ = UnsafeBufferPointer<Int8>(start: str, count: 0) // expected-error {{initialization of 'UnsafeBufferPointer<Int8>' results in a dangling buffer pointer}} // expected-note@-1 {{implicit argument conversion from 'String' to 'UnsafePointer<Int8>?' produces a pointer valid only for the duration of the call to 'init(start:count:)'}} // expected-note@-2 {{use the 'withCString' method on String in order to explicitly convert argument to pointer valid for a defined scope}} _ = UnsafeBufferPointer<Int8>.init(start: str, count: 0) // expected-error {{initialization of 'UnsafeBufferPointer<Int8>' results in a dangling buffer pointer}} // expected-note@-1 {{implicit argument conversion from 'String' to 'UnsafePointer<Int8>?' produces a pointer valid only for the duration of the call to 'init(start:count:)'}} // expected-note@-2 {{use the 'withCString' method on String in order to explicitly convert argument to pointer valid for a defined scope}} _ = UnsafeBufferPointer(start: arr, count: 0) // expected-error {{initialization of 'UnsafeBufferPointer<Int>' results in a dangling buffer pointer}} // expected-note@-1 {{implicit argument conversion from '[Int]' to 'UnsafePointer<Int>?' produces a pointer valid only for the duration of the call to 'init(start:count:)'}} // expected-note@-2 {{use the 'withUnsafeBufferPointer' method on Array in order to explicitly convert argument to buffer pointer valid for a defined scope}} _ = UnsafeBufferPointer(start: &arr, count: 0) // expected-error {{initialization of 'UnsafeBufferPointer<Int>' results in a dangling buffer pointer}} // expected-note@-1 {{implicit argument conversion from '[Int]' to 'UnsafePointer<Int>?' produces a pointer valid only for the duration of the call to 'init(start:count:)'}} // expected-note@-2 {{use the 'withUnsafeBufferPointer' method on Array in order to explicitly convert argument to buffer pointer valid for a defined scope}} _ = UnsafeBufferPointer(start: optionalArr, count: 0) // expected-error {{initialization of 'UnsafeBufferPointer<Int>' results in a dangling buffer pointer}} // expected-note@-1 {{implicit argument conversion from '[Int]?' to 'UnsafePointer<Int>?' produces a pointer valid only for the duration of the call to 'init(start:count:)'}} _ = UnsafeMutableBufferPointer(start: &foo, count: 0) // expected-error {{initialization of 'UnsafeMutableBufferPointer<Int>' results in a dangling buffer pointer}} // expected-note@-1 {{implicit argument conversion from 'Int' to 'UnsafeMutablePointer<Int>?' produces a pointer valid only for the duration of the call to 'init(start:count:)'}} // expected-note@-2 {{use 'withUnsafeMutablePointer' in order to explicitly convert argument to pointer valid for a defined scope}} _ = UnsafeMutableBufferPointer(start: &arr, count: 0) // expected-error {{initialization of 'UnsafeMutableBufferPointer<Int>' results in a dangling buffer pointer}} // expected-note@-1 {{implicit argument conversion from '[Int]' to 'UnsafeMutablePointer<Int>?' produces a pointer valid only for the duration of the call to 'init(start:count:)'}} // expected-note@-2 {{use the 'withUnsafeMutableBufferPointer' method on Array in order to explicitly convert argument to buffer pointer valid for a defined scope}} _ = UnsafeRawBufferPointer(start: &foo, count: 0) // expected-error {{initialization of 'UnsafeRawBufferPointer' results in a dangling buffer pointer}} // expected-note@-1 {{implicit argument conversion from 'Int' to 'UnsafeRawPointer?' produces a pointer valid only for the duration of the call to 'init(start:count:)'}} // expected-note@-2 {{use 'withUnsafeBytes' in order to explicitly convert argument to buffer pointer valid for a defined scope}} _ = UnsafeRawBufferPointer(start: str, count: 0) // expected-error {{initialization of 'UnsafeRawBufferPointer' results in a dangling buffer pointer}} // expected-note@-1 {{implicit argument conversion from 'String' to 'UnsafeRawPointer?' produces a pointer valid only for the duration of the call to 'init(start:count:)'}} // expected-note@-2 {{use the 'withCString' method on String in order to explicitly convert argument to pointer valid for a defined scope}} _ = UnsafeRawBufferPointer(start: arr, count: 0) // expected-error {{initialization of 'UnsafeRawBufferPointer' results in a dangling buffer pointer}} // expected-note@-1 {{implicit argument conversion from '[Int]' to 'UnsafeRawPointer?' produces a pointer valid only for the duration of the call to 'init(start:count:)'}} // expected-note@-2 {{use the 'withUnsafeBytes' method on Array in order to explicitly convert argument to buffer pointer valid for a defined scope}} _ = UnsafeRawBufferPointer(start: &arr, count: 0) // expected-error {{initialization of 'UnsafeRawBufferPointer' results in a dangling buffer pointer}} // expected-note@-1 {{implicit argument conversion from '[Int]' to 'UnsafeRawPointer?' produces a pointer valid only for the duration of the call to 'init(start:count:)'}} // expected-note@-2 {{use the 'withUnsafeBytes' method on Array in order to explicitly convert argument to buffer pointer valid for a defined scope}} _ = UnsafeRawBufferPointer(start: optionalArr, count: 0) // expected-error {{initialization of 'UnsafeRawBufferPointer' results in a dangling buffer pointer}} // expected-note@-1 {{implicit argument conversion from '[Int]?' to 'UnsafeRawPointer?' produces a pointer valid only for the duration of the call to 'init(start:count:)'}} _ = UnsafeMutableRawBufferPointer(start: &foo, count: 0) // expected-error {{initialization of 'UnsafeMutableRawBufferPointer' results in a dangling buffer pointer}} // expected-note@-1 {{implicit argument conversion from 'Int' to 'UnsafeMutableRawPointer?' produces a pointer valid only for the duration of the call to 'init(start:count:)'}} // expected-note@-2 {{use 'withUnsafeMutableBytes' in order to explicitly convert argument to buffer pointer valid for a defined scope}} _ = UnsafeMutableRawBufferPointer(start: &arr, count: 0) // expected-error {{initialization of 'UnsafeMutableRawBufferPointer' results in a dangling buffer pointer}} // expected-note@-1 {{implicit argument conversion from '[Int]' to 'UnsafeMutableRawPointer?' produces a pointer valid only for the duration of the call to 'init(start:count:)'}} // expected-note@-2 {{use the 'withUnsafeMutableBytes' method on Array in order to explicitly convert argument to buffer pointer valid for a defined scope}} // FIXME: This is currently ambiguous. _ = OpaquePointer(&foo) // expected-error {{no exact matches in call to initializer}} // FIXME: This is currently ambiguous. _ = OpaquePointer(&arr) // expected-error {{no exact matches in call to initializer}} _ = OpaquePointer(arr) // expected-error {{initialization of 'OpaquePointer' results in a dangling pointer}} // expected-note@-1 {{implicit argument conversion from '[Int]' to 'UnsafeRawPointer' produces a pointer valid only for the duration of the call to 'init(_:)'}} // expected-note@-2 {{use the 'withUnsafeBytes' method on Array in order to explicitly convert argument to buffer pointer valid for a defined scope}} _ = OpaquePointer(str) // expected-error {{initialization of 'OpaquePointer' results in a dangling pointer}} // expected-note@-1 {{implicit argument conversion from 'String' to 'UnsafeRawPointer' produces a pointer valid only for the duration of the call to 'init(_:)'}} // expected-note@-2 {{use the 'withCString' method on String in order to explicitly convert argument to pointer valid for a defined scope}} } var global = 0 // Test that we allow non-ephemeral conversions, such as inout-to-pointer for globals. func unsafePointerInitNonEphemeralConversions() { _ = UnsafePointer(&global) _ = UnsafeMutablePointer(&global) _ = UnsafeRawPointer(&global) _ = UnsafeMutableRawPointer(&global) _ = UnsafeBufferPointer(start: &global, count: 0) _ = UnsafeMutableBufferPointer(start: &global, count: 0) _ = UnsafeRawBufferPointer(start: &global, count: 0) _ = UnsafeMutableRawBufferPointer(start: &global, count: 0) // FIXME: This is currently ambiguous. _ = OpaquePointer(&global) // expected-error {{ambiguous use of 'init(_:)'}} }
apache-2.0
b5e2771a94d87058d9b2e8af42d31cae
85.532432
233
0.748165
4.644857
false
false
false
false
ReactiveKit/ReactiveGitter
Views/Utilities.swift
1
5055
// // Utilities.swift // ReactiveGitter // // Created by Srdan Rasic on 15/01/2017. // Copyright © 2017 ReactiveKit. All rights reserved. // import Foundation import UIKit public enum ViewController {} public protocol SetupProtocol: AnyObject {} extension SetupProtocol { @discardableResult public func setup(_ configure: (Self) -> Void) -> Self { configure(self) return self } } extension SetupProtocol where Self: UIView { public var autoLayouting: Self { self.translatesAutoresizingMaskIntoConstraints = false return self } public func setup(_ configure: (Self) -> Void = { _ in }) -> Self { self.translatesAutoresizingMaskIntoConstraints = false configure(self) return self } } extension NSObject: SetupProtocol {} extension UITableViewCell { public static var classReuseIdentifier: String { return String(describing: type(of: self)) } } public extension UIEdgeInsets { public init(uniform value: CGFloat) { left = value right = value top = value bottom = value } } public enum Edge { case top case bottom case leading case left case trailing case right } public struct EdgeConstraints { public let leading: NSLayoutConstraint? public let trailing: NSLayoutConstraint? public let left: NSLayoutConstraint? public let right: NSLayoutConstraint? public let top: NSLayoutConstraint? public let bottom: NSLayoutConstraint? } public struct SizeConstraints { public let width: NSLayoutConstraint? public let height: NSLayoutConstraint? } public enum LayoutCenter { case x case y } public protocol Anchorable { var leadingAnchor: NSLayoutXAxisAnchor { get } var trailingAnchor: NSLayoutXAxisAnchor { get } var leftAnchor: NSLayoutXAxisAnchor { get } var rightAnchor: NSLayoutXAxisAnchor { get } var topAnchor: NSLayoutYAxisAnchor { get } var bottomAnchor: NSLayoutYAxisAnchor { get } var widthAnchor: NSLayoutDimension { get } var heightAnchor: NSLayoutDimension { get } var centerXAnchor: NSLayoutXAxisAnchor { get } var centerYAnchor: NSLayoutYAxisAnchor { get } } extension UIView: Anchorable {} extension UILayoutGuide: Anchorable {} public extension Anchorable { @discardableResult func anchor(_ edges: [Edge] = [.top, .bottom, .left, .right], in view: Anchorable, insets: UIEdgeInsets = .zero, isActive: Bool = true) -> EdgeConstraints { let top: NSLayoutConstraint? = edges.contains(.top) ? topAnchor.constraint(equalTo: view.topAnchor, constant: insets.top) : nil let bottom: NSLayoutConstraint? = edges.contains(.bottom) ? bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -insets.bottom) : nil let leading: NSLayoutConstraint? = edges.contains(.leading) ? leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: insets.left) : nil let trailing: NSLayoutConstraint? = edges.contains(.trailing) ? trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -insets.right) : nil let left: NSLayoutConstraint? = edges.contains(.left) ? leftAnchor.constraint(equalTo: view.leftAnchor, constant: insets.left) : nil let right: NSLayoutConstraint? = edges.contains(.right) ? rightAnchor.constraint(equalTo: view.rightAnchor, constant: -insets.right) : nil [top, leading, bottom, trailing, left, right].forEach { $0?.isActive = isActive } return EdgeConstraints(leading: leading, trailing: trailing, left: left, right: right, top: top, bottom: bottom) } @discardableResult func center(_ layoutCenters: [LayoutCenter] = [.x, .y], in view: Anchorable, isActive: Bool = true, offset: CGPoint = .zero) -> (x: NSLayoutConstraint?, y: NSLayoutConstraint?) { let x: NSLayoutConstraint? = layoutCenters.contains(.x) ? centerXAnchor.constraint(equalTo: view.centerXAnchor, constant: offset.x) : nil let y: NSLayoutConstraint? = layoutCenters.contains(.y) ? centerYAnchor.constraint(equalTo: view.centerYAnchor, constant: offset.y) : nil if isActive { x?.isActive = true y?.isActive = true } return (x, y) } @discardableResult func constrain(widthTo width: CGFloat? = nil, heightTo height: CGFloat? = nil, isActive: Bool = true) -> SizeConstraints { let constraints = SizeConstraints( width: width.flatMap { widthAnchor.constraint(equalToConstant: $0) }, height: height.flatMap { heightAnchor.constraint(equalToConstant: $0) } ) if isActive { constraints.width?.isActive = true constraints.height?.isActive = true } return constraints } @discardableResult func constrain(widthTo widthView: Anchorable? = nil, heightTo heightView: Anchorable? = nil, isActive: Bool = true) -> SizeConstraints { let constraints = SizeConstraints( width: widthView.flatMap { widthAnchor.constraint(equalTo: $0.widthAnchor) }, height: heightView.flatMap { heightAnchor.constraint(equalTo: $0.heightAnchor) } ) if isActive { constraints.width?.isActive = true constraints.height?.isActive = true } return constraints } }
mit
0594692f7c3937fd6d3adb312119fa94
30.786164
180
0.722002
4.445031
false
false
false
false
igormatyushkin014/Visuality
Source/Views/Containers/ScrollableContainerView/ScrollableContainerView.swift
1
6989
// // ScrollableContainerView.swift // Visuality // // Created by Igor Matyushkin on 06.11.16. // Copyright © 2016 Igor Matyushkin. All rights reserved. // import UIKit internal class ScrollableContainerView: UIView { // MARK: Class variables & properties // MARK: Public class methods // MARK: Private class methods fileprivate class func defaultScrollDirection() -> ScrollDirection { return .vertical } // MARK: Initializers public override init(frame: CGRect) { super.init(frame: frame) customInitialization() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) customInitialization() } // MARK: Deinitializer deinit { // Remove references lastContentSize = nil _internalScrollView = nil _contentView = nil _scrollDirection = nil } // MARK: Outlets // MARK: Object variables & properties fileprivate var lastContentSize: CGSize! fileprivate var _internalScrollView: UIScrollView! fileprivate var internalScrollView: UIScrollView { get { return _internalScrollView } } fileprivate var _contentView: UIView? public var contentView: UIView? { get { return _contentView } set { // Update content view setContentView(contentView: newValue, forScrollDirection: scrollDirection) } } fileprivate var _scrollDirection: ScrollDirection! public var scrollDirection: ScrollDirection { get { return _scrollDirection } set { // Update private variable _scrollDirection = newValue // Update content view setContentView(contentView: _contentView, forScrollDirection: newValue) } } // MARK: Public object methods public override func layoutSubviews() { super.layoutSubviews() // Update internal scroll view internalScrollView.frame = bounds let contentSizeForInternalScrollView = obtain(contentSizeForContentView: contentView, andScrollDirection: scrollDirection) if contentSizeForInternalScrollView != lastContentSize { internalScrollView.contentSize = contentSizeForInternalScrollView lastContentSize = contentSizeForInternalScrollView } } public func setContentView<ContentView: UIView>(ofType contentViewType: ContentView.Type, fromNib nibQuery: NibQuery, locatedInBundle bundleQuery: BundleQuery, withScrollDirection scrollDirection: ScrollDirection, configure configureContentView: ((_ contentView: ContentView) -> Void)?) { // Create new content view let viewInitializer = ViewInitializer(viewClass: ContentView.self) let newContentView = viewInitializer.view(fromNib: nibQuery, locatedInBundle: bundleQuery) // Update scroll direction _scrollDirection = scrollDirection // Update current content view contentView = newContentView // Configure new content view if needed configureContentView?(newContentView) } // MARK: Private object methods fileprivate func customInitialization() { // Initialize view backgroundColor = .clear // Initialize internal scroll view _internalScrollView = UIScrollView(frame: bounds) internalScrollView.backgroundColor = .clear let contentSizeForInternalScrollView: CGSize = .zero lastContentSize = contentSizeForInternalScrollView internalScrollView.contentSize = contentSizeForInternalScrollView addSubview(internalScrollView) // Initialize scroll direction _scrollDirection = ScrollableContainerView.defaultScrollDirection() // Update view setNeedsLayout() } fileprivate func obtain(frameForContentView contentView: UIView?, andScrollDirection scrollDirection: ScrollDirection) -> CGRect { if contentView == nil { return .zero } else { // Obtain frame for content view var frameForContentView: CGRect? switch scrollDirection { case .horizontal: frameForContentView = CGRect(x: 0.0, y: 0.0, width: contentView!.bounds.size.width, height: internalScrollView.bounds.size.height) break case .vertical: frameForContentView = CGRect(x: 0.0, y: 0.0, width: internalScrollView.bounds.size.width, height: contentView!.bounds.size.height) break } return frameForContentView! } } fileprivate func obtain(contentSizeForContentView contentView: UIView?, andScrollDirection scrollDirection: ScrollDirection) -> CGSize { let frameForContentView = obtain(frameForContentView: contentView, andScrollDirection: scrollDirection) let requiredContentSize = frameForContentView.size return requiredContentSize } fileprivate func setContentView(contentView: UIView?, forScrollDirection scrollDirection: ScrollDirection) { // Remove previous content view if needed if _contentView != nil { _contentView!.removeFromSuperview() } // Update private variable _contentView = contentView // Update internal scroll view if contentView != nil { // Obtain frame for content view var frameForContentView: CGRect? switch scrollDirection { case .horizontal: frameForContentView = CGRect(x: 0.0, y: 0.0, width: contentView!.bounds.size.width, height: internalScrollView.bounds.size.height) break case .vertical: frameForContentView = CGRect(x: 0.0, y: 0.0, width: internalScrollView.bounds.size.width, height: contentView!.bounds.size.height) break } // Update content view contentView!.frame = frameForContentView! // Update container internalScrollView.addSubview(contentView!) // Update view setNeedsLayout() } } // MARK: Actions // MARK: Protocol methods } internal extension ScrollableContainerView { internal enum ScrollDirection { case horizontal case vertical } }
mit
a6f03a3eee4afa1d324bf6051af3b9ec
28.73617
292
0.600172
6.23372
false
false
false
false
mapzen/ios
MapzenSDKTests/TGMapViewControllerMocks.swift
1
4891
// // TestTGMapViewController.swift // ios-sdk // // Created by Sarah Lensing on 2/15/17. // Copyright © 2017 Mapzen. All rights reserved. // import Foundation import TangramMap import XCTest class FailingTGMapViewController: TestTGMapViewController { override func animate(toPosition position: TGGeoPoint, withDuration seconds: Float) { XCTFail() } override func animate(toPosition position: TGGeoPoint, withDuration seconds: Float, with easeType: TGEaseType) { XCTFail() } override func animate(toZoomLevel zoomLevel: Float, withDuration seconds: Float) { XCTFail() } override func animate(toZoomLevel zoomLevel: Float, withDuration seconds: Float, with easeType: TGEaseType) { XCTFail() } override func animate(toRotation radians: Float, withDuration seconds: Float) { XCTFail() } override func animate(toRotation radians: Float, withDuration seconds: Float, with easeType: TGEaseType) { XCTFail() } override func animate(toTilt radians: Float, withDuration seconds: Float) { XCTFail() } override func animate(toTilt radians: Float, withDuration seconds: Float, with easeType: TGEaseType) { XCTFail() } } class TestTGMapViewController: TGMapViewController { var removedAllMarkers = false var coordinate = TGGeoPoint() var duration: Float = 0.0 var easeType = TGEaseType.cubic var scenePath = URL(fileURLWithPath: "") var sceneUpdates: [TGSceneUpdate] = [] var sceneUpdateComponentPath = "" var sceneUpdateValue = "" var appliedSceneUpdates = false var lngLatForScreenPosition = TGGeoPoint() var screenPositionForLngLat = CGPoint() var labelPickPosition = CGPoint() var markerPickPosition = CGPoint() var featurePickPosition = CGPoint() var mockSceneId: Int32 = 0 var yamlString = "" override func markerRemoveAll() { removedAllMarkers = true } override func loadScene(from url: URL) -> Int32 { scenePath = url return mockSceneId } override func loadScene(from url: URL, with updates: [TGSceneUpdate]) -> Int32 { scenePath = url sceneUpdates = updates return mockSceneId } override func loadSceneAsync(from url: URL) -> Int32 { scenePath = url return mockSceneId } override func loadSceneAsync(from url: URL, with updates: [TGSceneUpdate]) -> Int32 { scenePath = url sceneUpdates = updates return mockSceneId } override func loadScene(fromYAML yaml: String, relativeTo url: URL, with updates: [TGSceneUpdate]) -> Int32 { scenePath = url yamlString = yaml sceneUpdates = updates return mockSceneId } override func loadSceneAsync(fromYAML yaml: String, relativeTo url: URL, with updates: [TGSceneUpdate]) -> Int32 { scenePath = url yamlString = yaml sceneUpdates = updates return mockSceneId } override func updateSceneAsync(_ updates: [TGSceneUpdate]) -> Int32 { sceneUpdates = updates appliedSceneUpdates = true return mockSceneId } override func lngLat(toScreenPosition lngLat: TGGeoPoint) -> CGPoint { lngLatForScreenPosition = lngLat return CGPoint() } override func screenPosition(toLngLat screenPosition: CGPoint) -> TGGeoPoint { screenPositionForLngLat = screenPosition return TGGeoPoint() } override func animate(toPosition position: TGGeoPoint, withDuration seconds: Float) { coordinate = position duration = seconds } override func animate(toPosition position: TGGeoPoint, withDuration seconds: Float, with easeType: TGEaseType) { coordinate = position duration = seconds self.easeType = easeType } override func animate(toZoomLevel zoomLevel: Float, withDuration seconds: Float) { zoom = zoomLevel duration = seconds } override func animate(toZoomLevel zoomLevel: Float, withDuration seconds: Float, with easeType: TGEaseType) { zoom = zoomLevel duration = seconds self.easeType = easeType } override func animate(toRotation radians: Float, withDuration seconds: Float) { rotation = radians duration = seconds } override func animate(toRotation radians: Float, withDuration seconds: Float, with easeType: TGEaseType) { rotation = radians duration = seconds self.easeType = easeType } override func animate(toTilt radians: Float, withDuration seconds: Float) { tilt = radians duration = seconds } override func animate(toTilt radians: Float, withDuration seconds: Float, with easeType: TGEaseType) { tilt = radians duration = seconds self.easeType = easeType } override func pickLabel(at screenPosition: CGPoint) { labelPickPosition = screenPosition } override func pickMarker(at screenPosition: CGPoint) { markerPickPosition = screenPosition } override func pickFeature(at screenPosition: CGPoint) { featurePickPosition = screenPosition } }
apache-2.0
494bbebc75538e7b678ed94ecec180d3
27.103448
116
0.719632
4.289474
false
false
false
false
RunningCharles/Arithmetic
src/17MaxDecreasingSequence.swift
1
869
#!/usr/bin/swift func maxDecreasingSequence(_ values: [Int], _ table: inout [Int]) -> Int { var maxLen = 0 for i in (0 ..< values.count).reversed() { var maxLenTmp = 0 for j in (i + 1) ..< values.count { if (values[i] > values[j]) { maxLenTmp = max(maxLenTmp, table[j]) } } table[i] = maxLenTmp + 1 maxLen = max(maxLen, table[i]) } return maxLen } let values = [9, 4, 3, 2, 5, 4, 3, 2] var table: [Int] = values.map { $0 * 0 } let maxLen = maxDecreasingSequence(values, &table) var ml = maxLen var lv = Int.max var maxDS: [Int] = [] for i in 0 ..< table.count { if ml == table[i] && values[i] < lv { maxDS.append(values[i]) lv = values[i] ml -= 1 } } print("values:", values) print("table:", table) print("maxDS:", maxDS)
bsd-3-clause
2f83a231cccc92fd2bb53bb01ab9d891
21.868421
74
0.514384
3.103571
false
false
false
false
pietgk/EuropeanaApp
EuropeanaApp/EuropeanaApp/Classes/ViewControllers/IXSuggestionDetailVC.swift
1
6754
// // IXSuggestionDetailVC.swift // ArtWhisper // // Created by Axel Roest on 07/11/15. // Copyright © 2015 Phluxus. All rights reserved. // import UIKit enum SuggestionDetailCellType: Int { case Caption = 0 case Date = 1 case OpeningHours = 2 case Address = 3 case URL = 4 static let count: Int = { var max: Int = 0 while let _ = SuggestionDetailCellType(rawValue: ++max) {} return max }() } class IXSuggestionDetailVC: UIViewController , UITableViewDataSource, UITableViewDelegate { var poi : IXPoi? let kDefaultRowHeight : CGFloat = 44 let kMaxHeight : CGFloat = 600 let kCellMargin : CGFloat = 15 @IBOutlet weak var tableView: UITableView! @IBOutlet weak var imageView: UIImageView! @IBOutlet weak var navigationTitleItem: UINavigationItem! override func viewDidLoad() { super.viewDidLoad() createLabels() // Do any additional setup after loading the view. poi?.getImageWithBlock({ (image) -> Void in self.imageView.image = image; }); self.navigationTitleItem.title = poi?.name } // // override func viewDidAppear(animated: Bool) { // } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func createLabels() { } // MARK: UITableViewDataSource func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return SuggestionDetailCellType.count } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { let niceRow = SuggestionDetailCellType(rawValue: indexPath.row)! var height: CGFloat if (.Caption == niceRow) { // (poi?.caption != nil) let font = UIFont.systemFontOfSize(13.0) let attr = [NSFontAttributeName : font] let text = NSAttributedString(string: (poi?.caption)!, attributes: attr) let boundSize = CGSizeMake(self.tableView.frame.size.width - kCellMargin, kMaxHeight) // let options : NSStringDrawingOptions = [.UsesLineFragmentOrigin | .UsesFontLeading] let options = unsafeBitCast(NSStringDrawingOptions.UsesLineFragmentOrigin.rawValue | NSStringDrawingOptions.UsesFontLeading.rawValue, NSStringDrawingOptions.self) let rect : CGRect = text.boundingRectWithSize(boundSize, options: options, context: nil) // height + additionalHeightBuffer; height = rect.size.height + kCellMargin; } else { height = kDefaultRowHeight } return height } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("suggestionDetailCell", forIndexPath: indexPath) // Configure the cell... configureCell(cell, forRow: indexPath.row) return cell } func configureCell(cell : UITableViewCell, forRow row: Int) { let niceRow = SuggestionDetailCellType(rawValue: row)! switch (niceRow) { case .Caption : cell.imageView?.image = nil cell.textLabel?.font = UIFont.systemFontOfSize(13.0) cell.textLabel?.text = poi?.caption case .Date : cell.imageView?.image = IXIcons.iconImageFor(IXIconNameType.icon_calendar, backgroundColor: nil, iconColor: UIColor.blackColor(), fontSize: 24) cell.textLabel?.text = "Nov. 28, 2015 - Jan. 17, 2016" case .OpeningHours: cell.imageView?.image = IXIcons.iconImageFor(IXIconNameType.icon_clock, backgroundColor: nil, iconColor: UIColor.blackColor(), fontSize: 24) cell.textLabel?.text = "daily" case .Address: cell.imageView?.image = IXIcons.iconImageFor(IXIconNameType.icon_map2, backgroundColor: nil, iconColor: UIColor.blackColor(), fontSize: 24) cell.textLabel?.text = "venue address" case .URL: cell.imageView?.image = IXIcons.iconImageFor(IXIconNameType.icon_link, backgroundColor: nil, iconColor: UIColor.blackColor(), fontSize: 24) cell.textLabel?.text = self.poi?.venue } } /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
c4698036f456193ea32c009781de524d
36.726257
157
0.660447
5.08509
false
false
false
false
yanyuqingshi/ios-charts
Charts/Classes/Renderers/ChartXAxisRendererBarChart.swift
1
5486
// // ChartXAxisRendererBarChart.swift // Charts // // Created by Daniel Cohen Gindi on 3/3/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // import Foundation import CoreGraphics.CGBase import UIKit.UIFont public class ChartXAxisRendererBarChart: ChartXAxisRenderer { internal weak var _chart: BarChartView!; public init(viewPortHandler: ChartViewPortHandler, xAxis: ChartXAxis, transformer: ChartTransformer!, chart: BarChartView) { super.init(viewPortHandler: viewPortHandler, xAxis: xAxis, transformer: transformer); self._chart = chart; } /// draws the x-labels on the specified y-position internal override func drawLabels(#context: CGContext, pos: CGFloat) { if (_chart.data === nil) { return; } var paraStyle = NSParagraphStyle.defaultParagraphStyle().mutableCopy() as! NSMutableParagraphStyle; paraStyle.alignment = .Center; var labelAttrs = [NSFontAttributeName: _xAxis.labelFont, NSForegroundColorAttributeName: _xAxis.labelTextColor, NSParagraphStyleAttributeName: paraStyle]; var barData = _chart.data as! BarChartData; var step = barData.dataSetCount; var valueToPixelMatrix = transformer.valueToPixelMatrix; var position = CGPoint(x: 0.0, y: 0.0); var labelMaxSize = CGSize(); if (_xAxis.isWordWrapEnabled) { labelMaxSize.width = _xAxis.wordWrapWidthPercent * valueToPixelMatrix.a; } for (var i = _minX, maxX = min(_maxX + 1, _xAxis.values.count); i < maxX; i += _xAxis.axisLabelModulus) { var label = i >= 0 && i < _xAxis.values.count ? _xAxis.values[i] : nil; if (label == nil) { continue; } position.x = CGFloat(i * step) + CGFloat(i) * barData.groupSpace + barData.groupSpace / 2.0; position.y = 0.0; // consider groups (center label for each group) if (step > 1) { position.x += (CGFloat(step) - 1.0) / 2.0; } position = CGPointApplyAffineTransform(position, valueToPixelMatrix); if (viewPortHandler.isInBoundsX(position.x)) { var labelns = label! as NSString; if (_xAxis.isAvoidFirstLastClippingEnabled) { // avoid clipping of the last if (i == _xAxis.values.count - 1) { var width = label!.sizeWithAttributes(labelAttrs).width; if (width > viewPortHandler.offsetRight * 2.0 && position.x + width > viewPortHandler.chartWidth) { position.x -= width / 2.0; } } else if (i == 0) { // avoid clipping of the first var width = label!.sizeWithAttributes(labelAttrs).width; position.x += width / 2.0; } } ChartUtils.drawMultilineText(context: context, text: label!, point: CGPoint(x: position.x, y: pos), align: .Center, attributes: labelAttrs, constrainedToSize: labelMaxSize); } } } private var _gridLineSegmentsBuffer = [CGPoint](count: 2, repeatedValue: CGPoint()); public override func renderGridLines(#context: CGContext) { if (!_xAxis.isDrawGridLinesEnabled || !_xAxis.isEnabled) { return; } var barData = _chart.data as! BarChartData; var step = barData.dataSetCount; CGContextSaveGState(context); CGContextSetStrokeColorWithColor(context, _xAxis.gridColor.CGColor); CGContextSetLineWidth(context, _xAxis.gridLineWidth); if (_xAxis.gridLineDashLengths != nil) { CGContextSetLineDash(context, _xAxis.gridLineDashPhase, _xAxis.gridLineDashLengths, _xAxis.gridLineDashLengths.count); } else { CGContextSetLineDash(context, 0.0, nil, 0); } var valueToPixelMatrix = transformer.valueToPixelMatrix; var position = CGPoint(x: 0.0, y: 0.0); for (var i = _minX; i < _maxX; i += _xAxis.axisLabelModulus) { position.x = CGFloat(i * step) + CGFloat(i) * barData.groupSpace - 0.5; position.y = 0.0; position = CGPointApplyAffineTransform(position, valueToPixelMatrix); if (viewPortHandler.isInBoundsX(position.x)) { _gridLineSegmentsBuffer[0].x = position.x; _gridLineSegmentsBuffer[0].y = viewPortHandler.contentTop; _gridLineSegmentsBuffer[1].x = position.x; _gridLineSegmentsBuffer[1].y = viewPortHandler.contentBottom; CGContextStrokeLineSegments(context, _gridLineSegmentsBuffer, 2); } } CGContextRestoreGState(context); } }
apache-2.0
780686a73f976390875cbceab32a562a
34.862745
189
0.548487
5.352195
false
false
false
false
naokits/my-programming-marathon
iPhoneSensorDemo/Pods/RxCocoa/RxCocoa/iOS/DataSources/RxCollectionViewReactiveArrayDataSource.swift
27
3346
// // RxCollectionViewReactiveArrayDataSource.swift // RxCocoa // // Created by Krunoslav Zaher on 6/29/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // #if os(iOS) || os(tvOS) import Foundation import UIKit #if !RX_NO_MODULE import RxSwift #endif // objc monkey business class _RxCollectionViewReactiveArrayDataSource : NSObject , UICollectionViewDataSource { func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { return 1 } func _collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return 0 } func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return _collectionView(collectionView, numberOfItemsInSection: section) } func _collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { rxAbstractMethod() } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { return _collectionView(collectionView, cellForItemAtIndexPath: indexPath) } } class RxCollectionViewReactiveArrayDataSourceSequenceWrapper<S: SequenceType> : RxCollectionViewReactiveArrayDataSource<S.Generator.Element> , RxCollectionViewDataSourceType { typealias Element = S override init(cellFactory: CellFactory) { super.init(cellFactory: cellFactory) } func collectionView(collectionView: UICollectionView, observedEvent: Event<S>) { UIBindingObserver(UIElement: self) { collectionViewDataSource, sectionModels in let sections = Array(sectionModels) collectionViewDataSource.collectionView(collectionView, observedElements: sections) }.on(observedEvent) } } // Please take a look at `DelegateProxyType.swift` class RxCollectionViewReactiveArrayDataSource<Element> : _RxCollectionViewReactiveArrayDataSource , SectionedViewDataSourceType { typealias CellFactory = (UICollectionView, Int, Element) -> UICollectionViewCell var itemModels: [Element]? = nil func modelAtIndex(index: Int) -> Element? { return itemModels?[index] } func modelAtIndexPath(indexPath: NSIndexPath) throws -> Any { precondition(indexPath.section == 0) guard let item = itemModels?[indexPath.item] else { throw RxCocoaError.ItemsNotYetBound(object: self) } return item } var cellFactory: CellFactory init(cellFactory: CellFactory) { self.cellFactory = cellFactory } // data source override func _collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return itemModels?.count ?? 0 } override func _collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { return cellFactory(collectionView, indexPath.item, itemModels![indexPath.item]) } // reactive func collectionView(collectionView: UICollectionView, observedElements: [Element]) { self.itemModels = observedElements collectionView.reloadData() } } #endif
mit
5325b2fad02aa943afd490e5e04a30e4
30.261682
140
0.714499
5.889085
false
false
false
false
thehung111/visearch-widget-swift
ViSearchWidgets/ViSearchWidgets/Extensions/UIColors+Visenze.swift
2
3064
// // UIColors+Visenze.swift // ViSearchWidgets // // Created by Hung on 21/10/16. // Copyright © 2016 Visenze. All rights reserved. // import UIKit /** UIColor extension that add a whole bunch of utility functions like: - HTML/CSS RGB format conversion (i.e. 0x124672) - lighter color - darker color - color with modified brightness - color with hex string */ public extension UIColor { /// Construct a UIColor using an HTML/CSS RGB formatted value and an alpha value /// /// - parameter rgbValue: rgb value /// - parameter alpha: color alpha /// /// - returns: UIColor instance public class func colorWithRGB(rgbValue : UInt, alpha : CGFloat = 1.0) -> UIColor { let red = CGFloat((rgbValue & 0xFF0000) >> 16) / 255 let green = CGFloat((rgbValue & 0xFF00) >> 8) / 255 let blue = CGFloat(rgbValue & 0xFF) / 255 return UIColor(red: red, green: green, blue: blue, alpha: alpha) } /// Construct a UIColor by hex string. The hex string can start with # or without # /// /// - parameter hexString: 6 characters hexstring if without hash, or 7 characters with hash /// - parameter alpha: alpha value /// /// - returns: UIColor public class func colorWithHexString(_ hexString: String, alpha: CGFloat) -> UIColor? { var hex = hexString // Check for hash and remove the hash if hex.hasPrefix("#") { hex = hex.substring(from: hex.index(hex.startIndex, offsetBy: 1)) } guard let hexVal = Int(hex, radix: 16) else { print("Unable to create color. Invalid hex string: \(hexString)" ) return nil } return UIColor.colorWithRGB(rgbValue: UInt(hexVal), alpha : alpha) } /// Returns a lighter color by the provided percentage /// /// - parameter percent: lighting percentage /// /// - returns: lighter UIColor public func lighterColor(percent : Double) -> UIColor { return colorWithBrightnessFactor(factor: CGFloat(1 + percent)) } /// Returns a darker color by the provided percentage /// /// - parameter percent: darker percentage /// /// - returns: darker UIColor public func darkerColor(percent : Double) -> UIColor { return colorWithBrightnessFactor(factor: CGFloat(1 - percent)) } /// Return a modified color using the brightness factor provided /// /// - parameter factor: brightness factor /// /// - returns: modified color public func colorWithBrightnessFactor(factor: CGFloat) -> UIColor { var hue : CGFloat = 0 var saturation : CGFloat = 0 var brightness : CGFloat = 0 var alpha : CGFloat = 0 if getHue(&hue, saturation: &saturation, brightness: &brightness, alpha: &alpha) { return UIColor(hue: hue, saturation: saturation, brightness: brightness * factor, alpha: alpha) } else { return self } } }
mit
989a5c60ad4ae8411e0a80826e9d2516
31.242105
107
0.60986
4.564829
false
false
false
false
NextFaze/FazeKit
Sources/FazeKit/Classes/DataAdditions.swift
2
750
// // DataAdditions.swift // FazeKit // // Created by Shane Woolcock on 2/10/19. // import Foundation import CommonCrypto public extension Data { func md5() -> String { let digestLen = Int(CC_MD5_DIGEST_LENGTH) var digest = [UInt8](repeating: 0, count: digestLen) let count = self.count self.withUnsafeBytes { bytes -> Void in CC_MD5(bytes, CC_LONG(count), &digest) } let hash = NSMutableString() digest.forEach { hash.appendFormat("%02x", $0) } return String(format: hash as String) } func hex() -> String { let str = NSMutableString() self.forEach { str.appendFormat("%02x", $0) } return String(format: str as String) } }
apache-2.0
076434e372d43b86828846e0e96f4739
24.862069
60
0.589333
3.787879
false
false
false
false
Shopify/mobile-buy-sdk-ios
Buy/Generated/Storefront/ProductImageSortKeys.swift
1
1794
// // ProductImageSortKeys.swift // Buy // // Created by Shopify. // Copyright (c) 2017 Shopify Inc. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation extension Storefront { /// The set of valid sort keys for the ProductImage query. public enum ProductImageSortKeys: String { /// Sort by the `created_at` value. case createdAt = "CREATED_AT" /// Sort by the `id` value. case id = "ID" /// Sort by the `position` value. case position = "POSITION" /// Sort by relevance to the search terms when the `query` parameter is /// specified on the connection. Don't use this sort key when no search query /// is specified. case relevance = "RELEVANCE" case unknownValue = "" } }
mit
4c2bc19b7efe9f065079b8b58d24ee31
36.375
81
0.72408
4.031461
false
false
false
false
varun-naharia/VNOfficeHourPicker
VNOfficeHourPicker/Utilities/CustomLabel.swift
2
4326
// // CustomLabel.swift // OfficeHourPicker // // Created by Varun Naharia on 08/03/17. // Copyright © 2017 Varun Nahariah. All rights reserved. // import UIKit @IBDesignable class CustomLabel: UILabel { @IBInspectable public var cornerRadius :CGFloat { set { layer.cornerRadius = newValue } get { return layer.cornerRadius } } override init(frame: CGRect) { super.init(frame: frame) self.setUpView() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func awakeFromNib() { super.awakeFromNib() self.setUpView() } override func prepareForInterfaceBuilder() { super.prepareForInterfaceBuilder() } func setUpView() { } @IBInspectable var leftImage: UIImage? { didSet { updateView() } } @IBInspectable var rightImage: UIImage? { didSet { updateView() } } @IBInspectable var leftPadding: Int = 0 { didSet { updateView() } } @IBInspectable var rightPadding: Int = 0{ didSet { updateView() } } func updateView() { if let imageLeft = leftImage { //Resize image let newSize = CGSize(width: self.frame.size.height, height: self.frame.size.height) UIGraphicsBeginImageContextWithOptions(newSize, false, 0.0) imageLeft.draw(in: CGRect(x: 0, y: 1, width: newSize.width, height: newSize.height)) let imageResized = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() //Create attachment text with image let attachment = NSTextAttachment() attachment.image = imageResized let attachmentString = NSAttributedString(attachment: attachment) let myString = NSMutableAttributedString(string: "") myString.append(attachmentString) for _ in 0...leftPadding { myString.append(NSAttributedString(string: " ")) } myString.append(NSAttributedString(string: self.text!)) self.attributedText = myString } if let imageRight = rightImage { //Resize image let newSize = CGSize(width: self.frame.size.height, height: self.frame.size.height) UIGraphicsBeginImageContextWithOptions(newSize, false, 0.0) imageRight.draw(in: CGRect(x: 0, y: 2, width: newSize.width, height: newSize.height)) let imageResized = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() //Create attachment text with image let attachment = NSTextAttachment() attachment.image = imageResized let attachmentString = NSAttributedString(attachment: attachment) let myString = NSMutableAttributedString(string: self.text!) for _ in 0...rightPadding { myString.append(NSAttributedString(string: " ")) } myString.append(attachmentString) self.attributedText = myString } } /* // Only override draw() if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func draw(_ rect: CGRect) { // Drawing code } //Get image and set it's size let image = UIImage(named: "imageNameWithHeart") let newSize = CGSize(width: 10, height: 10) //Resize image UIGraphicsBeginImageContextWithOptions(newSize, false, 0.0) image?.drawInRect(CGRectMake(0, 0, newSize.width, newSize.height)) let imageResized = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() //Create attachment text with image var attachment = NSTextAttachment() attachment.image = imageResized var attachmentString = NSAttributedString(attachment: attachment) var myString = NSMutableAttributedString(string: "I love swift ") myString.appendAttributedString(attachmentString) myLabel.attributedText = myString */ }
mit
9da9d5e818a550cb840b3c011e2f8e13
30.115108
97
0.607168
5.440252
false
false
false
false
whiteshadow-gr/HatForIOS
HAT/Objects/Facebook/Posts/HATFacebookPlace.swift
1
3202
// /** * Copyright (C) 2018 HAT Data Exchange Ltd * * SPDX-License-Identifier: MPL2 * * This file is part of the Hub of All Things project (HAT). * * 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 SwiftyJSON // MARK: Struct public struct HATFacebookPlace: HATObject, HatApiType { // MARK: - Coding Keys /** The JSON fields used by the hat The Fields are the following: * `placeID` in JSON is `id` * `name` in JSON is `name` * `location` in JSON is `location` */ private enum CodingKeys: String, CodingKey { case placeID = "id" case name = "name" case location = "location" } // MARK: - Variables /// A unique id for the place public var placeID: String = "" /// The name of the place, eg. Five Guys public var name: String = "" /// The location object describing the location of the place, including latitude, longitude and more public var location: HATFacebookLocation = HATFacebookLocation() // MARK: - Initialisers /** The default initialiser. Initialises everything to default values. */ public init() { placeID = "" name = "" location = HATFacebookLocation() } /** It initialises everything from the received JSON file from the HAT - dictionary: The JSON file received */ public init(from dictionary: Dictionary<String, JSON>) { self.init() self.inititialize(dict: dictionary) } /** It initialises everything from the received JSON file from the HAT - dict: The JSON file received */ public mutating func inititialize(dict: Dictionary<String, JSON>) { if let tempPlaceID: String = dict[CodingKeys.placeID.rawValue]?.stringValue { placeID = tempPlaceID } if let tempName: String = dict[CodingKeys.name.rawValue]?.stringValue { name = tempName } if let tempLocation: [String: JSON] = dict[CodingKeys.location.rawValue]?.dictionaryValue { location = HATFacebookLocation(from: tempLocation) } } /** It initialises everything from the received JSON file from the cache - fromCache: The Dictionary file received from the cache */ public mutating func initialize(fromCache: Dictionary<String, Any>) { let dictionary: JSON = JSON(fromCache) self.inititialize(dict: dictionary.dictionaryValue) } // MARK: - JSON Mapper /** Returns the object as Dictionary, JSON - returns: Dictionary<String, String> */ public func toJSON() -> Dictionary<String, Any> { return [ CodingKeys.placeID.rawValue: self.placeID, CodingKeys.name.rawValue: self.name, CodingKeys.location.rawValue: self.location.toJSON() ] } }
mpl-2.0
58df156bd41387e5fe69fbdb36df58a9
25.907563
104
0.593691
4.779104
false
false
false
false
kwizzad/kwizzad-ios
Source/Logger.swift
1
4937
// // Logger.swift // // Created by Alejandro Barros Cuetos on 03/02/15. // Copyright (c) 2015 Alejandro Barros Cuetos. All rights reserved. // Adapted by Fares Ben Hamouda for TVSMILES. // // 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. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // import Foundation /** Available Log level for Logger - None: Print no message - Error: Message of level Error - Warning: Message of level Warning - Success: Message of level Success - Info: Message of level Info - Custom: Message of level Custom */ enum LoggerLevels: Int { case None = 0 case Error case Warning case Debug case Info case Custom } /** * Singleton class to print custom log messages easier to read * and analize. Based in glyphs and log levels */ class Logger { // MARK: - Properties var verbosityLevel: LoggerLevels = .Custom var errorGlyph: String = "\u{1F6AB}" // Glyph for messages of level .Error var warningGlyph: String = "\u{1F514}" // Glyph for messages of level .Warning var successGlyph: String = "\u{2705}" // Glyph for messages of level .Success var infoGlyph: String = "\u{1F535}" // Glyph for messages of level .Info var customGlyph: String = "\u{1F536}" // Glyph for messages of level .Custom // MARK: Public methods /** Prints a formatted message through the debug console, showing a glyph based on the loglevel and the name of the file invoking it if present :param: message Message to print :param: logLevel Level of the log message :param: file Implicit parameter, file calling the method :param: line Implicit parameter, line which the call was made */ func logMessage(_ message: String , _ logLevel: LoggerLevels = .Info, file: String = #file, line: UInt = #line) { if (KwizzadSDK.instance.showDebugMessages) { if self.verbosityLevel.rawValue > LoggerLevels.None.rawValue && logLevel.rawValue <= self.verbosityLevel.rawValue { print("\(getGlyphForLogLevel(logLevel: logLevel))\(message) [\(file):\(line)] \(message)") } } } /** Prints a formatted message through the debug console, showing a glyph based on the loglevel and the name of the class invoking it if present :param: message Message to print :param: logLevel Level of the log message :param: file Implicit parameter, file calling the method :param: line Implicit parameter, line which the call was made :returns: A formatted string */ func getMessage(message: String, _ logLevel: LoggerLevels = .Info, file: String = #file, line: UInt = #line) -> String { return("\(getGlyphForLogLevel(logLevel: logLevel))\(message) [\(file):\(line)] \(message)") } // MARK: - Private Methods /** Returns the Glyph to use according to the passed LogLevel :param: logLevel :returns: A formatted string with the matching glyph */ private func getGlyphForLogLevel(logLevel: LoggerLevels) -> String { switch logLevel { case .Error: return "\(errorGlyph) " case .Warning: return "\(warningGlyph) " case .Debug: return "\(successGlyph) " case .Info: return "\(infoGlyph) " case .Custom: return "\(customGlyph) " default: return " " } } // MARK: - Singleton Pattern class var sharedInstance: Logger { struct Singleton { static let instance = Logger() } return Singleton.instance } }
mit
8dd1841be4c6dda75787e1ac120fb6fe
33.284722
128
0.661535
4.439748
false
false
false
false
tomasharkema/R.swift
Sources/RswiftCore/SwiftTypes/Type.swift
1
5073
// // Type.swift // R.swift // // Created by Mathijs Kadijk on 10-12-15. // From: https://github.com/mac-cain13/R.swift // License: MIT License // import Foundation struct UsedType: Hashable { let type: Type fileprivate init(type: Type) { self.type = type } } struct Type: UsedTypesProvider, CustomStringConvertible, Hashable { static let _Void = Type(module: .stdLib, name: "Void") static let _Any = Type(module: .stdLib, name: "Any") static let _AnyObject = Type(module: .stdLib, name: "AnyObject") static let _String = Type(module: .stdLib, name: "String") static let _Bool = Type(module: .stdLib, name: "Bool") static let _Array = Type(module: .stdLib, name: "Array") static let _Tuple = Type(module: .stdLib, name: "_TUPLE_") static let _Int = Type(module: .stdLib, name: "Int") static let _UInt = Type(module: .stdLib, name: "UInt") static let _Double = Type(module: .stdLib, name: "Double") static let _Character = Type(module: .stdLib, name: "Character") static let _CStringPointer = Type(module: .stdLib, name: "UnsafePointer<CChar>") static let _VoidPointer = Type(module: .stdLib, name: "UnsafePointer<Void>") static let _URL = Type(module: "Foundation", name: "URL") static let _Bundle = Type(module: "Foundation", name: "Bundle") static let _Locale = Type(module: "Foundation", name: "Locale") static let _UINib = Type(module: "UIKit", name: "UINib") static let _UIView = Type(module: "UIKit", name: "UIView") static let _UIImage = Type(module: "UIKit", name: "UIImage") static let _UIStoryboard = Type(module: "UIKit", name: "UIStoryboard") static let _UITableViewCell = Type(module: "UIKit", name: "UITableViewCell") static let _UICollectionViewCell = Type(module: "UIKit", name: "UICollectionViewCell") static let _UICollectionReusableView = Type(module: "UIKit", name: "UICollectionReusableView") static let _UIStoryboardSegue = Type(module: "UIKit", name: "UIStoryboardSegue") static let _UITraitCollection = Type(module: "UIKit", name: "UITraitCollection") static let _UIViewController = Type(module: "UIKit", name: "UIViewController") static let _UIFont = Type(module: "UIKit", name: "UIFont") static let _UIColor = Type(module: "UIKit", name: "UIColor") static let _CGFloat = Type(module: .stdLib, name: "CGFloat") static let _CVarArgType = Type(module: .stdLib, name: "CVarArgType...") static let ReuseIdentifier = Type(module: "Rswift", name: "ReuseIdentifier", genericArgs: [TypeVar(description: "T", usedTypes: [])]) static let ReuseIdentifierType = Type(module: "Rswift", name: "ReuseIdentifierType") static let StoryboardResourceType = Type(module: "Rswift", name: "StoryboardResourceType") static let StoryboardResourceWithInitialControllerType = Type(module: "Rswift", name: "StoryboardResourceWithInitialControllerType") static let StoryboardViewControllerResource = Type(module: "Rswift", name: "StoryboardViewControllerResource") static let NibResourceType = Type(module: "Rswift", name: "NibResourceType") static let FileResource = Type(module: "Rswift", name: "FileResource") static let FontResource = Type(module: "Rswift", name: "FontResource") static let ColorResource = Type(module: "Rswift", name: "ColorResource") static let ImageResource = Type(module: "Rswift", name: "ImageResource") static let StringResource = Type(module: "Rswift", name: "StringResource") static let Strings = Type(module: "Rswift", name: "Strings") static let Validatable = Type(module: "Rswift", name: "Validatable") static let TypedStoryboardSegueInfo = Type(module: "Rswift", name: "TypedStoryboardSegueInfo", genericArgs: [TypeVar(description: "Segue", usedTypes: []), TypeVar(description: "Source", usedTypes: []), TypeVar(description: "Destination", usedTypes: [])]) let module: Module let name: SwiftIdentifier let genericArgs: [TypeVar] let optional: Bool var usedTypes: [UsedType] { return [UsedType(type: self)] + genericArgs.flatMap(getUsedTypes) } var description: String { return TypePrinter(type: self).swiftCode } init(module: Module, name: SwiftIdentifier, genericArgs: [TypeVar] = [], optional: Bool = false) { self.module = module self.name = name self.genericArgs = genericArgs self.optional = optional } init(module: Module, name: SwiftIdentifier, genericArgs: [Type], optional: Bool = false) { self.module = module self.name = name self.genericArgs = genericArgs.map(TypeVar.init) self.optional = optional } func asOptional() -> Type { return Type(module: module, name: name, genericArgs: genericArgs, optional: true) } func asNonOptional() -> Type { return Type(module: module, name: name, genericArgs: genericArgs, optional: false) } func withGenericArgs(_ genericArgs: [TypeVar]) -> Type { return Type(module: module, name: name, genericArgs: genericArgs, optional: optional) } func withGenericArgs(_ genericArgs: [Type]) -> Type { return Type(module: module, name: name, genericArgs: genericArgs, optional: optional) } }
mit
2a9fe34bb8eed5bdfa92b44696bf5044
45.541284
256
0.709048
3.780179
false
false
false
false
sswierczek/Helix-Movie-Guide-iOS
Helix Movie GuideTests/DetailsPresenterTest.swift
1
4207
// // DetailsPresenterTest.swift // Helix Movie Guide // // Created by Sebastian Swierczek on 25/03/2017. // Copyright © 2017 user. All rights reserved. // @testable import Helix_Movie_Guide import XCTest import Cuckoo import ObjectMapper import RxSwift enum TestError: Error { case error } class DetailsPresenterTest: XCTestCase { // FIXME Find a way to ommit constructor arguments in generated mocks var detailsUseCase = MockGetMovieDetailsUseCase(api: MockMovieApi()) var movieVideosUseCase = MockGetMovieVideosUseCase(api: MockMovieApi()) var view = MockDetailsView() var testMovieId = 1234 var detailsPresenter: DetailsPresenter? override func setUp() { super.setUp() detailsPresenter = DetailsPresenter(getMovieDetailsUseCase: detailsUseCase, getMovieVideosUseCase: movieVideosUseCase) stub(view) { stub in when(stub.showError(errorMessage: anyString())).thenDoNothing() when(stub.showLoading(show: any())).thenDoNothing() when(stub.showMovieDetails(movie: any())).thenDoNothing() when(stub.showVideos(videos: any())).thenDoNothing() } mock_movieDetails(movie: nil) mock_videos(videos: nil) } override func tearDown() { detailsPresenter?.detachView() } func test_GIVEN_movieId_WHEN_attachView_THEN_loadMovieDetails() { detailsPresenter?.itemSelected(id: testMovieId) detailsPresenter?.attachView(view: view) verify(detailsUseCase).execute(movieId: testMovieId) } func test_GIVEN_movieId_WHEN_attachView_THEN_loadMovieVideos() { detailsPresenter?.itemSelected(id: testMovieId) detailsPresenter?.attachView(view: view) verify(movieVideosUseCase).execute(movieId: testMovieId) } func test_GIVEN_noMovieId_WHEN_attachView_THEN_doNothing() { detailsPresenter?.attachView(view: view) verify(detailsUseCase, never()).execute(movieId: anyInt()) verify(movieVideosUseCase, never()).execute(movieId: anyInt()) } func test_WHEN_movieFetched_THEN_showMovieDetails() { mock_movieDetails(movie: Movie(JSONString: "{\"id\":\"\(testMovieId)\"}")) detailsPresenter?.itemSelected(id: testMovieId) detailsPresenter?.attachView(view: view) verify(view).showMovieDetails(movie: any()) } func test_WHEN_movieVideosFetched_THEN_showVideos() { mock_videos(videos: [Video(JSONString: "{\"id\":\"\(testMovieId)\"}")!]) detailsPresenter?.itemSelected(id: testMovieId) detailsPresenter?.attachView(view: view) verify(view).showVideos(videos: any()) } func test_WHEN_errorFetchingDetails_THEN_showsError() { mock_movieDetails(error: TestError.error) detailsPresenter?.itemSelected(id: testMovieId) detailsPresenter?.attachView(view: view) verify(view).showError(errorMessage: TestError.error.localizedDescription) } func test_WHEN_errorFetchingVideos_THEN_showsError() { mock_videos(error: TestError.error) detailsPresenter?.itemSelected(id: testMovieId) detailsPresenter?.attachView(view: view) verify(view).showError(errorMessage: TestError.error.localizedDescription) } func mock_movieDetails(movie: Movie?) { let data = movie == nil ? Observable.empty() : Observable.just(movie!) stub(detailsUseCase) { stub in when(stub.execute(movieId: anyInt())).thenReturn(data) } } func mock_movieDetails(error: TestError) { stub(detailsUseCase) { stub in when(stub.execute(movieId: anyInt())).thenReturn(Observable.error(error)) } } func mock_videos(videos: [Video]?) { let data = videos == nil ? Observable.empty() : Observable.just(videos!) stub(movieVideosUseCase) { stub in when(stub.execute(movieId: anyInt())).thenReturn(data) } } func mock_videos(error: TestError) { stub(movieVideosUseCase) { stub in when(stub.execute(movieId: anyInt())).thenReturn(Observable.error(error)) } } }
apache-2.0
f0e741fa4b86c607805b96655d553796
30.155556
86
0.665002
4.349535
false
true
false
false
OHeroJ/twicebook
Sources/App/Controllers/MessageBoardController.swift
1
1353
// // MessageBoardController.swift // App // // Created by laijihua on 13/11/2017. // import Foundation import Vapor /// 用户留言板 final class MessageBoardController: ControllerRoutable { init(builder: RouteBuilder) { builder.get("/", handler: list) builder.post("create", handler: create) } func list(req: Request) throws -> ResponseRepresentable { guard let userId = req.data[MessageBoard.Key.userId]?.int else {return try ApiRes.error(code: 1, msg: "miss userId")} let query = try MessageBoard.makeQuery().filter(MessageBoard.Key.userId, userId) return try MessageBoard.page(request: req, query: query) } func create(req: Request) throws -> ResponseRepresentable { guard let userId = req.data[MessageBoard.Key.userId]?.int else {return try ApiRes.error(code: 1, msg: "miss userId")} guard let creatId = req.data[MessageBoard.Key.senderId]?.int else { return try ApiRes.error(code: 2, msg: "miss senderId") } guard let content = req.data[MessageBoard.Key.content]?.string else { return try ApiRes.error(code: 3, msg: "miss content") } let board = MessageBoard(userId: userId, senderId: creatId, content: content) try board.save() return try ApiRes.success(data:["success": true]) } }
mit
e30a0e933954ae087cc7ae5f2b34623b
35.297297
125
0.658228
3.938416
false
false
false
false
lyimin/iOS-Animation-Demo
iOS-Animation学习笔记/iOS-Animation学习笔记/加载进度条/ProgressAnimationController.swift
1
2073
// // ProgressAnimationController.swift // iOS-Animation学习笔记 // // Created by 梁亦明 on 16/5/26. // Copyright © 2016年 xiaoming. All rights reserved. // import UIKit class ProgressAnimationController: UIViewController { struct Gallon { // MARK: - Properties let ouncesDrank = 0 let totalOunces = 128 } let gallon = Gallon() let progressView = ProgressView.createView() override func viewDidLoad() { super.viewDidLoad() self.view.addSubview(addBtn) progressView.center = self.view.center self.view.addSubview(progressView) // 设置初始值 configureProgressView() } func configureProgressView() { progressView.curValue = CGFloat(gallon.ouncesDrank) progressView.range = CGFloat(gallon.totalOunces) } func addBtnDidClick() { guard progressView.curValue < CGFloat(gallon.totalOunces) else { return } // Increment progressView curValue. let eightOunceCup = 8 progressView.curValue = progressView.curValue + CGFloat(eightOunceCup) // Update label based on progressView curValue. let percentage = (Double(progressView.curValue) / Double(gallon.totalOunces)) progressView.percentLabel.text = numberAsPercentage(percentage) } func numberAsPercentage(_ number: Double) -> String { let formatter = NumberFormatter() formatter.numberStyle = .percent formatter.percentSymbol = "" return formatter.string(from: NSNumber(value: number))! } fileprivate lazy var addBtn: UIButton = { let btn = UIButton(type: UIButtonType.contactAdd) btn.addTarget(self, action: #selector(ProgressAnimationController.addBtnDidClick), for: .touchUpInside) btn.frame = CGRect(x: 0, y: 0, width: 54, height: 54) btn.center = CGPoint(x: self.view.width/2, y: self.view.height*0.8) return btn }() }
mit
a66f1e5931929f3c2ec13cd4bb4fec19
28.228571
111
0.627566
4.447826
false
false
false
false
andreaperizzato/CoreStore
CoreStore/Observing/ObjectMonitor.swift
2
12534
// // ObjectMonitor.swift // CoreStore // // Copyright (c) 2015 John Rommel Estropia // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import Foundation import CoreData import GCDKit // MARK: - ObjectMonitor /** The `ObjectMonitor` monitors changes to a single `NSManagedObject` instance. Observers that implement the `ObjectObserver` protocol may then register themselves to the `ObjectMonitor`'s `addObserver(_:)` method: let monitor = CoreStore.monitorObject(object) monitor.addObserver(self) The created `ObjectMonitor` instance needs to be held on (retained) for as long as the object needs to be observed. Observers registered via `addObserver(_:)` are not retained. `ObjectMonitor` only keeps a `weak` reference to all observers, thus keeping itself free from retain-cycles. */ public final class ObjectMonitor<T: NSManagedObject> { // MARK: Public /** Returns the `NSManagedObject` instance being observed, or `nil` if the object was already deleted. */ public var object: T? { return self.fetchedResultsController.fetchedObjects?.first as? T } /** Returns `true` if the `NSManagedObject` instance being observed still exists, or `false` if the object was already deleted. */ public var isObjectDeleted: Bool { return self.object?.managedObjectContext == nil } /** Registers an `ObjectObserver` to be notified when changes to the receiver's `object` are made. To prevent retain-cycles, `ObjectMonitor` only keeps `weak` references to its observers. For thread safety, this method needs to be called from the main thread. An assertion failure will occur (on debug builds only) if called from any thread other than the main thread. Calling `addObserver(_:)` multiple times on the same observer is safe, as `ObjectMonitor` unregisters previous notifications to the observer before re-registering them. - parameter observer: an `ObjectObserver` to send change notifications to */ public func addObserver<U: ObjectObserver where U.ObjectEntityType == T>(observer: U) { CoreStore.assert( NSThread.isMainThread(), "Attempted to add an observer of type \(typeName(observer)) outside the main thread." ) self.removeObserver(observer) self.registerChangeNotification( &self.willChangeObjectKey, name: ObjectMonitorWillChangeObjectNotification, toObserver: observer, callback: { [weak observer] (monitor) -> Void in guard let object = monitor.object, let observer = observer else { return } observer.objectMonitor(monitor, willUpdateObject: object) } ) self.registerObjectNotification( &self.didDeleteObjectKey, name: ObjectMonitorDidDeleteObjectNotification, toObserver: observer, callback: { [weak observer] (monitor, object) -> Void in guard let observer = observer else { return } observer.objectMonitor(monitor, didDeleteObject: object) } ) self.registerObjectNotification( &self.didUpdateObjectKey, name: ObjectMonitorDidUpdateObjectNotification, toObserver: observer, callback: { [weak self, weak observer] (monitor, object) -> Void in guard let strongSelf = self, let observer = observer else { return } let previousCommitedAttributes = strongSelf.lastCommittedAttributes let currentCommitedAttributes = object.committedValuesForKeys(nil) as! [String: NSObject] var changedKeys = Set<String>() for key in currentCommitedAttributes.keys { if previousCommitedAttributes[key] != currentCommitedAttributes[key] { changedKeys.insert(key) } } strongSelf.lastCommittedAttributes = currentCommitedAttributes observer.objectMonitor( monitor, didUpdateObject: object, changedPersistentKeys: changedKeys ) } ) } /** Unregisters an `ObjectObserver` from receiving notifications for changes to the receiver's `object`. For thread safety, this method needs to be called from the main thread. An assertion failure will occur (on debug builds only) if called from any thread other than the main thread. - parameter observer: an `ObjectObserver` to unregister notifications to */ public func removeObserver<U: ObjectObserver where U.ObjectEntityType == T>(observer: U) { CoreStore.assert( NSThread.isMainThread(), "Attempted to remove an observer of type \(typeName(observer)) outside the main thread." ) let nilValue: AnyObject? = nil setAssociatedRetainedObject(nilValue, forKey: &self.willChangeObjectKey, inObject: observer) setAssociatedRetainedObject(nilValue, forKey: &self.didDeleteObjectKey, inObject: observer) setAssociatedRetainedObject(nilValue, forKey: &self.didUpdateObjectKey, inObject: observer) } // MARK: Internal internal init(dataStack: DataStack, object: T) { let context = dataStack.mainContext let fetchRequest = NSFetchRequest() fetchRequest.entity = object.entity fetchRequest.fetchLimit = 0 fetchRequest.resultType = .ManagedObjectResultType fetchRequest.sortDescriptors = [] fetchRequest.includesPendingChanges = false fetchRequest.shouldRefreshRefetchedObjects = true let originalObjectID = object.objectID Where("SELF", isEqualTo: originalObjectID).applyToFetchRequest(fetchRequest) let fetchedResultsController = NSFetchedResultsController( fetchRequest: fetchRequest, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: nil ) let fetchedResultsControllerDelegate = FetchedResultsControllerDelegate() self.fetchedResultsController = fetchedResultsController self.fetchedResultsControllerDelegate = fetchedResultsControllerDelegate self.parentStack = dataStack fetchedResultsControllerDelegate.handler = self fetchedResultsControllerDelegate.fetchedResultsController = fetchedResultsController try! fetchedResultsController.performFetch() self.lastCommittedAttributes = (self.object?.committedValuesForKeys(nil) as? [String: NSObject]) ?? [:] } // MARK: Private private let fetchedResultsController: NSFetchedResultsController private let fetchedResultsControllerDelegate: FetchedResultsControllerDelegate private var lastCommittedAttributes = [String: NSObject]() private weak var parentStack: DataStack? private var willChangeObjectKey: Void? private var didDeleteObjectKey: Void? private var didUpdateObjectKey: Void? private func registerChangeNotification(notificationKey: UnsafePointer<Void>, name: String, toObserver observer: AnyObject, callback: (monitor: ObjectMonitor<T>) -> Void) { setAssociatedRetainedObject( NotificationObserver( notificationName: name, object: self, closure: { [weak self] (note) -> Void in guard let strongSelf = self else { return } callback(monitor: strongSelf) } ), forKey: notificationKey, inObject: observer ) } private func registerObjectNotification(notificationKey: UnsafePointer<Void>, name: String, toObserver observer: AnyObject, callback: (monitor: ObjectMonitor<T>, object: T) -> Void) { setAssociatedRetainedObject( NotificationObserver( notificationName: name, object: self, closure: { [weak self] (note) -> Void in guard let strongSelf = self, let userInfo = note.userInfo, let object = userInfo[UserInfoKeyObject] as? T else { return } callback(monitor: strongSelf, object: object) } ), forKey: notificationKey, inObject: observer ) } } // MARK: - ObjectMonitor: Equatable public func ==<T: NSManagedObject>(lhs: ObjectMonitor<T>, rhs: ObjectMonitor<T>) -> Bool { return lhs === rhs } extension ObjectMonitor: Equatable { } // MARK: - ObjectMonitor: FetchedResultsControllerHandler extension ObjectMonitor: FetchedResultsControllerHandler { // MARK: FetchedResultsControllerHandler internal func controllerWillChangeContent(controller: NSFetchedResultsController) { NSNotificationCenter.defaultCenter().postNotificationName( ObjectMonitorWillChangeObjectNotification, object: self ) } internal func controllerDidChangeContent(controller: NSFetchedResultsController) { } internal func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?) { switch type { case .Delete: NSNotificationCenter.defaultCenter().postNotificationName( ObjectMonitorDidDeleteObjectNotification, object: self, userInfo: [UserInfoKeyObject: anObject] ) case .Update: NSNotificationCenter.defaultCenter().postNotificationName( ObjectMonitorDidUpdateObjectNotification, object: self, userInfo: [UserInfoKeyObject: anObject] ) default: break } } internal func controller(controller: NSFetchedResultsController, didChangeSection sectionInfo: NSFetchedResultsSectionInfo, atIndex sectionIndex: Int, forChangeType type: NSFetchedResultsChangeType) { } internal func controller(controller: NSFetchedResultsController, sectionIndexTitleForSectionName sectionName: String?) -> String? { return sectionName } } private let ObjectMonitorWillChangeObjectNotification = "ObjectMonitorWillChangeObjectNotification" private let ObjectMonitorDidDeleteObjectNotification = "ObjectMonitorDidDeleteObjectNotification" private let ObjectMonitorDidUpdateObjectNotification = "ObjectMonitorDidUpdateObjectNotification" private let UserInfoKeyObject = "UserInfoKeyObject"
mit
74575e4f4b3c039c44887c664b4a541c
38.16875
220
0.639381
6.00575
false
false
false
false
coffeestats/coffeestats-ios
Coffeestats/Classes/QRCodeScannerViewController.swift
1
3794
// // QRCodeScannerViewController.swift // Coffeestats // // Created by Danilo Bürger on 16/03/2017. // Copyright © 2017 Danilo Bürger. All rights reserved. // import UIKit import AVFoundation protocol QRCodeScannerDelegate: class { func isAcceptable(_ qrCode: String) -> Bool func didScan(_ qrCode: String) } class QRCodeScannerViewController: UIViewController, AVCaptureMetadataOutputObjectsDelegate { weak var delegate: QRCodeScannerDelegate? private let previewLayer: AVCaptureVideoPreviewLayer private var stoppedCapture = false private let captureSession = AVCaptureSession() private let queue = DispatchQueue(label: "QRCodeScannerViewController queue") required init?(coder aDecoder: NSCoder) { previewLayer = AVCaptureVideoPreviewLayer(session: captureSession) super.init(coder: aDecoder) setup() } override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { previewLayer = AVCaptureVideoPreviewLayer(session: captureSession) super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) setup() } convenience init() { self.init(nibName:nil, bundle:nil) } func setup() { previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill previewLayer.backgroundColor = UIColor.black.cgColor } override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() previewLayer.frame = view.layer.bounds } override func viewDidLoad() { super.viewDidLoad() view.layer.addSublayer(previewLayer) AVCaptureDevice.requestAccess(forMediaType: AVMediaTypeVideo) { (granted) in if granted { self.setupCaptureDevice() } else { // TODO(danilo): Handle error } } } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) stopCapture() } private func setupCaptureDevice() { let captureDevice = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo) let input = try? AVCaptureDeviceInput(device: captureDevice) if captureSession.canAddInput(input) { captureSession.addInput(input) } else { // TODO(danilo): Handle error } let metadataOutput = AVCaptureMetadataOutput() if captureSession.canAddOutput(metadataOutput) { captureSession.addOutput(metadataOutput) metadataOutput.setMetadataObjectsDelegate(self, queue: DispatchQueue.main) metadataOutput.metadataObjectTypes = [AVMetadataObjectTypeQRCode] } else { // TODO(danilo): Handle error } queue.async { self.captureSession.startRunning() } } private func stopCapture() { guard !stoppedCapture else { return } stoppedCapture = false previewLayer.connection.isEnabled = false queue.async { self.captureSession.stopRunning() } } // MARK: - AVCaptureMetadataOutputObjectsDelegate func captureOutput(_ captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [Any]!, from connection: AVCaptureConnection!) { guard !stoppedCapture else { return } guard let delegate = delegate else { return } guard metadataObjects != nil && metadataObjects.count > 0 else { return } if let metadata = metadataObjects[0] as? AVMetadataMachineReadableCodeObject, metadata.type == AVMetadataObjectTypeQRCode, metadata.stringValue != nil, delegate.isAcceptable(metadata.stringValue) { delegate.didScan(metadata.stringValue) } } }
mit
856629662ca146f2d2ef5aedb998f4d3
29.328
113
0.66526
5.700752
false
false
false
false
nathawes/swift
test/decl/async/objc.swift
1
1726
// RUN: %target-swift-frontend -disable-objc-attr-requires-foundation-module -typecheck -verify %s -swift-version 5 -enable-experimental-concurrency // RUN: %target-swift-ide-test -skip-deinit=false -print-ast-typechecked -source-filename %s -function-definitions=true -prefer-type-repr=false -print-implicit-attrs=true -explode-pattern-binding-decls=true -disable-objc-attr-requires-foundation-module -swift-version 5 -enable-experimental-concurrency | %FileCheck %s // REQUIRES: objc_interop import Foundation import ObjectiveC @objc protocol P { func doBigJob() async -> Int } // Infer @objc from protocol conformance // CHECK: class ConformsToP class ConformsToP: P { // CHECK: @objc func doBigJob() async -> Int func doBigJob() async -> Int { 5 } } // Infer @objc from superclass class Super { @objc func longRunningRequest() async throws -> [String] { [] } } // CHECK: class Sub class Sub : Super { // CHECK-NEXT: @objc override func longRunningRequest() async throws -> [String] override func longRunningRequest() async throws -> [String] { [] } } // Check selector computation. @objc protocol MakeSelectors { func selectorAsync() async -> Int func selector(value: Int) async -> Int } func testSelectors() { // expected-warning@+1{{use '#selector' instead of explicitly constructing a 'Selector'}} _ = Selector("selectorAsyncWithCompletionHandler:") // expected-warning@+1{{use '#selector' instead of explicitly constructing a 'Selector'}} _ = Selector("selectorWithValue:completionHandler:") _ = Selector("canary:") // expected-warning{{no method declared with Objective-C selector 'canary:'}} // expected-note@-1{{wrap the selector name in parentheses to suppress this warning}} }
apache-2.0
a28deec6c26ec7cdaf09d2c7726da206
38.227273
318
0.73175
4.013953
false
false
false
false
yangyouyong0/SwiftLearnLog
YYPlayer/YYPlayer/ViewController.swift
1
1174
// // ViewController.swift // YYPlayer // // Created by yangyouyong on 15/7/5. // Copyright (c) 2015年 yangyouyong. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. var request:Request? { didSet { oldValue?.cancel() self.title = request?.description } } } // func loadRequest() { // let mainAPI:String = "http://online.dongting.com/recomm/new_songs_more?page=1&size=30"; // Alamofire.manager.request(Method.GET, mainAPI).validate().responseImage(){ // (request,_,image,error)in // // if error == nil { // if request.URLString.isEqual(imageURL){ // cell.userImageView.image = image // } // } // } // } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
apache-2.0
c9013f14721d630882fd7944d917b1c8
25.044444
97
0.540102
4.324723
false
false
false
false
MateuszKarwat/Napi
Napi/Controllers/MainFlowController.swift
1
6119
// // Created by Mateusz Karwat on 22/05/2017. // Copyright © 2017 Mateusz Karwat. All rights reserved. // import AppKit final class MainFlowController { private let mainWindowController = Storyboard.Main.instantiate(MainWindowController.self) private var requestedSpecificSubtitleProvider: SupportedSubtitleProvider? // MARK: - Public Methods /// Brings application to front. /// If none window is open, it shows main window. func showApplicationInterface() { if NSApp.mainWindow == nil && NSApp.keyWindow == nil { mainWindowController.showWindow(self) } NSApp.activate(ignoringOtherApps: true) } /// Presents a modal window to choose video files to scan. func presentOpenPanel() { let panel = NSOpenPanel() panel.canChooseFiles = true panel.canChooseDirectories = true panel.allowsMultipleSelection = true panel.allowedFileTypes = ["public.movie"] if panel.runModal() == .OK { InputHandler.applicationDidReceiveURLs(panel.urls) } else { requestedSpecificSubtitleProvider = nil } } /// Presents selection view to choose video files to scan. func handleUnknownFiles(at urls: [URL]) { if Preferences[.showDownloadSelection] { presentCheckboxTableViewController(with: urls) } else { handleVideoFiles(at: urls) } } /// Immediately starts a download with progress view as a presenter. func handleVideoFiles(at videoURLs: [URL]) { if videoURLs.isNotEmpty { presentProgressWindow(withVideoURLs: videoURLs) } else { requestedSpecificSubtitleProvider = nil } } // MARK: - Private Methods private func presentCheckboxTableViewController(with urls: [URL]) { guard let mainViewController = mainWindowController.contentViewController as? MainViewController, mainWindowController.window?.attachedSheet == nil else { return } let elements: [CheckboxTableViewModel.Element] = urls.map { let fileInformation = FileInformation(url: $0) let image = fileInformation?.image let description = fileInformation?.name ?? $0.description return .init(value: $0, isSelected: true, image: image, description: description) } let viewModel = CheckboxTableViewModel(elements: elements) viewModel.showCellImage = true viewModel.description = "Download_Video_Selection_Description".localized viewModel.onApply = { [unowned self] selectedValues in self.handleVideoFiles(at: selectedValues.map { $0 as! URL }) } let viewController = Storyboard.Selection.instantiate(CheckboxTableViewController.self) viewController.viewModel = viewModel mainViewController.presentAsSheet(viewController) } private func presentProgressWindow(withVideoURLs videoURLs: [URL]) { guard let mainViewController = mainWindowController.contentViewController as? MainViewController else { requestedSpecificSubtitleProvider = nil return } if let attachedViewController = mainWindowController.window?.attachedSheet?.contentViewController, attachedViewController.isKind(of: ProgressViewController.self) { requestedSpecificSubtitleProvider = nil return } let napiEngine: NapiEngine if let requestedSpecificSubtitleProvider = requestedSpecificSubtitleProvider { napiEngine = NapiEngine(subtitleProviders: [requestedSpecificSubtitleProvider.instance]) } else { napiEngine = NapiEngine(subtitleProviders: Preferences[.providers]) } let progressViewModel = ProgressViewModel(engine: napiEngine, videoURLs: videoURLs) progressViewModel.delegate = self let progressViewController = Storyboard.Progress.instantiate(ProgressViewController.self) progressViewController.viewModel = progressViewModel mainViewController.presentAsSheet(progressViewController) } fileprivate func presentCompletionAlert() { guard let mainWindow = mainWindowController.window else { return } let downloadCompleteAlert = NSAlert() downloadCompleteAlert.alertStyle = .informational downloadCompleteAlert.messageText = "Download_Summary_Message".localized downloadCompleteAlert.informativeText = "Download_Summary_Informative".localized downloadCompleteAlert.beginSheetModal(for: mainWindow) { _ in if Preferences[.closeApplicationWhenFinished] { NSApp.terminate(nil) } } } } extension MainFlowController: ProgressViewModelDelegate { func progressViewModelDidFinish(_ progressViewModel: ProgressViewModel) { DispatchQueue.main.async { if let mainWindow = self.mainWindowController.window, let attachedSheet = mainWindow.attachedSheet { mainWindow.endSheet(attachedSheet) } if Preferences[.showDownloadSummary] { self.presentCompletionAlert() } else { if Preferences[.closeApplicationWhenFinished] { NSApp.terminate(nil) } } } } } extension MainFlowController: StatusBarItemControllerDelegate { func statusBarItemController( _ sbic: StatusBarItemController, didSelectDownloadSubtitlesUsing provider: SupportedSubtitleProvider ) { requestedSpecificSubtitleProvider = provider presentOpenPanel() } } fileprivate extension FileInformation { /// Returns an image of a file. var image: NSImage? { guard let resourceValues = try? (url as NSURL).resourceValues(forKeys: [URLResourceKey.effectiveIconKey]) else { return nil } return resourceValues[URLResourceKey.effectiveIconKey] as? NSImage } }
mit
faa9f3487abc9f7c068175a891e21c88
34.569767
120
0.668683
5.571949
false
false
false
false
Mioke/KMPhotoBrowser
KMPhotoBrowser/KMPhotoBrowserViewController.swift
1
13140
// // KMPhotoBrowserViewController.swift // KMPhotoBrowserDemo // // Created by Klein Mioke on 15/12/14. // Copyright © 2015年 KleinMioke. All rights reserved. // import UIKit @objc protocol KMPhotoBrowserDelegate { optional func photoBrowserVC(vc: KMPhotoBrowserViewController, deleteImageAtIndex index: Int) -> Void } class KMPhotoBrowserViewController: UIViewController { weak var delegate: protocol<KMPhotoBrowserDelegate>? var cacheOptions = SDWebImageOptions.CacheMemoryOnly var scrollView: UIScrollView! var images: Array<UIImage>? var imageURLs: [String]? var clickForBack: Bool = false var currentIndex: Int = 0 { didSet { if self.titleLabel != nil { if self.images != nil { self.titleLabel.text = "\(self.currentIndex + 1)/\(self.images!.count)" } else { self.titleLabel.text = "\(self.currentIndex + 1)/\(self.imageURLs!.count)" } } } } var topBar: UIView! var titleLabel: UILabel! var bottomBar: UIView! var isModified: Bool = false var callBack: ((images: [UIImage], isModified: Bool)->())? var rightNavigationItemOption: PBVCRightNaviItemOption? var rightNavigationItemOption_oc: NSDictionary? struct PBVCRightNaviItemOption { var icon: UIImage var text: NSAttributedString var action: UIViewController -> Void } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. assert(self.images != nil || self.imageURLs != nil, "PhotoBrowserVC必须传入UIImage数组") self.edgesForExtendedLayout = .All self.scrollView = { let view = UIScrollView(frame: CGRectMake(0, 0, self.view.width, self.view.height)) view.backgroundColor = UIColor.blackColor() view.pagingEnabled = true view.delegate = self self.view.addSubview(view) // let gesture = UITapGestureRecognizer(target: self, action: "handleClickAction") // view.addGestureRecognizer(gesture) return view }() self.topBar = { let bar = UIView(frame: CGRectMake(0, 0, UIScreen.mainScreen().bounds.size.width, 64)) bar.backgroundColor = UIColor.darkGrayColor().colorWithAlphaComponent(0.3) let backButton = UIButton(frame: CGRectMake(0, 20, 60, 44)) backButton.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 20) backButton.setImage(UIImage(named: "back"), forState: UIControlState.Normal) backButton.setImage(UIImage(named: "back_p"), forState: UIControlState.Highlighted) backButton.addTarget(self, action: "back", forControlEvents: UIControlEvents.TouchUpInside) bar.addSubview(backButton) let deleteButton = UIButton(frame: CGRectMake(UIScreen.mainScreen().bounds.size.width - 60, 20, 60, 44)) if let option = self.rightNavigationItemOption { deleteButton.setImage(option.icon, forState: UIControlState.Normal) deleteButton.setAttributedTitle(option.text, forState: UIControlState.Normal) } else { if let option = self.rightNavigationItemOption_oc { deleteButton.setImage(option["icon"] as? UIImage, forState: UIControlState.Normal) deleteButton.setAttributedTitle(option["text"] as? NSAttributedString, forState: UIControlState.Normal) } else { // deleteButton.setTitle("删除", forState: UIControlState.Normal) // deleteButton.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal) // deleteButton.titleLabel?.font = UIFont.systemFontOfSize(14) deleteButton.setImage(UIImage(named: "del"), forState: UIControlState.Normal) deleteButton.setImage(UIImage(named: "del_p"), forState: UIControlState.Highlighted) deleteButton.imageEdgeInsets = UIEdgeInsetsMake(0, 20, 0, 0) } } deleteButton.addTarget(self, action: "deletePicture", forControlEvents: UIControlEvents.TouchUpInside) bar.addSubview(deleteButton) self.view.addSubview(bar) self.titleLabel = { let label = UILabel(frame: CGRectMake((bar.width - 200) / 2, 20, 200, 44)) label.textColor = UIColor.whiteColor() label.textAlignment = .Center label.font = UIFont.systemFontOfSize(16) bar.addSubview(label) return label }() return bar }() self.currentIndex = Int(self.currentIndex) self.loadContent() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) if self.clickForBack { let tap = UITapGestureRecognizer(target: self, action: "back") self.scrollView?.addGestureRecognizer(tap) } } func loadContent() { for view in self.scrollView.subviews { view.removeFromSuperview() } var xPoint: CGFloat = 0 var tag = 100 if self.images != nil { for image in self.images! { let view = UIImageView(image: image) view.backgroundColor = UIColor.clearColor() view.contentMode = .ScaleAspectFit view.tag = tag view.frame = CGRectMake(0, 0, self.scrollView.width, self.scrollView.width * image.size.height / image.size.width) let container = UIScrollView(frame: CGRectMake(xPoint, 0, self.scrollView.width, self.scrollView.height)) container.backgroundColor = UIColor.clearColor() container.clipsToBounds = true container.maximumZoomScale = 2.0 // container.showsHorizontalScrollIndicator = false container.delegate = self container.tag = 100 + tag++ container.addSubview(view) view.center = CGRectGetCenter(container.bounds) self.scrollView.addSubview(container) xPoint += self.view.width } } else if self.imageURLs != nil { for urlString in self.imageURLs! { let view = UIImageView() weak var weakView = view var url: NSURL if urlString.isLocalPath() { url = NSURL(fileURLWithPath: urlString) } else { url = NSURL(string: urlString)! } view.sd_setImageWithURL(url, placeholderImage: UIImage(named: "share_photo_placeholder"), options: self.cacheOptions, completed: { (img: UIImage!, error: NSError!, cacheType: SDImageCacheType, url: NSURL!) -> Void in if img != nil { weakView?.frame = CGRectMake(0, 0, self.scrollView.width, self.scrollView.width * img.size.height / img.size.width) weakView?.center = CGRectGetCenter(self.view.bounds) } }) view.backgroundColor = UIColor.clearColor() view.contentMode = .ScaleAspectFit view.tag = tag let container = UIScrollView(frame: CGRectMake(xPoint, 0, self.scrollView.width, self.scrollView.height)) container.backgroundColor = UIColor.clearColor() container.clipsToBounds = true container.maximumZoomScale = 2.0 // container.showsHorizontalScrollIndicator = false container.delegate = self container.tag = 100 + tag++ container.addSubview(view) view.center = CGRectGetCenter(container.bounds) self.scrollView.addSubview(container) xPoint += self.view.width } } self.scrollView.contentSize = CGSizeMake(xPoint, 0) self.scrollView.setContentOffset(CGPointMake(self.view.width * CGFloat(self.currentIndex), 0), animated: true) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func handleClickAction() -> Void { } func deletePicture() { guard self.images != nil else { return } if let option = self.rightNavigationItemOption { option.action(self) } else { if let option = self.rightNavigationItemOption_oc { if let action = option["action"] as? UIViewController -> Void { action(self) } } else { if self.images!.count != 0 { let sheet = UIActionSheet(title: "要删除这张照片吗?", delegate: self, cancelButtonTitle: "取消", destructiveButtonTitle: "删除") sheet.actionSheetStyle = .BlackTranslucent sheet.showInView(self.view) } } } } func back() { if self.clickForBack { self.modalTransitionStyle = .CrossDissolve } self.callBack?(images: self.images!, isModified: self.isModified) self.dismissViewControllerAnimated(true, completion: nil) } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ } extension KMPhotoBrowserViewController: UIScrollViewDelegate { func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? { if scrollView != self.scrollView { return scrollView.viewWithTag(100 + self.currentIndex) } return nil } func scrollViewDidZoom(scrollView: UIScrollView) { if let view = scrollView.viewWithTag(100 + self.currentIndex) { var offsetX = (scrollView.bounds.size.width - scrollView.contentSize.width) * 0.5 offsetX = offsetX > 0 ? offsetX : 0 var offsetY = (scrollView.bounds.size.height - scrollView.contentSize.height) * 0.5 offsetY = offsetY > 0 ? offsetY : 0 view.center = CGPointMake(offsetX + scrollView.contentSize.width * 0.5, offsetY + scrollView.contentSize.height * 0.5) } } func scrollViewDidEndZooming(scrollView: UIScrollView, withView view: UIView?, atScale scale: CGFloat) { } func scrollViewWillEndDragging(scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) { if scrollView == self.scrollView { let targetX = targetContentOffset.memory.x let targetPage = Int(ceil(targetX / self.view.width)) if targetPage != self.currentIndex { if let container = self.scrollView.viewWithTag(200 + self.currentIndex) as? UIScrollView { container.setZoomScale(1, animated: true) } } self.currentIndex = targetPage } } } extension KMPhotoBrowserViewController: UIActionSheetDelegate { func actionSheet(actionSheet: UIActionSheet, clickedButtonAtIndex buttonIndex: Int) { if buttonIndex == actionSheet.destructiveButtonIndex { self.images!.removeAtIndex(self.currentIndex) self.isModified = true self.delegate?.photoBrowserVC?(self, deleteImageAtIndex: self.currentIndex) if self.images!.count <= self.currentIndex { self.currentIndex = self.images!.count - 1 } else { self.currentIndex = Int(self.currentIndex) } self.loadContent() } } }
mit
1b6264aa02be0bbd4f6b9b12e06b7715
36.42
232
0.559441
5.582694
false
false
false
false
psturmfels/ktp-ios-app
KTP/KTPPledgeMeetingsCell.swift
1
3120
// // KTPPledgeMeetingsCell.swift // KTP // // Created by Owen Yang on 2/15/15. // Copyright (c) 2015 Kappa Theta Pi. All rights reserved. // import Foundation import UIKit class KTPPledgeMeetingsCell : UITableViewCell { private var completedBackground : UIView = UIView(); private var meetingLabel : UILabel = UILabel(); // Meeting variable represented in the cell: var meeting : KTPPledgeMeeting? { didSet { loadLabelValues(); } } // Changes background depending on if the meeting has been completed or not: override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: .Default, reuseIdentifier: reuseIdentifier); contentView.addSubview(meetingLabel); contentView.addSubview(completedBackground); self.completedBackground.backgroundColor = UIColor(white: 1, alpha: 0.5); contentView.bringSubviewToFront(completedBackground); autoLayout(); } convenience required init(coder aDecoder: NSCoder) { self.init(style: .Default, reuseIdentifier: "Cell"); } // MARK: - Overridden setters/getters override func setEditing(editing: Bool, animated: Bool) { super.setEditing(editing, animated: animated); self.completedBackground.hidden = editing || !(meeting?.complete ?? false); } // MARK: - Loading subviews func loadLabelValues() { // Load name of pledge or active meetingLabel.text = KTPSUser.currentUserIsPledge() ? meeting!.active.firstName + " " + meeting!.active.lastName : meeting!.pledge.firstName + " " + meeting!.pledge.lastName; // Load some sort of boolean indicator for "have they met" accessoryType = meeting!.complete ? .Checkmark : .None; self.completedBackground.hidden = !(meeting!.complete); } private func autoLayout() { completedBackground.setTranslatesAutoresizingMaskIntoConstraints(false); meetingLabel.setTranslatesAutoresizingMaskIntoConstraints(false); let views = [ "meetingLabel" : meetingLabel, "completedBackground" : completedBackground ]; // Auto Layout for text and graying out: contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-\(separatorInset.left)-[meetingLabel]-0-|", options: NSLayoutFormatOptions.AlignAllCenterY, metrics: nil, views: views)); contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[meetingLabel]-0-|", options: NSLayoutFormatOptions(0), metrics: nil, views: views)); contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[completedBackground]-0-|", options:NSLayoutFormatOptions(0), metrics: nil, views: views)); contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[completedBackground]-0-|", options:NSLayoutFormatOptions(0), metrics: nil, views: views)); } }
mit
5f5f2b3ffedd882f1c2fab4e39b19e93
36.142857
208
0.667628
5.174129
false
false
false
false
gitdoapp/SoundCloudSwift
Pods/Mockingjay/Mockingjay/NSURLSessionConfiguration.swift
6
1727
// // NSURLSessionConfiguration.swift // Mockingjay // // Created by Kyle Fuller on 01/03/2015. // Copyright (c) 2015 Cocode. All rights reserved. // import Foundation var mockingjaySessionSwizzleToken: dispatch_once_t = 0 extension NSURLSessionConfiguration { /// Swizzles NSURLSessionConfiguration's default and ephermeral sessions to add Mockingjay public class func mockingjaySwizzleDefaultSessionConfiguration() { dispatch_once(&mockingjaySessionSwizzleToken) { let defaultSessionConfiguration = class_getClassMethod(self, "defaultSessionConfiguration") let mockingjayDefaultSessionConfiguration = class_getClassMethod(self, "mockingjayDefaultSessionConfiguration") method_exchangeImplementations(defaultSessionConfiguration, mockingjayDefaultSessionConfiguration) let ephemeralSessionConfiguration = class_getClassMethod(self, "ephemeralSessionConfiguration") let mockingjayEphemeralSessionConfiguration = class_getClassMethod(self, "mockingjayEphemeralSessionConfiguration") method_exchangeImplementations(ephemeralSessionConfiguration, mockingjayEphemeralSessionConfiguration) } } class func mockingjayDefaultSessionConfiguration() -> NSURLSessionConfiguration { let configuration = mockingjayDefaultSessionConfiguration() configuration.protocolClasses = [MockingjayProtocol.self] as [AnyClass] + configuration.protocolClasses! return configuration } class func mockingjayEphemeralSessionConfiguration() -> NSURLSessionConfiguration { let configuration = mockingjayEphemeralSessionConfiguration() configuration.protocolClasses = [MockingjayProtocol.self] as [AnyClass] + configuration.protocolClasses! return configuration } }
mit
e271538096d0120b5f405ea6e7efcc8b
44.447368
121
0.812391
6.21223
false
true
false
false
liuweicode/LinkimFoundation
Example/LinkimFoundation/Foundation/System/Network/NetworkClient.swift
1
4773
// // NetworkClient.swift // Pods // // Created by 刘伟 on 16/6/30. // // import UIKit import Alamofire typealias NetworkSuccessBlock = (message:NetworkMessage) -> Void typealias NetworkFailBlock = (message:NetworkMessage) -> Void enum NetworkRequestMethod : Int { case POST, GET } var clientNO:UInt = 1 class NetworkClient : NSObject { // 网络数据封装 lazy var message = NetworkMessage() // 回调者 private var target:NSObject // 超时时间 let networkTimeout:NSTimeInterval = 30 // 请求任务 var task:Request? // 当前任务标识 var clientId:NSNumber? // 回调 var successBlock:NetworkSuccessBlock? var failBlock:NetworkFailBlock? init(target obj:NSObject) { target = obj super.init() clientNO = clientNO + 1 clientId = NSNumber(unsignedInteger: clientNO) NetworkClientManager.sharedInstance.addClient(client: self, forClientId: clientId!) } func send(method method:NetworkRequestMethod, params:[String:AnyObject], url:String, successBlock:NetworkSuccessBlock, failBlock:NetworkFailBlock ) -> NSNumber? { self.message.request.url = url self.message.request.params = params self.message.request.method = method self.successBlock = successBlock self.failBlock = failBlock return self.send() } private func send() -> NSNumber? { switch self.message.request.method { case .POST: self.task = self.POST() case .GET: self.task = self.GET() } return self.clientId } private func POST() -> Request? { return Alamofire.request(.POST, self.message.request.url!, parameters:[:], encoding: Alamofire.ParameterEncoding.Custom({ (convertible, params) -> (NSMutableURLRequest, NSError?) in var data:NSData? do{ data = try NSJSONSerialization.dataWithJSONObject(self.message.request.params!, options: NSJSONWritingOptions.init(rawValue: 0)) }catch{ print("--------请求参数报错-------") } let mutableRequest = convertible.URLRequest.copy() as! NSMutableURLRequest mutableRequest.HTTPBody = data mutableRequest.addValue("abcdefg", forHTTPHeaderField: "id") return (mutableRequest, nil) }), headers: nil ).validate().response(completionHandler: {[weak self] (request, response, data, error) in // 设置请求头信息 self?.message.request.headers = request?.allHTTPHeaderFields // 设置响应信息 self?.message.response.data = data self?.message.response.headers = response?.allHeaderFields // 是否有错误 if let responseError = error{ self?.message.networkError = .httpError(responseError.code, responseError.description) self?.failure() }else{ self?.success() } NetworkClientManager.sharedInstance.removeClientWithId((self?.clientId!)!) }) } private func GET() -> Request? { return Alamofire.request(.GET, self.message.request.url!, parameters:self.message.request.params, encoding: Alamofire.ParameterEncoding.JSON, headers: nil ).validate().response(completionHandler: {[weak self] (request, response, data, error) in // 设置请求头信息 self?.message.request.headers = request?.allHTTPHeaderFields // 设置响应信息 self?.message.response.data = data self?.message.response.headers = response?.allHeaderFields // 是否有错误 if let responseError = error{ self?.message.networkError = .httpError(responseError.code, responseError.description) self?.failure() }else{ self?.success() } NetworkClientManager.sharedInstance.removeClientWithId((self?.clientId!)!) }) } private func success() { self.successBlock?(message:self.message) } private func failure() { self.failBlock?(message:self.message) } // 取消请求 func cancel() { self.task?.cancel() } // 获取调用者 func requestReceive() -> NSObject { return self.target } }
mit
d95e52b121b1d27cf9d133d5271f806c
30.623288
166
0.566385
5.107301
false
false
false
false
inderdhir/Gifmaster-ios
GifMaster/ViewController.swift
1
6351
// // ViewController.swift // GifMaster // // Created by Inder Dhir on 9/5/16. // Copyright © 2016 Inder Dhir. All rights reserved. // import UIKit import SDWebImage import RxSwift import RxCocoa import Alamofire extension UIViewController { func hideKeyboardWhenTappedAround() { let tap: UITapGestureRecognizer = UITapGestureRecognizer( target: self, action: #selector(UIViewController.dismissKeyboard)) view.addGestureRecognizer(tap) } func dismissKeyboard() { view.endEditing(true) } } extension UIImage { static func from(color: UIColor) -> UIImage? { let rect = CGRect(x: 0, y: 0, width: 1, height: 1) UIGraphicsBeginImageContext(rect.size) let context = UIGraphicsGetCurrentContext() context?.setFillColor(color.cgColor) context?.fill(rect) let img = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return img } } extension UITableView { func scrollToTop() { let topIndexPath = IndexPath.init(row: 0, section: 0) scrollToRow(at: topIndexPath, at: .top, animated: false) } } class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { @IBOutlet weak var searchForGifsTextField: UITextField! @IBOutlet weak var tableView: UITableView! private let cellReuseIdentifier = "GifItem" private let imagePlaceholder = UIImage.from(color: .lightGray) private let refreshControl: UIRefreshControl = UIRefreshControl() private let backgroundScheduler = ConcurrentDispatchQueueScheduler(qos: .background) private var giphyService: Service! private var searchQuery: String = "" private var gifItems: [GifItem] = [] private var disposeBag = DisposeBag() override func viewDidLoad() { super.viewDidLoad() giphyService = GiphyService() dismissKeyboard() initTableView() hideKeyboardWhenTappedAround() initSearchField() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: Table view data source func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return gifItems.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier, for: indexPath) as! GifTableViewCell cell.selectionStyle = .none let currentGifItem = gifItems[indexPath.row] cell.gifImageView.sd_setImage(with: URL.init(string: currentGifItem.url!), placeholderImage: imagePlaceholder, options: .retryFailed, completed: nil) return cell } // MARK: Private private func initTableView() { tableView.delegate = self tableView.dataSource = self setupPullDownRefresh() setupInfiniteScroll() } private func initSearchField() { searchForGifsTextField.text = "" searchForGifsTextField.clearButtonMode = .whileEditing searchForGifsTextField.rx.text .debounce(0.3, scheduler: MainScheduler.instance) .subscribe(onNext: { [unowned self] text in self.searchQuery = text ?? "" self.getFreshGifs() }).addDisposableTo(disposeBag) } private func setupPullDownRefresh() { refreshControl.tintColor = ColorUtils.mainUIColor() refreshControl.addTarget(self, action: #selector(getFreshGifs), for: .valueChanged) tableView.addSubview(refreshControl) } private func setupInfiniteScroll() { tableView.addInfiniteScroll { [weak self] (tableView) -> Void in self?.getGifs() tableView.finishInfiniteScroll() } tableView.infiniteScrollTriggerOffset = 500 } func getFreshGifs() { getGifs(true) } // Get Gifs either based on user text or just trending private func getGifs(_ loadFreshGifs: Bool) { if searchQuery.isEmpty { giphyService.getTrendingGifs(gifItems.count) .subscribeOn(backgroundScheduler) .observeOn(MainScheduler.instance) .subscribe(onNext: { [weak self] newGifItems in self?.addItemsToTable(newGifItems, loadFreshGifs: loadFreshGifs) self?.refreshControl.endRefreshing() }, onError: { _ in // TODO: Show error screen }, onCompleted: { }, onDisposed: { }).disposed(by: disposeBag) } else { giphyService.searchForGifs(searchQuery, offset: gifItems.count) .subscribeOn(backgroundScheduler) .observeOn(MainScheduler.instance) .subscribe(onNext: { [weak self] newGifItems in self?.addItemsToTable(newGifItems, loadFreshGifs: loadFreshGifs) self?.refreshControl.endRefreshing() if loadFreshGifs { self?.tableView.scrollToTop() } }, onError: { _ in }, onCompleted: { }, onDisposed: { }).disposed(by: disposeBag) } } private func getGifs() { getGifs(false) } private func addItemsToTable(_ newGifItems: [GifItem], loadFreshGifs: Bool) { if loadFreshGifs { gifItems.removeAll() } var startingRowIndex = gifItems.count gifItems.append(contentsOf: newGifItems) if loadFreshGifs { tableView.reloadData() } else { var indexPaths = [IndexPath]() while startingRowIndex < gifItems.count { indexPaths.append(IndexPath.init(row: startingRowIndex, section: 0)) startingRowIndex = startingRowIndex + 1 } tableView.beginUpdates() tableView.insertRows(at: indexPaths, with: .none) tableView.endUpdates() } } }
mit
3aab368d06f1f91ac02c4aead67916c6
32.246073
100
0.612756
5.183673
false
false
false
false
iosdevzone/IDZSwiftCommonCrypto
IDZSwiftCommonCrypto/Random.swift
1
2315
// // Random.swift // SwiftCommonCrypto // // Created by idz on 9/19/14. // Copyright (c) 2014 iOS Developer Zone. All rights reserved. // // https://opensource.apple.com/source/CommonCrypto/CommonCrypto-60061/lib/CommonRandom.c import Foundation import CommonCrypto /// An alias for `Status` public typealias RNGStatus = Status /// /// Generates buffers of random bytes. /// open class Random { /** Wraps native CCRandomeGenerateBytes call. :note: CCRNGStatus is typealiased to CCStatus but this routine can only return kCCSuccess or kCCRNGFailure - parameter bytes: a pointer to the buffer that will receive the bytes - return: .Success or .RNGFailure as appropriate. */ open class func generateBytes(bytes: UnsafeMutableRawPointer, byteCount: Int ) -> RNGStatus { let statusCode = CCRandomGenerateBytes(bytes, byteCount) guard let status = Status(rawValue: statusCode) else { fatalError("CCRandomGenerateBytes returned unexpected status code: \(statusCode)") } return status } /** Generates an array of random bytes. - parameter bytesCount: number of random bytes to generate - return: an array of random bytes - throws: an `RNGStatus` on failure */ open class func generateBytes(byteCount: Int ) throws -> [UInt8] { guard byteCount > 0 else { throw RNGStatus.paramError } var bytes : [UInt8] = Array(repeating: UInt8(0), count: byteCount) let status = generateBytes(bytes: &bytes, byteCount: byteCount) guard status == .success else { throw status } return bytes } /** A version of generateBytes that always throws an error. Use it to test that code handles this. - parameter bytesCount: number of random bytes to generate - return: an array of random bytes */ open class func generateBytesThrow(byteCount: Int ) throws -> [UInt8] { if(byteCount <= 0) { fatalError("generateBytes: byteCount must be positve and non-zero") } var bytes : [UInt8] = Array(repeating: UInt8(0), count: byteCount) let status = generateBytes(bytes: &bytes, byteCount: byteCount) throw status //return bytes } }
mit
f379290d194fc5df34bc63a52fcfcce3
29.866667
110
0.6527
4.426386
false
false
false
false
FrancisBaileyH/Garden-Wall
Garden Wall/CustomRuleFactory.swift
1
3340
// // CustomRuleFactory.swift // Garden Wall // // Created by Francis Bailey on 2015-12-07. // Copyright © 2015 Francis Bailey. All rights reserved. // import Foundation class CustomRuleFactory { struct fields { static let type = "type" static let loadType = "loadType" static let selector = "selector" static let ifDomain = "ifDomain" static let urlFilter = "urlFilter" static let resourceType = "resourceType" static let urlCaseSensitive = "urlCaseSensitive" } /* * Produce a content blocker rule from an NSDictionary of AnyObject: AnyObject */ static func build(values: NSDictionary) -> ContentBlockerRule { var trigger = ContentBlockerRuleTrigger() var action = ContentBlockerRuleAction() for (key, field) in values { switch (key as! String) { case fields.urlFilter: trigger.urlFilter = field as? String break case fields.urlCaseSensitive: trigger.urlFilterIsCaseSensitive = field as? Bool break case fields.loadType: let transformer = FormEnumValueTransform<ContentBlockerRuleTriggerLoadType, String>() if let values = field as? [String] { trigger.loadType = transformer.transformFromFormValue(values) } break case fields.resourceType: let transformer = FormEnumValueTransform<ContentBlockerRuleTriggerResourceType, String>() if let values = field as? [String] { trigger.resourceType = transformer.transformFromFormValue(values) } break case fields.type: if let type = field as? [String] { if let rawValue = type.first { action.type = ContentBlockerRuleActionType(rawValue: rawValue) } } break case fields.selector: action.selector = field as? String break case fields.ifDomain: if let domains = field as? String { var values: [String] = [String]() for domain in domains.componentsSeparatedByString("\n") { values.append(domain) } if values.count > 0 { trigger.ifDomain = values } } break default: break } } return ContentBlockerRule(trigger: trigger, action: action) } }
mit
7cad4afbb93742197d55cfb23de1b17a
31.115385
109
0.436059
6.598814
false
false
false
false
nhatminh12369/LineChart
LineChart/ViewController.swift
1
1576
// // ViewController.swift // LineChart // // Created by Nguyen Vu Nhat Minh on 25/8/17. // Copyright © 2017 Nguyen Vu Nhat Minh. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var lineChart: LineChart! @IBOutlet weak var curvedlineChart: LineChart! override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = #colorLiteral(red: 0, green: 0.3529411765, blue: 0.6156862745, alpha: 1) // Sample dataset // let dataEntries = [PointEntry(value: 0, title: ""), PointEntry(value: 100, title: ""), PointEntry(value: 100, title: ""), PointEntry(value: 100, title: ""), PointEntry(value: 20, title: ""), PointEntry(value: 30, title: ""), PointEntry(value: 120, title: "")] let dataEntries = generateRandomEntries() lineChart.dataEntries = dataEntries lineChart.isCurved = false curvedlineChart.dataEntries = dataEntries curvedlineChart.isCurved = true } private func generateRandomEntries() -> [PointEntry] { var result: [PointEntry] = [] for i in 0..<100 { let value = Int(arc4random() % 500) let formatter = DateFormatter() formatter.dateFormat = "d MMM" var date = Date() date.addTimeInterval(TimeInterval(24*60*60*i)) result.append(PointEntry(value: value, label: formatter.string(from: date))) } return result } }
mit
bec6c4f053241fcf1befd83846f2c5aa
31.142857
269
0.59619
4.387187
false
false
false
false
hollance/swift-algorithm-club
AVL Tree/AVLTree.swift
3
12567
// The MIT License (MIT) // Copyright (c) 2016 Mike Taghavi (mitghi[at]me.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. public class TreeNode<Key: Comparable, Payload> { public typealias Node = TreeNode<Key, Payload> var payload: Payload? // Value held by the node fileprivate var key: Key // Node's name internal var leftChild: Node? internal var rightChild: Node? fileprivate var height: Int weak fileprivate var parent: Node? public init(key: Key, payload: Payload?, leftChild: Node?, rightChild: Node?, parent: Node?, height: Int) { self.key = key self.payload = payload self.leftChild = leftChild self.rightChild = rightChild self.parent = parent self.height = height self.leftChild?.parent = self self.rightChild?.parent = self } public convenience init(key: Key, payload: Payload?) { self.init(key: key, payload: payload, leftChild: nil, rightChild: nil, parent: nil, height: 1) } public convenience init(key: Key) { self.init(key: key, payload: nil) } var isRoot: Bool { return parent == nil } var isLeaf: Bool { return rightChild == nil && leftChild == nil } var isLeftChild: Bool { return parent?.leftChild === self } var isRightChild: Bool { return parent?.rightChild === self } var hasLeftChild: Bool { return leftChild != nil } var hasRightChild: Bool { return rightChild != nil } var hasAnyChild: Bool { return leftChild != nil || rightChild != nil } var hasBothChildren: Bool { return leftChild != nil && rightChild != nil } } // MARK: - The AVL tree open class AVLTree<Key: Comparable, Payload> { public typealias Node = TreeNode<Key, Payload> fileprivate(set) var root: Node? fileprivate(set) var size = 0 public init() { } } // MARK: - Searching extension TreeNode { public func minimum() -> TreeNode? { return leftChild?.minimum() ?? self } public func maximum() -> TreeNode? { return rightChild?.maximum() ?? self } } extension AVLTree { subscript(key: Key) -> Payload? { get { return search(input: key) } set { insert(key: key, payload: newValue) } } public func search(input: Key) -> Payload? { return search(key: input, node: root)?.payload } fileprivate func search(key: Key, node: Node?) -> Node? { if let node = node { if key == node.key { return node } else if key < node.key { return search(key: key, node: node.leftChild) } else { return search(key: key, node: node.rightChild) } } return nil } } // MARK: - Inserting new items extension AVLTree { public func insert(key: Key, payload: Payload? = nil) { if let root = root { insert(input: key, payload: payload, node: root) } else { root = Node(key: key, payload: payload) } size += 1 } private func insert(input: Key, payload: Payload?, node: Node) { if input < node.key { if let child = node.leftChild { insert(input: input, payload: payload, node: child) } else { let child = Node(key: input, payload: payload, leftChild: nil, rightChild: nil, parent: node, height: 1) node.leftChild = child balance(node: child) } } else if input != node.key { if let child = node.rightChild { insert(input: input, payload: payload, node: child) } else { let child = Node(key: input, payload: payload, leftChild: nil, rightChild: nil, parent: node, height: 1) node.rightChild = child balance(node: child) } } } } // MARK: - Balancing tree extension AVLTree { fileprivate func updateHeightUpwards(node: Node?) { if let node = node { let lHeight = node.leftChild?.height ?? 0 let rHeight = node.rightChild?.height ?? 0 node.height = max(lHeight, rHeight) + 1 updateHeightUpwards(node: node.parent) } } fileprivate func lrDifference(node: Node?) -> Int { let lHeight = node?.leftChild?.height ?? 0 let rHeight = node?.rightChild?.height ?? 0 return lHeight - rHeight } fileprivate func balance(node: Node?) { guard let node = node else { return } updateHeightUpwards(node: node.leftChild) updateHeightUpwards(node: node.rightChild) var nodes = [Node?](repeating: nil, count: 3) var subtrees = [Node?](repeating: nil, count: 4) let nodeParent = node.parent let lrFactor = lrDifference(node: node) if lrFactor > 1 { // left-left or left-right if lrDifference(node: node.leftChild) > 0 { // left-left nodes[0] = node nodes[2] = node.leftChild nodes[1] = nodes[2]?.leftChild subtrees[0] = nodes[1]?.leftChild subtrees[1] = nodes[1]?.rightChild subtrees[2] = nodes[2]?.rightChild subtrees[3] = nodes[0]?.rightChild } else { // left-right nodes[0] = node nodes[1] = node.leftChild nodes[2] = nodes[1]?.rightChild subtrees[0] = nodes[1]?.leftChild subtrees[1] = nodes[2]?.leftChild subtrees[2] = nodes[2]?.rightChild subtrees[3] = nodes[0]?.rightChild } } else if lrFactor < -1 { // right-left or right-right if lrDifference(node: node.rightChild) < 0 { // right-right nodes[1] = node nodes[2] = node.rightChild nodes[0] = nodes[2]?.rightChild subtrees[0] = nodes[1]?.leftChild subtrees[1] = nodes[2]?.leftChild subtrees[2] = nodes[0]?.leftChild subtrees[3] = nodes[0]?.rightChild } else { // right-left nodes[1] = node nodes[0] = node.rightChild nodes[2] = nodes[0]?.leftChild subtrees[0] = nodes[1]?.leftChild subtrees[1] = nodes[2]?.leftChild subtrees[2] = nodes[2]?.rightChild subtrees[3] = nodes[0]?.rightChild } } else { // Don't need to balance 'node', go for parent balance(node: node.parent) return } // nodes[2] is always the head if node.isRoot { root = nodes[2] root?.parent = nil } else if node.isLeftChild { nodeParent?.leftChild = nodes[2] nodes[2]?.parent = nodeParent } else if node.isRightChild { nodeParent?.rightChild = nodes[2] nodes[2]?.parent = nodeParent } nodes[2]?.leftChild = nodes[1] nodes[1]?.parent = nodes[2] nodes[2]?.rightChild = nodes[0] nodes[0]?.parent = nodes[2] nodes[1]?.leftChild = subtrees[0] subtrees[0]?.parent = nodes[1] nodes[1]?.rightChild = subtrees[1] subtrees[1]?.parent = nodes[1] nodes[0]?.leftChild = subtrees[2] subtrees[2]?.parent = nodes[0] nodes[0]?.rightChild = subtrees[3] subtrees[3]?.parent = nodes[0] updateHeightUpwards(node: nodes[1]) // Update height from left updateHeightUpwards(node: nodes[0]) // Update height from right balance(node: nodes[2]?.parent) } } // MARK: - Displaying tree extension AVLTree { fileprivate func display(node: Node?, level: Int) { if let node = node { display(node: node.rightChild, level: level + 1) print("") if node.isRoot { print("Root -> ", terminator: "") } for _ in 0..<level { print(" ", terminator: "") } print("(\(node.key):\(node.height))", terminator: "") display(node: node.leftChild, level: level + 1) } } public func display(node: Node) { display(node: node, level: 0) print("") } public func inorder(node: Node?) -> String { var output = "" if let node = node { output = "\(inorder(node: node.leftChild)) \(print("\(node.key) ")) \(inorder(node: node.rightChild))" } return output } public func preorder(node: Node?) -> String { var output = "" if let node = node { output = "\(preorder(node: node.leftChild)) \(print("\(node.key) ")) \(preorder(node: node.rightChild))" } return output } public func postorder(node: Node?) -> String { var output = "" if let node = node { output = "\(postorder(node: node.leftChild)) \(print("\(node.key) ")) \(postorder(node: node.rightChild))" } return output } } // MARK: - Delete node extension AVLTree { public func delete(key: Key) { if size == 1 { root = nil size -= 1 } else if let node = search(key: key, node: root) { delete(node: node) size -= 1 } } private func delete(node: Node) { if node.isLeaf { // Just remove and balance up if let parent = node.parent { guard node.isLeftChild || node.isRightChild else { // just in case fatalError("Error: tree is invalid.") } if node.isLeftChild { parent.leftChild = nil } else if node.isRightChild { parent.rightChild = nil } balance(node: parent) } else { // at root root = nil } } else { // Handle stem cases if let replacement = node.leftChild?.maximum(), replacement !== node { node.key = replacement.key node.payload = replacement.payload delete(node: replacement) } else if let replacement = node.rightChild?.minimum(), replacement !== node { node.key = replacement.key node.payload = replacement.payload delete(node: replacement) } } } } // MARK: - Advanced Stuff extension AVLTree { public func doInOrder(node: Node?, _ completion: (Node) -> Void) { if let node = node { doInOrder(node: node.leftChild) { lnode in completion(lnode) } completion(node) doInOrder(node: node.rightChild) { rnode in completion(rnode) } } } public func doInPreOrder(node: Node?, _ completion: (Node) -> Void) { if let node = node { completion(node) doInPreOrder(node: node.leftChild) { lnode in completion(lnode) } doInPreOrder(node: node.rightChild) { rnode in completion(rnode) } } } public func doInPostOrder(node: Node?, _ completion: (Node) -> Void) { if let node = node { doInPostOrder(node: node.leftChild) { lnode in completion(lnode) } doInPostOrder(node: node.rightChild) { rnode in completion(rnode) } completion(node) } } } // MARK: - Debugging extension TreeNode: CustomDebugStringConvertible { public var debugDescription: String { var s = "key: \(key), payload: \(payload), height: \(height)" if let parent = parent { s += ", parent: \(parent.key)" } if let left = leftChild { s += ", left = [" + left.debugDescription + "]" } if let right = rightChild { s += ", right = [" + right.debugDescription + "]" } return s } } extension AVLTree: CustomDebugStringConvertible { public var debugDescription: String { return root?.debugDescription ?? "[]" } } extension TreeNode: CustomStringConvertible { public var description: String { var s = "" if let left = leftChild { s += "(\(left.description)) <- " } s += "\(key)" if let right = rightChild { s += " -> (\(right.description))" } return s } } extension AVLTree: CustomStringConvertible { public var description: String { return root?.description ?? "[]" } }
mit
0ebace6c9465e1108e0607c05efdd7fe
26.142549
112
0.601337
3.970616
false
false
false
false
MetamediaTechnology/longdo-map-demo-ios
Longdo Map Framework Demo/ViewController.swift
1
53132
// // ViewController.swift // Longdo Map Test // // Created by กมลภพ จารุจิตต์ on 3/12/2564 BE. // import UIKit import LongdoMapFramework import CoreLocation // TODO: key input, unbind protocol MenuDelegate { func selectLanguage() func setBaseLayer() func addLayer() func removeTrafficLayer() func removeLayer() func clearAllLayer() func addEventsAndCameras() func removeEventsAndCameras() func addWMSLayer() func addTMSLayer() func addWTMSLayer() func addURLMarker() func addHTMLMarker() func addRotateMarker() func removeMarker() func markerList() func markerCount() func clearAllOverlays() func addPopup() func addCustomPopup() func addHTMLPopup() func removePopup() func dropMarker() func startBounceMarker() func stopBounceMarker() func moveMarker() func followPathMarker() func addLocalTag() func addLongdoTag() func addTagWithOption() func addTagWithGeocode() func removeTag() func clearAllTag() func addLine() func removeLine() func addLineWithOption() func addDashLine() func addCurve() func addPolygon() func addCircle() func addDot() func addDonut() func addRectangle() func geometryLocation() func addBangkok() func addEastRegion() func addBangkokDistrict() func addMultipleSubdistrict() func addProvinceWithOption() func addSubdistrictByName() func addLongdoPlace() func removeGeometryObject() func getRoute() func autoReroute() func getRouteByCost() func getRouteByDistance() func getRouteWithoutTollway() func getRouteWithMotorcycle() func getRouteGuide() func clearRoute() func searchCentral() func searchInEnglish() func suggestCentral() func clearSearch() func getGeoCode() func locationEvent() func zoomEvent() func zoomRangeEvent() // func readyEvent() func resizeEvent() func clickEvent() func dragEvent() func dropEvent() func layerChangeEvent() func toolbarChangeEvent() func clearMeasureEvent() func overlayClickEvent() func overlayChangeEvent() func overlaySelectEvent() func overlayLoadEvent() func overlayMoveEvent() func overlayDropEvent() func setCustomLocation() func setGeoLocation() func getLocation() func setZoom() func zoomIn() func zoomOut() func setZoomRange() func getZoomRange() func setBound() func getBound() func toggleDPad() func toggleZoombar() // func toggleToolbar() func toggleLayerSelector() // func toggleCrosshair() func toggleScale() func toggleTouchAndDrag() // func toggleTouch() func toggleDrag() // func toggleInertia() func addButtonMenu() // func addDropdownMenu() // func addTagPanel() // func addTagPanelWithOption() func addCustomMenu() func removeMenu() func getOverlayType() func getDistance() func getContain() func nearPOI() // func locationBound() } class ViewController: UIViewController, MenuDelegate, CLLocationManagerDelegate { @IBOutlet weak var map: LongdoMap! @IBOutlet weak var displayTextField: UITextField! let locationManager = CLLocationManager() let loc = CLLocationCoordinate2D(latitude: 13.7, longitude: 100.5) var home: LongdoMap.LDObject? var marker: LongdoMap.LDObject? var layer: LongdoMap.LDObject? var popup: LongdoMap.LDObject? var geom: LongdoMap.LDObject? var object: LongdoMap.LDObject? var menu: LongdoMap.LDObject? var searchPoi: [LongdoMap.LDObject] = [] var moveTimer: Timer? var followPathTimer: Timer? var guideTimer: Timer? var currentMethod: String? override func viewDidLoad() { super.viewDidLoad() #warning("Please insert your Longdo Map API key.") map.apiKey = "***REMOVED***" map.options.layer = map.ldstatic("Layers", with: "NORMAL") map.options.location = CLLocationCoordinate2D(latitude: 15, longitude: 102) map.options.zoomRange = 7...18 map.options.zoom = 10 readyEvent() map.render() } func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { if currentMethod == "location" { let _ = self.map.call(method: "location", args: [ locations[0].coordinate ]) } locationManager.stopUpdatingLocation() } func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) { print(error) } @IBAction func selectMenu() { performSegue(withIdentifier: "menu", sender: nil) } @IBAction func clearAll() { let _ = map.call(method: "Layers.setBase", args: [map.ldstatic("Layers", with: "NORMAL")]) let _ = map.call(method: "language", args: [LongdoLocale.Thai]) displayTextField.isHidden = true clearAllLayer() clearAllOverlays() clearAllTag() removeEventsAndCameras() removeGeometryObject() clearRoute() clearSearch() removeMenu() } func alert(message: String, placeholder: String?, completionHandler: ((String) -> Void)?) { let alert = UIAlertController( title: NSLocalizedString("Longdo Map", comment: ""), message: message, preferredStyle: .alert ) alert.addAction(UIAlertAction( title: NSLocalizedString("OK", comment: ""), style: .default ) { action -> Void in if let c = completionHandler { let firstTextField = alert.textFields!.first c(firstTextField?.text ?? "") } }) if let p = placeholder { alert.addTextField { (textField : UITextField!) -> Void in textField.placeholder = p } } present(alert, animated: true, completion: nil) } // MARK: - Map Layers func selectLanguage() { let _ = map.call(method: "language", args: [LongdoLocale.English]) } func setBaseLayer() { let _ = map.call(method: "Layers.setBase", args: [map.ldstatic("Layers", with: "GRAY")]) } func addLayer() { let _ = map.call(method: "Layers.add", args: [map.ldstatic("Layers", with: "TRAFFIC")]) } func removeTrafficLayer() { let _ = map.call(method: "Layers.remove", args: [map.ldstatic("Layers", with: "TRAFFIC")]) } func clearAllLayer() { let _ = map.call(method: "Layers.clear", args: nil) } func addEventsAndCameras() { let _ = map.call(method: "Overlays.load", args: [map.ldstatic("Overlays", with: "events")]) let _ = map.call(method: "Overlays.load", args: [map.ldstatic("Overlays", with: "cameras")]) } func removeEventsAndCameras() { let _ = map.call(method: "Overlays.unload", args: [map.ldstatic("Overlays", with: "events")]) let _ = map.call(method: "Overlays.unload", args: [map.ldstatic("Overlays", with: "cameras")]) } func addWMSLayer() { layer = map.ldobject("Layer", with: [ "roadnet2:Road_FGDS", [ "type": map.ldstatic("LayerType", with: "WMS"), "url": "https://apix.longdo.com/vector/test-tile.php", "zoomRange": 1...9, "refresh": 180, "opacity": 0.5, "weight": 10, "bound": [ "minLon": 100, "minLat": 10, "maxLon": 105, "maxLat": 20 ] ] ]) let _ = map.call(method: "Layers.add", args: [layer!]) } func addTMSLayer() { layer = map.ldobject("Layer", with: [ "roadnet2:Road_FGDS@EPSG:900913@png", [ "type": map.ldstatic("LayerType", with: "TMS"), "url": "https://apix.longdo.com/vector/test-tile.php?tms=", "zoomOffset": 0 ] ]) let _ = map.call(method: "Layers.add", args: [layer!]) } func addWTMSLayer() { layer = map.ldobject("Layer", with: [ "roadnet2:Road_FGDS", [ "type": map.ldstatic("LayerType", with: "WMTS"), "url": "https://apix.longdo.com/vector/test-tile.php", "srs": "EPSG:900913", "tileMatrix": map.ldfunction("z => 'EPSG:900913:' + z") ] ]) let _ = map.call(method: "Layers.add", args: [layer!]) } func removeLayer() { if let l = layer { let _ = map.call(method: "Layers.remove", args: [l]) } } // MARK: - Marker func addURLMarker() { DispatchQueue.main.async { self.marker = self.map.ldobject("Marker", with: [ CLLocationCoordinate2D(latitude: 12.8, longitude: 101.2), [ "title": "Marker", "icon": [ "url": "https://map.longdo.com/mmmap/images/pin_mark.png", "offset": [ "x": 12, "y": 45 ] ], "detail": "Drag me", "visibleRange": 7...9, "draggable": true, "weight": self.map.ldstatic("OverlayWeight", with: "Top") ] ]) let _ = self.map.call(method: "Overlays.add", args: [self.marker!]) } } func addHTMLMarker() { marker = map.ldobject("Marker", with: [ CLLocationCoordinate2D(latitude: 14.25, longitude: 99.35), [ "title": "Custom Marker", "icon": [ "html": "<div style=\"font-size: 36px; border: 1px solid #000;\">♨</div>", "offset": [ "x": 0, "y": 0 ] ], "popup": [ "html": "<div style=\"font-size: 24px; background: #eef;\">Onsen</div>" ] ] ]) let _ = map.call(method: "Overlays.add", args: [marker!]) } func addRotateMarker() { marker = map.ldobject("Marker", with: [ CLLocationCoordinate2D(latitude: 13.84, longitude: 100.41), [ "title": "Rotate Marker", "rotate": 90 ] ]) let _ = map.call(method: "Overlays.add", args: [marker!]) } func removeMarker() { if let m = marker { moveTimer?.invalidate() followPathTimer?.invalidate() let _ = map.call(method: "Overlays.remove", args: [m]) } } func markerList() { let result = map.call(method: "Overlays.list", args: nil) alert(message: "\(result ?? "no result")", placeholder: nil, completionHandler: nil) } func markerCount() { let result = map.call(method: "Overlays.size", args: nil) alert(message: "\(result ?? "no result")", placeholder: nil, completionHandler: nil) } func clearAllOverlays() { moveTimer?.invalidate() followPathTimer?.invalidate() let _ = map.call(method: "Overlays.clear", args: nil) } func addPopup() { popup = map.ldobject("Popup", with: [ CLLocationCoordinate2D(latitude: 14, longitude: 99), [ "title": "Popup", "detail": "Simple popup" ] ]) let _ = map.call(method: "Overlays.add", args: [popup!]) } func addCustomPopup() { popup = map.ldobject("Popup", with: [ CLLocationCoordinate2D(latitude: 14, longitude: 101), [ "title": "Popup", "detail": "Popup detail...", "loadDetail": map.ldfunction("e => setTimeout(() => e.innerHTML = 'Content changed', 1000)"), "size": [ "width": 200, "height": 200 ], "closable": false ] ]) let _ = map.call(method: "Overlays.add", args: [popup!]) } func addHTMLPopup() { popup = map.ldobject("Popup", with: [ CLLocationCoordinate2D(latitude: 14, longitude: 102), [ "html": "<div style=\"background: #eeeeff;\">popup</div>" ] ]) let _ = map.call(method: "Overlays.add", args: [popup!]) } func removePopup() { if let p = popup { let _ = map.call(method: "Overlays.remove", args: [p]) } } //Not Available func dropMarker() { marker = map.ldobject("Marker", with: [ CLLocationCoordinate2D(latitude: 14.525007, longitude: 100.643005) ]) let _ = map.call(method: "Overlays.drop", args: [marker!]) } func startBounceMarker() { marker = map.ldobject("Marker", with: [ CLLocationCoordinate2D(latitude: 14.525007, longitude: 101.643005) ]) let _ = map.call(method: "Overlays.add", args: [marker!]) let _ = map.call(method: "Overlays.bounce", args: [marker!]) } func stopBounceMarker() { let _ = map.call(method: "Overlays.bounce", args: nil) } func moveMarker() { marker = map.ldobject("Marker", with: [ CLLocationCoordinate2D(latitude: 15.525007, longitude: 100.643005) ]) let _ = map.call(method: "Overlays.add", args: [marker!]) moveOut() } @objc func moveOut() { let _ = map.objectCall(ldobject: marker!, method: "move", args: [ CLLocationCoordinate2D(latitude: 15, longitude: 102), true ]) moveTimer = Timer.scheduledTimer(timeInterval: 5.0, target: self, selector: #selector(self.moveBack), userInfo: nil, repeats: false) } @objc func moveBack() { let _ = map.objectCall(ldobject: marker!, method: "move", args: [ CLLocationCoordinate2D(latitude: 15.525007, longitude: 100.643005), true ]) moveTimer = Timer.scheduledTimer(timeInterval: 5.0, target: self, selector: #selector(self.moveOut), userInfo: nil, repeats: false) } //Not available func followPathMarker() { marker = map.ldobject("Marker", with: [ CLLocationCoordinate2D(latitude: 15.525007, longitude: 101.643005) ]) let _ = map.call(method: "Overlays.add", args: [marker!]) followPathTimer = Timer.scheduledTimer(timeInterval: 5.0, target: self, selector: #selector(self.followPath), userInfo: nil, repeats: true) } @objc func followPath() { let line = map.ldobject("Polyline", with: [ CLLocationCoordinate2D(latitude: 18, longitude: 102), CLLocationCoordinate2D(latitude: 17, longitude: 98), CLLocationCoordinate2D(latitude: 14, longitude: 99), CLLocationCoordinate2D(latitude: 15.525007, longitude: 101.643005) ]) let _ = map.call(method: "Overlays.pathAnimation", args: [ marker!, line ]) } // MARK: - Tag func addLocalTag() { let _ = map.call(method: "Tags.add", args: [ { (tile: [String: Any], zoom: Int) -> Void in if let bbox = tile["bbox"] as? [String: Double] { for _ in 1...3 { let m = self.map.ldobject("Marker", with: [ CLLocationCoordinate2D( latitude: Double.random(in: bbox["south"]!...bbox["north"]!), longitude: Double.random(in: bbox["west"]!...bbox["east"]!) ), [ "visibleRange": zoom...zoom ] ]) let _ = self.map.call(method: "Overlays.add", args: [m]) } } } ]) } func addLongdoTag() { let _ = map.call(method: "Tags.add", args: ["shopping"]) } func addTagWithOption() { let _ = map.call(method: "Tags.add", args: [ "hotel", [ "visibleRange": 10...20, "icon": [ "big" //URL icon in Tags.add is not available for now. ] ] ]) } func addTagWithGeocode() { let _ = map.call(method: "Tags.add", args: [ "shopping", [ "area": 10 ] ]) } func removeTag() { let _ = map.call(method: "Tags.remove", args: ["hotel"]) let _ = map.call(method: "Tags.remove", args: ["shopping"]) } func clearAllTag() { let _ = map.call(method: "Tags.clear", args: nil) } // MARK: - Geometry func addLine() { geom = map.ldobject("Polyline", with: [[ CLLocationCoordinate2D(latitude: 15, longitude: 100), CLLocationCoordinate2D(latitude: 10, longitude: 100) ]]) let _ = map.call(method: "Overlays.add", args: [geom!]) } func removeLine() { if let g = geom { let _ = map.call(method: "Overlays.remove", args: [g]) } } func addLineWithOption() { geom = map.ldobject("Polyline", with: [ [ CLLocationCoordinate2D(latitude: 14, longitude: 100), CLLocationCoordinate2D(latitude: 15, longitude: 101), CLLocationCoordinate2D(latitude: 14, longitude: 102) ], [ "title": "Polyline", "detail": "-", "label": "Polyline", "lineWidth": 4, "lineColor": UIColor.systemRed ] ]) let _ = map.call(method: "Overlays.add", args: [geom!]) } func addDashLine() { geom = map.ldobject("Polyline", with: [ [ CLLocationCoordinate2D(latitude: 14, longitude: 99), CLLocationCoordinate2D(latitude: 15, longitude: 100), CLLocationCoordinate2D(latitude: 14, longitude: 101) ], [ "title": "Dashline", "detail": "-", "label": "Dashline", "lineWidth": 4, "lineColor": UIColor.systemGreen, "lineStyle": map.ldstatic("LineStyle", with: "Dashed") ] ]) let _ = map.call(method: "Overlays.add", args: [geom!]) } //Not Available func addCurve() { geom = map.ldobject("Polycurve", with: [ [ CLLocationCoordinate2D(latitude: 13.5, longitude: 99), CLLocationCoordinate2D(latitude: 14.5, longitude: 100), CLLocationCoordinate2D(latitude: 12.5, longitude: 100), CLLocationCoordinate2D(latitude: 13.5, longitude: 101) ], [ "title": "Polycurve", "detail": "-", "label": "Polycurve", "lineWidth": 4, "lineColor": UIColor.systemBlue, "weight": map.ldstatic("OverlayWeight", with: "Top") ] ]) let _ = map.call(method: "Overlays.add", args: [geom!]) } func addPolygon() { geom = map.ldobject("Polygon", with: [ [ CLLocationCoordinate2D(latitude: 14, longitude: 99), CLLocationCoordinate2D(latitude: 13, longitude: 100), CLLocationCoordinate2D(latitude: 13, longitude: 102), CLLocationCoordinate2D(latitude: 14, longitude: 103) ], [ "title": "Polygon", "detail": "-", "label": "Polygon", "lineWidth": 2, "lineColor": UIColor.black, "fillColor": UIColor.init(red: 1, green: 0, blue: 0, alpha: 0.4), "visibleRange": 7...18, "editable": true, "weight": map.ldstatic("OverlayWeight", with: "Top") ] ]) let _ = map.call(method: "Overlays.add", args: [geom!]) } func addCircle() { geom = map.ldobject("Circle", with: [ CLLocationCoordinate2D(latitude: 15, longitude: 101), 1, [ "title": "Geom 3", "detail": "-", "lineWidth": 2, "lineColor": UIColor.red.withAlphaComponent(0.8), "fillColor": UIColor.red.withAlphaComponent(0.4) ] ]) let _ = map.call(method: "Overlays.add", args: [geom!]) } func addDot() { geom = map.ldobject("Dot", with: [ CLLocationCoordinate2D(latitude: 12.5, longitude: 100.5), [ "lineWidth": 20, "draggable": true ] ]) let _ = map.call(method: "Overlays.add", args: [geom!]) } func addDonut() { geom = map.ldobject("Polygon", with: [ [ CLLocationCoordinate2D(latitude: 15, longitude: 101), CLLocationCoordinate2D(latitude: 15, longitude: 105), CLLocationCoordinate2D(latitude: 12, longitude: 103), nil, CLLocationCoordinate2D(latitude: 14.9, longitude: 103), CLLocationCoordinate2D(latitude: 13.5, longitude: 102.1), CLLocationCoordinate2D(latitude: 13.5, longitude: 103.9) ], [ "label": 20, "clickable": true ] ]) let _ = map.call(method: "Overlays.add", args: [geom!]) } func addRectangle() { geom = map.ldobject("Rectangle", with: [ CLLocationCoordinate2D(latitude: 17, longitude: 97), [ "width": 2, "height": 1 ], [ "editable": true ] ]) let _ = map.call(method: "Overlays.add", args: [geom!]) } func geometryLocation() { if let g = geom { let location = map.objectCall(ldobject: g, method: "location", args: nil) alert(message: "\(location ?? "N/A")", placeholder: nil, completionHandler: nil) } } func addBangkok() { object = map.ldobject("Overlays.Object", with: [ 10, "IG" ]) let _ = map.call(method: "Overlays.load", args: [object!]) } // MARK: - Administration func addEastRegion() { object = map.ldobject("Overlays.Object", with: [ "2_", "IG" ]) let _ = map.call(method: "Overlays.load", args: [object!]) } func addBangkokDistrict() { object = map.ldobject("Overlays.Object", with: [ "10__", "IG" ]) let _ = map.call(method: "Overlays.load", args: [object!]) } func addMultipleSubdistrict() { object = map.ldobject("Overlays.Object", with: [ "610604;610607;610703;610704;610802", "IG", [ "combine": true, "simplify": 0.00005, "ignorefragment": false ] ]) let _ = map.call(method: "Overlays.load", args: [object!]) } func addProvinceWithOption() { object = map.ldobject("Overlays.Object", with: [ "12", "IG", [ "title": "นนทบุรี", "label": "นนทบุรี", "lineColor": UIColor.init(white: 0.5, alpha: 1), "fillColor": nil ] ]) let _ = map.call(method: "Overlays.load", args: [object!]) } func addSubdistrictByName() { object = map.ldobject("Overlays.Object", with: [ "นนทบุรี", "ADM" ]) let _ = map.call(method: "Overlays.load", args: [object!]) } func addLongdoPlace() { object = map.ldobject("Overlays.Object", with: [ "A10000001", "LONGDO" ]) let _ = map.call(method: "Overlays.load", args: [object!]) } func removeGeometryObject() { if let o = object { let _ = map.call(method: "Overlays.unload", args: [o]) } } // MARK: - Route func getRoute() { marker = map.ldobject("Marker", with: [ CLLocationCoordinate2D(latitude: 13.764953, longitude: 100.538316), [ "title": "Victory monument", "detail": "I'm here" ] ]) let _ = map.call(method: "Route.add", args: [marker!]) let _ = map.call(method: "Route.add", args: [ CLLocationCoordinate2D(latitude: 15, longitude: 100) ]) let _ = map.call(method: "Route.search", args: nil) } func autoReroute() { clearRoute() getRoute() let _ = map.call(method: "Route.auto", args: [true]) } func getRouteByCost() { clearRoute() let _ = map.call(method: "Route.mode", args: [map.ldstatic("RouteMode", with: "Cost")]) getRoute() } func getRouteByDistance() { clearRoute() let _ = map.call(method: "Route.mode", args: [map.ldstatic("RouteMode", with: "Distance")]) getRoute() } func getRouteWithoutTollway() { clearRoute() let _ = map.call(method: "Route.enableRoute", args: [ map.ldstatic("RouteType", with: "Tollway"), false ]) getRoute() } func getRouteWithMotorcycle() { clearRoute() let _ = map.call(method: "Route.enableRestrict", args: [ map.ldstatic("RouteRestrict", with: "Bike"), true ]) getRoute() } func getRouteGuide() { clearRoute() unbind() let _ = map.call(method: "Event.bind", args: [ "pathComplete", { (guide: Any?) -> Void in print(guide ?? "no data") } ]) let _ = map.call(method: "Event.bind", args: [ "guideComplete", { (guide: Any?) -> Void in if let g = guide as? [[String: Any]], g.count > 0, let turn = g[0]["guide"] as? [[String: Any?]], let data = g[0]["data"] as? [String: Any] { var str = ["ออกจาก จุดเริ่มต้น \(round(data["fdistance"] as? Double ?? 0) / 1000) กม."] let turnText = ["เลี้ยวซ้ายสู่", "เลี้ยวขวาสู่", "เบี่ยงซ้ายสู่", "เบี่ยงขวาสู่", "ไปตาม", "ตรงไปตาม", "เข้าสู่", "", "", "ถึง", "", "", "", "", ""] for i in turn { str.append("\(turnText[(i["turn"] as? LongdoTurn ?? .Unknown).rawValue]) \(i["name"] as? String ?? "") \(round(i["distance"] as? Double ?? 0) / 1000) กม.") } str.append("รวมระยะทาง \(round(data["distance"] as? Double ?? 0) / 1000) กม. เวลา \(Int(floor((data["interval"] as? Double ?? 0) / 3600))) ชม. \(Int(ceil(Double((data["interval"] as? Int ?? 0) % 3600) / 60))) น.") self.alert(message: "\(str.joined(separator: "\n"))", placeholder: nil, completionHandler: nil) } } ]) getRoute() } func clearRoute() { let _ = map.call(method: "Route.clear", args: nil) } // MARK: - Search func searchCentral() { let _ = map.call(method: "Search.search", args: [ "central", [ "area": 10, //Bangkok geocode "tag": "hotel", "span": "2000km", "limit": 10 ] ]) { (data: Any?) -> Void in if let result = data as? [String: Any?], let poi = result["data"] as? [[String: Any?]] { self.searchPoi = [] for i in poi { if let lat = i["lat"] as? Double, let lon = i["lon"] as? Double { let poiMarker = self.map.ldobject("Marker", with: [ CLLocationCoordinate2D(latitude: lat, longitude: lon), [ "title": i["name"], "detail": i["address"] ] ]) self.searchPoi.append(poiMarker) if let newPoi = self.searchPoi.last { let _ = self.map.call(method: "Overlays.add", args: [newPoi]) } } } } } } func searchInEnglish() { let _ = map.call(method: "Search.language", args: [LongdoLocale.English]) searchCentral() } func suggestCentral() { let _ = map.call(method: "Search.suggest", args: [ "central", [ "area": 10 //Bangkok geocode ] ]) { (data: Any?) -> Void in if let result = data as? [String: Any?], let poi = result["data"] as? [[String: Any?]] { var str: [String] = [] for i in poi { if let word = i["w"] as? String { str.append("- \(word)") } } self.alert(message: str.joined(separator: "\n"), placeholder: nil, completionHandler: nil) } } } func clearSearch() { for m in searchPoi { let _ = map.call(method: "Overlays.remove", args: [m]) } } // MARK: - Conversion func getGeoCode() { if let pos = map.call(method: "location", args: nil) { let _ = map.call(method: "Search.address", args: [pos]) { (data: Any?) -> Void in self.alert(message: "\(data ?? "no data")", placeholder: nil, completionHandler: nil) } } } // MARK: - Events func locationEvent() { displayTextField.isHidden = false unbind() let _ = map.call(method: "Event.bind", args: [ "location", { () -> Void in if let pos = self.map.call(method: "location", args: nil) { self.displayTextField.text = "\(pos)" } } ]) } func zoomEvent() { displayTextField.isHidden = false unbind() let _ = map.call(method: "Event.bind", args: [ "zoom", { () -> Void in if let zoom = self.map.call(method: "zoom", args: nil) { self.displayTextField.text = "\(zoom)" } } ]) } func zoomRangeEvent() { displayTextField.isHidden = false unbind() let _ = map.call(method: "Event.bind", args: [ "zoomRange", { () -> Void in if let zr = self.map.call(method: "zoomRange", args: nil) { self.displayTextField.text = "\(zr)" } } ]) let _ = map.call(method: "zoomRange", args: [1...10]) } func readyEvent() { //Call before map.render() map.options.onReady = { () -> Void in self.alert(message: "Map is ready.", placeholder: nil, completionHandler: nil) } } func resizeEvent() { displayTextField.isHidden = false unbind() let _ = self.map.call(method: "Event.bind", args: [ "resize", { () -> Void in if let bound = self.map.call(method: "bound", args: nil) { self.displayTextField.text = "\(bound)" } } ]) } func clickEvent() { unbind() let _ = self.map.call(method: "Event.bind", args: [ "click", { (result: Any?) -> Void in if let pos = result as? [String: Double] { DispatchQueue.main.async { self.marker = self.map.ldobject("Marker", with: [pos]) let _ = self.map.call(method: "Overlays.add", args: [self.marker!]) } } } ]) } func dragEvent() { displayTextField.isHidden = false unbind() let _ = self.map.call(method: "Event.bind", args: [ "drag", { (result: Any?) -> Void in self.displayTextField.text = "Drag event triggered." } ]) } func dropEvent() { displayTextField.isHidden = false unbind() let _ = self.map.call(method: "Event.bind", args: [ "drop", { (result: Any?) -> Void in self.displayTextField.text = "Drop event triggered." } ]) } func layerChangeEvent() { unbind() let _ = self.map.call(method: "Event.bind", args: [ "layerChange", { (result: Any?) -> Void in self.alert(message: "\(result ?? "no data")", placeholder: nil, completionHandler: nil) } ]) addLayer() } func toolbarChangeEvent() { //Not implemented now. } func clearMeasureEvent() { //Not implemented now. } func overlayClickEvent() { unbind() let _ = self.map.call(method: "Event.bind", args: [ "overlayClick", { (result: Any?) -> Void in self.alert(message: "\(result ?? "no data")", placeholder: nil, completionHandler: nil) } ]) addURLMarker() } func overlayChangeEvent() { unbind() let _ = self.map.call(method: "Event.bind", args: [ "overlayChange", { (result: Any?) -> Void in self.alert(message: "\(result ?? "no data")", placeholder: nil, completionHandler: nil) } ]) addURLMarker() } func overlaySelectEvent() { //Not implemented now. unbind() let _ = self.map.call(method: "Event.bind", args: [ "overlaySelect", { (result: Any?) -> Void in self.alert(message: "\(result ?? "no data")", placeholder: nil, completionHandler: nil) } ]) addURLMarker() } func overlayLoadEvent() { unbind() let _ = self.map.call(method: "Event.bind", args: [ "overlayLoad", { (result: Any?) -> Void in self.alert(message: "\(result ?? "no data")", placeholder: nil, completionHandler: nil) } ]) addBangkok() } func overlayMoveEvent() { //Not implemented now. unbind() let _ = self.map.call(method: "Event.bind", args: [ "overlayMove", { (result: Any?) -> Void in self.alert(message: "\(result ?? "no data")", placeholder: nil, completionHandler: nil) } ]) addURLMarker() } // FIXME: ?? func overlayDropEvent() { unbind() let _ = self.map.call(method: "Event.bind", args: [ "overlayDrop", { (result: Any?) -> Void in self.alert(message: "\(result ?? "no data")", placeholder: nil, completionHandler: nil) } ]) addURLMarker() } func unbind() { let event = ["pathComplete", "guideComplete", "location", "zoom", "zoomRange", "resize", "click", "drag", "drop", "layerChange", "overlayClick", "overlayChange", "overlaySelect", "overlayLoad", "overlayMove", "overlayDrop"] for i in event { let _ = self.map.call(method: "Event.unbind", args: [i]) } } // MARK: - User Interface func setCustomLocation() { let _ = self.map.call(method: "location", args: [ CLLocationCoordinate2D(latitude: 16, longitude: 100), true ]) } func setGeoLocation() { currentMethod = "location" locationManager.requestWhenInUseAuthorization() if CLLocationManager.locationServicesEnabled() { locationManager.delegate = self locationManager.startUpdatingLocation() } } func getLocation() { let location = map.call(method: "location", args: nil) alert(message: "\(location ?? "no data")", placeholder: nil, completionHandler: nil) } func setZoom() { let _ = map.call(method: "zoom", args: [14, true]) } func zoomIn() { let _ = map.call(method: "zoom", args: [true, true]) } func zoomOut() { let _ = map.call(method: "zoom", args: [false, true]) } func setZoomRange() { let _ = map.call(method: "zoomRange", args: [1...5]) } func getZoomRange() { let zoomRange = map.call(method: "zoomRange", args: nil) alert(message: "\(zoomRange ?? "no data")", placeholder: nil, completionHandler: nil) } func setBound() { let _ = map.call(method: "bound", args: [[ "minLat": 13, "maxLat": 14, "minLon": 100, "maxLon": 101 ]]) } func getBound() { let bound = map.call(method: "bound", args: nil) alert(message: "\(bound ?? "no data")", placeholder: nil, completionHandler: nil) } func toggleDPad() { let _ = map.call(method: "Ui.DPad.visible", args: [ !(map.call(method: "Ui.DPad.visible", args: nil) as? Bool ?? false) ]) } func toggleZoombar() { let _ = map.call(method: "Ui.Zoombar.visible", args: [ !(map.call(method: "Ui.Zoombar.visible", args: nil) as? Bool ?? false) ]) } //Not available func toggleToolbar() { let _ = map.call(method: "Ui.Toolbar.visible", args: [ !(map.call(method: "Ui.Toolbar.visible", args: nil) as? Bool ?? false) ]) } func toggleLayerSelector() { let _ = map.call(method: "Ui.LayerSelector.visible", args: [ !(map.call(method: "Ui.LayerSelector.visible", args: nil) as? Bool ?? false) ]) } //Not available func toggleCrosshair() { let _ = map.call(method: "Ui.Crosshair.visible", args: [ !(map.call(method: "Ui.Crosshair.visible", args: nil) as? Bool ?? false) ]) } func toggleScale() { let _ = map.call(method: "Ui.Scale.visible", args: [ !(map.call(method: "Ui.Scale.visible", args: nil) as? Bool ?? false) ]) } func toggleTouchAndDrag() { map.isUserInteractionEnabled = !map.isUserInteractionEnabled } //Not available func toggleTouch() { let _ = map.call(method: "Ui.Mouse.enableClick", args: [ !(map.call(method: "Ui.Mouse.enableClick", args: nil) as? Bool ?? false) ]) } func toggleDrag() { let _ = map.call(method: "Ui.Mouse.enableDrag", args: [ !(map.call(method: "Ui.Mouse.enableDrag", args: nil) as? Bool ?? false) ]) } //Not available func toggleInertia() { let _ = map.call(method: "Ui.Mouse.enableInertia", args: [ !(map.call(method: "Ui.Mouse.enableInertia", args: nil) as? Bool ?? false) ]) } func addButtonMenu() { menu = map.ldobject("MenuBar", with: [[ "button": [ [ "label": "first", "value": 1 ], [ "label": "second", "value": 2 ] ], "change": { (from: [String: Any?]?, to: [String: Any?]?) in let fromStr = from != nil ? (from!["value"] ?? "-") : "-" let toStr = to != nil ? (to!["value"] ?? "-") : "-" self.alert(message: "from: \(fromStr!) to: \(toStr!)", placeholder: nil, completionHandler: nil) } ]]) let _ = map.call(method: "Ui.add", args: [menu!]) } //Not available func addDropdownMenu() { menu = map.ldobject("MenuBar", with: [[ "dropdown": [ [ "label": "Group", "value": map.ldstatic("ButtonType", with: "Group") ], [ "label": "Normal" ], [ "label": "<div style=\"padding: 8px; text-align: center;\">custom<br/>HTML</div>", "value": map.ldstatic("ButtonType", with: "Custom") ] ], "dropdownLabel": "more", "change": { (from: [String: Any?]?, to: [String: Any?]?) in let fromStr = from != nil ? (from!["value"] ?? "-") : "-" let toStr = to != nil ? (to!["value"] ?? "-") : "-" self.alert(message: "from: \(fromStr!) to: \(toStr!)", placeholder: nil, completionHandler: nil) } ]]) let _ = map.call(method: "Ui.add", args: [menu!]) } //Not available func addTagPanel() { menu = map.ldobject("TagPanel", with: []) let _ = map.call(method: "Ui.add", args: [menu!]) } //Not available func addTagPanelWithOption() { menu = map.ldobject("TagPanel", with: [[ "tag": ["temple", "sizzler"] ]]) let _ = map.call(method: "Ui.add", args: [menu!]) } func addCustomMenu() { menu = map.ldobject("CustomControl", with: ["<button>go</button>"]) let _ = map.call(method: "Ui.add", args: [menu!]) } func removeMenu() { if let m = menu { let _ = map.call(method: "Ui.remove", args: [m]) } } // MARK: - Etc. func getOverlayType() { unbind() let _ = self.map.call(method: "Event.bind", args: [ "overlayClick", { (result: Any?) -> Void in if let overlay = result as? LongdoMap.LDObject { self.alert(message: "\(overlay.type)", placeholder: nil, completionHandler: nil) } } ]) DispatchQueue.main.async { self.marker = self.map.ldobject("Marker", with: [ CLLocationCoordinate2D(latitude: 12.8, longitude: 101.2) ]) let _ = self.map.call(method: "Overlays.add", args: [self.marker!]) } } func getDistance() { var markerCar1: LongdoMap.LDObject? var markerCar2: LongdoMap.LDObject? var geom1: LongdoMap.LDObject? unbind() let _ = self.map.call(method: "Event.bind", args: [ "overlayDrop", { (result: Any?) -> Void in let _ = self.map.call(method: "Overlays.remove", args: [geom1!]) geom1 = self.map.ldobject("Polyline", with: [ [ self.map.objectCall(ldobject: markerCar1!, method: "location", args: nil), self.map.objectCall(ldobject: markerCar2!, method: "location", args: nil) ], [ "lineColor": UIColor.blue.withAlphaComponent(0.6) ] ]) let _ = self.map.call(method: "Overlays.add", args: [geom1!]) if let distance = self.map.objectCall(ldobject: markerCar1!, method: "distance", args: [markerCar2!]) as? Double { self.alert(message: "ระยะกระจัด \(round(distance) / 1000.0) กิโลเมตร", placeholder: nil, completionHandler: nil) } } ]) DispatchQueue.main.async { markerCar1 = self.map.ldobject("Marker", with: [ CLLocationCoordinate2D(latitude: 13.686867, longitude: 100.426157), [ "draggable": true ] ]) markerCar2 = self.map.ldobject("Marker", with: [ CLLocationCoordinate2D(latitude: 13.712259, longitude: 100.457989), [ "draggable": true ] ]) geom1 = self.map.ldobject("Polyline", with: [ [ self.map.objectCall(ldobject: markerCar1!, method: "location", args: nil), self.map.objectCall(ldobject: markerCar2!, method: "location", args: nil) ], [ "lineColor": UIColor.blue.withAlphaComponent(0.6) ] ]) let _ = self.map.call(method: "Overlays.add", args: [markerCar1!]) let _ = self.map.call(method: "Overlays.add", args: [markerCar2!]) let _ = self.map.call(method: "Overlays.add", args: [geom1!]) if let distance = self.map.objectCall(ldobject: markerCar1!, method: "distance", args: [markerCar2!]) as? Double { self.alert(message: "ระยะกระจัด \(round(distance) / 1000.0) กิโลเมตร", placeholder: nil, completionHandler: nil) } } } func getContain() { var dropMarker: LongdoMap.LDObject? var geom1: LongdoMap.LDObject? var geom2: LongdoMap.LDObject? unbind() let _ = self.map.call(method: "Event.bind", args: [ "overlayDrop", { (result: Any?) -> Void in if let c = self.map.objectCall(ldobject: geom1!, method: "contains", args: [dropMarker!]) as? Bool, c { self.alert(message: "อยู่บนพื้นที่สีเหลือง", placeholder: nil, completionHandler: nil) } else if let c = self.map.objectCall(ldobject: geom2!, method: "contains", args: [dropMarker!]) as? Bool, c { self.alert(message: "อยู่บนพื้นที่สีแดง", placeholder: nil, completionHandler: nil) } else { self.alert(message: "ไม่อยู่บนพื้นที่สีใดเลย", placeholder: nil, completionHandler: nil) } } ]) DispatchQueue.main.async { dropMarker = self.map.ldobject("Marker", with: [ CLLocationCoordinate2D(latitude: 13.78, longitude: 100.43), [ "draggable": true, "weight": self.map.ldstatic("OverlayWeight", with: "Top") ] ]) geom1 = self.map.ldobject("Polygon", with: [ [ CLLocationCoordinate2D(latitude: 13.94, longitude: 100.2), CLLocationCoordinate2D(latitude: 13.94, longitude: 100.45), CLLocationCoordinate2D(latitude: 13.62, longitude: 100.45), CLLocationCoordinate2D(latitude: 13.62, longitude: 100.2) ], [ "title": "เหลือง", "lineWidth": 1, "lineColor": UIColor.black.withAlphaComponent(0.7), "fillColor": UIColor.init(red: 246 / 255.0, green: 210 / 255.0, blue: 88 / 255.0, alpha: 0.6), "label": "เหลือง" ] ]) geom2 = self.map.ldobject("Polygon", with: [ [ CLLocationCoordinate2D(latitude: 13.94, longitude: 100.7), CLLocationCoordinate2D(latitude: 13.94, longitude: 100.45), CLLocationCoordinate2D(latitude: 13.62, longitude: 100.45), CLLocationCoordinate2D(latitude: 13.62, longitude: 100.7) ], [ "title": "แดง", "lineWidth": 1, "lineColor": UIColor.black.withAlphaComponent(0.7), "fillColor": UIColor.init(red: 209 / 255.0, green: 47 / 255.0, blue: 47 / 255.0, alpha: 0.6), "label": "แดง" ] ]) let _ = self.map.call(method: "Overlays.add", args: [dropMarker!]) let _ = self.map.call(method: "Overlays.add", args: [geom1!]) let _ = self.map.call(method: "Overlays.add", args: [geom2!]) let _ = self.map.call(method: "bound", args: [[ "minLat": 13.57, "maxLat": 13.99, "minLon": 100.15, "maxLon": 100.75 ]]) } } func nearPOI() { if let loc = map.call(method: "location", args: nil) { let _ = map.call(method: "Search.nearPoi", args: [loc]) { (data: Any?) -> Void in if let result = data as? [String: Any?], let poi = result["data"] as? [[String: Any?]] { self.searchPoi = [] for i in poi { if let lat = i["lat"] as? Double, let lon = i["lon"] as? Double { let poiMarker = self.map.ldobject("Marker", with: [ CLLocationCoordinate2D(latitude: lat, longitude: lon), [ "title": i["name"], "detail": i["address"] ] ]) self.searchPoi.append(poiMarker) if let newPoi = self.searchPoi.last { let _ = self.map.call(method: "Overlays.add", args: [newPoi]) } } } self.locationBound() } } } } func locationBound() { var bound: [String: Double] = [ "minLat": 90, "minLon": 180, "maxLat": -90, "maxLon": -180 ] for poi in self.searchPoi { if let loc = self.map.objectCall(ldobject: poi, method: "location", args: nil) as? CLLocationCoordinate2D { if loc.latitude < bound["minLat"]! { bound["minLat"] = loc.latitude } if loc.latitude > bound["maxLat"]! { bound["maxLat"] = loc.latitude } if loc.longitude < bound["minLon"]! { bound["minLon"] = loc.longitude } if loc.longitude > bound["maxLon"]! { bound["maxLon"] = loc.longitude } } } let difLat = (bound["maxLat"]! - bound["minLat"]!) * 0.1 let difLon = (bound["maxLon"]! - bound["minLon"]!) * 0.1 bound["minLat"] = bound["minLat"]! - difLat bound["maxLat"] = bound["maxLat"]! + difLat bound["minLon"] = bound["minLon"]! - difLon bound["maxLon"] = bound["maxLon"]! + difLon let _ = self.map.call(method: "bound", args: [bound]) } //Not Available or use map.isUserInteractionEnabled instead. func lockMap() { let _ = map.call(method: "Ui.lockMap", args: nil) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "menu" { guard let vc = segue.destination as? MenuTableViewController else { return } vc.delegate = self } } }
apache-2.0
7fdbc81e74589a86f2b9e5ae30721b41
32.69763
233
0.48137
4.196745
false
false
false
false
byu-oit-appdev/ios-byuSuite
byuSuite/Apps/UniversityClassSchedule/controller/UniversityClassScheduleCoursesViewController.swift
1
2110
// // UniversityClassScheduleCoursesViewController.swift // byuSuite // // Created by Erik Brady on 5/2/18. // Copyright © 2018 Brigham Young University. All rights reserved. // class UniversityClassScheduleCoursesViewController: ByuSearchTableDataViewController { //MARK: Outlets @IBOutlet private weak var spinner: UIActivityIndicatorView! //MARK: Public Properties var yearTerm: YearTerm2! var teachingArea: RegTeachingArea! //MARK: Private Properties private var courses = [RegCourseRef]() override func viewDidLoad() { super.viewDidLoad() title = teachingArea.code loadCourses() } //MARK: Navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "showCourse", let vc = segue.destination as? UniversityClassScheduleCourseViewController, let courseRef: RegCourseRef = objectForSender(cellSender: sender) { vc.yearTerm = yearTerm vc.teachingArea = teachingArea vc.courseRef = courseRef } } //MARK: TableViewDataSource Methods override func sectionIndexTitles(for tableView: UITableView) -> [String]? { return nil } //MARK: Custom Methods private func loadCourses() { RegistrationClient2.getCourses(yearTermCode: yearTerm.code, teachingAreaCode: teachingArea.code) { (courses, error) in self.spinner.stopAnimating() if let courses = courses { self.courses = courses self.loadTableData() } else { super.displayAlert(error: error) } } } private func loadTableData() { var tempCourses = [Int: [Row]]() for course in courses { if let firstLetter = course.catalogNumber?.first, let firstNumber = Int("\(firstLetter)") { if tempCourses[firstNumber] == nil { tempCourses[firstNumber] = [Row]() } tempCourses[firstNumber]?.append(Row(text: course.catalogNumber, detailText: course.courseTitle, object: course)) } } masterTableData = TableData(sections: tempCourses.keys.map { Section(title: "\($0)00s", rows: tempCourses[$0] ?? []) }.sorted { $0.title ?? "" < $1.title ?? "" }) tableView.reloadData() } }
apache-2.0
cdc2e9dbd5f4cc0399b45e97ad83240b
25.3625
164
0.704599
3.772809
false
false
false
false
yzhou65/DSWeibo
DSWeibo/Classes/Main/VisitorView.swift
1
5838
// // VisitorView.swift // DSWeibo // // Created by Yue on 9/6/16. // Copyright © 2016 fda. All rights reserved. // import UIKit // Swift中如何定义协议 protocol VisitorViewDelegate: NSObjectProtocol { //点击登录按钮的回调 func loginBtnWillClick() //点击注册按钮的回调 func registerBtnWillClick() } class VisitorView: UIView { //定义一个属性保存代理对象. 一定要加weak来避免循环引用 weak var delegate: VisitorViewDelegate? /** 设置未登录界面 :param: isHome 是否是首页 :param: imageName 需要展示的图标名称 :param: message 需要展示的文本内容 */ func setupVisitorInfo(isHome:Bool, imageName:String, message:String) { //如果不是首页,就隐藏转盘背景 iconView.hidden = !isHome //修改中间图标 homeIcon.image = UIImage(named: imageName) //修改文本 messageLabel.text = message //判断是否需要执行动画 if isHome { startAnimation() } } //MARK: 按钮监听 func loginBtnClick() { // print(#function) delegate?.loginBtnWillClick() } func registerBtnClick() { // print(#function) //OC中调用代理要先判断是否respondToSelector,而Swift中直接用delegate? delegate?.registerBtnWillClick() } override init(frame: CGRect) { super.init(frame: frame) //添加子控件 addSubview(iconView) addSubview(maskBGView) addSubview(homeIcon) addSubview(messageLabel) addSubview(loginButton) addSubview(registerButton) //布局子控件 //布局背景 iconView.xmg_AlignInner(type: XMG_AlignType.Center, referView: self, size: nil) //布局小房子图标 homeIcon.xmg_AlignInner(type: XMG_AlignType.Center, referView: self, size: nil) //布局文本 messageLabel.xmg_AlignVertical(type: XMG_AlignType.BottomCenter, referView: iconView, size: nil) //给文本设置约束。公式:“哪个控件”的“什么属性” “等于” “另一个控件”的“什么属性” * “多少” + “constant” let widthCons = NSLayoutConstraint(item: messageLabel, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1.0, constant: 224) addConstraint(widthCons) //布局按钮 registerButton.xmg_AlignVertical(type: XMG_AlignType.BottomLeft, referView: messageLabel, size: CGSize(width: 100, height: 30), offset: CGPoint(x: 0, y: 20)) loginButton.xmg_AlignVertical(type: XMG_AlignType.BottomRight, referView: messageLabel, size: CGSize(width: 100, height: 30), offset: CGPoint(x: 0, y: 20)) //布局蒙版 maskBGView.xmg_Fill(self) } /** Swift推荐:当自定义一个控件时,要么用纯代码,要么就用xib/storyboard */ required init?(coder aDecoder: NSCoder) { //如果通过xib/storyboard创建该类,那么就会崩溃 fatalError("init(coder:) has not been implemented") } //MARK: 内部控制方法 private func startAnimation(){ //创建动画 let anim = CABasicAnimation(keyPath: "transform.rotation") //设置动画属性 anim.toValue = 2 * M_PI anim.duration = 20 anim.repeatCount = MAXFLOAT //改属性默认为true,代表动画只要执行完毕就移除,那么下次再进来同一个界面就不会再有动画。所以要避免这个问题,就要设置为false anim.removedOnCompletion = false //将动画添加到图层 iconView.layer.addAnimation(anim, forKey: nil) } //MARK: 懒加载控件 ///转盘形背景 private lazy var iconView: UIImageView = { let iv = UIImageView(image: UIImage(named: "visitordiscover_feed_image_smallicon")) return iv }() ///图标 private lazy var homeIcon: UIImageView = { let iv = UIImageView(image: UIImage(named: "visitordiscover_feed_image_house")) return iv }() ///文本 private lazy var messageLabel: UILabel = { let label = UILabel() label.text = "adfslfj" label.numberOfLines = 0 label.textColor = UIColor.darkGrayColor() return label }() ///登录按钮 private lazy var loginButton: UIButton = { let btn = UIButton() btn.setTitleColor(UIColor.darkGrayColor(), forState: UIControlState.Normal) btn.setTitle("登录", forState: UIControlState.Normal) btn.setBackgroundImage(UIImage(named:"common_button_white_disable"), forState: UIControlState.Normal) btn.addTarget(self, action: #selector(loginBtnClick), forControlEvents: UIControlEvents.TouchUpInside) return btn }() ///注册按钮 private lazy var registerButton: UIButton = { let btn = UIButton() btn.setTitleColor(UIColor.orangeColor(), forState: UIControlState.Normal) btn.setTitle("注册", forState: UIControlState.Normal) btn.setBackgroundImage(UIImage(named:"common_button_white_disable"), forState: UIControlState.Normal) btn.addTarget(self, action: #selector(registerBtnClick), forControlEvents: UIControlEvents.TouchUpInside) return btn }() private lazy var maskBGView: UIImageView = { let iv = UIImageView(image: UIImage(named: "visitordiscover_feed_mask_smallicon")) return iv }() }
apache-2.0
8ec1d17fb7c13a5eba69fdc1e2d6fd47
29.422619
223
0.622187
4.291352
false
false
false
false
qvacua/vimr
VimR/VimR/Theme.swift
1
3184
/** * Tae Won Ha - http://taewon.de - @hataewon * See LICENSE */ import Cocoa import Commons import NvimView func changeTheme(themePrefChanged: Bool, themeChanged: Bool, usesTheme: Bool, forTheme: () -> Void, forDefaultTheme: () -> Void) -> Bool { if themePrefChanged, usesTheme { forTheme() return true } if themePrefChanged, !usesTheme { forDefaultTheme() return true } if !themePrefChanged, themeChanged, usesTheme { forTheme() return true } return false } struct Theme: CustomStringConvertible { static let `default` = Theme() var foreground = NSColor.textColor var background = NSColor.textBackgroundColor var highlightForeground = NSColor.selectedMenuItemTextColor var highlightBackground = NSColor.selectedMenuItemColor var directoryForeground = NSColor.textColor var cssColor = NSColor(hex: "24292e")! var cssBackgroundColor = NSColor.white var cssA = NSColor(hex: "0366d6")! var cssHrBorderBackgroundColor = NSColor(hex: "dfe2e5")! var cssHrBorderBottomColor = NSColor(hex: "eeeeee")! var cssBlockquoteBorderLeftColor = NSColor(hex: "dfe2e5")! var cssBlockquoteColor = NSColor(hex: "6a737d")! var cssH2BorderBottomColor = NSColor(hex: "eaecef")! var cssH6Color = NSColor(hex: "6a737d")! var cssCodeColor = NSColor(hex: "24292e")! var cssCodeBackgroundColor = NSColor(hex: "1b1f23")! public var description: String { "Theme<" + "fg: \(self.foreground.hex), bg: \(self.background.hex), " + "hl-fg: \(self.highlightForeground.hex), hl-bg: \(self.highlightBackground.hex)" + "dir-fg: \(self.directoryForeground.hex)" + ">" } init() {} init(from nvimTheme: NvimView.Theme, additionalColorDict: [String: CellAttributes]) { self.foreground = nvimTheme.foreground self.background = nvimTheme.background self.highlightForeground = nvimTheme.visualForeground self.highlightBackground = nvimTheme.visualBackground self.directoryForeground = nvimTheme.directoryForeground self.updateCssColors(additionalColorDict) } private mutating func updateCssColors(_ colors: [String: CellAttributes]) { guard let normal = colors["Normal"], let directory = colors["Directory"], let question = colors["Question"], let cursorColumn = colors["CursorColumn"] else { return } self.cssColor = NSColor(rgb: normal.effectiveForeground) self.cssBackgroundColor = NSColor(rgb: normal.effectiveBackground) self.cssA = NSColor(rgb: directory.effectiveForeground) self.cssHrBorderBackgroundColor = NSColor(rgb: cursorColumn.effectiveForeground) self.cssHrBorderBottomColor = NSColor(rgb: cursorColumn.effectiveBackground) self.cssBlockquoteBorderLeftColor = NSColor(rgb: cursorColumn.effectiveForeground) self.cssBlockquoteColor = NSColor(rgb: question.effectiveBackground) self.cssH2BorderBottomColor = NSColor(rgb: cursorColumn.effectiveBackground) self.cssH6Color = NSColor(rgb: normal.effectiveForeground) self.cssCodeColor = NSColor(rgb: cursorColumn.effectiveForeground) self.cssCodeBackgroundColor = NSColor(rgb: cursorColumn.effectiveBackground) } }
mit
fb66150caa526e846c1cf9c8acd8c50d
32.87234
88
0.730214
4.025284
false
false
false
false
OperatorFoundation/Postcard
Postcard/Postcard/Controllers/ViewControllers/WelcomeViewController.swift
1
10240
// // WelcomeViewController.swift // Postcard // // Created by Adelita Schule on 5/20/16. // Copyright © 2016 operatorfoundation.org. All rights reserved. // import Cocoa import AppAuth import GoogleAPIClientForRESTCore import GoogleAPIClientForREST_Gmail import GTMAppAuth //import GoogleAPIClient class WelcomeViewController: NSViewController { @IBOutlet weak var descriptionLabel: NSTextField! @IBOutlet weak var descriptionView: NSView! @IBOutlet weak var googleLoginButton: NSButton! let appDelegate = NSApplication.shared.delegate as! AppDelegate var userGoogleName: String? var authorization: GTMAppAuthFetcherAuthorization? override func viewDidLoad() { super.viewDidLoad() //The description label should be at the same angle as the Big "Postcard" descriptionView.rotate(byDegrees: 11.0) //Load Google Authorization State loadState() } override func viewDidAppear() { if isAuthorized() { //Present Home View mainWindowController.showWindow(self) view.window?.close() } else { googleLoginButton.isEnabled = true } } func fetchUserFromCoreData(_ userEmail: String) -> User? { //Check if a user entity already exists //Get this User Entity let fetchRequest: NSFetchRequest<User> = User.fetchRequest() let managedObjectContext = appDelegate.managedObjectContext fetchRequest.predicate = NSPredicate(format: "emailAddress == %@", userEmail) do { let result = try managedObjectContext.fetch(fetchRequest) if result.count > 0 { let thisUser = result[0] return thisUser } else { return nil } } catch { //Could not fetch this Penpal from core data let fetchError = error as NSError print("Could not fetch user from core data:\(fetchError)") return nil } } func createUser(_ userEmail: String) -> User? { return createUser(userEmail, firstName: nil) } func createUser(_ userEmail: String, firstName: String?) -> User? { let managedObjectContext = appDelegate.managedObjectContext if let userEntity = NSEntityDescription.entity(forEntityName: "User", in: managedObjectContext) { let newUser = User(entity: userEntity, insertInto: managedObjectContext) newUser.emailAddress = userEmail //Save this user to core Data do { try newUser.managedObjectContext?.save() GlobalVars.currentUser = newUser return newUser } catch { let saveError = error as NSError print("Unable to save new user to core data. \n\(saveError)\n") return nil } } else { return nil } } func fetchGoodies() { MailController.sharedInstance.updateMail() PenPalController.sharedInstance.getGoogleContacts() } lazy var mainWindowController: MainWindowController = { let storyboard: NSStoryboard = NSStoryboard(name: "Main", bundle: nil) let newWindowController = storyboard.instantiateController(withIdentifier: "MainWindowController") as! MainWindowController return newWindowController }() //MARK: Actions @IBAction func googleSignInTap(_ sender: AnyObject) { buildAuthenticationRequest() } //MARK: Google App Auth Methods func isAuthorized() -> Bool { //Ensure Gmail API service is authorized and perform API calls (fetch postcards) if let authorizer = self.authorization { let canAuth = authorizer.canAuthorize() if canAuth { if (GlobalVars.currentUser?.emailAddress) != nil { fetchGoodies() } else { let service = GTMSessionFetcherService() service.authorizer = authorizer let userInfoEndpoint = "https://www.googleapis.com/oauth2/v3/userinfo" let fetcher = service.fetcher(withURLString: userInfoEndpoint) fetcher.beginFetch(completionHandler: { (maybeData, maybeError) in if let error = maybeError { print("User Info Call Error: \(error.localizedDescription)") } else if let data = maybeData { if let json = try? JSONSerialization.jsonObject(with: data, options: []) { print("json: \(json)") } } }) if let currentEmailAddress: String = authorizer.userEmail { //Check if a user entity already exists if let existingUser = fetchUserFromCoreData(currentEmailAddress) { GlobalVars.currentUser = existingUser self.fetchGoodies() } else { //Create a new user if createUser(currentEmailAddress) != nil { self.fetchGoodies() } // if let authWindowController = googleAuthWindowController, let name = authWindowController.signIn.userProfile["name"] as? String // { // if createUser(currentEmailAddress, firstName: name) != nil // { // self.fetchGoodies() // } // } // else // { // if createUser(currentEmailAddress) != nil // { // self.fetchGoodies() // } // } } } } } return true } else { return false } } func buildAuthenticationRequest() { if let redirectURL = URL(string: GmailProps.kRedirectURI) { //Convenience method to configure GTMAppAuth with the OAuth endpoints for Google. let configuration = GTMAppAuthFetcherAuthorization.configurationForGoogle() // builds authentication request let request = OIDAuthorizationRequest(configuration: configuration, clientId: GmailProps.kClientID, clientSecret: nil, scopes: GmailProps.scopes, redirectURL: redirectURL, responseType: OIDResponseTypeCode, additionalParameters: nil) // performs authentication request appDelegate.currentAuthorizationFlow = OIDAuthState.authState(byPresenting: request, callback: { (maybeAuthState, maybeError) in if let authState = maybeAuthState { let authorization = GTMAppAuthFetcherAuthorization(authState: authState) self.setAuthorization(auth: authorization) if self.isAuthorized() { //Present Home View self.mainWindowController.showWindow(self) self.view.window?.close() } } else if let error = maybeError { print("Authorization Error: \(error.localizedDescription)") } else { print("Unknown Authorization Error") } }) } } func saveState() { if self.authorization != nil { let canAuth = self.authorization!.canAuthorize() if canAuth { GTMAppAuthFetcherAuthorization.save(self.authorization!, toKeychainForName: GmailProps.kKeychainItemName) } else { GTMAppAuthFetcherAuthorization.removeFromKeychain(forName: GmailProps.kKeychainItemName) } } } func loadState() { if let authorization = GTMAppAuthFetcherAuthorization.init(fromKeychainForName: GmailProps.kKeychainItemName) { setAuthorization(auth: authorization) } } func setAuthorization(auth: GTMAppAuthFetcherAuthorization) { self.authorization = auth GmailProps.service.authorizer = auth GmailProps.servicePeople.authorizer = auth saveState() } //MARK: Helper Methods //Helper for showing an alert. func showAlert(_ message: String) { let alert = NSAlert() alert.messageText = message alert.addButton(withTitle: localizedOKButtonTitle) alert.runModal() } // }
mit
ef57abad4d18baea68991fb8f88f9ea9
33.13
245
0.488817
6.35568
false
false
false
false
Esri/arcgis-runtime-samples-ios
arcgis-ios-sdk-samples/Features/Feature layer rendering mode (map)/FeatureLayerRenderingModeMapViewController.swift
1
3831
// Copyright 2018 Esri. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import UIKit import ArcGIS class FeatureLayerRenderingModeMapViewController: UIViewController { @IBOutlet weak var dynamicMapView: AGSMapView! @IBOutlet weak var staticMapView: AGSMapView! private var zoomed = false var zoomedInViewpoint: AGSViewpoint! var zoomedOutViewpoint: AGSViewpoint! override func viewDidLoad() { super.viewDidLoad() // add the source code button item to the right of navigation bar (self.navigationItem.rightBarButtonItem as! SourceCodeBarButtonItem).filenames = ["FeatureLayerRenderingModeMapViewController"] // points for zoomed in and zoomed out let zoomedInPoint = AGSPoint(x: -118.37, y: 34.46, spatialReference: .wgs84()) let zoomedOutPoint = AGSPoint(x: -118.45, y: 34.395, spatialReference: .wgs84()) zoomedInViewpoint = AGSViewpoint(center: zoomedInPoint, scale: 650000, rotation: 0) zoomedOutViewpoint = AGSViewpoint(center: zoomedOutPoint, scale: 50000, rotation: 90) // assign maps to the map views self.dynamicMapView.map = AGSMap() self.staticMapView.map = AGSMap() // create service feature tables using point,polygon, and polyline services let pointTable = AGSServiceFeatureTable(url: URL(string: "https://sampleserver6.arcgisonline.com/arcgis/rest/services/Energy/Geology/FeatureServer/0")!) let polylineTable = AGSServiceFeatureTable(url: URL(string: "https://sampleserver6.arcgisonline.com/arcgis/rest/services/Energy/Geology/FeatureServer/8")!) let polygonTable = AGSServiceFeatureTable(url: URL(string: "https://sampleserver6.arcgisonline.com/arcgis/rest/services/Energy/Geology/FeatureServer/9")!) // create feature layers from the feature tables let featureLayers: [AGSFeatureLayer] = [ AGSFeatureLayer(featureTable: polygonTable), AGSFeatureLayer(featureTable: polylineTable), AGSFeatureLayer(featureTable: pointTable)] for featureLayer in featureLayers { // add the layer to the dynamic view featureLayer.renderingMode = AGSFeatureRenderingMode.dynamic self.dynamicMapView.map?.operationalLayers.add(featureLayer) // add the layer to the static view let staticFeatureLayer = featureLayer.copy() as! AGSFeatureLayer staticFeatureLayer.renderingMode = AGSFeatureRenderingMode.static self.staticMapView.map?.operationalLayers.add(staticFeatureLayer) } // set the initial viewpoint self.dynamicMapView.setViewpoint(zoomedOutViewpoint) self.staticMapView.setViewpoint(zoomedOutViewpoint) } @IBAction func animateZoom(_ sender: Any) { if zoomed { self.dynamicMapView.setViewpoint(zoomedOutViewpoint, duration: 5, completion: nil) self.staticMapView.setViewpoint(zoomedOutViewpoint, duration: 5, completion: nil) } else { self.dynamicMapView.setViewpoint(zoomedInViewpoint, duration: 5, completion: nil) self.staticMapView.setViewpoint(zoomedInViewpoint, duration: 5, completion: nil) } zoomed.toggle() } }
apache-2.0
232274bd6bda8cd7b391033e5e179bd9
47.493671
163
0.699817
4.549881
false
false
false
false
ccrama/Slide-iOS
Slide for Reddit/ReplyViewController.swift
1
75637
// // ReplyViewController.swift // Slide for Reddit // // Created by Carlos Crane on 1/10/17. // Copyright © 2017 Haptic Apps. All rights reserved. // import Anchorage import MobileCoreServices import Photos import RealmSwift import reddift import SDCAlertView import SwiftyJSON import Then import UIKit import YYText class ReplyViewController: MediaViewController, UITextViewDelegate { public enum ReplyType { case NEW_MESSAGE case REPLY_MESSAGE case SUBMIT_IMAGE case SUBMIT_LINK case SUBMIT_TEXT case EDIT_SELFTEXT case REPLY_SUBMISSION case CROSSPOST func isEdit() -> Bool { return self == ReplyType.EDIT_SELFTEXT } func isComment() -> Bool { return self == ReplyType.REPLY_SUBMISSION } func isSubmission() -> Bool { return self == ReplyType.SUBMIT_IMAGE || self == ReplyType.SUBMIT_LINK || self == ReplyType.SUBMIT_TEXT || self == ReplyType.EDIT_SELFTEXT || self == ReplyType.CROSSPOST } func isMessage() -> Bool { return self == ReplyType.NEW_MESSAGE || self == ReplyType.REPLY_MESSAGE } } var type = ReplyType.NEW_MESSAGE var text: [UITextView]? var extras: [UIView]? var toolbar: ToolbarTextView? var toReplyTo: Object? var replyingView: UIView? var replyButtons: UIScrollView? var replies: UIStateButton? var distinguish: UIStateButton? var sticky: UIStateButton? var info: UIStateButton? var subject: String? var message: String? var subreddit = "" var canMod = false var scrollView = UIScrollView() var username: String? //Callbacks var messageCallback: (Any?, Error?) -> Void = { (comment, error) in } var submissionCallback: (Link?, Error?) -> Void = { (link, error) in } var commentReplyCallback: (Comment?, Error?) -> Void = { (comment, error) in } //New message no reply init(completion: @escaping(String?) -> Void) { type = .NEW_MESSAGE super.init(nibName: nil, bundle: nil) setBarColors(color: ColorUtil.getColorForSub(sub: "")) self.messageCallback = { (message, error) in DispatchQueue.main.async { if error != nil { self.toolbar?.saveDraft(self) self.alertController?.dismiss(animated: false, completion: { let alert = UIAlertController(title: "Uh oh, something went wrong", message: "Your message has not been sent, please try again\n\nError:\(error!.localizedDescription)", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Ok", style: .cancel, handler: nil)) self.present(alert, animated: true, completion: nil) }) } else { self.alertController?.dismiss(animated: false, completion: { self.dismiss(animated: true, completion: nil) completion("") }) } } } } //New message with sub colors convenience init(name: String, completion: @escaping(String?) -> Void) { self.init(completion: completion) self.username = name setBarColors(color: ColorUtil.getColorForUser(name: name)) } //New message with sub colors convenience init(name: String, subject: String, message: String, completion: @escaping(String?) -> Void) { self.init(completion: completion) self.subject = subject.isEmpty ? nil : subject self.message = message.isEmpty ? nil : message self.username = name.isEmpty ? nil : name setBarColors(color: ColorUtil.getColorForUser(name: name)) } //New message reply init(message: RMessage?, completion: @escaping (String?) -> Void) { type = .REPLY_MESSAGE toReplyTo = message super.init(nibName: nil, bundle: nil) setBarColors(color: ColorUtil.getColorForUser(name: message!.author)) self.messageCallback = { (message, error) in DispatchQueue.main.async { if error != nil { if error!.localizedDescription.contains("25") { self.alertController?.dismiss(animated: false, completion: { self.dismiss(animated: true, completion: { completion("") }) }) } else { self.toolbar?.saveDraft(self) self.alertController?.dismiss(animated: false, completion: { let alert = UIAlertController(title: "Uh oh, something went wrong", message: "Your message has not been sent, please try again\n\nError:\(error!.localizedDescription)", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Ok", style: .cancel, handler: nil)) self.present(alert, animated: true, completion: nil) }) } } else { self.alertController?.dismiss(animated: false, completion: { self.dismiss(animated: true, completion: { completion("") }) }) } } } } var errorText = "" //Edit selftext init(submission: RSubmission, sub: String, completion: @escaping (Link?) -> Void) { type = .EDIT_SELFTEXT toReplyTo = submission super.init(nibName: nil, bundle: nil) setBarColors(color: ColorUtil.getColorForSub(sub: sub)) self.submissionCallback = { (link, error) in DispatchQueue.main.async { if error == nil && link == nil { self.alertController?.dismiss(animated: false, completion: { let alert = UIAlertController(title: "Uh oh, something went wrong", message: "Reddit did not allow this post to be made.\nError message: \(self.errorText)", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Ok", style: .cancel, handler: nil)) self.present(alert, animated: true, completion: nil) }) } else if error != nil { self.toolbar?.saveDraft(self) self.alertController?.dismiss(animated: false, completion: { let alert = UIAlertController(title: "Uh oh, something went wrong", message: "Your submission has not been edited (but has been saved as a draft), please try again\n\nError:\(error!.localizedDescription)", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Ok", style: .cancel, handler: nil)) self.present(alert, animated: true, completion: nil) }) } else { self.alertController?.dismiss(animated: false, completion: { self.dismiss(animated: true, completion: { completion(link) }) }) } } } } //Crosspost init(submission: RSubmission, completion: @escaping (Link?) -> Void) { type = .CROSSPOST toReplyTo = submission super.init(nibName: nil, bundle: nil) subject = submission.title setBarColors(color: ColorUtil.getColorForSub(sub: submission.subreddit)) self.submissionCallback = { (link, error) in DispatchQueue.main.async { if error == nil && link == nil { self.alertController?.dismiss(animated: false, completion: { let alert = UIAlertController(title: "Uh oh, something went wrong", message: "Reddit did not allow this post to be made.\nError message: \(self.errorText)", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Ok", style: .cancel, handler: nil)) self.present(alert, animated: true, completion: nil) }) } else if error != nil { self.alertController?.dismiss(animated: false, completion: { let alert = UIAlertController(title: "Uh oh, something went wrong", message: "Reddit did not allow this post to be made.\n\nError message:\(error!.localizedDescription)", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Ok", style: .cancel, handler: nil)) self.present(alert, animated: true, completion: nil) }) } else { self.alertController?.dismiss(animated: false, completion: { self.dismiss(animated: true, completion: { completion(link) }) }) } } } } //Reply to submission init(submission: RSubmission, sub: String, delegate: ReplyDelegate) { subreddit = sub type = .REPLY_SUBMISSION self.canMod = AccountController.modSubs.contains(sub) toReplyTo = submission super.init(nibName: nil, bundle: nil) setBarColors(color: ColorUtil.getColorForSub(sub: sub)) self.commentReplyCallback = { (comment, error) in DispatchQueue.main.async { if error != nil { self.toolbar?.saveDraft(self) self.alertController?.dismiss(animated: false, completion: { let alert = UIAlertController(title: "Uh oh, something went wrong", message: "Your comment has not been posted (but has been saved as a draft), please try again\n\nError:\(error!.localizedDescription)", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Ok", style: .cancel, handler: nil)) self.present(alert, animated: true, completion: nil) }) } else { self.alertController?.dismiss(animated: false, completion: { self.dismiss(animated: true, completion: { delegate.replySent(comment: comment, cell: nil) }) }) } } } } var modText: String? init(submission: RSubmission, sub: String, modMessage: String, completion: @escaping (Comment?) -> Void) { type = .REPLY_SUBMISSION toReplyTo = submission self.canMod = true super.init(nibName: nil, bundle: nil) self.modText = modMessage setBarColors(color: ColorUtil.getColorForSub(sub: sub)) self.commentReplyCallback = { (comment, error) in DispatchQueue.main.async { if error == nil && comment == nil { self.alertController?.dismiss(animated: false, completion: { let alert = UIAlertController(title: "Uh oh, something went wrong", message: "Reddit did not allow this post to be made.\nError message: \(self.errorText)", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Ok", style: .cancel, handler: nil)) self.present(alert, animated: true, completion: nil) }) } else if error != nil { self.toolbar?.saveDraft(self) self.alertController?.dismiss(animated: false, completion: { let alert = UIAlertController(title: "Uh oh, something went wrong", message: "Your submission has not been edited (but has been saved as a draft), please try again\n\nError:\(error!.localizedDescription)", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Ok", style: .cancel, handler: nil)) self.present(alert, animated: true, completion: nil) }) } else { self.alertController?.dismiss(animated: false, completion: { self.dismiss(animated: true, completion: { completion(comment) }) }) } } } } init(type: ReplyType, completion: @escaping (Link?) -> Void) { self.type = type super.init(nibName: nil, bundle: nil) self.submissionCallback = { (link, error) in DispatchQueue.main.async { if error == nil && link == nil { self.alertController?.dismiss(animated: false, completion: { let alert = UIAlertController(title: "Uh oh, something went wrong", message: "Reddit did not allow this post to be made.\nError message: \(self.errorText)", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Ok", style: .cancel, handler: nil)) self.present(alert, animated: true, completion: nil) }) } else if error != nil { self.toolbar?.saveDraft(self) self.alertController?.dismiss(animated: false, completion: { let alert = UIAlertController(title: "Uh oh, something went wrong", message: "Your post has not been created, please try again\n\nError:\(error!.localizedDescription)", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Ok", style: .cancel, handler: nil)) self.present(alert, animated: true, completion: nil) }) } else { self.alertController?.dismiss(animated: false, completion: { self.dismiss(animated: true, completion: { completion(link) }) }) } } } } var crosspostHeight = CGFloat(0) var lastLength = 0 /* This is probably broken*/ @objc func textViewDidChange(_ textView: UITextView) { textView.sizeToFitHeight() let split = textView.text.split("\n").suffix(1) if split.first != nil && split.first!.startsWith("* ") && textView.text.endsWith("\n") { if split.first == "* " { textView.text = textView.text.substring(0, length: textView.text.length - 3) + "\n" } else if lastLength < textView.text.length { textView.text += "* " textView.selectedTextRange = textView.textRange(from: textView.endOfDocument, to: textView.endOfDocument) } } else if split.first != nil && split.first!.startsWith("- ") && textView.text.endsWith("\n") { if split.first == "- " { textView.text = textView.text.substring(0, length: textView.text.length - 3) + "\n" } else if lastLength < textView.text.length { textView.text += "- " textView.selectedTextRange = textView.textRange(from: textView.endOfDocument, to: textView.endOfDocument) } } else if split.first != nil && split.first!.length > 1 && split.first!.substring(0, length: 1).isNumeric() && split.first!.substring(1, length: 1) == "." && textView.text.endsWith("\n") { let num = (Int(split.first!.substring(0, length: 1)) ?? 0) + 1 if split.first?.length ?? 0 < 4 { textView.text = textView.text.substring(0, length: textView.text.length - 4) + "\n" } else if lastLength < textView.text.length { textView.text += "\(num). " textView.selectedTextRange = textView.textRange(from: textView.endOfDocument, to: textView.endOfDocument) } } var height = CGFloat(8) for view in extras! { height += CGFloat(8) height += view.frame.size.height } for textView in text! { height += CGFloat(8) height += textView.frame.size.height } height += CGFloat(8) height += crosspostHeight if replyButtons != nil { height += CGFloat(46) } if #available(iOS 13, *), !textView.text.isEmpty { self.isModalInPresentation = true } scrollView.contentSize = CGSize.init(width: scrollView.frame.size.width, height: height) lastLength = textView.text.length } //Create a new post convenience init(subreddit: String, type: ReplyType, completion: @escaping (Link?) -> Void) { self.init(type: type, completion: completion) self.subreddit = subreddit self.canMod = AccountController.modSubs.contains(subreddit) setBarColors(color: ColorUtil.getColorForSub(sub: subreddit)) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil) } @objc func keyboardWillShow(notification: NSNotification) { let userInfo = notification.userInfo! var keyboardFrame: CGRect = (userInfo[UIResponder.keyboardFrameBeginUserInfoKey] as! NSValue).cgRectValue keyboardFrame = self.view.convert(keyboardFrame, from: nil) var contentInset: UIEdgeInsets = self.scrollView.contentInset contentInset.bottom = keyboardFrame.size.height + CGFloat(60) scrollView.contentInset = contentInset } @objc func keyboardWillHide(notification: NSNotification) { let contentInset: UIEdgeInsets = UIEdgeInsets.zero scrollView.contentInset = contentInset } func doButtons() { if replyButtons != nil { for view in replyButtons!.subviews { view.removeFromSuperview() } } else { replyButtons = TouchUIScrollView().then { $0.accessibilityIdentifier = "Reply Extra Buttons" } } replies = UIStateButton.init(frame: CGRect.init(x: 0, y: 0, width: 100, height: 30)).then { $0.layer.cornerRadius = 15 $0.clipsToBounds = true $0.setTitle("Inbox replies on", for: .selected) $0.setTitle("Inbox replies off", for: .normal) $0.setTitleColor(GMColor.blue500Color(), for: .normal) $0.setTitleColor(.white, for: .selected) $0.titleLabel?.textAlignment = .center $0.titleLabel?.font = UIFont.systemFont(ofSize: 12) } replies!.color = GMColor.blue500Color() replies!.isSelected = true replies!.addTarget(self, action: #selector(self.changeState(_:)), for: .touchUpInside) replies!.heightAnchor == CGFloat(30) let width = replies!.currentTitle!.size(with: replies!.titleLabel!.font).width + CGFloat(45) replies!.widthAnchor == width info = UIStateButton.init(frame: CGRect.init(x: 0, y: 0, width: 100, height: 30)).then { $0.layer.cornerRadius = 15 $0.clipsToBounds = true $0.setTitle("Subreddit sidebar", for: .selected) $0.setTitle("Subreddit sidebar", for: .normal) $0.setTitleColor(GMColor.blue500Color(), for: .normal) $0.setTitleColor(.white, for: .selected) $0.titleLabel?.textAlignment = .center $0.titleLabel?.font = UIFont.systemFont(ofSize: 12) } info!.color = GMColor.blue500Color() info!.isSelected = true info!.addTarget(self, action: #selector(self.info(_:)), for: .touchUpInside) info!.heightAnchor == CGFloat(30) let widthI = info!.currentTitle!.size(with: replies!.titleLabel!.font).width + CGFloat(45) info!.widthAnchor == widthI sticky = UIStateButton.init(frame: CGRect.init(x: 0, y: 0, width: 100, height: 45)).then { $0.layer.cornerRadius = 15 $0.clipsToBounds = true $0.setTitle(type == .REPLY_SUBMISSION ? "Comment stickied": "Post stickied", for: .selected) $0.setTitle(type == .REPLY_SUBMISSION ? "Comment not stickied": "Post not stickied", for: .normal) $0.setTitleColor(GMColor.green500Color(), for: .normal) $0.setTitleColor(.white, for: .selected) $0.titleLabel?.textAlignment = .center $0.titleLabel?.font = UIFont.systemFont(ofSize: 12) } sticky!.color = GMColor.green500Color() sticky!.isSelected = modText != nil sticky!.addTarget(self, action: #selector(self.changeState(_:)), for: .touchUpInside) sticky!.heightAnchor == CGFloat(30) let widthS = sticky!.currentTitle!.size(with: replies!.titleLabel!.font).width + CGFloat(45) sticky!.widthAnchor == widthS let buttonBase = UIStackView().then { $0.accessibilityIdentifier = "Reply VC Buttons" $0.axis = .horizontal $0.spacing = 8 } buttonBase.addArrangedSubviews(info!, replies!, sticky!) var finalWidth = CGFloat(0) if type == .REPLY_SUBMISSION { info!.isHidden = true if canMod { finalWidth = CGFloat(8) + width + widthS } else { sticky!.isHidden = true finalWidth = width } } else { if canMod || (toReplyTo != nil && (toReplyTo as! RSubmission).canMod) { finalWidth = CGFloat(8 * 2) + width + widthI + widthS } else { sticky!.isHidden = true finalWidth = CGFloat(8) + width + widthI } } replyButtons!.addSubview(buttonBase) buttonBase.heightAnchor == CGFloat(30) buttonBase.edgeAnchors == replyButtons!.edgeAnchors buttonBase.centerYAnchor == replyButtons!.centerYAnchor replyButtons?.contentSize = CGSize.init(width: finalWidth, height: CGFloat(30)) replyButtons?.alwaysBounceHorizontal = true replyButtons?.showsHorizontalScrollIndicator = false if type == .SUBMIT_LINK || type == .SUBMIT_TEXT || type == .SUBMIT_IMAGE || type == .CROSSPOST { do { self.session = (UIApplication.shared.delegate as! AppDelegate).session try session?.getSubmitFlairs(subreddit, completion: { (result) in switch result { case .failure(let error): //do nothing print(error) DispatchQueue.main.async { buttonBase.widthAnchor == finalWidth } case .success(let json): if json is JSONArray { for item in json as! JSONArray { let flair = item as! [String: Any] if let type = flair["type"] as? String, type == "richtext" { if let text = flair["text"] as? String { if let id = flair["id"] as? String { let fo = FlairObject() fo.title = text fo.id = id self.flairs.append(fo) } } } else if let type = flair["type"] as? String, type == "text" { if let text = flair["text"] as? String { if let id = flair["id"] as? String { let fo = FlairObject() fo.title = text fo.id = id self.flairs.append(fo) } } } } } if !self.flairs.isEmpty { DispatchQueue.main.async { let flairs = UIStateButton.init(frame: CGRect.init(x: 0, y: 0, width: 100, height: 45)).then { $0.layer.cornerRadius = 15 $0.clipsToBounds = true $0.setTitle("Submission flair", for: .selected) $0.setTitle("Submission flair", for: .normal) $0.setTitleColor(.white, for: .normal) $0.setTitleColor(.white, for: .selected) $0.titleLabel?.textAlignment = .center $0.backgroundColor = ColorUtil.getColorForSub(sub: self.subreddit) $0.titleLabel?.font = UIFont.systemFont(ofSize: 12) } flairs.addTarget(self, action: #selector(self.flairs(_:)), for: .touchUpInside) let widthF = flairs.currentTitle!.size(with: flairs.titleLabel!.font).width + CGFloat(45) flairs.widthAnchor == widthS buttonBase.widthAnchor == finalWidth + CGFloat(8) + widthF buttonBase.addArrangedSubview(flairs) self.replyButtons?.contentSize = CGSize.init(width: finalWidth + CGFloat(8) + widthF, height: CGFloat(30)) } } } }) } catch let error { print(error) buttonBase.widthAnchor == finalWidth } } else { buttonBase.widthAnchor == finalWidth } } @objc func flairs(_ sender: AnyObject) { let alert = UIAlertController(title: "Select post flair", message: nil, preferredStyle: .alert) for item in flairs { alert.addAction(UIAlertAction(title: item.title, style: .default, handler: { (_) in self.selectedFlair = item.id self.text?[0].placeholder = item.title })) } alert.addAction(UIAlertAction(title: "No flair", style: .cancel, handler: { (_) in self.selectedFlair = nil })) alert.showWindowless() } var flairs = [FlairObject]() var selectedFlair: String? class FlairObject { var title = "" var id = "" } @objc func changeState(_ sender: UIStateButton) { sender.isSelected = !sender.isSelected } @objc func info(_ sender: UIStateButton) { Sidebar.init(parent: self, subname: subreddit).displaySidebar() } func layoutForType() { self.scrollView = UIScrollView.init(frame: CGRect.init(x: 0, y: 0, width: self.view.frame.size.width, height: self.view.frame.size.height)) self.view.addSubview(scrollView) extras = [UIView]() self.scrollView.backgroundColor = ColorUtil.theme.backgroundColor self.scrollView.isUserInteractionEnabled = true self.scrollView.contentInset = UIEdgeInsets.init(top: 8, left: 0, bottom: 0, right: 0) self.scrollView.bottomAnchor == self.view.bottomAnchor - 64 self.scrollView.topAnchor == self.view.topAnchor self.view.backgroundColor = ColorUtil.theme.backgroundColor self.scrollView.horizontalAnchors == self.view.horizontalAnchors let stack = UIStackView().then { $0.accessibilityIdentifier = "Reply Stack Vertical" $0.axis = .vertical $0.alignment = .center $0.distribution = .fill $0.spacing = 8 } if type.isMessage() { if type == .REPLY_MESSAGE { //two let text1 = YYLabel.init(frame: CGRect.init(x: 0, y: 0, width: CGFloat.greatestFiniteMagnitude, height: 60)).then({ $0.textColor = ColorUtil.theme.fontColor $0.backgroundColor = ColorUtil.theme.foregroundColor $0.clipsToBounds = true $0.layer.cornerRadius = 10 $0.font = UIFont.systemFont(ofSize: 16) $0.numberOfLines = 0 }) extras?.append(text1) let html = (toReplyTo as! RMessage).htmlBody let content = TextDisplayStackView.createAttributedChunk(baseHTML: html, fontSize: 16, submission: false, accentColor: ColorUtil.baseAccent, fontColor: ColorUtil.theme.fontColor, linksCallback: nil, indexCallback: nil) // TODO: - this /* let activeLinkAttributes = NSMutableDictionary(dictionary: text1.activeLinkAttributes) activeLinkAttributes[kCTForegroundColorAttributeName] = ColorUtil.baseAccent text1.activeLinkAttributes = activeLinkAttributes as NSDictionary as? [AnyHashable: Any] text1.linkAttributes = activeLinkAttributes as NSDictionary as? [AnyHashable: Any] */ text1.attributedText = content text1.highlightTapAction = { (containerView: UIView, text: NSAttributedString, range: NSRange, rect: CGRect) in text.enumerateAttributes(in: range, options: .longestEffectiveRangeNotRequired, using: { (attrs, _, _) in for attr in attrs { if attr.value is YYTextHighlight { if let url = (attr.value as! YYTextHighlight).userInfo?["url"] as? URL { self.doShow(url: url, heroView: nil, finalSize: nil, heroVC: nil, link: RSubmission()) return } } } }) } text1.textContainerInset = UIEdgeInsets(top: 8, left: 8, bottom: 8, right: 8) text1.preferredMaxLayoutWidth = self.view.frame.size.width - 16 let text3 = UITextView.init(frame: CGRect.init(x: 0, y: 0, width: CGFloat.greatestFiniteMagnitude, height: 60)).then({ $0.isEditable = true $0.placeholder = "Body" $0.textColor = ColorUtil.theme.fontColor $0.backgroundColor = ColorUtil.theme.foregroundColor $0.layer.masksToBounds = false $0.layer.cornerRadius = 10 $0.font = UIFont.systemFont(ofSize: 16) $0.isScrollEnabled = false $0.textContainerInset = UIEdgeInsets.init(top: 24, left: 8, bottom: 8, right: 8) $0.delegate = self }) stack.addArrangedSubviews(text1, text3) text1.horizontalAnchors == stack.horizontalAnchors + CGFloat(8) text3.horizontalAnchors == stack.horizontalAnchors + CGFloat(8) text3.heightAnchor >= CGFloat(70) scrollView.addSubview(stack) stack.widthAnchor == scrollView.widthAnchor stack.verticalAnchors == scrollView.verticalAnchors text = [text3] toolbar = ToolbarTextView.init(textView: text3, parent: self) } else { //three let text1 = UITextView.init(frame: CGRect.init(x: 0, y: 0, width: CGFloat.greatestFiniteMagnitude, height: 60)).then({ $0.isEditable = true $0.textColor = ColorUtil.theme.fontColor $0.backgroundColor = ColorUtil.theme.foregroundColor $0.layer.masksToBounds = false $0.layer.cornerRadius = 10 $0.delegate = self $0.font = UIFont.systemFont(ofSize: 16) $0.isScrollEnabled = false $0.textContainerInset = UIEdgeInsets.init(top: 24, left: 8, bottom: 8, right: 8) }) if !ColorUtil.theme.isLight { text1.keyboardAppearance = .dark } let text2 = UITextView.init(frame: CGRect.init(x: 0, y: 0, width: CGFloat.greatestFiniteMagnitude, height: 60)).then({ $0.isEditable = true $0.textColor = ColorUtil.theme.fontColor $0.backgroundColor = ColorUtil.theme.foregroundColor $0.layer.masksToBounds = false $0.layer.cornerRadius = 10 $0.font = UIFont.systemFont(ofSize: 16) $0.textContainer.maximumNumberOfLines = 0 $0.delegate = self $0.textContainer.lineBreakMode = .byTruncatingTail $0.isScrollEnabled = false $0.textContainerInset = UIEdgeInsets.init(top: 24, left: 8, bottom: 8, right: 8) }) if toReplyTo != nil { text1.text = "re: \((toReplyTo as! RMessage).subject.escapeHTML)" text1.isEditable = false text2.text = ((toReplyTo as! RMessage).author) text2.isEditable = false } text1.placeholder = "Subject" text2.placeholder = "User" if username != nil { text2.text = username! text2.isEditable = false if username!.contains("/r/") { text2.placeholder = "Subreddit" } } let text3 = UITextView.init(frame: CGRect.init(x: 0, y: 0, width: CGFloat.greatestFiniteMagnitude, height: 60)).then({ $0.isEditable = true $0.placeholder = "Body" $0.textColor = ColorUtil.theme.fontColor $0.backgroundColor = ColorUtil.theme.foregroundColor $0.layer.masksToBounds = false $0.layer.cornerRadius = 10 $0.font = UIFont.systemFont(ofSize: 16) $0.isScrollEnabled = false $0.textContainerInset = UIEdgeInsets.init(top: 24, left: 8, bottom: 8, right: 8) $0.delegate = self }) if subject != nil { text1.text = subject! } if message != nil { text3.text = message! } stack.addArrangedSubviews(text1, text2, text3) text1.horizontalAnchors == stack.horizontalAnchors + CGFloat(8) text1.heightAnchor >= CGFloat(70) text2.horizontalAnchors == stack.horizontalAnchors + CGFloat(8) text2.heightAnchor == CGFloat(70) text3.horizontalAnchors == stack.horizontalAnchors + CGFloat(8) scrollView.addSubview(stack) stack.widthAnchor == scrollView.widthAnchor stack.verticalAnchors == scrollView.verticalAnchors text = [text1, text2, text3] toolbar = ToolbarTextView.init(textView: text3, parent: self) } } else if type.isSubmission() { //three let text1 = UITextView.init(frame: CGRect.init(x: 0, y: 0, width: CGFloat.greatestFiniteMagnitude, height: 60)).then({ $0.isEditable = true $0.textColor = ColorUtil.theme.fontColor $0.backgroundColor = ColorUtil.theme.foregroundColor $0.layer.masksToBounds = false $0.layer.cornerRadius = 10 $0.delegate = self $0.font = UIFont.systemFont(ofSize: 16) $0.isScrollEnabled = false $0.textContainerInset = UIEdgeInsets.init(top: 24, left: 8, bottom: 8, right: 8) }) let text2 = UITextView.init(frame: CGRect.init(x: 0, y: 0, width: CGFloat.greatestFiniteMagnitude, height: 60)).then({ $0.isEditable = true $0.textColor = ColorUtil.theme.fontColor $0.backgroundColor = ColorUtil.theme.foregroundColor $0.layer.masksToBounds = false $0.layer.cornerRadius = 10 $0.textContainer.maximumNumberOfLines = 1 $0.textContainer.lineBreakMode = .byTruncatingTail $0.font = UIFont.systemFont(ofSize: 16) $0.isScrollEnabled = false $0.textContainerInset = UIEdgeInsets.init(top: 24, left: 8, bottom: 8, right: 8) }) if toReplyTo != nil && type != .CROSSPOST { text1.text = "\((toReplyTo as! RSubmission).title)" text1.isEditable = false text2.text = ((toReplyTo as! RSubmission).subreddit) text2.isEditable = false } text1.placeholder = "Title" text2.placeholder = "Subreddit" if !subreddit.isEmpty() && subreddit != "all" && subreddit != "frontpage" && subreddit != "popular" && subreddit != "friends" && subreddit != "mod" && !subreddit.contains("m/") { text2.text = subreddit } text2.isEditable = false text2.addTapGestureRecognizer { let search = SubredditFindReturnViewController(includeSubscriptions: true, includeCollections: false, includeTrending: false, subscribe: false, callback: { (subreddit) in text2.text = subreddit self.subreddit = subreddit self.doButtons() self.setBarColors(color: ColorUtil.getColorForSub(sub: subreddit)) }) VCPresenter.presentModally(viewController: search, self, nil) } let text3 = UITextView.init(frame: CGRect.init(x: 0, y: 0, width: CGFloat.greatestFiniteMagnitude, height: 60)).then({ $0.isEditable = true $0.placeholder = "Body" $0.textColor = ColorUtil.theme.fontColor $0.backgroundColor = ColorUtil.theme.foregroundColor $0.layer.masksToBounds = false $0.layer.cornerRadius = 10 $0.font = UIFont.systemFont(ofSize: 16) $0.isScrollEnabled = false $0.textContainerInset = UIEdgeInsets.init(top: 24, left: 8, bottom: 8, right: 8) $0.delegate = self }) if type != .SUBMIT_TEXT && type != .EDIT_SELFTEXT && type != .CROSSPOST { text3.placeholder = "Link" text3.textContainer.maximumNumberOfLines = 0 if type == .SUBMIT_IMAGE { text3.addTapGestureRecognizer { self.toolbar?.uploadImage(UIButton()) } text3.placeholder = "Tap to choose an image" } } if type != .EDIT_SELFTEXT { doButtons() if type == .CROSSPOST { let link = toReplyTo as! RSubmission let linkCV = link.isSelf ? TextLinkCellView(frame: CGRect.zero) : ThumbnailLinkCellView(frame: CGRect.zero) linkCV.aspectWidth = self.view.frame.size.width - 16 linkCV.configure(submission: link, parent: self, nav: nil, baseSub: "all", embedded: true, parentWidth: self.view.frame.size.width - 16, np: false) let linkView = linkCV.contentView linkView.isUserInteractionEnabled = false let height = linkCV.estimateHeight(false, true, np: false) stack.addArrangedSubviews(linkView, text1, text2, replyButtons!) replyButtons!.heightAnchor == CGFloat(30) replyButtons!.horizontalAnchors == stack.horizontalAnchors + CGFloat(8) linkView.horizontalAnchors == stack.horizontalAnchors + CGFloat(8) linkView.heightAnchor == CGFloat(height) self.crosspostHeight = CGFloat(height) text1.horizontalAnchors == stack.horizontalAnchors + CGFloat(8) text1.heightAnchor >= CGFloat(70) text2.horizontalAnchors == stack.horizontalAnchors + CGFloat(8) text2.heightAnchor == CGFloat(70) scrollView.addSubview(stack) stack.widthAnchor == scrollView.widthAnchor stack.verticalAnchors == scrollView.verticalAnchors text = [text1, text2] toolbar = ToolbarTextView.init(textView: text2, parent: self) } else { stack.addArrangedSubviews(text1, text2, replyButtons!, text3) replyButtons!.heightAnchor == CGFloat(30) replyButtons!.horizontalAnchors == stack.horizontalAnchors + CGFloat(8) text1.horizontalAnchors == stack.horizontalAnchors + CGFloat(8) text1.heightAnchor >= CGFloat(70) text2.horizontalAnchors == stack.horizontalAnchors + CGFloat(8) text2.heightAnchor == CGFloat(70) text3.horizontalAnchors == stack.horizontalAnchors + CGFloat(8) text3.heightAnchor >= CGFloat(70) scrollView.addSubview(stack) stack.widthAnchor == scrollView.widthAnchor stack.verticalAnchors == scrollView.verticalAnchors text = [text1, text2, text3] toolbar = ToolbarTextView.init(textView: text3, parent: self) } } else { stack.addArrangedSubviews(text1, text2, text3) text3.text = (toReplyTo as! RSubmission).body text1.horizontalAnchors == stack.horizontalAnchors + CGFloat(8) text1.heightAnchor >= CGFloat(70) text2.horizontalAnchors == stack.horizontalAnchors + CGFloat(8) text2.heightAnchor == CGFloat(70) text3.horizontalAnchors == stack.horizontalAnchors + CGFloat(8) text3.heightAnchor >= CGFloat(70) scrollView.addSubview(stack) stack.widthAnchor == scrollView.widthAnchor stack.verticalAnchors == scrollView.verticalAnchors text = [text1, text2, text3] toolbar = ToolbarTextView.init(textView: text3, parent: self) } } else if type.isComment() { if (toReplyTo as! RSubmission).type == .SELF && !(toReplyTo as! RSubmission).htmlBody.trimmed().isEmpty { //two let text1 = YYLabel.init(frame: CGRect.init(x: 0, y: 0, width: CGFloat.greatestFiniteMagnitude, height: 60)).then({ $0.textColor = ColorUtil.theme.fontColor $0.backgroundColor = ColorUtil.theme.foregroundColor $0.clipsToBounds = true $0.numberOfLines = 0 $0.layer.cornerRadius = 10 $0.font = UIFont.systemFont(ofSize: 16) }) extras?.append(text1) let html = (toReplyTo as! RSubmission).htmlBody let content = TextDisplayStackView.createAttributedChunk(baseHTML: html, fontSize: 16, submission: false, accentColor: ColorUtil.baseAccent, fontColor: ColorUtil.theme.fontColor, linksCallback: nil, indexCallback: nil) // TODO: - this /* let activeLinkAttributes = NSMutableDictionary(dictionary: text1.activeLinkAttributes) activeLinkAttributes[kCTForegroundColorAttributeName] = ColorUtil.baseAccent text1.activeLinkAttributes = activeLinkAttributes as NSDictionary as? [AnyHashable: Any] text1.linkAttributes = activeLinkAttributes as NSDictionary as? [AnyHashable: Any] */ text1.attributedText = content text1.highlightTapAction = { (containerView: UIView, text: NSAttributedString, range: NSRange, rect: CGRect) in text.enumerateAttributes(in: range, options: .longestEffectiveRangeNotRequired, using: { (attrs, _, _) in for attr in attrs { if attr.value is YYTextHighlight { if let url = (attr.value as! YYTextHighlight).userInfo?["url"] as? URL { self.doShow(url: url, heroView: nil, finalSize: nil, heroVC: nil, link: RSubmission()) return } } } }) } text1.textContainerInset = UIEdgeInsets(top: 8, left: 8, bottom: 8, right: 8) text1.preferredMaxLayoutWidth = self.view.frame.size.width - 16 let text3 = UITextView.init(frame: CGRect.init(x: 0, y: 0, width: CGFloat.greatestFiniteMagnitude, height: 60)).then({ $0.isEditable = true $0.placeholder = "Body" $0.textColor = ColorUtil.theme.fontColor $0.backgroundColor = ColorUtil.theme.foregroundColor $0.layer.masksToBounds = false $0.layer.cornerRadius = 10 $0.font = UIFont.systemFont(ofSize: 16) $0.isScrollEnabled = false $0.textContainerInset = UIEdgeInsets.init(top: 24, left: 8, bottom: 8, right: 8) $0.delegate = self }) if modText != nil { text3.text = "Hi u/\((toReplyTo as! RSubmission).author),\n\nYour submission has been removed for the following reason:\n\n\(modText!.replacingOccurrences(of: "\n", with: "\n\n"))\n\n" } doButtons() stack.addArrangedSubviews(text1, replyButtons!, text3) replyButtons!.heightAnchor == CGFloat(30) replyButtons!.horizontalAnchors == stack.horizontalAnchors + CGFloat(8) stack.addArrangedSubviews(text1, text3) text1.horizontalAnchors == stack.horizontalAnchors + CGFloat(8) text3.horizontalAnchors == stack.horizontalAnchors + CGFloat(8) text3.heightAnchor >= CGFloat(70) // text1.sizeToFitHeight() scrollView.addSubview(stack) stack.widthAnchor == scrollView.widthAnchor stack.verticalAnchors == scrollView.verticalAnchors text = [text3] toolbar = ToolbarTextView.init(textView: text3, parent: self) } else { //one let text3 = UITextView.init(frame: CGRect.init(x: 0, y: 0, width: CGFloat.greatestFiniteMagnitude, height: 60)).then({ $0.isEditable = true $0.placeholder = "Body" $0.textColor = ColorUtil.theme.fontColor $0.backgroundColor = ColorUtil.theme.foregroundColor $0.layer.masksToBounds = false $0.layer.cornerRadius = 10 $0.font = UIFont.systemFont(ofSize: 16) $0.isScrollEnabled = false $0.textContainerInset = UIEdgeInsets.init(top: 24, left: 8, bottom: 8, right: 8) $0.delegate = self }) if modText != nil { text3.text = "Hi u/\((toReplyTo as! RSubmission).author),\n\nYour submission has been removed for the following reason:\n\n\(modText!.replacingOccurrences(of: "\n", with: "\n\n"))\n\n" } doButtons() stack.addArrangedSubviews(replyButtons!, text3) replyButtons!.heightAnchor == CGFloat(30) replyButtons!.horizontalAnchors == stack.horizontalAnchors + CGFloat(8) text3.horizontalAnchors == stack.horizontalAnchors + CGFloat(8) text3.heightAnchor >= CGFloat(70) scrollView.addSubview(stack) stack.widthAnchor == scrollView.widthAnchor stack.verticalAnchors == scrollView.verticalAnchors text = [text3] toolbar = ToolbarTextView.init(textView: text3, parent: self) } } else if type.isEdit() { //two let text1 = UITextView.init(frame: CGRect.init(x: 0, y: 0, width: CGFloat.greatestFiniteMagnitude, height: 60)).then({ $0.isEditable = true $0.textColor = ColorUtil.theme.fontColor $0.backgroundColor = ColorUtil.theme.foregroundColor $0.layer.masksToBounds = false $0.layer.cornerRadius = 10 $0.delegate = self $0.font = UIFont.systemFont(ofSize: 16) $0.isScrollEnabled = false $0.textContainerInset = UIEdgeInsets.init(top: 24, left: 8, bottom: 8, right: 8) }) if toReplyTo != nil { text1.text = "\((toReplyTo as! RSubmission).title)" text1.isEditable = false } text1.placeholder = "Title" let text3 = UITextView.init(frame: CGRect.init(x: 0, y: 0, width: CGFloat.greatestFiniteMagnitude, height: 60)).then({ $0.isEditable = true $0.placeholder = "Body" $0.textColor = ColorUtil.theme.fontColor $0.backgroundColor = ColorUtil.theme.foregroundColor $0.layer.masksToBounds = false $0.layer.cornerRadius = 10 $0.font = UIFont.systemFont(ofSize: 16) $0.isScrollEnabled = false $0.textContainerInset = UIEdgeInsets.init(top: 24, left: 8, bottom: 8, right: 8) $0.delegate = self $0.text = (toReplyTo as! RSubmission).body }) stack.addArrangedSubviews(text1, text3) text1.horizontalAnchors == stack.horizontalAnchors + CGFloat(8) text1.heightAnchor >= CGFloat(70) text3.horizontalAnchors == stack.horizontalAnchors + CGFloat(8) text3.heightAnchor >= CGFloat(70) scrollView.addSubview(stack) stack.widthAnchor == scrollView.widthAnchor stack.verticalAnchors == scrollView.verticalAnchors text = [text1, text3] toolbar = ToolbarTextView.init(textView: text3, parent: self) } } var doneOnceLayout = false override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() if !doneOnceLayout { layoutForType() doneOnceLayout = true var first = false for textField in text! { if textField.isEditable && !first { first = true textField.becomeFirstResponder() } if !ColorUtil.theme.isLight { textField.keyboardAppearance = .dark } } } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.navigationController?.setToolbarHidden(true, animated: false) self.navigationController?.setNavigationBarHidden(false, animated: true) if type.isMessage() { title = "New message" if type == ReplyType.REPLY_MESSAGE { let author = (toReplyTo is RMessage) ? ((toReplyTo as! RMessage).author) : ((toReplyTo as! RSubmission).author) title = "Reply to \(author)" } } else { if type == .EDIT_SELFTEXT { title = "Editing" } else if type.isComment() { title = "Replying to \((toReplyTo as! RSubmission).author)" } else if type == .CROSSPOST { title = "Crosspost submission" } else { title = "New submission" } } let send = UIButton.init(type: .custom) send.imageView?.contentMode = UIView.ContentMode.scaleAspectFit send.setImage(UIImage(sfString: SFSymbol.paperplaneFill, overrideString: "send")!.navIcon(), for: UIControl.State.normal) send.addTarget(self, action: #selector(self.send(_:)), for: UIControl.Event.touchUpInside) send.frame = CGRect.init(x: 0, y: 0, width: 25, height: 25) send.accessibilityLabel = "Send" let sendB = UIBarButtonItem.init(customView: send) navigationItem.rightBarButtonItem = sendB let button = UIButtonWithContext.init(type: .custom) button.imageView?.contentMode = UIView.ContentMode.scaleAspectFit button.setImage(UIImage(sfString: SFSymbol.xmark, overrideString: "close")!.navIcon(), for: UIControl.State.normal) button.frame = CGRect.init(x: 0, y: 0, width: 25, height: 25) button.accessibilityLabel = "Close" button.addTarget(self, action: #selector(self.close(_:)), for: .touchUpInside) let barButton = UIBarButtonItem.init(customView: button) navigationItem.leftBarButtonItem = barButton } @objc func close(_ sender: AnyObject) { let alert = UIAlertController.init(title: "Discard this \(type.isMessage() ? "message" : (type.isComment()) ? "comment" : type.isEdit() ? "edit" : "submission")?", message: "", preferredStyle: .alert) alert.addAction(UIAlertAction.init(title: "Yes", style: .destructive, handler: { (_) in if self.navigationController?.viewControllers.count ?? 1 == 1 { self.navigationController?.dismiss(animated: true, completion: nil) } else { self.navigationController?.popViewController(animated: true) } })) alert.addAction(UIAlertAction.init(title: "No", style: .cancel)) present(alert, animated: true) } var alertController: UIAlertController? var session: Session? func getSubmissionEdited(_ name: String) { DispatchQueue.main.async { if (self.type == .SUBMIT_LINK || self.type == .SUBMIT_IMAGE || self.type == .SUBMIT_TEXT) && self.sticky != nil && self.sticky!.isSelected { do { try self.session?.sticky("t3_\(name)", sticky: true, completion: { (_) in self.completeGetSubmission(name) }) } catch { self.completeGetSubmission(name) } } else { self.completeGetSubmission(name) } } } var doneOnce = false override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) if type == .SUBMIT_IMAGE && !doneOnce { toolbar?.uploadImage(UIButton()) doneOnce = true } var first = false for textField in text! { if textField.isEditable && !first { first = true textField.becomeFirstResponder() textViewDidChange(textField) UIView.animate(withDuration: 0.25) { textField.insertText("") } } } } func completeGetSubmission(_ name: String) { do { try self.session?.getInfo([name.contains("t3") ? name : "t3_\(name)"], completion: { (res) in switch res { case .failure: print(res.error ?? "Error?") self.submissionCallback(nil, res.error) case .success(let listing): if listing.children.count == 1 { if let submission = listing.children[0] as? Link { self.submissionCallback(submission, nil) } } } }) } catch { // TODO: - success but null child self.submissionCallback(nil, error) } } var triedOnce = false func submitLink() { let title = text![0] let subreddit = text![1] let body = text![2] if title.text.isEmpty() { BannerUtil.makeBanner(text: "Title cannot be empty", color: GMColor.red500Color(), seconds: 5, context: self, top: true) return } if subreddit.text.isEmpty() { BannerUtil.makeBanner(text: "Subreddit cannot be empty", color: GMColor.red500Color(), seconds: 5, context: self, top: true) return } if body.text.isEmpty() && (type == .SUBMIT_LINK || type == .SUBMIT_IMAGE) { BannerUtil.makeBanner(text: (type == .SUBMIT_LINK || type == .SUBMIT_IMAGE) ? "Link cannot be empty" : "Body cannot be empty", color: GMColor.red500Color(), seconds: 5, context: self, top: true) return } if type == .EDIT_SELFTEXT { alertController = UIAlertController(title: "Editing submission...\n\n\n", message: nil, preferredStyle: .alert) let spinnerIndicator = UIActivityIndicatorView(style: .whiteLarge) spinnerIndicator.center = CGPoint(x: 135.0, y: 65.5) spinnerIndicator.color = ColorUtil.theme.fontColor spinnerIndicator.startAnimating() alertController?.view.addSubview(spinnerIndicator) self.present(alertController!, animated: true, completion: nil) session = (UIApplication.shared.delegate as! AppDelegate).session do { let name = toReplyTo is RMessage ? (toReplyTo as! RMessage).getId() : toReplyTo is RComment ? (toReplyTo as! RComment).getId() : (toReplyTo as! RSubmission).getId() try self.session?.editCommentOrLink(name, newBody: body.text, completion: { (_) in self.getSubmissionEdited(name) }) } catch { print((error as NSError).description) } } else { alertController = UIAlertController(title: "Posting submission...\n\n\n", message: nil, preferredStyle: .alert) let spinnerIndicator = UIActivityIndicatorView(style: .whiteLarge) spinnerIndicator.center = CGPoint(x: 135.0, y: 65.5) spinnerIndicator.color = ColorUtil.theme.fontColor spinnerIndicator.startAnimating() alertController?.view.addSubview(spinnerIndicator) self.present(alertController!, animated: true, completion: nil) session = (UIApplication.shared.delegate as! AppDelegate).session do { if type == .SUBMIT_TEXT { try self.session?.submitText(Subreddit.init(subreddit: subreddit.text), title: title.text, text: body.text ?? "", sendReplies: replies!.isSelected, captcha: "", captchaIden: "", flairID: self.selectedFlair, completion: { (result) -> Void in switch result { case .failure(let error): print(error.description) self.submissionCallback(nil, error) case .success(let submission): if let string = self.getIDString(submission).value { self.getSubmissionEdited(string) } else { self.errorText = self.getError(submission) self.submissionCallback(nil, nil) } } }) } else { try self.session?.submitLink(Subreddit.init(subreddit: subreddit.text), title: title.text, URL: body.text, sendReplies: replies!.isSelected, captcha: "", captchaIden: "", flairID: self.selectedFlair, completion: { (result) -> Void in switch result { case .failure(let error): print(error.description) self.submissionCallback(nil, error) case .success(let submission): if let string = self.getIDString(submission).value { self.getSubmissionEdited(string) } else { self.errorText = self.getError(submission) self.submissionCallback(nil, nil) } } }) } } catch { print((error as NSError).description) } } } func crosspost() { let title = text![0] let subreddit = text![1] let cLink = toReplyTo as! RSubmission if title.text.isEmpty() { BannerUtil.makeBanner(text: "Title cannot be empty", color: GMColor.red500Color(), seconds: 5, context: self, top: true) return } if subreddit.text.isEmpty() { BannerUtil.makeBanner(text: "Subreddit cannot be empty", color: GMColor.red500Color(), seconds: 5, context: self, top: true) return } alertController = UIAlertController(title: "Crossposting...\n\n\n", message: nil, preferredStyle: .alert) let spinnerIndicator = UIActivityIndicatorView(style: .whiteLarge) spinnerIndicator.center = CGPoint(x: 135.0, y: 65.5) spinnerIndicator.color = ColorUtil.theme.fontColor spinnerIndicator.startAnimating() alertController?.view.addSubview(spinnerIndicator) self.present(alertController!, animated: true, completion: nil) session = (UIApplication.shared.delegate as! AppDelegate).session do { try (UIApplication.shared.delegate as! AppDelegate).session?.crosspost(Link.init(id: cLink.id), subreddit: subreddit.text, newTitle: title.text) { result in switch result { case .failure(let error): print(error.description) self.submissionCallback(nil, error) case .success(let submission): if let string = self.getIDString(submission).value { self.getSubmissionEdited(string) } else { self.errorText = self.getError(submission) self.submissionCallback(nil, nil) } } } } catch { } } func submitMessage() { let body: String let user: String let title: String if self.type == .REPLY_MESSAGE { body = text![text!.count - 1].text title = "" user = "" if body.isEmpty() { BannerUtil.makeBanner(text: "Body cannot be empty", color: GMColor.red500Color(), seconds: 5, context: self, top: true) return } } else { title = text![0].text user = text![1].text body = text![2].text if title.isEmpty() { BannerUtil.makeBanner(text: "Title cannot be empty", color: GMColor.red500Color(), seconds: 5, context: self, top: true) return } if user.isEmpty() { BannerUtil.makeBanner(text: "Recipient cannot be empty", color: GMColor.red500Color(), seconds: 5, context: self, top: true) return } if body.isEmpty() { BannerUtil.makeBanner(text: "Body cannot be empty", color: GMColor.red500Color(), seconds: 5, context: self, top: true) return } } alertController = UIAlertController(title: "Sending message...\n\n\n", message: nil, preferredStyle: .alert) let spinnerIndicator = UIActivityIndicatorView(style: .whiteLarge) spinnerIndicator.center = CGPoint(x: 135.0, y: 65.5) spinnerIndicator.color = ColorUtil.theme.fontColor spinnerIndicator.startAnimating() alertController?.view.addSubview(spinnerIndicator) self.present(alertController!, animated: true, completion: nil) session = (UIApplication.shared.delegate as! AppDelegate).session if type == .NEW_MESSAGE { do { try self.session?.composeMessage(user, subject: title, text: body, completion: { (result) in switch result { case .failure(let error): print(error.description) self.messageCallback(nil, error) case .success(let message): self.messageCallback(message, nil) } }) } catch { print((error as NSError).description) } } else { do { let name = toReplyTo!.getIdentifier() try self.session?.replyMessage(body, parentName: name, completion: { (result) -> Void in switch result { case .failure(let error): print(error.description) self.messageCallback(nil, error) case .success(let comment): self.messageCallback(comment, nil) } }) } catch { print((error as NSError).description) } } } func submitComment() { let body = text!.last! alertController = UIAlertController(title: "Posting comment...\n\n\n", message: nil, preferredStyle: .alert) let spinnerIndicator = UIActivityIndicatorView(style: .whiteLarge) spinnerIndicator.center = CGPoint(x: 135.0, y: 65.5) spinnerIndicator.color = ColorUtil.theme.fontColor spinnerIndicator.startAnimating() alertController?.view.addSubview(spinnerIndicator) self.present(alertController!, animated: true, completion: nil) session = (UIApplication.shared.delegate as! AppDelegate).session do { let name = toReplyTo!.getIdentifier() try self.session?.postComment(body.text, parentName: name, completion: { (result) -> Void in switch result { case .failure(let error): print(error.description) self.commentReplyCallback(nil, error) case .success(let comment): self.checkSticky(comment) } }) } catch { print((error as NSError).description) } } func checkSticky(_ comment: Comment) { DispatchQueue.main.async { if self.sticky != nil && self.sticky!.isSelected { do { try self.session?.distinguish(comment.getId(), how: "yes", sticky: true, completion: { (_) -> Void in var newComment = comment newComment.stickied = true newComment.distinguished = .moderator self.checkReplies(newComment) }) } catch { self.checkReplies(comment) } } else { self.checkReplies(comment) } } } func checkReplies(_ comment: Comment) { DispatchQueue.main.async { if self.replies != nil && !self.replies!.isSelected { do { try self.session?.setReplies(false, name: comment.getId(), completion: { (_) in self.commentReplyCallback(comment, nil) }) } catch { self.commentReplyCallback(comment, nil) } } else { self.commentReplyCallback(comment, nil) } } } @objc func send(_ sender: AnyObject) { switch type { case .SUBMIT_IMAGE: fallthrough case .SUBMIT_LINK: fallthrough case .SUBMIT_TEXT: fallthrough case .EDIT_SELFTEXT: submitLink() case .REPLY_SUBMISSION: submitComment() case .NEW_MESSAGE: fallthrough case .REPLY_MESSAGE: submitMessage() case .CROSSPOST: crosspost() } } func getIDString(_ json: JSONAny) -> reddift.Result<String> { if let json = json as? JSONDictionary { if let j = json["json"] as? JSONDictionary { if let data = j["data"] as? JSONDictionary { if let iden = data["id"] as? String { return Result(value: iden) } } } } return Result(error: ReddiftError.identifierOfCAPTCHAIsMalformed as NSError) } func getError(_ json: JSONAny) -> String { if let json = json as? JSONDictionary { if let j = json["json"] as? JSONDictionary { if let data = j["errors"] as? JSONArray { if let iden = data[0] as? JSONArray { if iden.count >= 2 { return "\(iden[0]): \(iden[1])" } else { return "\(iden[0])" } } } } } return "" } @objc func dismiss(_ sender: AnyObject) { self.dismiss(animated: true, completion: nil) } } extension UIView { func embedInScrollView() -> UIView { let cont = UIScrollView() self.translatesAutoresizingMaskIntoConstraints = false cont.translatesAutoresizingMaskIntoConstraints = false cont.addSubview(self) cont.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[innerView]|", options: NSLayoutConstraint.FormatOptions(rawValue: 0), metrics: nil, views: ["innerView": self])) cont.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[innerView]|", options: NSLayoutConstraint.FormatOptions(rawValue: 0), metrics: nil, views: ["innerView": self])) cont.addConstraint(NSLayoutConstraint(item: self, attribute: .width, relatedBy: .equal, toItem: cont, attribute: .width, multiplier: 1.0, constant: 0)) return cont } } extension UITextView: UITextViewDelegate { // Placeholder text var placeholder: String? { get { // Get the placeholder text from the label var placeholderText: String? if let placeHolderLabel = self.viewWithTag(100) as? UILabel { placeholderText = placeHolderLabel.text } return placeholderText } set { // Store the placeholder text in the label let placeHolderLabel = self.viewWithTag(100) as! UILabel? if placeHolderLabel == nil { // Add placeholder label to text view self.addPlaceholderLabel(placeholderText: newValue!) } else { placeHolderLabel?.text = newValue placeHolderLabel?.sizeToFit() } } } // Hide the placeholder label if there is no text // in the text viewotherwise, show the label public func textViewDidChange(_ textView: UITextView) { /* maybe... let placeHolderLabel = self.viewWithTag(100) UIView.animate(withDuration: 0.15, delay: 0.0, options: UIViewAnimationOptions.curveEaseOut, animations: { if !self.hasText { // Get the placeholder label placeHolderLabel?.alpha = 1 } else { placeHolderLabel?.alpha = 0 } }, completion: { finished in })*/ } // Add a placeholder label to the text view func addPlaceholderLabel(placeholderText: String) { // Create the label and set its properties let placeholderLabel = UILabel() let placeholderImage = placeholderText.startsWith("[") ? placeholderText.substring(1, length: placeholderText.indexOf("]")! - 1) : "" var text = placeholderText if !placeholderImage.isEmpty { text = text.substring(placeholderText.indexOf("]")! + 1, length: text.length - placeholderText.indexOf("]")! - 1) } placeholderLabel.text = " " + text placeholderLabel.font = UIFont.systemFont(ofSize: 14) placeholderLabel.textColor = ColorUtil.accentColorForSub(sub: "").withAlphaComponent(0.8) placeholderLabel.tag = 100 if !placeholderImage.isEmpty { placeholderLabel.addImage(imageName: placeholderImage) } placeholderLabel.sizeToFit() placeholderLabel.frame.origin.x += 10 placeholderLabel.frame.origin.y += 4 // Hide the label if there is text in the text view placeholderLabel.isHidden = ((self.text.length) > 0) self.addSubview(placeholderLabel) self.delegate = self } } public class UIStateButton: UIButton { var color = UIColor.white override open var isSelected: Bool { didSet { backgroundColor = isSelected ? color : ColorUtil.theme.foregroundColor self.layer.borderColor = color .cgColor self.layer.borderWidth = isSelected ? CGFloat(0) : CGFloat(2) } } }
apache-2.0
628b80a74cf346f8a1bd920f8ff194d9
44.536424
260
0.535565
5.105711
false
false
false
false
mitochrome/complex-gestures-demo
apps/GestureRecognizer/Carthage/Checkouts/RxSwift/RxSwift/Observables/ShareReplayScope.swift
53
15843
// // ShareReplayScope.swift // RxSwift // // Created by Krunoslav Zaher on 5/28/17. // Copyright © 2017 Krunoslav Zaher. All rights reserved. // /// Subject lifetime scope public enum SubjectLifetimeScope { /** **Each connection will have it's own subject instance to store replay events.** **Connections will be isolated from each another.** Configures the underlying implementation to behave equivalent to. ``` source.multicast(makeSubject: { MySubject() }).refCount() ``` **This is the recommended default.** This has the following consequences: * `retry` or `concat` operators will function as expected because terminating the sequence will clear internal state. * Each connection to source observable sequence will use it's own subject. * When the number of subscribers drops from 1 to 0 and connection to source sequence is disposed, subject will be cleared. ``` let xs = Observable.deferred { () -> Observable<TimeInterval> in print("Performing work ...") return Observable.just(Date().timeIntervalSince1970) } .share(replay: 1, scope: .whileConnected) _ = xs.subscribe(onNext: { print("next \($0)") }, onCompleted: { print("completed\n") }) _ = xs.subscribe(onNext: { print("next \($0)") }, onCompleted: { print("completed\n") }) _ = xs.subscribe(onNext: { print("next \($0)") }, onCompleted: { print("completed\n") }) ``` Notice how time interval is different and `Performing work ...` is printed each time) ``` Performing work ... next 1495998900.82141 completed Performing work ... next 1495998900.82359 completed Performing work ... next 1495998900.82444 completed ``` */ case whileConnected /** **One subject will store replay events for all connections to source.** **Connections won't be isolated from each another.** Configures the underlying implementation behave equivalent to. ``` source.multicast(MySubject()).refCount() ``` This has the following consequences: * Using `retry` or `concat` operators after this operator usually isn't advised. * Each connection to source observable sequence will share the same subject. * After number of subscribers drops from 1 to 0 and connection to source observable sequence is dispose, this operator will continue holding a reference to the same subject. If at some later moment a new observer initiates a new connection to source it can potentially receive some of the stale events received during previous connection. * After source sequence terminates any new observer will always immediatelly receive replayed elements and terminal event. No new subscriptions to source observable sequence will be attempted. ``` let xs = Observable.deferred { () -> Observable<TimeInterval> in print("Performing work ...") return Observable.just(Date().timeIntervalSince1970) } .share(replay: 1, scope: .forever) _ = xs.subscribe(onNext: { print("next \($0)") }, onCompleted: { print("completed\n") }) _ = xs.subscribe(onNext: { print("next \($0)") }, onCompleted: { print("completed\n") }) _ = xs.subscribe(onNext: { print("next \($0)") }, onCompleted: { print("completed\n") }) ``` Notice how time interval is the same, replayed, and `Performing work ...` is printed only once ``` Performing work ... next 1495999013.76356 completed next 1495999013.76356 completed next 1495999013.76356 completed ``` */ case forever } extension ObservableType { /** Returns an observable sequence that **shares a single subscription to the underlying sequence**, and immediately upon subscription replays elements in buffer. This operator is equivalent to: * `.whileConnected` ``` // Each connection will have it's own subject instance to store replay events. // Connections will be isolated from each another. source.multicast(makeSubject: { Replay.create(bufferSize: replay) }).refCount() ``` * `.forever` ``` // One subject will store replay events for all connections to source. // Connections won't be isolated from each another. source.multicast(Replay.create(bufferSize: replay)).refCount() ``` It uses optimized versions of the operators for most common operations. - parameter replay: Maximum element count of the replay buffer. - parameter scope: Lifetime scope of sharing subject. For more information see `SubjectLifetimeScope` enum. - seealso: [shareReplay operator on reactivex.io](http://reactivex.io/documentation/operators/replay.html) - returns: An observable sequence that contains the elements of a sequence produced by multicasting the source sequence. */ public func share(replay: Int = 0, scope: SubjectLifetimeScope) -> Observable<E> { switch scope { case .forever: switch replay { case 0: return self.multicast(PublishSubject()).refCount() default: return shareReplay(replay) } case .whileConnected: switch replay { case 0: return ShareWhileConnected(source: self.asObservable()) case 1: return ShareReplay1WhileConnected(source: self.asObservable()) default: return self.multicast(makeSubject: { ReplaySubject.create(bufferSize: replay) }).refCount() } } } } extension ObservableType { /** Returns an observable sequence that shares a single subscription to the underlying sequence, and immediately upon subscription replays latest element in buffer. This operator is a specialization of replay which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed. Unlike `shareReplay(bufferSize: Int)`, this operator will clear latest element from replay buffer in case number of subscribers drops from one to zero. In case sequence completes or errors out replay buffer is also cleared. - seealso: [shareReplay operator on reactivex.io](http://reactivex.io/documentation/operators/replay.html) - returns: An observable sequence that contains the elements of a sequence produced by multicasting the source sequence. */ public func shareReplayLatestWhileConnected() -> Observable<E> { return ShareReplay1WhileConnected(source: self.asObservable()) } } extension ObservableType { /** Returns an observable sequence that shares a single subscription to the underlying sequence, and immediately upon subscription replays maximum number of elements in buffer. This operator is a specialization of replay which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed. - seealso: [shareReplay operator on reactivex.io](http://reactivex.io/documentation/operators/replay.html) - parameter bufferSize: Maximum element count of the replay buffer. - returns: An observable sequence that contains the elements of a sequence produced by multicasting the source sequence. */ public func shareReplay(_ bufferSize: Int) -> Observable<E> { return self.replay(bufferSize).refCount() } } fileprivate final class ShareReplay1WhileConnectedConnection<Element> : ObserverType , SynchronizedUnsubscribeType { typealias E = Element typealias Observers = AnyObserver<Element>.s typealias DisposeKey = Observers.KeyType typealias Parent = ShareReplay1WhileConnected<Element> private let _parent: Parent private let _subscription = SingleAssignmentDisposable() private let _lock: RecursiveLock private var _disposed: Bool = false fileprivate var _observers = Observers() fileprivate var _element: Element? init(parent: Parent, lock: RecursiveLock) { _parent = parent _lock = lock #if TRACE_RESOURCES _ = Resources.incrementTotal() #endif } final func on(_ event: Event<E>) { _lock.lock() let observers = _synchronized_on(event) _lock.unlock() dispatch(observers, event) } final private func _synchronized_on(_ event: Event<E>) -> Observers { if _disposed { return Observers() } switch event { case .next(let element): _element = element return _observers case .error, .completed: let observers = _observers self._synchronized_dispose() return observers } } final func connect() { _subscription.setDisposable(_parent._source.subscribe(self)) } final func _synchronized_subscribe<O : ObserverType>(_ observer: O) -> Disposable where O.E == Element { _lock.lock(); defer { _lock.unlock() } if let element = _element { observer.on(.next(element)) } let disposeKey = _observers.insert(observer.on) return SubscriptionDisposable(owner: self, key: disposeKey) } final private func _synchronized_dispose() { _disposed = true if _parent._connection === self { _parent._connection = nil } _observers = Observers() } final func synchronizedUnsubscribe(_ disposeKey: DisposeKey) { _lock.lock() let shouldDisconnect = _synchronized_unsubscribe(disposeKey) _lock.unlock() if shouldDisconnect { _subscription.dispose() } } @inline(__always) final private func _synchronized_unsubscribe(_ disposeKey: DisposeKey) -> Bool { // if already unsubscribed, just return if self._observers.removeKey(disposeKey) == nil { return false } if _observers.count == 0 { _synchronized_dispose() return true } return false } #if TRACE_RESOURCES deinit { _ = Resources.decrementTotal() } #endif } // optimized version of share replay for most common case final fileprivate class ShareReplay1WhileConnected<Element> : Observable<Element> { fileprivate typealias Connection = ShareReplay1WhileConnectedConnection<Element> fileprivate let _source: Observable<Element> fileprivate let _lock = RecursiveLock() fileprivate var _connection: Connection? init(source: Observable<Element>) { self._source = source } override func subscribe<O : ObserverType>(_ observer: O) -> Disposable where O.E == E { _lock.lock() let connection = _synchronized_subscribe(observer) let count = connection._observers.count let disposable = connection._synchronized_subscribe(observer) _lock.unlock() if count == 0 { connection.connect() } return disposable } @inline(__always) private func _synchronized_subscribe<O : ObserverType>(_ observer: O) -> Connection where O.E == E { let connection: Connection if let existingConnection = _connection { connection = existingConnection } else { connection = ShareReplay1WhileConnectedConnection<Element>( parent: self, lock: _lock) _connection = connection } return connection } } fileprivate final class ShareWhileConnectedConnection<Element> : ObserverType , SynchronizedUnsubscribeType { typealias E = Element typealias Observers = AnyObserver<Element>.s typealias DisposeKey = Observers.KeyType typealias Parent = ShareWhileConnected<Element> private let _parent: Parent private let _subscription = SingleAssignmentDisposable() private let _lock: RecursiveLock private var _disposed: Bool = false fileprivate var _observers = Observers() init(parent: Parent, lock: RecursiveLock) { _parent = parent _lock = lock #if TRACE_RESOURCES _ = Resources.incrementTotal() #endif } final func on(_ event: Event<E>) { _lock.lock() let observers = _synchronized_on(event) _lock.unlock() dispatch(observers, event) } final private func _synchronized_on(_ event: Event<E>) -> Observers { if _disposed { return Observers() } switch event { case .next: return _observers case .error, .completed: let observers = _observers self._synchronized_dispose() return observers } } final func connect() { _subscription.setDisposable(_parent._source.subscribe(self)) } final func _synchronized_subscribe<O : ObserverType>(_ observer: O) -> Disposable where O.E == Element { _lock.lock(); defer { _lock.unlock() } let disposeKey = _observers.insert(observer.on) return SubscriptionDisposable(owner: self, key: disposeKey) } final private func _synchronized_dispose() { _disposed = true if _parent._connection === self { _parent._connection = nil } _observers = Observers() } final func synchronizedUnsubscribe(_ disposeKey: DisposeKey) { _lock.lock() let shouldDisconnect = _synchronized_unsubscribe(disposeKey) _lock.unlock() if shouldDisconnect { _subscription.dispose() } } @inline(__always) final private func _synchronized_unsubscribe(_ disposeKey: DisposeKey) -> Bool { // if already unsubscribed, just return if self._observers.removeKey(disposeKey) == nil { return false } if _observers.count == 0 { _synchronized_dispose() return true } return false } #if TRACE_RESOURCES deinit { _ = Resources.decrementTotal() } #endif } // optimized version of share replay for most common case final fileprivate class ShareWhileConnected<Element> : Observable<Element> { fileprivate typealias Connection = ShareWhileConnectedConnection<Element> fileprivate let _source: Observable<Element> fileprivate let _lock = RecursiveLock() fileprivate var _connection: Connection? init(source: Observable<Element>) { self._source = source } override func subscribe<O : ObserverType>(_ observer: O) -> Disposable where O.E == E { _lock.lock() let connection = _synchronized_subscribe(observer) let count = connection._observers.count let disposable = connection._synchronized_subscribe(observer) _lock.unlock() if count == 0 { connection.connect() } return disposable } @inline(__always) private func _synchronized_subscribe<O : ObserverType>(_ observer: O) -> Connection where O.E == E { let connection: Connection if let existingConnection = _connection { connection = existingConnection } else { connection = ShareWhileConnectedConnection<Element>( parent: self, lock: _lock) _connection = connection } return connection } }
mit
7fd1ddd5d850cd63539d5a269349d55b
30.939516
281
0.642911
5.029206
false
false
false
false
plutoless/fgo-pluto
FgoPluto/FgoPluto/extensions/UIView.swift
1
1959
// // UIView.swift // FgoPluto // // Created by Zhang, Qianze on 10/10/2017. // Copyright © 2017 Plutoless Studio. All rights reserved. // import Foundation import UIKit typealias GradientPoints = (startPoint: CGPoint, endPoint: CGPoint) enum GradientOrientation { case topRightBottomLeft case topLeftBottomRight case horizontal case vertical var startPoint : CGPoint { return points.startPoint } var endPoint : CGPoint { return points.endPoint } var points : GradientPoints { get { switch(self) { case .topRightBottomLeft: return (CGPoint(x: 0.0,y: 1.0), CGPoint(x: 1.0,y: 0.0)) case .topLeftBottomRight: return (CGPoint(x: 0.0,y: 0.0), CGPoint(x: 1,y: 1)) case .horizontal: return (CGPoint(x: 0.0,y: 0.5), CGPoint(x: 1.0,y: 0.5)) case .vertical: return (CGPoint(x: 0.0,y: 0.0), CGPoint(x: 0.0,y: 1.0)) } } } } extension UIView { func applyShadow(){ self.layer.shadowOffset = CGSize(width: 0, height: 0) self.layer.shadowRadius = 5.0 self.layer.shadowOpacity = 0.2 } func applyGradient(withColours colours: [UIColor], locations: [NSNumber]? = nil) -> CAGradientLayer { let gradient = CAGradientLayer() gradient.frame = self.bounds gradient.colors = colours.map { $0.cgColor } gradient.locations = locations return gradient } func applyGradient(withColours colours: [UIColor], gradientOrientation orientation: GradientOrientation) -> Void { let gradient = CAGradientLayer() gradient.frame = self.bounds gradient.colors = colours.map { $0.cgColor } gradient.startPoint = orientation.startPoint gradient.endPoint = orientation.endPoint self.layer.insertSublayer(gradient, at: 0) } }
apache-2.0
e973f96a16b3574860efed0dc6ba38da
28.223881
118
0.602656
4.096234
false
false
false
false
mrdepth/EVEUniverse
Neocom/Neocom/Database/TypesSearch.swift
2
3661
// // TypesSearch.swift // Neocom // // Created by Artem Shimanski on 11/28/19. // Copyright © 2019 Artem Shimanski. All rights reserved. // import SwiftUI import Combine import Expressible import CoreData struct TypesSearch<Content: View>: View { @Environment(\.managedObjectContext) var managedObjectContext @Environment(\.backgroundManagedObjectContext) var backgroundManagedObjectContext var predicate: PredicateProtocol? = nil @Binding var searchString: String @Binding var searchResults: [FetchedResultsController<SDEInvType>.Section]? var content: () -> Content @State private var isEditing = false init(predicate: PredicateProtocol? = nil, searchString: Binding<String>, searchResults: Binding<[FetchedResultsController<SDEInvType>.Section]?>, @ViewBuilder content: @escaping () -> Content) { self.predicate = predicate _searchString = searchString _searchResults = searchResults self.content = content } func search(_ string: String) -> AnyPublisher<[FetchedResultsController<SDEInvType>.Section]?, Never> { Future<FetchedResultsController<NSDictionary>?, Never> { promise in self.backgroundManagedObjectContext.perform { let string = string.trimmingCharacters(in: .whitespacesAndNewlines) if string.isEmpty { promise(.success(nil)) } else { var request = self.backgroundManagedObjectContext.from(SDEInvType.self) if let predicate = self.predicate { request = request.filter(predicate) } request = request.filter((/\SDEInvType.typeName).caseInsensitive.contains(string)) let controller = request.sort(by: \SDEInvType.metaGroup?.metaGroupID, ascending: true) .sort(by: \SDEInvType.metaLevel, ascending: true) .sort(by: \SDEInvType.typeName, ascending: true) .select([(/\SDEInvType.self).as(NSManagedObjectID.self, name: "objectID"), (/\SDEInvType.metaGroup?.metaGroupID).as(Int.self, name: "metaGroupID")]) .limit(100) .fetchedResultsController(sectionName: (/\SDEInvType.metaGroup?.metaGroupName).as(Int.self, name: "metaGroupID")) try? controller.performFetch() promise(.success(FetchedResultsController(controller))) } } }.receive(on: RunLoop.main).map { controller in controller?.sections.map{ section in FetchedResultsController<SDEInvType>.Section(name: section.name, objects: section.objects .compactMap{$0["objectID"] as? NSManagedObjectID} .compactMap {self.managedObjectContext.object(with: $0) as? SDEInvType}) } }.eraseToAnyPublisher() } var body: some View { SearchList(text: $searchString, results: $searchResults, isEditing: $isEditing, search: search, content: content) .listStyle(GroupedListStyle()) .overlay(searchResults?.isEmpty == true ? Text(RuntimeError.noResult) : nil) } } #if DEBUG struct TypesSearch_Previews: PreviewProvider { static var previews: some View { NavigationView { TypeCategories() } .modifier(ServicesViewModifier.testModifier()) } } #endif
lgpl-2.1
84839044b0c5c8944194d4a6f236c64d
43.634146
198
0.599727
5.545455
false
false
false
false
kristopherjohnson/kjchess
kjchess/Position.swift
1
10495
// // Position.swift // kjchess // // Copyright © 2017 Kristopher Johnson. All rights reserved. // /// A chess position. /// /// Contains the current board layout, the player to move, /// and complete history of moves. public struct Position { /// Information needed to undo a move applied to a Position. public struct MoveDelta { let move: Move let enPassantCaptureLocation: Location? let halfmoveClock: Int let moveNumber: Int let castlingOptions: CastlingOptions } // Important: When data members are added, be sure to update func ==() // at the bottom of this file. public fileprivate(set) var board: Board public fileprivate(set) var toMove: Player /// En-passant target square /// /// Set whenever previous move was a two-square pawn move. /// /// This is set even if there is no pawn in position to make the en-passant capture. public fileprivate(set) var enPassantCaptureLocation: Location? /// Number of halfmoves since the last capture or pawn advance. public fileprivate(set) var halfmoveClock: Int /// The number of the full move. /// /// Incremented after Black's move. public fileprivate(set) var moveNumber: Int // These flags are false if the associated king or rook has been moved. // Their states do not reflect whether a castling move is legal based // upon piece locations. public fileprivate(set) var castlingOptions: CastlingOptions public var whiteCanCastleKingside: Bool { return castlingOptions.contains(.whiteCanCastleKingside) } public var whiteCanCastleQueenside: Bool { return castlingOptions.contains(.whiteCanCastleQueenside) } public var blackCanCastleKingside: Bool { return castlingOptions.contains(.blackCanCastleKingside) } public var blackCanCastleQueenside: Bool { return castlingOptions.contains(.blackCanCastleQueenside) } /// Initializer. public init(board: Board, toMove: Player, enPassantCaptureLocation: Location? = nil, castlingOptions: CastlingOptions = CastlingOptions.all, halfmoveClock: Int = 0, moveNumber: Int = 1) { self.board = board self.toMove = toMove self.enPassantCaptureLocation = enPassantCaptureLocation self.castlingOptions = castlingOptions self.halfmoveClock = halfmoveClock self.moveNumber = moveNumber } /// Return position for the start of a new game. public static func newGame() -> Position { return Position(board: Board.newGame, toMove: .white) } /// Return new position after applying a move. public func after(_ move: Move) -> Position { var newPosition = self _ = newPosition.apply(move) return newPosition } /// Apply a move to a position, mutating it. /// /// - returns: A `MoveDelta` that can be used to `unapply()` the move. public mutating func apply(_ move: Move) -> MoveDelta { assert(move.player == toMove) let delta = MoveDelta(move: move, enPassantCaptureLocation: enPassantCaptureLocation, halfmoveClock: halfmoveClock, moveNumber: moveNumber, castlingOptions: castlingOptions) board.apply(move) toMove = toMove.opponent enPassantCaptureLocation = enPassantCaptureLocation(after: move) castlingOptions = castlingOptions(after: move) halfmoveClock = halfmoveClock(after: move) moveNumber = moveNumber(after: move) return delta } /// Undo a move, mutating this position. /// /// Results are undefined if the given delta is not for the /// last move applied to the board. public mutating func unapply(_ delta: MoveDelta) { board.unapply(delta.move) toMove = delta.move.player enPassantCaptureLocation = delta.enPassantCaptureLocation castlingOptions = delta.castlingOptions halfmoveClock = delta.halfmoveClock moveNumber = delta.moveNumber } /// Determine new value for the `castlingOptions` property after a move. private func castlingOptions(after move: Move) -> CastlingOptions { var newCastlingOptions = castlingOptions switch move.piece { case WK: newCastlingOptions.remove(.whiteCanCastleKingside) newCastlingOptions.remove(.whiteCanCastleQueenside) case BK: newCastlingOptions.remove(.blackCanCastleKingside) newCastlingOptions.remove(.blackCanCastleQueenside) case WR: if move.from == a1 { newCastlingOptions.remove(.whiteCanCastleQueenside) } else if move.from == h1 { newCastlingOptions.remove(.whiteCanCastleKingside) } case BR: if move.from == a8 { newCastlingOptions.remove(.blackCanCastleQueenside) } else if move.from == h8 { newCastlingOptions.remove(.blackCanCastleKingside) } default: break } return newCastlingOptions } /// If move is a two-square pawn move, return the square behind the move destination. /// /// - returns: `Location` behind the moved pawn, or `nil` if not a two-square pawn move. private func enPassantCaptureLocation(after move: Move) -> Location? { switch move.piece { case BP: let from = move.from let to = move.to if from.rank == 6 && to.rank == 4 { return Location(to.file, to.rank + 1) } case WP: let from = move.from let to = move.to if from.rank == 1 && to.rank == 3 { return Location(to.file, to.rank - 1) } default: break } return nil } /// Determine value of halfmove clock after given move. /// /// Resets to zero if move is a capture or pawn advance. /// Otherwise increments by 1. private func halfmoveClock(after move: Move) -> Int { return (move.isCapture || move.piece.kind == .pawn) ? 0 : self.halfmoveClock + 1 } /// Determine value of full move number after given move. /// /// Increments after Black's move. private func moveNumber(after move: Move) -> Int { return (move.player == .black) ? self.moveNumber + 1 : self.moveNumber } } // MARK:- Equatable extension Position: Equatable {} public func ==(lhs: Position, rhs: Position) -> Bool { return lhs.board == rhs.board && lhs.toMove == rhs.toMove && lhs.enPassantCaptureLocation == rhs.enPassantCaptureLocation && lhs.whiteCanCastleKingside == rhs.whiteCanCastleKingside && lhs.whiteCanCastleQueenside == rhs.whiteCanCastleQueenside && lhs.blackCanCastleKingside == rhs.blackCanCastleKingside && lhs.blackCanCastleQueenside == rhs.blackCanCastleQueenside && lhs.halfmoveClock == rhs.halfmoveClock && lhs.moveNumber == rhs.moveNumber } extension Position { // MARK:- FEN /// Return FEN record for the position. public var fen: String { return [ board.fen, fenPlayerToMove, fenCastlingOptions, fenEnPassantCaptureLocation, fenHalfmoveClock, fenMoveNumber ].joined(separator: " ") } /// Initialize from a FEN (Forsyth-Edwards Notation) record. public init(fen: String) throws { let tokens = fen.whitespaceSeparatedTokens() if tokens.count != 6 { throw ChessError.fenStringRequiresExactlySixFields(fen: fen) } board = try Board(fenBoard: tokens[0]) toMove = try Position.playerToMove(fenPlayerToMove: tokens[1]) castlingOptions = Position.castlingOptions(fenCastlingOptions: tokens[2]) enPassantCaptureLocation = Location(tokens[3]) if let halfmoveClock = Int(tokens[4]), halfmoveClock >= 0 { self.halfmoveClock = halfmoveClock } else { throw ChessError.fenInvalidHalfmoveClock(fenHalfmoveClock: tokens[4]) } if let moveNumber = Int(tokens[5]), moveNumber > 0 { self.moveNumber = moveNumber } else { throw ChessError.fenInvalidMoveNumber(fenMoveNumber: tokens[5]) } } private var fenPlayerToMove: String { switch toMove { case .white: return "w" case .black: return "b" } } private static func playerToMove(fenPlayerToMove: String) throws -> Player { switch fenPlayerToMove { case "w": return .white case "b": return .black default: throw ChessError.fenInvalidPlayerToMove(fenPlayerToMove: fenPlayerToMove); } } private var fenCastlingOptions: String { var result = "" if whiteCanCastleKingside { result.append("K") } if whiteCanCastleQueenside { result.append("Q") } if blackCanCastleKingside { result.append("k") } if blackCanCastleQueenside { result.append("q") } if result.isEmpty { return "-" } else { return result } } private static func castlingOptions(fenCastlingOptions opts: String) -> CastlingOptions { var castlingOptions = CastlingOptions.none if opts.contains("K") { castlingOptions.insert(.whiteCanCastleKingside) } if opts.contains("Q") { castlingOptions.insert(.whiteCanCastleQueenside) } if opts.contains("k") { castlingOptions.insert(.blackCanCastleKingside) } if opts.contains("q") { castlingOptions.insert(.blackCanCastleQueenside) } return castlingOptions } private var fenEnPassantCaptureLocation: String { if let location = enPassantCaptureLocation { return location.symbol } else { return "-" } } private var fenHalfmoveClock: String { return halfmoveClock.description } private var fenMoveNumber: String { return moveNumber.description } } extension Position: CustomStringConvertible { public var description: String { return fen } }
mit
5953094db976381349aa931d029ada68
30.993902
93
0.621498
4.314967
false
false
false
false
wireapp/wire-ios-data-model
Source/Notifications/Change detection/ModifiedObjects.swift
1
2723
// // Wire // Copyright (C) 2020 Wire Swiss GmbH // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // import Foundation struct ModifiedObjects { let updated: Set<ZMManagedObject> let refreshed: Set<ZMManagedObject> let inserted: Set<ZMManagedObject> let deleted: Set<ZMManagedObject> var updatedAndRefreshed: Set<ZMManagedObject> { return updated.union(refreshed) } var allObjects: Set<ZMManagedObject> { return [updated, refreshed, inserted, deleted].reduce(Set()) { $0.union($1) } } init?(notification: Notification) { guard let userInfo = notification.userInfo as? [String: Any] else { return nil } self.init( updated: Self.extractObjects(for: NSUpdatedObjectsKey, from: userInfo), refreshed: Self.extractObjects(for: NSRefreshedObjectsKey, from: userInfo), inserted: Self.extractObjects(for: NSInsertedObjectsKey, from: userInfo), deleted: Self.extractObjects(for: NSDeletedObjectsKey, from: userInfo) ) } init( updated: Set<ZMManagedObject> = [], refreshed: Set<ZMManagedObject> = [], inserted: Set<ZMManagedObject> = [], deleted: Set<ZMManagedObject> = [] ) { self.updated = updated self.refreshed = refreshed self.inserted = inserted self.deleted = deleted } private static func extractObjects(for key: String, from userInfo: [String: Any]) -> Set<ZMManagedObject> { guard let objects = userInfo[key] else { return Set() } switch objects { case let managedObjects as Set<ZMManagedObject>: return managedObjects case let nsObjects as Set<NSObject>: NotificationDispatcher.log.warn("Unable to cast userInfo content to Set of ZMManagedObject. Is there a new entity that does not inherit form it?") let managedObjects = nsObjects.compactMap { $0 as? ZMManagedObject } return Set(managedObjects) default: assertionFailure("Unable to extract objects in userInfo") return Set() } } }
gpl-3.0
cf36168361ae7b0e1c8ee3009640fc71
34.828947
158
0.670951
4.553512
false
false
false
false
jrocha2/DynamicBG-OSX
DynamicBG-OSX/AppDelegate.swift
1
5706
// // AppDelegate.swift // DynamicBG-OSX // // Created by John Rocha on 5/15/16. // Copyright © 2016 John Rocha. All rights reserved. // import Cocoa @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { @IBOutlet weak var statusMenu: NSMenu! let statusItem = NSStatusBar.systemStatusBar().statusItemWithLength(-1) let startURL = NSBundle.mainBundle().URLForResource("startup", withExtension: "scpt") let closeURL = NSBundle.mainBundle().URLForResource("close", withExtension: "scpt") let prefURL = NSBundle.mainBundle().URLForResource("pref", withExtension: "scpt") let defaults = NSUserDefaults() var dontShowInfo = false func applicationDidFinishLaunching(aNotification: NSNotification) { let icon = NSImage(named: "spring") icon?.template = true statusItem.image = icon statusItem.menu = statusMenu let shouldStartRunning = defaults.objectForKey("shouldStartRunning") as? Bool ?? false dontShowInfo = defaults.objectForKey("dontShowInfo") as? Bool ?? false if shouldStartRunning { setDynamicBGEnabled(true) statusMenu.itemArray[0].state = NSOnState } NSWorkspace.sharedWorkspace().notificationCenter.addObserver(self, selector: #selector(applicationWillWake), name: NSWorkspaceDidWakeNotification, object: nil) NSWorkspace.sharedWorkspace().notificationCenter.addObserver(self, selector: #selector(applicationWillPowerOff), name: NSWorkspaceWillPowerOffNotification, object: nil) } func applicationWillWake(aNotification: NSNotification) { if statusMenu.itemArray[0].state == NSOnState { setDynamicBGEnabled(true) } } func applicationWillPowerOff(aNotification: NSNotification) { if statusMenu.itemArray[0].state == NSOnState { defaults.setObject(true, forKey: "shouldStartRunning") } else { defaults.setObject(false, forKey: "shouldStartRunning") } } func applicationWillTerminate(aNotification: NSNotification) { setDynamicBGEnabled(false) } @IBAction func menuClicked(sender: NSMenuItem) { if sender.state == NSOnState { sender.state = NSOffState setDynamicBGEnabled(false) } else { sender.state = NSOnState setDynamicBGEnabled(true) } } @IBAction func chooseBackground(sender: NSMenuItem) { let fileWindow = NSOpenPanel() fileWindow.allowsMultipleSelection = false fileWindow.canChooseDirectories = false fileWindow.canCreateDirectories = false fileWindow.canChooseFiles = true let selection = fileWindow.runModal() if selection == NSModalResponseOK { if let filePath = fileWindow.URL?.path { if fileWindow.URL?.pathExtension == "saver" || fileWindow.URL?.pathExtension == "qtz" { addBackground(filePath) } else { let alert = NSAlert() alert.messageText = "Error Selecting a File" alert.informativeText = "This error is most likely because the file you choose did not have a file extension of .qtz or .saver" alert.runModal() } } } } func addBackground(path: String) { // Copy file to correct folder let text = "set s to \"\(path)\"\n" + "set d to \"/Library/Screen Savers\"\n" + "do shell script \"cp -r \" & quoted form of s & \" \" & quoted form of d with administrator privileges" let script = NSAppleScript(source: text) var errors : NSDictionary? = [:] script!.executeAndReturnError(&errors) print(errors) if statusMenu.itemArray[0].state == NSOnState { setDynamicBGEnabled(false) setDynamicBGEnabled(true) } } // Open System Preferences to allow choice @IBAction func selectBackground(sender: NSMenuItem) { if !dontShowInfo { let alert = NSAlert() alert.alertStyle = .InformationalAlertStyle alert.showsSuppressionButton = true alert.messageText = "Select Background" alert.informativeText = "In order to simulate a dynamic background, please set it as your screen saver in the next screen even if you choose the option to start \"Never\"" alert.runModal() if alert.suppressionButton?.state == 0 { dontShowInfo = false } else { dontShowInfo = true defaults.setObject(true, forKey: "dontShowInfo") } } var errors : NSDictionary? = [:] let script = NSAppleScript(contentsOfURL: prefURL!, error: &errors)! script.executeAndReturnError(&errors) print(errors) statusMenu.itemArray[0].state = NSOffState setDynamicBGEnabled(false) } @IBAction func quitApplication(sender: NSMenuItem) { NSApplication.sharedApplication().terminate(self) } func setDynamicBGEnabled(bool: Bool) { var script = NSAppleScript() var errors : NSDictionary? = [:] if bool { script = NSAppleScript(contentsOfURL: startURL!, error: &errors)! } else { script = NSAppleScript(contentsOfURL: closeURL!, error: &errors)! } script.executeAndReturnError(&errors) print(errors) } }
mit
5f6b5bc6bfbbeb66f6da4cb506703dec
35.33758
183
0.611744
5.195811
false
false
false
false
lorentey/swift
test/SILGen/lifetime.swift
2
30748
// RUN: %target-swift-emit-silgen -module-name lifetime -Xllvm -sil-full-demangle -parse-as-library -primary-file %s | %FileCheck %s struct Buh<T> { var x: Int { get {} set {} } } class Ref { init() { } } struct Val { } // CHECK-LABEL: sil hidden [ossa] @$s8lifetime13local_valtypeyyF func local_valtype() { var b: Val // CHECK: [[B:%[0-9]+]] = alloc_box ${ var Val } // CHECK: [[MARKED_B:%.*]] = mark_uninitialized [var] [[B]] // CHECK: destroy_value [[MARKED_B]] // CHECK: return } // CHECK-LABEL: sil hidden [ossa] @$s8lifetime20local_valtype_branch{{[_0-9a-zA-Z]*}}F func local_valtype_branch(_ a: Bool) { var a = a // CHECK: [[A:%[0-9]+]] = alloc_box ${ var Bool } if a { return } // CHECK: cond_br // CHECK: {{bb.*:}} // CHECK: br [[EPILOG:bb[0-9]+]] var x:Int // CHECK: [[X:%[0-9]+]] = alloc_box ${ var Int } // CHECK: [[MARKED_X:%.*]] = mark_uninitialized [var] [[X]] if a { return } // CHECK: cond_br // CHECK: {{bb.*:}} // CHECK: destroy_value [[MARKED_X]] // CHECK: br [[EPILOG]] while a { // CHECK: cond_br if a { break } // CHECK: cond_br // CHECK: {{bb.*:}} // CHECK-NOT: destroy_value [[X]] // CHECK: br if a { return } // CHECK: cond_br // CHECK: {{bb.*:}} // CHECK: destroy_value [[MARKED_X]] // CHECK: br [[EPILOG]] var y:Int // CHECK: [[Y:%[0-9]+]] = alloc_box ${ var Int } // CHECK: [[MARKED_Y:%.*]] = mark_uninitialized [var] [[Y]] if a { break } // CHECK: cond_br // CHECK: {{bb.*:}} // CHECK: destroy_value [[MARKED_Y]] // CHECK-NOT: destroy_value [[MARKED_X]] // CHECK-NOT: destroy_value [[A]] // CHECK: br if a { return } // CHECK: cond_br // CHECK: {{bb.*:}} // CHECK: destroy_value [[MARKED_Y]] // CHECK: destroy_value [[MARKED_X]] // CHECK: br [[EPILOG]] if true { var z:Int // CHECK: [[Z:%[0-9]+]] = alloc_box ${ var Int } // CHECK: [[MARKED_Z:%.*]] = mark_uninitialized [var] [[Z]] if a { break } // CHECK: cond_br // CHECK: {{bb.*:}} // CHECK: destroy_value [[MARKED_Z]] // CHECK: destroy_value [[MARKED_Y]] // CHECK-NOT: destroy_value [[MARKED_X]] // CHECK-NOT: destroy_value [[A]] // CHECK: br if a { return } // CHECK: cond_br // CHECK: {{bb.*:}} // CHECK: destroy_value [[MARKED_Z]] // CHECK: destroy_value [[MARKED_Y]] // CHECK: destroy_value [[MARKED_X]] // CHECK: br [[EPILOG]] // CHECK: destroy_value [[MARKED_Z]] } if a { break } // CHECK: cond_br // CHECK: {{bb.*:}} // CHECK: destroy_value [[MARKED_Y]] // CHECK-NOT: destroy_value [[MARKED_X]] // CHECK-NOT: destroy_value [[A]] // CHECK: br // CHECK: {{bb.*:}} // CHECK: destroy_value [[MARKED_Y]] // CHECK: br } // CHECK: destroy_value [[MARKED_X]] // CHECK: [[EPILOG]]: // CHECK: return } func reftype_func() -> Ref {} func reftype_func_with_arg(_ x: Ref) -> Ref {} // CHECK-LABEL: sil hidden [ossa] @$s8lifetime14reftype_returnAA3RefCyF func reftype_return() -> Ref { return reftype_func() // CHECK: [[RF:%[0-9]+]] = function_ref @$s8lifetime12reftype_funcAA3RefCyF : $@convention(thin) () -> @owned Ref // CHECK-NOT: destroy_value // CHECK: [[RET:%[0-9]+]] = apply [[RF]]() // CHECK-NOT: destroy_value // CHECK: return [[RET]] } // CHECK-LABEL: sil hidden [ossa] @$s8lifetime11reftype_argyyAA3RefCF : $@convention(thin) (@guaranteed Ref) -> () { // CHECK: bb0([[A:%[0-9]+]] : @guaranteed $Ref): // CHECK: [[AADDR:%[0-9]+]] = alloc_box ${ var Ref } // CHECK: [[PA:%[0-9]+]] = project_box [[AADDR]] // CHECK: [[A_COPY:%.*]] = copy_value [[A]] // CHECK: store [[A_COPY]] to [init] [[PA]] // CHECK: destroy_value [[AADDR]] // CHECK-NOT: destroy_value [[A]] // CHECK: return // CHECK: } // end sil function '$s8lifetime11reftype_argyyAA3RefCF' func reftype_arg(_ a: Ref) { var a = a } // CHECK-LABEL: sil hidden [ossa] @$s8lifetime26reftype_call_ignore_returnyyF func reftype_call_ignore_return() { reftype_func() // CHECK: = function_ref @$s8lifetime12reftype_funcAA3RefCyF : $@convention(thin) () -> @owned Ref // CHECK-NEXT: [[R:%[0-9]+]] = apply // CHECK: destroy_value [[R]] // CHECK: return } // CHECK-LABEL: sil hidden [ossa] @$s8lifetime27reftype_call_store_to_localyyF func reftype_call_store_to_local() { var a = reftype_func() // CHECK: [[A:%[0-9]+]] = alloc_box ${ var Ref } // CHECK-NEXT: [[PB:%.*]] = project_box [[A]] // CHECK: = function_ref @$s8lifetime12reftype_funcAA3RefCyF : $@convention(thin) () -> @owned Ref // CHECK-NEXT: [[R:%[0-9]+]] = apply // CHECK-NOT: copy_value [[R]] // CHECK: store [[R]] to [init] [[PB]] // CHECK-NOT: destroy_value [[R]] // CHECK: destroy_value [[A]] // CHECK-NOT: destroy_value [[R]] // CHECK: return } // CHECK-LABEL: sil hidden [ossa] @$s8lifetime16reftype_call_argyyF func reftype_call_arg() { reftype_func_with_arg(reftype_func()) // CHECK: [[RF:%[0-9]+]] = function_ref @$s8lifetime12reftype_func{{[_0-9a-zA-Z]*}}F // CHECK: [[R1:%[0-9]+]] = apply [[RF]] // CHECK: [[RFWA:%[0-9]+]] = function_ref @$s8lifetime21reftype_func_with_arg{{[_0-9a-zA-Z]*}}F // CHECK: [[R2:%[0-9]+]] = apply [[RFWA]]([[R1]]) // CHECK: destroy_value [[R2]] // CHECK: return } // CHECK-LABEL: sil hidden [ossa] @$s8lifetime21reftype_call_with_arg{{[_0-9a-zA-Z]*}}F // CHECK: bb0([[A1:%[0-9]+]] : @guaranteed $Ref): // CHECK: [[AADDR:%[0-9]+]] = alloc_box ${ var Ref } // CHECK: [[PB:%.*]] = project_box [[AADDR]] // CHECK: [[A1_COPY:%.*]] = copy_value [[A1]] // CHECK: store [[A1_COPY]] to [init] [[PB]] // CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PB]] // CHECK: [[A2:%[0-9]+]] = load [copy] [[READ]] // CHECK: [[RFWA:%[0-9]+]] = function_ref @$s8lifetime21reftype_func_with_arg{{[_0-9a-zA-Z]*}}F // CHECK: [[RESULT:%.*]] = apply [[RFWA]]([[A2]]) // CHECK: destroy_value [[RESULT]] // CHECK: destroy_value [[AADDR]] // CHECK-NOT: destroy_value [[A1]] // CHECK: return func reftype_call_with_arg(_ a: Ref) { var a = a reftype_func_with_arg(a) } // CHECK-LABEL: sil hidden [ossa] @$s8lifetime16reftype_reassign{{[_0-9a-zA-Z]*}}F func reftype_reassign(_ a: inout Ref, b: Ref) { var b = b // CHECK: bb0([[AADDR:%[0-9]+]] : $*Ref, [[B1:%[0-9]+]] : @guaranteed $Ref): // CHECK: [[BADDR:%[0-9]+]] = alloc_box ${ var Ref } // CHECK: [[PBB:%.*]] = project_box [[BADDR]] a = b // CHECK: destroy_value // CHECK: return } func tuple_with_ref_elements() -> (Val, (Ref, Val), Ref) {} // CHECK-LABEL: sil hidden [ossa] @$s8lifetime28tuple_with_ref_ignore_returnyyF func tuple_with_ref_ignore_return() { tuple_with_ref_elements() // CHECK: [[FUNC:%[0-9]+]] = function_ref @$s8lifetime23tuple_with_ref_elementsAA3ValV_AA3RefC_ADtAFtyF // CHECK: [[TUPLE:%[0-9]+]] = apply [[FUNC]] // CHECK: ([[T0:%.*]], [[T1_0:%.*]], [[T1_1:%.*]], [[T2:%.*]]) = destructure_tuple [[TUPLE]] // CHECK: destroy_value [[T2]] // CHECK: destroy_value [[T1_0]] // CHECK: return } struct Aleph { var a:Ref var b:Val // -- loadable value constructor: // CHECK-LABEL: sil hidden [ossa] @$s8lifetime5AlephV{{[_0-9a-zA-Z]*}}fC : $@convention(method) (@owned Ref, Val, @thin Aleph.Type) -> @owned Aleph // CHECK: bb0([[A:%.*]] : @owned $Ref, [[B:%.*]] : $Val, {{%.*}} : $@thin Aleph.Type): // CHECK-NEXT: [[RET:%.*]] = struct $Aleph ([[A]] : {{.*}}, [[B]] : {{.*}}) // CHECK-NEXT: return [[RET]] } struct Beth { var a:Val var b:Aleph var c:Ref func gimel() {} } protocol Unloadable {} struct Daleth { var a:Aleph var b:Beth var c:Unloadable // -- address-only value constructor: // CHECK-LABEL: sil hidden [ossa] @$s8lifetime6DalethV{{[_0-9a-zA-Z]*}}fC : $@convention(method) (@owned Aleph, @owned Beth, @in Unloadable, @thin Daleth.Type) -> @out Daleth { // CHECK: bb0([[THIS:%.*]] : $*Daleth, [[A:%.*]] : @owned $Aleph, [[B:%.*]] : @owned $Beth, [[C:%.*]] : $*Unloadable, {{%.*}} : $@thin Daleth.Type): // CHECK-NEXT: [[A_ADDR:%.*]] = struct_element_addr [[THIS]] : $*Daleth, #Daleth.a // CHECK-NEXT: store [[A]] to [init] [[A_ADDR]] // CHECK-NEXT: [[B_ADDR:%.*]] = struct_element_addr [[THIS]] : $*Daleth, #Daleth.b // CHECK-NEXT: store [[B]] to [init] [[B_ADDR]] // CHECK-NEXT: [[C_ADDR:%.*]] = struct_element_addr [[THIS]] : $*Daleth, #Daleth.c // CHECK-NEXT: copy_addr [take] [[C]] to [initialization] [[C_ADDR]] // CHECK-NEXT: tuple () // CHECK-NEXT: return } class He { // -- default allocator: // CHECK-LABEL: sil hidden [exact_self_class] [ossa] @$s8lifetime2HeC{{[_0-9a-zA-Z]*}}fC : $@convention(method) (@thick He.Type) -> @owned He { // CHECK: bb0({{%.*}} : $@thick He.Type): // CHECK-NEXT: [[THIS:%.*]] = alloc_ref $He // CHECK-NEXT: // function_ref lifetime.He.init // CHECK-NEXT: [[INIT:%.*]] = function_ref @$s8lifetime2HeC{{[_0-9a-zA-Z]*}}fc : $@convention(method) (@owned He) -> @owned He // CHECK-NEXT: [[THIS1:%.*]] = apply [[INIT]]([[THIS]]) // CHECK-NEXT: return [[THIS1]] // CHECK-NEXT: } // -- default initializer: // CHECK-LABEL: sil hidden [ossa] @$s8lifetime2HeC{{[_0-9a-zA-Z]*}}fc : $@convention(method) (@owned He) -> @owned He { // CHECK: bb0([[SELF:%.*]] : @owned $He): // CHECK-NEXT: debug_value // CHECK-NEXT: [[UNINITIALIZED_SELF:%.*]] = mark_uninitialized [rootself] [[SELF]] // CHECK-NEXT: [[UNINITIALIZED_SELF_COPY:%.*]] = copy_value [[UNINITIALIZED_SELF]] // CHECK-NEXT: destroy_value [[UNINITIALIZED_SELF]] // CHECK-NEXT: return [[UNINITIALIZED_SELF_COPY]] // CHECK: } // end sil function '$s8lifetime2HeC{{[_0-9a-zA-Z]*}}fc' init() { } } struct Waw { var a:(Ref, Val) var b:Val // -- loadable value initializer with tuple destructuring: // CHECK-LABEL: sil hidden [ossa] @$s8lifetime3WawV{{[_0-9a-zA-Z]*}}fC : $@convention(method) (@owned Ref, Val, Val, @thin Waw.Type) -> @owned Waw // CHECK: bb0([[A0:%.*]] : @owned $Ref, [[A1:%.*]] : $Val, [[B:%.*]] : $Val, {{%.*}} : $@thin Waw.Type): // CHECK-NEXT: [[A:%.*]] = tuple ([[A0]] : {{.*}}, [[A1]] : {{.*}}) // CHECK-NEXT: [[RET:%.*]] = struct $Waw ([[A]] : {{.*}}, [[B]] : {{.*}}) // CHECK-NEXT: return [[RET]] } struct Zayin { var a:(Unloadable, Val) var b:Unloadable // -- address-only value initializer with tuple destructuring: // CHECK-LABEL: sil hidden [ossa] @$s8lifetime5ZayinV{{[_0-9a-zA-Z]*}}fC : $@convention(method) (@in Unloadable, Val, @in Unloadable, @thin Zayin.Type) -> @out Zayin // CHECK: bb0([[THIS:%.*]] : $*Zayin, [[A0:%.*]] : $*Unloadable, [[A1:%.*]] : $Val, [[B:%.*]] : $*Unloadable, {{%.*}} : $@thin Zayin.Type): // CHECK-NEXT: [[THIS_A_ADDR:%.*]] = struct_element_addr [[THIS]] : $*Zayin, #Zayin.a // CHECK-NEXT: [[THIS_A0_ADDR:%.*]] = tuple_element_addr [[THIS_A_ADDR]] : {{.*}}, 0 // CHECK-NEXT: [[THIS_A1_ADDR:%.*]] = tuple_element_addr [[THIS_A_ADDR]] : {{.*}}, 1 // CHECK-NEXT: copy_addr [take] [[A0]] to [initialization] [[THIS_A0_ADDR]] // CHECK-NEXT: store [[A1]] to [trivial] [[THIS_A1_ADDR]] // CHECK-NEXT: [[THIS_B_ADDR:%.*]] = struct_element_addr [[THIS]] : $*Zayin, #Zayin.b // CHECK-NEXT: copy_addr [take] [[B]] to [initialization] [[THIS_B_ADDR]] // CHECK-NEXT: tuple () // CHECK-NEXT: return } func fragile_struct_with_ref_elements() -> Beth {} // CHECK-LABEL: sil hidden [ossa] @$s8lifetime29struct_with_ref_ignore_returnyyF func struct_with_ref_ignore_return() { fragile_struct_with_ref_elements() // CHECK: [[FUNC:%[0-9]+]] = function_ref @$s8lifetime32fragile_struct_with_ref_elementsAA4BethVyF // CHECK: [[STRUCT:%[0-9]+]] = apply [[FUNC]] // CHECK: destroy_value [[STRUCT]] : $Beth // CHECK: return } // CHECK-LABEL: sil hidden [ossa] @$s8lifetime28struct_with_ref_materializedyyF func struct_with_ref_materialized() { fragile_struct_with_ref_elements().gimel() // CHECK: [[FUNC:%[0-9]+]] = function_ref @$s8lifetime32fragile_struct_with_ref_elementsAA4BethVyF // CHECK: [[STRUCT:%[0-9]+]] = apply [[FUNC]] // CHECK: [[METHOD:%[0-9]+]] = function_ref @$s8lifetime4BethV5gimel{{[_0-9a-zA-Z]*}}F // CHECK: apply [[METHOD]]([[STRUCT]]) } class RefWithProp { var int_prop: Int { get {} set {} } var aleph_prop: Aleph { get {} set {} } } // CHECK-LABEL: sil hidden [ossa] @$s8lifetime015logical_lvalue_A0yyAA11RefWithPropC_SiAA3ValVtF : $@convention(thin) (@guaranteed RefWithProp, Int, Val) -> () { func logical_lvalue_lifetime(_ r: RefWithProp, _ i: Int, _ v: Val) { var r = r var i = i var v = v // CHECK: [[RADDR:%[0-9]+]] = alloc_box ${ var RefWithProp } // CHECK: [[PR:%[0-9]+]] = project_box [[RADDR]] // CHECK: [[IADDR:%[0-9]+]] = alloc_box ${ var Int } // CHECK: [[PI:%[0-9]+]] = project_box [[IADDR]] // CHECK: store %1 to [trivial] [[PI]] // CHECK: [[VADDR:%[0-9]+]] = alloc_box ${ var Val } // CHECK: [[PV:%[0-9]+]] = project_box [[VADDR]] // -- Reference types need to be copy_valued as property method args. r.int_prop = i // CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PR]] // CHECK: [[R1:%[0-9]+]] = load [copy] [[READ]] // CHECK: [[SETTER_METHOD:%[0-9]+]] = class_method {{.*}} : $RefWithProp, #RefWithProp.int_prop!setter.1 : (RefWithProp) -> (Int) -> (), $@convention(method) (Int, @guaranteed RefWithProp) -> () // CHECK: apply [[SETTER_METHOD]]({{.*}}, [[R1]]) // CHECK: destroy_value [[R1]] r.aleph_prop.b = v // CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PR]] // CHECK: [[R2:%[0-9]+]] = load [copy] [[READ]] // CHECK: [[R2BORROW:%[0-9]+]] = begin_borrow [[R2]] // CHECK: [[MODIFY:%[0-9]+]] = class_method [[R2BORROW]] : $RefWithProp, #RefWithProp.aleph_prop!modify.1 : // CHECK: ([[ADDR:%.*]], [[TOKEN:%.*]]) = begin_apply [[MODIFY]]([[R2BORROW]]) // CHECK: end_apply [[TOKEN]] } func bar() -> Int {} class Foo<T> { var x : Int var y = (Int(), Ref()) var z : T var w = Ref() class func makeT() -> T {} // Class initializer init() { // -- allocating entry point // CHECK-LABEL: sil hidden [exact_self_class] [ossa] @$s8lifetime3FooC{{[_0-9a-zA-Z]*}}fC : // CHECK: bb0([[METATYPE:%[0-9]+]] : $@thick Foo<T>.Type): // CHECK: [[THIS:%[0-9]+]] = alloc_ref $Foo<T> // CHECK: [[INIT_METHOD:%[0-9]+]] = function_ref @$s8lifetime3FooC{{[_0-9a-zA-Z]*}}fc // CHECK: [[INIT_THIS:%[0-9]+]] = apply [[INIT_METHOD]]<{{.*}}>([[THIS]]) // CHECK: return [[INIT_THIS]] // -- initializing entry point // CHECK-LABEL: sil hidden [ossa] @$s8lifetime3FooC{{[_0-9a-zA-Z]*}}fc : // CHECK: bb0([[THISIN:%[0-9]+]] : @owned $Foo<T>): // CHECK: [[THIS:%[0-9]+]] = mark_uninitialized // -- initialization for y // CHECK: [[Y_INIT:%[0-9]+]] = function_ref @$s8lifetime3FooC1ySi_AA3RefCtvpfi : $@convention(thin) <τ_0_0> () -> (Int, @owned Ref) // CHECK: [[Y_VALUE:%[0-9]+]] = apply [[Y_INIT]]<T>() // CHECK: ([[Y_EXTRACTED_0:%.*]], [[Y_EXTRACTED_1:%.*]]) = destructure_tuple // CHECK: [[BORROWED_THIS:%.*]] = begin_borrow [[THIS]] // CHECK: [[THIS_Y:%.*]] = ref_element_addr [[BORROWED_THIS]] : {{.*}}, #Foo.y // CHECK: [[WRITE:%.*]] = begin_access [modify] [dynamic] [[THIS_Y]] : $*(Int, Ref) // CHECK: [[THIS_Y_0:%.*]] = tuple_element_addr [[WRITE]] : $*(Int, Ref), 0 // CHECK: assign [[Y_EXTRACTED_0]] to [[THIS_Y_0]] // CHECK: [[THIS_Y_1:%.*]] = tuple_element_addr [[WRITE]] : $*(Int, Ref), 1 // CHECK: assign [[Y_EXTRACTED_1]] to [[THIS_Y_1]] // CHECK: end_access [[WRITE]] : $*(Int, Ref) // CHECK: end_borrow [[BORROWED_THIS]] // -- Initialization for w // CHECK: [[Z_FUNC:%.*]] = function_ref @$s{{.*}}8lifetime3FooC1wAA3RefCvpfi : $@convention(thin) <τ_0_0> () -> @owned Ref // CHECK: [[Z_RESULT:%.*]] = apply [[Z_FUNC]]<T>() // CHECK: [[BORROWED_THIS:%.*]] = begin_borrow [[THIS]] // CHECK: [[THIS_Z:%.*]] = ref_element_addr [[BORROWED_THIS]] // CHECK: [[WRITE:%.*]] = begin_access [modify] [dynamic] [[THIS_Z]] : $*Ref // CHECK: assign [[Z_RESULT]] to [[WRITE]] // CHECK: end_borrow [[BORROWED_THIS]] // -- Initialization for x // CHECK: [[BORROWED_THIS:%.*]] = begin_borrow [[THIS]] // CHECK: [[THIS_X:%[0-9]+]] = ref_element_addr [[BORROWED_THIS]] : {{.*}}, #Foo.x // CHECK: [[WRITE:%.*]] = begin_access [modify] [dynamic] [[THIS_X]] : $*Int // CHECK: assign {{.*}} to [[WRITE]] // CHECK: end_borrow [[BORROWED_THIS]] x = bar() z = Foo<T>.makeT() // CHECK: [[FOOMETA:%[0-9]+]] = metatype $@thick Foo<T>.Type // CHECK: [[MAKET:%[0-9]+]] = class_method [[FOOMETA]] : {{.*}}, #Foo.makeT!1 // CHECK: ref_element_addr // -- cleanup this lvalue and return this // CHECK: [[THIS_RESULT:%.*]] = copy_value [[THIS]] // -- TODO: This copy should be unnecessary. // CHECK: destroy_value [[THIS]] // CHECK: return [[THIS_RESULT]] } init(chi:Int) { var chi = chi z = Foo<T>.makeT() // -- allocating entry point // CHECK-LABEL: sil hidden [exact_self_class] [ossa] @$s8lifetime3FooC{{[_0-9a-zA-Z]*}}fC : // CHECK: bb0([[CHI:%[0-9]+]] : $Int, [[METATYPE:%[0-9]+]] : $@thick Foo<T>.Type): // CHECK: [[THIS:%[0-9]+]] = alloc_ref $Foo<T> // CHECK: [[INIT_METHOD:%[0-9]+]] = function_ref @$s8lifetime3FooC{{[_0-9a-zA-Z]*}}fc // CHECK: [[INIT_THIS:%[0-9]+]] = apply [[INIT_METHOD]]<{{.*}}>([[CHI]], [[THIS]]) // CHECK: return [[INIT_THIS]] // -- initializing entry point // CHECK-LABEL: sil hidden [ossa] @$s8lifetime3FooC3chiACyxGSi_tcfc : $@convention(method) <T> (Int, @owned Foo<T>) -> @owned Foo<T> { // CHECK: bb0([[CHI:%[0-9]+]] : $Int, [[THISIN:%[0-9]+]] : @owned $Foo<T>): // CHECK: [[THIS:%[0-9]+]] = mark_uninitialized [rootself] [[THISIN]] // -- First we initialize #Foo.y. // CHECK: [[BORROWED_THIS:%.*]] = begin_borrow [[THIS]] // CHECK: [[THIS_Y:%.*]] = ref_element_addr [[BORROWED_THIS]] : $Foo<T>, #Foo.y // CHECK: [[WRITE:%.*]] = begin_access [modify] [dynamic] [[THIS_Y]] : $*(Int, Ref) // CHECK: [[THIS_Y_1:%.*]] = tuple_element_addr [[WRITE]] : $*(Int, Ref), 0 // CHECK: assign {{.*}} to [[THIS_Y_1]] : $*Int // CHECK: [[THIS_Y_2:%.*]] = tuple_element_addr [[WRITE]] : $*(Int, Ref), 1 // CHECK: assign {{.*}} to [[THIS_Y_2]] : $*Ref // CHECK: end_borrow [[BORROWED_THIS]] // -- Then we create a box that we will use to perform a copy_addr into #Foo.x a bit later. // CHECK: [[CHIADDR:%[0-9]+]] = alloc_box ${ var Int }, var, name "chi" // CHECK: [[PCHI:%[0-9]+]] = project_box [[CHIADDR]] // CHECK: store [[CHI]] to [trivial] [[PCHI]] // -- Then we initialize #Foo.z // CHECK: [[BORROWED_THIS:%.*]] = begin_borrow [[THIS]] // CHECK: [[THIS_Z:%.*]] = ref_element_addr [[BORROWED_THIS]] : {{.*}}, #Foo.z // CHECK: [[WRITE:%.*]] = begin_access [modify] [dynamic] [[THIS_Z]] : $*T // CHECK: copy_addr [take] {{.*}} to [[WRITE]] // CHECK: end_borrow [[BORROWED_THIS]] // -- Then initialize #Foo.x using the earlier stored value of CHI to THIS_Z. x = chi // CHECK: [[BORROWED_THIS:%.*]] = begin_borrow [[THIS]] // CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PCHI]] // CHECK: [[X:%.*]] = load [trivial] [[READ]] // CHECK: [[THIS_X:%[0-9]+]] = ref_element_addr [[BORROWED_THIS]] : {{.*}}, #Foo.x // CHECK: [[WRITE:%.*]] = begin_access [modify] [dynamic] [[THIS_X]] : $*Int // CHECK: assign [[X]] to [[WRITE]] // CHECK: end_borrow [[BORROWED_THIS]] // -- cleanup chi // CHECK: destroy_value [[CHIADDR]] // -- Then begin the epilogue sequence // CHECK: [[THIS_RETURN:%.*]] = copy_value [[THIS]] // CHECK: destroy_value [[THIS]] // CHECK: return [[THIS_RETURN]] // CHECK: } // end sil function '$s8lifetime3FooC3chiACyxGSi_tcfc' } // -- allocating entry point // CHECK-LABEL: sil hidden [exact_self_class] [ossa] @$s8lifetime3FooC{{[_0-9a-zA-Z]*}}fC : // CHECK: [[INIT_METHOD:%[0-9]+]] = function_ref @$s8lifetime3FooC{{[_0-9a-zA-Z]*}}fc // -- initializing entry point // CHECK-LABEL: sil hidden [ossa] @$s8lifetime3FooC{{[_0-9a-zA-Z]*}}fc : init<U:Intifiable>(chi:U) { z = Foo<T>.makeT() x = chi.intify() } // CHECK-LABEL: sil hidden [ossa] @$s8lifetime3FooCfd : $@convention(method) <T> (@guaranteed Foo<T>) -> @owned Builtin.NativeObject deinit { // CHECK: bb0([[THIS:%[0-9]+]] : @guaranteed $Foo<T>): bar() // CHECK: function_ref @$s8lifetime3barSiyF // CHECK: apply // -- don't need to destroy_value x because it's trivial // CHECK-NOT: ref_element_addr [[THIS]] : {{.*}}, #Foo.x // -- destroy_value y // CHECK: [[YADDR:%[0-9]+]] = ref_element_addr [[THIS]] : {{.*}}, #Foo.y // CHECK: destroy_addr [[YADDR]] // -- destroy_value z // CHECK: [[ZADDR:%[0-9]+]] = ref_element_addr [[THIS]] : {{.*}}, #Foo.z // CHECK: destroy_addr [[ZADDR]] // -- destroy_value w // CHECK: [[WADDR:%[0-9]+]] = ref_element_addr [[THIS]] : {{.*}}, #Foo.w // CHECK: destroy_addr [[WADDR]] // -- return back this // CHECK: [[PTR:%.*]] = unchecked_ref_cast [[THIS]] : $Foo<T> to $Builtin.NativeObject // CHECK: [[PTR_OWNED:%.*]] = unchecked_ownership_conversion [[PTR]] : $Builtin.NativeObject, @guaranteed to @owned // CHECK: return [[PTR_OWNED]] // CHECK: } // end sil function '$s8lifetime3FooCfd' } // Deallocating destructor for Foo. // CHECK-LABEL: sil hidden [ossa] @$s8lifetime3FooCfD : $@convention(method) <T> (@owned Foo<T>) -> () // CHECK: bb0([[SELF:%[0-9]+]] : @owned $Foo<T>): // CHECK: [[DESTROYING_REF:%[0-9]+]] = function_ref @$s8lifetime3FooCfd : $@convention(method) <τ_0_0> (@guaranteed Foo<τ_0_0>) -> @owned Builtin.NativeObject // CHECK-NEXT: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]] // CHECK-NEXT: [[RESULT_SELF:%[0-9]+]] = apply [[DESTROYING_REF]]<T>([[BORROWED_SELF]]) : $@convention(method) <τ_0_0> (@guaranteed Foo<τ_0_0>) -> @owned Builtin.NativeObject // CHECK-NEXT: end_borrow [[BORROWED_SELF]] // CHECK-NEXT: end_lifetime [[SELF]] // CHECK-NEXT: [[SELF:%[0-9]+]] = unchecked_ref_cast [[RESULT_SELF]] : $Builtin.NativeObject to $Foo<T> // CHECK-NEXT: dealloc_ref [[SELF]] : $Foo<T> // CHECK-NEXT: [[RESULT:%[0-9]+]] = tuple () // CHECK-NEXT: return [[RESULT]] : $() // CHECK-NEXT: } // end sil function '$s8lifetime3FooCfD' } class FooSubclass<T> : Foo<T> { // CHECK-LABEL: sil hidden [ossa] @$s8lifetime11FooSubclassCfd : $@convention(method) <T> (@guaranteed FooSubclass<T>) -> @owned Builtin.NativeObject // CHECK: bb0([[THIS:%[0-9]+]] : @guaranteed $FooSubclass<T>): // -- base dtor // CHECK: [[BASE:%[0-9]+]] = upcast [[THIS]] : ${{.*}} to $Foo<T> // CHECK: [[BASE_DTOR:%[0-9]+]] = function_ref @$s8lifetime3FooCfd : $@convention(method) <τ_0_0> (@guaranteed Foo<τ_0_0>) -> @owned Builtin.NativeObject // CHECK: [[PTR:%.*]] = apply [[BASE_DTOR]]<T>([[BASE]]) // CHECK: [[BORROWED_PTR:%.*]] = begin_borrow [[PTR]] // CHECK: end_borrow [[BORROWED_PTR]] // CHECK: return [[PTR]] deinit { bar() } } class ImplicitDtor { var x:Int var y:(Int, Ref) var w:Ref init() { } // CHECK-LABEL: sil hidden [ossa] @$s8lifetime12ImplicitDtorCfd // CHECK: bb0([[THIS:%[0-9]+]] : @guaranteed $ImplicitDtor): // -- don't need to destroy_value x because it's trivial // CHECK-NOT: ref_element_addr [[THIS]] : {{.*}}, #ImplicitDtor.x // -- destroy_value y // CHECK: [[YADDR:%[0-9]+]] = ref_element_addr [[THIS]] : {{.*}}, #ImplicitDtor.y // CHECK: destroy_addr [[YADDR]] // -- destroy_value w // CHECK: [[WADDR:%[0-9]+]] = ref_element_addr [[THIS]] : {{.*}}, #ImplicitDtor.w // CHECK: destroy_addr [[WADDR]] // CHECK: return } class ImplicitDtorDerived<T> : ImplicitDtor { var z:T init(z : T) { super.init() self.z = z } // CHECK: sil hidden [ossa] @$s8lifetime19ImplicitDtorDerivedCfd : $@convention(method) <T> (@guaranteed ImplicitDtorDerived<T>) -> @owned Builtin.NativeObject { // CHECK: bb0([[THIS:%[0-9]+]] : @guaranteed $ImplicitDtorDerived<T>): // -- base dtor // CHECK: [[BASE:%[0-9]+]] = upcast [[THIS]] : ${{.*}} to $ImplicitDtor // CHECK: [[BASE_DTOR:%[0-9]+]] = function_ref @$s8lifetime12ImplicitDtorCfd // CHECK: [[PTR:%.*]] = apply [[BASE_DTOR]]([[BASE]]) // -- destroy_value z // CHECK: [[BORROWED_PTR:%.*]] = begin_borrow [[PTR]] // CHECK: [[CAST_BORROWED_PTR:%.*]] = unchecked_ref_cast [[BORROWED_PTR]] : $Builtin.NativeObject to $ImplicitDtorDerived<T> // CHECK: [[ZADDR:%[0-9]+]] = ref_element_addr [[CAST_BORROWED_PTR]] : {{.*}}, #ImplicitDtorDerived.z // CHECK: destroy_addr [[ZADDR]] // CHECK: end_borrow [[BORROWED_PTR]] // -- epilog // CHECK-NOT: unchecked_ref_cast // CHECK-NOT: unchecked_ownership_conversion // CHECK: return [[PTR]] } class ImplicitDtorDerivedFromGeneric<T> : ImplicitDtorDerived<Int> { init() { super.init(z: 5) } // CHECK-LABEL: sil hidden [ossa] @$s8lifetime30ImplicitDtorDerivedFromGenericC{{[_0-9a-zA-Z]*}}fc // CHECK: bb0([[THIS:%[0-9]+]] : @guaranteed $ImplicitDtorDerivedFromGeneric<T>): // -- base dtor // CHECK: [[BASE:%[0-9]+]] = upcast [[THIS]] : ${{.*}} to $ImplicitDtorDerived<Int> // CHECK: [[BASE_DTOR:%[0-9]+]] = function_ref @$s8lifetime19ImplicitDtorDerivedCfd // CHECK: [[PTR:%.*]] = apply [[BASE_DTOR]]<Int>([[BASE]]) // CHECK: return [[PTR]] } protocol Intifiable { func intify() -> Int } struct Bar { var x:Int // Loadable struct initializer // CHECK-LABEL: sil hidden [ossa] @$s8lifetime3BarV{{[_0-9a-zA-Z]*}}fC init() { // CHECK: bb0([[METATYPE:%[0-9]+]] : $@thin Bar.Type): // CHECK: [[SELF_BOX:%[0-9]+]] = alloc_box ${ var Bar } // CHECK: [[MARKED_SELF_BOX:%[0-9]+]] = mark_uninitialized [rootself] [[SELF_BOX]] // CHECK: [[PB_BOX:%.*]] = project_box [[MARKED_SELF_BOX]] x = bar() // CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] [[PB_BOX]] // CHECK: [[SELF_X:%[0-9]+]] = struct_element_addr [[WRITE]] : $*Bar, #Bar.x // CHECK: assign {{.*}} to [[SELF_X]] // -- load and return this // CHECK: [[SELF_VAL:%[0-9]+]] = load [trivial] [[PB_BOX]] // CHECK: destroy_value [[MARKED_SELF_BOX]] // CHECK: return [[SELF_VAL]] } init<T:Intifiable>(xx:T) { x = xx.intify() } } struct Bas<T> { var x:Int var y:T // Address-only struct initializer // CHECK-LABEL: sil hidden [ossa] @$s8lifetime3BasV{{[_0-9a-zA-Z]*}}fC init(yy:T) { // CHECK: bb0([[THISADDRPTR:%[0-9]+]] : $*Bas<T>, [[YYADDR:%[0-9]+]] : $*T, [[META:%[0-9]+]] : $@thin Bas<T>.Type): // CHECK: [[SELF_BOX:%[0-9]+]] = alloc_box $<τ_0_0> { var Bas<τ_0_0> } <T> // CHECK: [[MARKED_SELF_BOX:%[0-9]+]] = mark_uninitialized [rootself] [[SELF_BOX]] // CHECK: [[PB_BOX:%.*]] = project_box [[MARKED_SELF_BOX]] x = bar() // CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] [[PB_BOX]] // CHECK: [[SELF_X:%[0-9]+]] = struct_element_addr [[WRITE]] : $*Bas<T>, #Bas.x // CHECK: assign {{.*}} to [[SELF_X]] y = yy // CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] [[PB_BOX]] // CHECK: [[SELF_Y:%[0-9]+]] = struct_element_addr [[WRITE]] : $*Bas<T>, #Bas.y // CHECK: copy_addr {{.*}} to [[SELF_Y]] // CHECK: destroy_value // -- 'self' was emplaced into indirect return slot // CHECK: return } init<U:Intifiable>(xx:U, yy:T) { x = xx.intify() y = yy } } class B { init(y:Int) {} } class D : B { // CHECK-LABEL: sil hidden [ossa] @$s8lifetime1DC1x1yACSi_Sitcfc // CHECK: bb0([[X:%[0-9]+]] : $Int, [[Y:%[0-9]+]] : $Int, [[SELF:%[0-9]+]] : @owned $D): init(x: Int, y: Int) { var x = x var y = y // CHECK: [[SELF_BOX:%[0-9]+]] = alloc_box ${ var D } // CHECK: [[MARKED_SELF_BOX:%[0-9]+]] = mark_uninitialized [derivedself] [[SELF_BOX]] // CHECK: [[PB_BOX:%[0-9]+]] = project_box [[MARKED_SELF_BOX]] // CHECK: store [[SELF]] to [init] [[PB_BOX]] // CHECK: [[XADDR:%[0-9]+]] = alloc_box ${ var Int } // CHECK: [[PX:%[0-9]+]] = project_box [[XADDR]] // CHECK: store [[X]] to [trivial] [[PX]] // CHECK: [[YADDR:%[0-9]+]] = alloc_box ${ var Int } // CHECK: [[PY:%[0-9]+]] = project_box [[YADDR]] // CHECK: store [[Y]] to [trivial] [[PY]] super.init(y: y) // CHECK: [[THIS1:%[0-9]+]] = load [take] [[PB_BOX]] // CHECK: [[THIS1_SUP:%[0-9]+]] = upcast [[THIS1]] : ${{.*}} to $B // CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PY]] // CHECK: [[Y:%[0-9]+]] = load [trivial] [[READ]] // CHECK: [[SUPER_CTOR:%[0-9]+]] = function_ref @$s8lifetime1BC1yACSi_tcfc : $@convention(method) (Int, @owned B) -> @owned B // CHECK: [[THIS2_SUP:%[0-9]+]] = apply [[SUPER_CTOR]]([[Y]], [[THIS1_SUP]]) // CHECK: [[THIS2:%[0-9]+]] = unchecked_ref_cast [[THIS2_SUP]] : $B to $D // CHECK: [[THIS1:%[0-9]+]] = load [copy] [[PB_BOX]] // CHECK: destroy_value [[MARKED_SELF_BOX]] } func foo() {} } // CHECK-LABEL: sil hidden [ossa] @$s8lifetime8downcast{{[_0-9a-zA-Z]*}}F func downcast(_ b: B) { var b = b // CHECK: [[BADDR:%[0-9]+]] = alloc_box ${ var B } // CHECK: [[PB:%[0-9]+]] = project_box [[BADDR]] (b as! D).foo() // CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PB]] // CHECK: [[B:%[0-9]+]] = load [copy] [[READ]] // CHECK: [[D:%[0-9]+]] = unconditional_checked_cast [[B]] : {{.*}} to D // CHECK: apply {{.*}}([[D]]) // CHECK-NOT: destroy_value [[B]] // CHECK: destroy_value [[D]] // CHECK: destroy_value [[BADDR]] // CHECK: return } func int(_ x: Int) {} func ref(_ x: Ref) {} func tuple() -> (Int, Ref) { return (1, Ref()) } func tuple_explosion() { int(tuple().0) // CHECK: [[F:%[0-9]+]] = function_ref @$s8lifetime5tupleSi_AA3RefCtyF // CHECK: [[TUPLE:%[0-9]+]] = apply [[F]]() // CHECK: ({{%.*}}, [[T1:%.*]]) = destructure_tuple [[TUPLE]] // CHECK: destroy_value [[T1]] // CHECK-NOT: destructure_tuple [[TUPLE]] // CHECK-NOT: tuple_extract [[TUPLE]] // CHECK-NOT: destroy_value ref(tuple().1) // CHECK: [[F:%[0-9]+]] = function_ref @$s8lifetime5tupleSi_AA3RefCtyF // CHECK: [[TUPLE:%[0-9]+]] = apply [[F]]() // CHECK: ({{%.*}}, [[T1:%.*]]) = destructure_tuple [[TUPLE]] // CHECK: destroy_value [[T1]] // CHECK-NOT: destructure_tuple [[TUPLE]] // CHECK-NOT: tuple_extract [[TUPLE]] // CHECK-NOT: destroy_value [[TUPLE]] }
apache-2.0
9a990c7d30e79c28d0cb753431936b0e
38.919481
196
0.547401
3.040958
false
false
false
false
fredfoc/OpenWit
OpenWit/Classes/OpenWitConverseExtension.swift
1
2518
// // OpenWitConverseExtension.swift // OpenWit // // Created by fauquette fred on 8/12/16. // Copyright © 2016 Fred Fauquette. All rights reserved. // import Foundation import Foundation import Moya import ObjectMapper // MARK: - an extension to handle converse analyse extension OpenWit { public func conversationMessage(_ message: String, sessionId: String, context: Mappable? = nil, completion: @escaping (_ result: OpenWitResult<OpenWitConverseModel, OpenWitError>) -> ()) { guard let serviceManager = try? OpenWitServiceManager(WitToken: WITTokenAcces, serverToken: WITServerTokenAcces, isMocked: isMocked) else { completion(OpenWitResult(failure: OpenWitError.tokenIsUndefined)) return } guard message.isNotTooLong else { completion(OpenWitResult(failure: OpenWitError.messageTooLong)) return } _ = serviceManager.provider.requestObject(OpenWitService.converseMessage(apiVersion: apiVersion, message: message, sessionId: sessionId, context: context), completion: completion) } public func conversationAction(_ action: Mappable, sessionId: String, context: Mappable? = nil, completion: @escaping (_ result: OpenWitResult<OpenWitConverseModel, OpenWitError>) -> ()) { guard let serviceManager = try? OpenWitServiceManager(WitToken: WITTokenAcces, serverToken: WITServerTokenAcces, isMocked: isMocked) else { completion(OpenWitResult(failure: OpenWitError.tokenIsUndefined)) return } _ = serviceManager.provider.requestObject(OpenWitService.action(apiVersion: apiVersion, action: action, sessionId: sessionId, context: context), completion: completion) } }
mit
9c650edaac48f9241314dcaf88d17731
44.763636
147
0.49702
6.021531
false
false
false
false
syoung-smallwisdom/ResearchUXFactory-iOS
ResearchUXFactory/SBALoadingViewPresenter.swift
1
2906
// // SBALoadingViewPresenter.swift // ResearchUXFactory // // Copyright © 2016 Sage Bionetworks. All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation and/or // other materials provided with the distribution. // // 3. Neither the name of the copyright holder(s) nor the names of any contributors // may be used to endorse or promote products derived from this software without // specific prior written permission. No license is granted to the trademarks of // the copyright holders even if such marks are included in this software. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // import Foundation public protocol SBALoadingViewPresenter { var view: UIView! { get } } extension SBALoadingViewPresenter { public var standardLoadingView: SBALoadingView? { return self.view.subviews.find({ $0 is SBALoadingView }) as? SBALoadingView } public func showLoadingView() { var loadingView: SBALoadingView? = self.standardLoadingView if (loadingView == nil) { // if nil, create and add the loading view loadingView = SBALoadingView(frame: self.view.bounds) loadingView!.isHidden = true self.view.addSubview(loadingView!) loadingView!.constrainToFillSuperview() } if (!loadingView!.isAnimating || loadingView!.isHidden) { loadingView!.startAnimating() } } public func hideLoadingView(_ completion: (() -> Void)? = nil) { guard let loadingView = standardLoadingView, loadingView.isAnimating else { completion?() return } loadingView.stopAnimating({ loadingView.removeFromSuperview() completion?() }) } }
bsd-3-clause
427b26d983b9ab736edcba831f485e85
40.5
84
0.710499
5.017271
false
false
false
false
chicio/RangeUISlider
Source/Logic/KnobsPropertiesFactory.swift
1
1958
// // KnobsPropertiesFactory.swift // RangeUISlider // // Created by Fabrizio Duroni on 01/02/21. // 2021 Fabrizio Duroni. // import UIKit class KnobsPropertiesBuilder { private let target: UIView private let leftKnobSelector: Selector private let rightKnobSelector: Selector private var leftKnobWidth: CGFloat = 0.0 private var leftKnobHeight: CGFloat = 0.0 private var rightKnobWidth: CGFloat = 0.0 private var rightKnobHeight: CGFloat = 0.0 init(target: UIView, leftKnobSelector: Selector, rightKnobSelector: Selector) { self.target = target self.leftKnobSelector = leftKnobSelector self.rightKnobSelector = rightKnobSelector } func leftKnobWidth(_ value: CGFloat) -> KnobsPropertiesBuilder { leftKnobWidth = value return self } func leftKnobHeight(_ value: CGFloat) -> KnobsPropertiesBuilder { leftKnobHeight = value return self } func rightKnobWidth(_ value: CGFloat) -> KnobsPropertiesBuilder { rightKnobWidth = value return self } func rightKnobHeight(_ value: CGFloat) -> KnobsPropertiesBuilder { rightKnobHeight = value return self } func build() -> KnobsProperties { return KnobsProperties( leftKnobProperties: KnobProperties( accessibilityIdentifier: "LeftKnob", position: .left, dimensions: Dimensions(width: leftKnobWidth, height: leftKnobHeight), gesture: KnobGesturesProperties(target: target, selector: leftKnobSelector) ), rightKnobProperties: KnobProperties( accessibilityIdentifier: "RightKnob", position: .right, dimensions: Dimensions(width: rightKnobWidth, height: rightKnobHeight), gesture: KnobGesturesProperties(target: target, selector: rightKnobSelector) ) ) } }
mit
cae287ae140261e1f63a34e226d249af
30.580645
92
0.651685
4.834568
false
false
false
false
andrebocchini/SwiftChattyOSX
Pods/SwiftChatty/SwiftChatty/Common Models/Mappable/ThreadPostId.swift
1
929
// // ThreadPostId.swift // SwiftChatty // // Created by Andre Bocchini on 1/17/16. // Copyright © 2016 Andre Bocchini. All rights reserved. // import Genome /// Model used in the response to GetThreadPostId /// /// - SeeAlso: http://winchatty.com/v2/readme#_Toc421451666 public struct ThreadPostId { public var threadId: Int = 0 public var postIds: [Int] = [] public init() {} } extension ThreadPostId: CommonMappableModel { public mutating func sequence(map: Map) throws { var threadIdString: String = "" try threadIdString <~ map["threadId"] if let idInt = Int(threadIdString) { threadId = idInt } var postIdStrings: [String] = [] try postIdStrings <~ map["postIds"] for postIdString in postIdStrings { if let postIdInt = Int(postIdString) { postIds.append(postIdInt) } } } }
mit
174fa32026e0f487203d86ab93989e31
21.634146
59
0.609914
3.965812
false
false
false
false
shlyren/ONE-Swift
ONE_Swift/Classes/Reading-阅读/Controller/Read/JENReadQuestionViewController.swift
1
1226
// // JENReadQuestionViewController.swift // ONE_Swift // // Created by 任玉祥 on 16/5/4. // Copyright © 2016年 任玉祥. All rights reserved. // import UIKit class JENReadQuestionViewController: JENReadTableViewController { override var readItems: [AnyObject] { get { return readList.question } } override var readType: JENReadType { get { return .Question } } } // MARK: - tableView protocol extension JENReadQuestionViewController { override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> JENReadCell { let cell = super.tableView(tableView, cellForRowAtIndexPath: indexPath) cell.question = readItems[indexPath.row] as! JENReadQuestionItem return cell } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let questionVc = JENQuestionDetailViewController() guard let question_id = (readItems[indexPath.row] as! JENReadQuestionItem).question_id else { return } questionVc.detail_id = question_id navigationController?.pushViewController(questionVc, animated: true) } }
mit
39fcaace853f33cf40722b6087782fbd
28.560976
114
0.69199
4.552632
false
false
false
false
jrmgx/swift
Example/Tests/JrmgxAsyncTests.swift
1
1558
import UIKit import XCTest import jrmgx class JrmgxAsyncTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testGetNamedQueue() { XCTAssert(JrmgxAsync.GetNamedQueue() === DispatchQueue.main, "Did not get main queue") } func testExecute() { let expectation = self.expectation(description: "Execute") JrmgxAsync.Execute { expectation.fulfill() } waitForExpectations(timeout: 3) { error in if let error = error { print(error.localizedDescription) } } } func testExecuteAfterSeconds() { let expectation = self.expectation(description: "Execute") let seconds = 3.0 let timeBefore = Date().timeIntervalSince1970 var timeAfter = timeBefore JrmgxAsync.Execute(onNamedQueue: "test", afterSeconds: seconds) { timeAfter = Date().timeIntervalSince1970 XCTAssertLessThan(timeBefore + seconds - 1, timeAfter, "Did not wait") expectation.fulfill() } waitForExpectations(timeout: 5) { error in if let error = error { print(error.localizedDescription) } } } }
mit
ee6590c773ad9ab3bb8f0254039ec527
27.851852
111
0.597561
4.961783
false
true
false
false
zoeyzhong520/SlidingMenu
SlidingMenu/Kingfisher-master/Demo/Kingfisher-macOS-Demo/ViewController.swift
4
3222
// // ViewController.swift // Kingfisher-macOS-Demo // // Created by Wei Wang on 16/1/6. // // Copyright (c) 2017 Wei Wang <onevcat@gmail.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 AppKit import Kingfisher class ViewController: NSViewController { @IBOutlet weak var collectionView: NSCollectionView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. title = "Kingfisher" } @IBAction func clearCachePressed(sender: AnyObject) { KingfisherManager.shared.cache.clearMemoryCache() KingfisherManager.shared.cache.clearDiskCache() } @IBAction func reloadPressed(sender: AnyObject) { collectionView.reloadData() } } extension ViewController: NSCollectionViewDataSource { func collectionView(_ collectionView: NSCollectionView, numberOfItemsInSection section: Int) -> Int { return 10 } func collectionView(_ collectionView: NSCollectionView, itemForRepresentedObjectAt indexPath: IndexPath) -> NSCollectionViewItem { let item = collectionView.makeItem(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "Cell"), for: indexPath) let url = URL(string: "https://raw.githubusercontent.com/onevcat/Kingfisher/master/images/kingfisher-\(indexPath.item + 1).jpg")! item.imageView?.kf.indicatorType = .activity item.imageView?.kf.setImage(with: url, placeholder: nil, options: nil, progressBlock: { receivedSize, totalSize in print("\(indexPath.item + 1): \(receivedSize)/\(totalSize)") }, completionHandler: { image, error, cacheType, imageURL in print("\(indexPath.item + 1): Finished") }) // Set imageView's `animates` to true if you are loading a GIF. // item.imageView?.animates = true return item } }
mit
9d558d3a686708dbed5edef8c06d832f
43.136986
137
0.646803
5.213592
false
false
false
false
gridNA/GNAContextMenu
gnaContextMenu/GNAContextMenu/GNAMenuItem.swift
1
5221
// // Created by Kateryna Gridina. // Copyright (c) gridNA. All rights reserved. // Latest version can be found at https://github.com/gridNA/GNAContextMenu // import UIKit public class GNAMenuItem: UIView { public var itemId: String? public var angle: CGFloat = 0 public var defaultLabelMargin: CGFloat = 6 private var titleView: UIView? private var titleLabel: UILabel? private var menuIcon: UIImageView! private var titleText: String? private var activeMenuIcon: UIImageView? @objc public convenience init(icon: UIImage, activeIcon: UIImage?, title: String?) { let frame = CGRect(x: 0, y: 0, width: 55, height: 55) self.init(icon: icon, activeIcon: activeIcon, title: title, frame: frame) } @objc public init(icon: UIImage, activeIcon: UIImage?, title: String?, frame: CGRect) { super.init(frame: frame) menuIcon = createMenuIcon(withImage: icon) if let aIcon = activeIcon { activeMenuIcon = createMenuIcon(withImage: aIcon) } if let t = title { createLabel(withTitle: t) } activate(shouldActivate: false) } @objc required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func createLabel(withTitle title: String, fontSize: CGFloat? = 11.0, color: UIColor? = .white, bgColor: UIColor? = .black) { titleLabel = createTitleLabel(withTitle: title, fontSize: fontSize, color: color) titleView = createTitleView(withColor: bgColor) updateTitlePositions() titleView!.addSubview(titleLabel!) addSubview(titleView!) } private func createTitleLabel(withTitle title: String, fontSize: CGFloat? = 11.0, color: UIColor? = .white) -> UILabel { let itemTitleLabel = UILabel() itemTitleLabel.font = UIFont.systemFont(ofSize: fontSize ?? 11, weight: UIFont.Weight(rawValue: 1)) itemTitleLabel.textColor = color itemTitleLabel.textAlignment = .center itemTitleLabel.text = title return itemTitleLabel } private func createTitleView(withColor color: UIColor?) -> UIView { let itemTitleView = UIView() itemTitleView.backgroundColor = color itemTitleView.alpha = 0.7 itemTitleView.layer.cornerRadius = 5 return itemTitleView } private func setupLabelPosition() { guard let tLabel = titleLabel else { return } tLabel.sizeToFit() tLabel.center = CGPoint(x: (tLabel.frame.width + defaultLabelMargin)/2, y: tLabel.frame.height/2) } private func setupTitleViewPosition() { guard let tView = titleView, let tLabel = titleLabel else { return } tView.frame = CGRect(origin: .zero, size: CGSize(width: tLabel.frame.width + defaultLabelMargin, height: tLabel.frame.height)) } private func updateTitlePositions() { setupLabelPosition() setupTitleViewPosition() } private func createMenuIcon(withImage image: UIImage) -> UIImageView { let iconView = UIImageView(image: image) iconView.frame = self.bounds iconView.contentMode = .scaleAspectFit self.addSubview(iconView) return iconView } private func showHideTitle(toShow: Bool) { guard let tView = titleView else { return } tView.isHidden = !toShow UIView.animate(withDuration: 1, delay: 0, usingSpringWithDamping: 0.4, initialSpringVelocity: 1, options: [], animations: { tView.center = CGPoint(x: self.frame.width/2, y: -(self.titleLabel?.frame.height ?? 0)) }, completion: nil) } // MARK: Public methods @objc public func activate(shouldActivate: Bool) { menuIcon.isHidden = shouldActivate activeMenuIcon?.isHidden = !shouldActivate showHideTitle(toShow: shouldActivate) } @objc public func changeTitleLabel(withLabel label: UILabel) { let labelText = label.text ?? titleLabel?.text titleLabel?.removeFromSuperview() titleLabel = label titleLabel?.text = labelText titleView?.addSubview(titleLabel!) updateTitlePositions() } @objc public func changeTitleView(withView view: UIView) { titleView?.removeFromSuperview() titleView = view titleView?.addSubview(titleLabel ?? UIView()) addSubview(titleView!) showHideTitle(toShow: false) updateTitlePositions() } @objc public func changeTitle(withTitle title: String) { titleLabel?.text = title updateTitlePositions() } @objc public func changeIcon(withIcon icon: UIImage) { menuIcon.removeFromSuperview() menuIcon = createMenuIcon(withImage: icon) } @objc public func changeActiveIcon(withIcon icon: UIImage) { activeMenuIcon?.removeFromSuperview() activeMenuIcon = createMenuIcon(withImage: icon) activeMenuIcon?.isHidden = true } }
mit
9d89a9c8eaa84a304b3eb041b3bd50b2
35.006897
134
0.634361
4.759344
false
false
false
false
LiskUser1234/SwiftyLisk
Lisk/Delegate/Operations/DelegateGetForgedByAccountOperation.swift
1
2810
/* The MIT License Copyright (C) 2017 LiskUser1234 - Github: https://github.com/liskuser1234 Please vote LiskUser1234 for delegate to support this project. For donations: - Lisk: 6137947831033853925L - Bitcoin: 1NCTZwBJF7ZFpwPeQKiSgci9r2pQV3G7RG Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import Foundation import SwiftyJSON open class DelegateGetForgedByAccountOperation : APIOperation { private let publicKey: String private let startIdx: Int64? private let endIdx: Int64? private let feesPtr: UnsafeMutablePointer<Double>? private let rewardsPtr: UnsafeMutablePointer<Double>? private let forgedPtr: UnsafeMutablePointer<Double>? public init(publicKey: String, start: Int64?, end: Int64?, feesPtr: UnsafeMutablePointer<Double>?, rewardsPtr: UnsafeMutablePointer<Double>?, forgedPtr: UnsafeMutablePointer<Double>?, errorPtr: UnsafeMutablePointer<String?>? = nil) { self.publicKey = publicKey self.startIdx = start self.endIdx = end self.feesPtr = feesPtr self.rewardsPtr = rewardsPtr self.forgedPtr = forgedPtr super.init(errorPtr: errorPtr) } override open func start() { DelegateAPI.getForgedByAccount(publicKey: publicKey, start: startIdx, end: endIdx, callback: callback) } override internal func processResponse(json: JSON) { self.feesPtr?.pointee = json["fees"].doubleValue self.rewardsPtr?.pointee = json["rewards"].doubleValue self.forgedPtr?.pointee = json["forged"].doubleValue } }
mit
4abef97a7cebb4af6995e381eddbc661
35.973684
78
0.680783
4.811644
false
false
false
false
HLoveMe/HSetting
BaseSetting/BaseSetting/BaseSetting/View/SettingTableViewCell.swift
1
7020
// // SettingTableViewCell.swift // BaseSetting // // Created by space on 16/1/28. // Copyright © 2016年 Space. All rights reserved. // import UIKit class SettingTableViewCell: UITableViewCell { let screenWidth:CGFloat = UIScreen.mainScreen().bounds.width private var currentAssistView:UIView? var settingModel:BaseModel!{ didSet{ self.loadSubViews() } } func loadSubViews(){ (self.contentView.subviews as NSArray).enumerateObjectsUsingBlock { (View, _, _) -> Void in View.removeFromSuperview() } self.imageView?.image = UIImage.init(named: self.settingModel.imageName) self.textLabel?.font = UIFont.systemFontOfSize(settingModel.cellStatus.cellLabelSize) self.textLabel?.text = self.settingModel.title self.selectionStyle = .None; self.accessoryView = nil self.currentAssistView = nil self.currentAssistView = settingModel.assistView if (settingModel is SettingArrowModel){ self.selectionStyle = .Blue let model = settingModel as! SettingArrowModel model.assistView?.removeFromSuperview() self.accessoryType = .DisclosureIndicator if model.type == .Label{ let assistView:UILabel = self.settingModel.assistView as! UILabel self.contentView.addSubview(assistView) let size = assistView.text!.getSize(settingModel.cellStatus.cellAssistFont, size: CGSizeMake(settingModel.cellStatus.cellAssistLabelWidth, settingModel.cellStatus.cellAssistSize)) assistView.frame = CGRectMake(screenWidth - size.width - 34 , 0, size.width,settingModel.cellStatus.cellHeight) assistView.textAlignment = .Center assistView.font = settingModel.cellStatus.cellAssistFont }else if let custom = model.assistView { let x = screenWidth - custom.width - 34 let hei = custom.height < settingModel.cellStatus.cellHeight ? custom.height : settingModel.cellStatus.cellHeight let y = (settingModel.cellStatus.cellHeight - hei)/2 custom.frame = CGRectMake(x,y, custom.width,hei) self.contentView.addSubview(custom) } }else if(settingModel is SettingRefreshModel){ self.accessoryType = .None let model = settingModel as! SettingRefreshModel model.assistView?.removeFromSuperview() switch model.type{ case .None: self.selectionStyle = .Blue break case .Label: let assistView:UILabel = self.settingModel.assistView as! UILabel self.selectionStyle = .Blue self.contentView.addSubview(assistView) self.accessoryView = assistView let size = assistView.text!.getSize(settingModel.cellStatus.cellAssistFont, size: CGSizeMake(settingModel.cellStatus.cellAssistLabelWidth, settingModel.cellStatus.cellAssistSize)) assistView.frame = CGRectMake(0 , 0, size.width+10,settingModel.cellStatus.cellHeight) assistView.font = settingModel.cellStatus.cellAssistFont assistView.textAlignment = .Center break case .Custom: guard let custom = model.assistView else{break} let x = self.contentView.width - custom.width + 15 let hei = custom.height < settingModel.cellStatus.cellHeight ? custom.height : settingModel.cellStatus.cellHeight let y = (settingModel.cellStatus.cellHeight - hei)/2 custom.frame = CGRectMake(x, y, custom.width,hei) self.contentView.addSubview(custom) self.accessoryView = custom break case .Switch: let customView:SettingSwitch = model.assistView! as! SettingSwitch customView.removeTarget(self, action: #selector(SettingTableViewCell.switchStateChange(_:)), forControlEvents: .ValueChanged) customView.addTarget(self, action:#selector(SettingTableViewCell.switchStateChange(_:)), forControlEvents:.ValueChanged) self.accessoryView = customView customView.mark = self.textLabel?.text let flag = NSUserDefaults.getSwitchState((self.textLabel?.text)!) if let _ = flag{ customView.setOn(flag!, animated:true) }else{ customView.setOn(model.assistSwitchInitialState, animated: true) } break } } guard let _ = self.settingModel.operationBlock else{return} self.settingModel.operationBlock!(self) } } extension SettingTableViewCell{ class func CellWithTableView(tableView:UITableView)->SettingTableViewCell{ let ID:String = "ID" var cell:SettingTableViewCell? = tableView.dequeueReusableCellWithIdentifier(ID) as? SettingTableViewCell if cell == nil { cell = SettingTableViewCell(style: UITableViewCellStyle.Value1, reuseIdentifier: ID) } return cell! } } extension SettingTableViewCell{ func switchStateChange(swith:SettingSwitch){ guard let _ = swith.mark else {return} NSUserDefaults.saveSwitchState(swith.mark!, state: swith.on) } func getCurrentAssistView()->UIView?{ return self.currentAssistView } } extension UIView{ /**width*/ var width:CGFloat { get{ return self.bounds.size.width } set{ self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y, newValue, self.frame.size.height) } } /**height*/ var height:CGFloat { get{ return self.bounds.size.height } set{ self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y,self.frame.size.width,newValue) } } var y:CGFloat{ get{ return self.frame.origin.y } set{ var rect:CGRect = self.frame rect.origin = CGPointMake(rect.origin.x,newValue) self.frame = rect } } } extension String{ func getSize(font:UIFont,size:CGSize)->CGSize{ let str:NSString = self as NSString return str.boundingRectWithSize(size, options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: [NSFontAttributeName:font], context: nil).size } } extension NSUserDefaults{ /**得到switch状态*/ class func getSwitchState(title:String)->Bool?{ return NSUserDefaults.standardUserDefaults().objectForKey(title)?.boolValue } /**保存开关状态*/ class func saveSwitchState(title:String,state:Bool){ NSUserDefaults.standardUserDefaults().setBool(state, forKey: title) NSUserDefaults.standardUserDefaults().synchronize() } }
apache-2.0
ce93692f31a9803381ed0e49606ddec7
41.932515
195
0.632414
4.792466
false
false
false
false
chernyog/CYWeibo
CYWeibo/CYWeibo/CYWeibo/Classes/Tools/String+Regex.swift
1
4652
// // String+Regex.swift // CYWeibo // // Created by 陈勇 on 15/3/14. // Copyright (c) 2015年 zhssit. All rights reserved. // import Foundation extension String { /// 获取a标签的文本 /// /// :returns: func getHrefText() -> String? { // <a href="baidu.com">百度一下,你就知道</a> let pattern = "<a.*?>(.*?)</a>" /* CaseInsensitive: 不区分大小写 AllowCommentsAndWhitespace: IgnoreMetacharacters: DotMatchesLineSeparators:使用 . 可以匹配换行符 AnchorsMatchLines: UseUnixLineSeparators: UseUnicodeWordBoundaries: */ let regex = NSRegularExpression(pattern: pattern, options: NSRegularExpressionOptions.CaseInsensitive | NSRegularExpressionOptions.DotMatchesLineSeparators, error: nil) println(regex) var aaa: ObjCBool = false // 提示:不要直接使用 String.length,包含UNICODE的编码长度,会出现数组越界 var length = (self as NSString).length // regex?.enumerateMatchesInString(self, options: NSMatchingOptions.allZeros, range: NSMakeRange(0, length), usingBlock: { (result, flag, aaa) -> Void in // printLine() // println("\(result) \(flag) \(aaa)") // // }) // 2. 匹配文字 // firstMatchInString 在字符串中查找第一个匹配的内容 // rangeAtIndex 函数是使用正则最重要的函数 -> 从 result 中获取到匹配文字的 range // index == 0,取出与 pattern 刚好匹配的内容 // index == 1,取出第一个()中要匹配的内容 // index 可以依次递增,对于复杂字符串过滤,可以使用多几个 () if let result = regex?.firstMatchInString(self, options: NSMatchingOptions.allZeros, range: NSMakeRange(0, length)) { let aString = self as NSString println(result.rangeAtIndex(0)) println(result.rangeAtIndex(1)) println("count=\(result.numberOfRanges)") return aString.substringWithRange(result.rangeAtIndex(1)) } return nil } func emotionString() -> NSAttributedString? { let pattern = "\\[(.*?)\\]" let text = self as NSString let regex = NSRegularExpression(pattern: pattern, options: NSRegularExpressionOptions.CaseInsensitive | NSRegularExpressionOptions.DotMatchesLineSeparators, error: nil)! let checkingResults = regex.matchesInString(self, options: NSMatchingOptions.allZeros, range: NSMakeRange(0, text.length)) as! [NSTextCheckingResult] var attrString = NSMutableAttributedString(string: self) // 倒序遍历,防止前面的被替换之后,导致字符串的长度发生变化! for var index = checkingResults.count - 1; index >= 0; index-- { let checkingResult = checkingResults[index] let range = checkingResult.rangeAtIndex(0) // println(text.substringWithRange(range)) // 获取文本 let str = text.substringWithRange(range) // 根据文本,获取指定的表情 if let emo = emotion(str) { if emo.png != nil { // 替换文字 let tmpStr = EmoteTextAttachment.getAttributedString(emo, height: 18) attrString.replaceCharactersInRange(range, withAttributedString: tmpStr) } } } // for checkingResult in checkingResults // { // let range = checkingResult.rangeAtIndex(0) // println("\(text) \(range)") // // 获取文本 // let str = text.substringWithRange(range) // // 根据文本,获取指定的表情 // if let emo = emotion(str) // { // if emo.png != nil // { // // 替换文字 // let tmpStr = EmoteTextAttachment.getAttributedString(emo, height: 18) // attrString.replaceCharactersInRange(range, withAttributedString: tmpStr) // } // } // } return attrString } private func emotion(str: String) -> Emoticon? { let emoticons = EmoticonList.sharedInstance.emoticons println(emoticons.count) for emo in emoticons { println(emo.code) } for emo in emoticons { if emo.chs == str { return emo } } return nil } }
mit
5f5336efd634bdf081b92579d974dc74
32.204724
177
0.568311
4.485106
false
false
false
false
plu/FBSimulatorControl
fbsimctl/FBSimulatorControlKit/Sources/Bridging.swift
1
9512
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ import Foundation import FBSimulatorControl extension FBSimulatorState { public var description: String { get { return FBSimulator.stateString(from: self) }} } extension FBiOSTargetQuery { static func parseUDIDToken(_ token: String) throws -> String { if let _ = UUID(uuidString: token) { return token } if token.characters.count != 40 { throw ParseError.couldNotInterpret("UDID is not 40 characters long", token) } let nonDeviceUDIDSet = CharacterSet(charactersIn: "0123456789ABCDEFabcdef").inverted if let range = token.rangeOfCharacter(from: nonDeviceUDIDSet) { let invalidCharacters = token.substring(with: range) throw ParseError.couldNotInterpret("UDID contains non-hex character '\(invalidCharacters)'", token) } return token } } extension URL { static func urlRelativeTo(_ basePath: String, component: String, isDirectory: Bool) -> URL { let url = URL(fileURLWithPath: basePath) return url.appendingPathComponent(component, isDirectory: isDirectory) } var bridgedAbsoluteString: String { get { return self.absoluteString }} } public typealias ControlCoreValue = FBJSONSerializable & CustomStringConvertible @objc open class ControlCoreLoggerBridge : NSObject { let reporter: EventReporter init(reporter: EventReporter) { self.reporter = reporter } @objc open func log(_ level: Int32, string: String) { let subject = LogSubject(logString: string, level: level) self.reporter.report(subject) } } extension FBiOSTargetType : Accumulator { public func append(_ other: FBiOSTargetType) -> FBiOSTargetType { return self == FBiOSTargetType.all ? self.intersection(other) : self.union(other) } } extension FBiOSTargetQuery { public static func ofCount(_ count: Int) -> FBiOSTargetQuery { return self.allTargets().ofCount(count) } public func ofCount(_ count: Int) -> FBiOSTargetQuery { return self.range(NSRange(location: 0, length: count)) } } extension FBiOSTargetQuery : Accumulator { public func append(_ other: FBiOSTargetQuery) -> Self { let targetType = self.targetType.append(other.targetType) return self .udids(Array(other.udids)) .names(Array(other.names)) .states(other.states) .architectures(Array(other.architectures)) .targetType(targetType) .osVersions(Array(other.osVersions)) .devices(Array(other.devices)) .range(other.range) } } extension FBiOSTargetFormatKey { public static var allFields: [FBiOSTargetFormatKey] { get { return [ FBiOSTargetFormatKey.UDID, FBiOSTargetFormatKey.name, FBiOSTargetFormatKey.model, FBiOSTargetFormatKey.osVersion, FBiOSTargetFormatKey.state, FBiOSTargetFormatKey.architecture, FBiOSTargetFormatKey.processIdentifier, FBiOSTargetFormatKey.containerApplicationProcessIdentifier, ] }} } extension FBArchitecture { public static var allFields: [FBArchitecture] { get { return [ .I386, .X86_64, .armv7, .armv7s, .arm64, ] }} } extension FBiOSTargetFormat : Accumulator { public func append(_ other: FBiOSTargetFormat) -> Self { return self.appendFields(other.fields) } } extension FBSimulatorBootConfiguration : Accumulator { public func append(_ other: FBSimulatorBootConfiguration) -> Self { var configuration = self if let locale = other.localizationOverride ?? self.localizationOverride { configuration = configuration.withLocalizationOverride(locale) } if let framebuffer = other.framebuffer ?? self.framebuffer { configuration = configuration.withFramebuffer(framebuffer) } if let scale = other.scale ?? self.scale { configuration = configuration.withScale(scale) } configuration = configuration.withOptions(self.options.union(other.options)) return configuration; } } extension FBProcessOutputConfiguration : Accumulator { public func append(_ other: FBProcessOutputConfiguration) -> Self { var configuration = self if other.stdOut is String { configuration = try! configuration.withStdOut(other.stdOut) } if other.stdErr is String { configuration = try! configuration.withStdErr(other.stdErr) } return configuration } } extension IndividualCreationConfiguration { public var simulatorConfiguration : FBSimulatorConfiguration { get { var configuration = FBSimulatorConfiguration.default() if let model = self.model { configuration = configuration.withDeviceModel(model) } if let os = self.os { configuration = configuration.withOSNamed(os) } if let auxDirectory = self.auxDirectory { configuration = configuration.withAuxillaryDirectory(auxDirectory) } return configuration }} } extension FBApplicationDescriptor { static func findOrExtract(atPath: String) throws -> (String, URL?) { var url: NSURL? = nil let result = try FBApplicationDescriptor.findOrExtractApplication(atPath: atPath, extractPathOut: &url) return (result, url as URL?) } } extension Bool { static func fallback(from: String?, to: Bool) -> Bool { guard let from = from else { return false } switch from.lowercased() { case "1", "true": return true case "0", "false": return false default: return false } } } extension HttpRequest { func getBoolQueryParam(_ key: String, _ fallback: Bool) -> Bool { return Bool.fallback(from: self.query[key], to: fallback) } } struct LineBufferDataIterator : IteratorProtocol { let lineBuffer: FBLineBuffer mutating func next() -> Data? { return self.lineBuffer.consumeLineData() } } struct LineBufferStringIterator : IteratorProtocol { let lineBuffer: FBLineBuffer mutating func next() -> String? { return self.lineBuffer.consumeLineString() } } extension FBLineBuffer { func dataIterator() -> LineBufferDataIterator { return LineBufferDataIterator(lineBuffer: self) } func stringIterator() -> LineBufferStringIterator { return LineBufferStringIterator(lineBuffer: self) } } @objc class AccumilatingActionDelegate : NSObject, FBiOSTargetActionDelegate { var handle: FBTerminationHandle? = nil let reporter: EventReporter init(reporter: EventReporter) { self.reporter = reporter super.init() } func action(_ action: FBiOSTargetAction, target: FBiOSTarget, didGenerate terminationHandle: FBTerminationHandle) { self.handle = terminationHandle } } @objc class ActionReaderDelegateBridge : NSObject, FBiOSActionReaderDelegate { let interpreter: EventInterpreter init(interpreter: EventInterpreter) { self.interpreter = interpreter super.init() } func interpret(_ action: FBiOSTargetAction, _ eventType: EventType) -> String { let subject = SimpleSubject(action.eventName, .started, ControlCoreSubject(action as! ControlCoreValue)) return self.interpret(subject) } func interpret(_ subject: EventReporterSubject) -> String { let lines = self.interpreter.interpret(subject) return lines.joined(separator: "\n") + "\n" } func readerDidFinishReading(_ reader: FBiOSActionReader) { } func reader(_ reader: FBiOSActionReader, failedToInterpretInput input: String, error: Error) -> String? { return error.localizedDescription + "\n" } func reader(_ reader: FBiOSActionReader, willStartPerforming action: FBiOSTargetAction, on target: FBiOSTarget) -> String? { return self.interpret(action, .started) } func reader(_ reader: FBiOSActionReader, didProcessAction action: FBiOSTargetAction, on target: FBiOSTarget) -> String? { return self.interpret(action, .ended) } func reader(_ reader: FBiOSActionReader, didFailToProcessAction action: FBiOSTargetAction, on target: FBiOSTarget, error: Error) -> String? { let subject = SimpleSubject(.failure, .discrete, error.localizedDescription) return self.interpret(subject) } } extension FBiOSTargetAction { func runAction(target: FBiOSTarget, reporter: EventReporter) throws -> FBTerminationHandle? { let delegate = AccumilatingActionDelegate(reporter: reporter) try self.run(with: target, delegate: delegate) return delegate.handle } public var eventName: EventName { get { let actionType = type(of: self).actionType switch actionType { case FBiOSTargetActionType.applicationLaunch: return .launch case FBiOSTargetActionType.agentLaunch: return .launch case FBiOSTargetActionType.testLaunch: return .launchXCTest default: return actionType } }} public func printable() -> String { let json = try! JSON.encode(FBiOSActionRouter.json(from: self) as AnyObject) return try! json.serializeToString(false) } } extension FBProcessLaunchConfiguration : EnvironmentAdditive {} extension FBTestLaunchConfiguration : EnvironmentAdditive { func withEnvironmentAdditions(_ environmentAdditions: [String : String]) -> Self { guard let appLaunchConf = self.applicationLaunchConfiguration else { return self } return self.withApplicationLaunchConfiguration(appLaunchConf.withEnvironmentAdditions(environmentAdditions)) } }
bsd-3-clause
a0ee9ac0359f1a67ccfc6290e1efae9c
29.101266
143
0.724769
4.292419
false
true
false
false
ambientlight/Perfect
Sources/PerfectLib/PerfectError.swift
3
1983
// // PerfectError.swift // PerfectLib // // Created by Kyle Jessup on 7/5/15. // Copyright (C) 2015 PerfectlySoft, Inc. // //===----------------------------------------------------------------------===// // // This source file is part of the Perfect.org open source project // // Copyright (c) 2015 - 2016 PerfectlySoft Inc. and the Perfect project authors // Licensed under Apache License v2.0 // // See http://perfect.org/licensing.html for license information // //===----------------------------------------------------------------------===// // #if os(Linux) import SwiftGlibc var errno: Int32 { return __errno_location().pointee } #else import Darwin #endif /// Some but not all of the exception types which may be thrown by the system public enum PerfectError : Error { /// A network related error code and message. case networkError(Int32, String) /// A file system related error code and message. case fileError(Int32, String) /// A OS level error code and message. case systemError(Int32, String) /// An API exception error message. case apiError(String) } func ThrowFileError(file: String = #file, function: String = #function, line: Int = #line) throws -> Never { let err = errno let msg = String(validatingUTF8: strerror(err))! // print("FileError: \(err) \(msg)") throw PerfectError.fileError(err, msg + " \(file) \(function) \(line)") } func ThrowSystemError(file: String = #file, function: String = #function, line: Int = #line) throws -> Never { let err = errno let msg = String(validatingUTF8: strerror(err))! // print("SystemError: \(err) \(msg)") throw PerfectError.systemError(err, msg + " \(file) \(function) \(line)") } func ThrowNetworkError(file: String = #file, function: String = #function, line: Int = #line) throws -> Never { let err = errno let msg = String(validatingUTF8: strerror(err))! // print("NetworkError: \(err) \(msg)") throw PerfectError.networkError(err, msg + " \(file) \(function) \(line)") }
apache-2.0
83dda4427ff50a59d5b473ae800694b6
27.328571
112
0.633384
3.699627
false
false
false
false
samnm/material-components-ios
demos/Shrine/Shrine/ShrineFlexibleHeaderContainerViewController.swift
3
1569
/* Copyright 2016-present the Material Components for iOS authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import UIKit import MaterialComponents.MaterialFlexibleHeader class ShrineFlexibleHeaderContainerViewController: MDCFlexibleHeaderContainerViewController { init() { let layout = UICollectionViewFlowLayout() let sectionInset: CGFloat = 10.0 layout.sectionInset = UIEdgeInsets(top: sectionInset, left: sectionInset, bottom: sectionInset, right: sectionInset) #if swift(>=3.2) if #available(iOS 11.0, *) { layout.sectionInsetReference = .fromSafeArea } #endif let collectionVC = ShrineCollectionViewController(collectionViewLayout: layout) super.init(contentViewController: collectionVC) collectionVC.headerViewController = self.headerViewController collectionVC.setupHeaderView() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } }
apache-2.0
5a932be33a3225b7217a29c54d0477f2
33.108696
93
0.708732
5.178218
false
false
false
false
nathantannar4/Parse-Dashboard-for-iOS-Pro
Parse Dashboard for iOS/SectionControllers/SchemaSectionController.swift
1
3075
// // SchemaSectionController.swift // Parse Dashboard for iOS // // Copyright © 2018 Nathan Tannar. // // 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. // // Created by Nathan Tannar on 4/29/18. // import UIKit import IGListKit final class SchemaSectionController: ListSectionController { weak var schema: PFSchema? override init() { super.init() inset = UIEdgeInsets(top: 8, left: 8, bottom: 0, right: 8) } override func didUpdate(to object: Any) { schema = object as? PFSchema } override func numberOfItems() -> Int { return 1 } override func sizeForItem(at index: Int) -> CGSize { guard let width = collectionContext?.containerSize.width else { return .zero } return CGSize(width: width - inset.left - inset.right, height: 40) } override func cellForItem(at index: Int) -> UICollectionViewCell { guard let cell = collectionContext?.dequeueReusableCell(of: SchemaCell.self, for: self, at: index) as? SchemaCell else { fatalError() } cell.bindViewModel(schema as Any) return cell } override func didSelectItem(at index: Int) { guard let schema = schema else { return } let classViewController = ClassViewController(for: schema) viewController?.navigationController?.pushViewController(classViewController, animated: true) } override func didHighlightItem(at index: Int) { guard let cell = collectionContext?.cellForItem(at: index, sectionController: self) else { return } UIView.animate(withDuration: 1) { cell.contentView.backgroundColor = UIColor.lightBlueAccent.darker() } } override func didUnhighlightItem(at index: Int) { guard let cell = collectionContext?.cellForItem(at: index, sectionController: self) else { return } UIView.animate(withDuration: 0.3) { cell.contentView.backgroundColor = .lightBlueAccent } } }
mit
8b8c197e5bcfa647cee4f0172e45cb23
36.950617
128
0.686402
4.622556
false
false
false
false
itsaboutcode/WordPress-iOS
WordPress/Classes/ViewRelated/Comments/CommentAnalytics.swift
2
3558
import Foundation @objc class CommentAnalytics: NSObject { struct Constants { static let sites = "sites" static let reader = "reader" static let notifications = "notifications" static let unknown = "unknown" static let context = "context" } static func trackingContext() -> String { let screen = WPTabBarController.sharedInstance()?.currentlySelectedScreen() ?? Constants.unknown switch screen { case WPTabBarCurrentlySelectedScreenSites: return Constants.sites case WPTabBarCurrentlySelectedScreenReader: return Constants.reader case WPTabBarCurrentlySelectedScreenNotifications: return Constants.notifications default: return Constants.unknown } } static func defaultProperties(comment: Comment) -> [AnyHashable: Any] { return [ Constants.context: trackingContext(), WPAppAnalyticsKeyPostID: comment.postID, WPAppAnalyticsKeyCommentID: comment.commentID ] } @objc static func trackCommentViewed(comment: Comment) { trackCommentEvent(comment: comment, event: .commentViewed) } @objc static func trackCommentEditorOpened(comment: Comment) { trackCommentEvent(comment: comment, event: .commentEditorOpened) } @objc static func trackCommentEdited(comment: Comment) { trackCommentEvent(comment: comment, event: .commentEdited) } @objc static func trackCommentApproved(comment: Comment) { trackCommentEvent(comment: comment, event: .commentApproved) } @objc static func trackCommentUnApproved(comment: Comment) { trackCommentEvent(comment: comment, event: .commentUnApproved) } @objc static func trackCommentTrashed(comment: Comment) { trackCommentEvent(comment: comment, event: .commentTrashed) } @objc static func trackCommentSpammed(comment: Comment) { trackCommentEvent(comment: comment, event: .commentSpammed) } @objc static func trackCommentLiked(comment: Comment) { trackCommentEvent(comment: comment, event: .commentLiked) } @objc static func trackCommentUnLiked(comment: Comment) { trackCommentEvent(comment: comment, event: .commentUnliked) } @objc static func trackCommentRepliedTo(comment: Comment) { trackCommentEvent(comment: comment, event: .commentRepliedTo) } private static func trackCommentEvent(comment: Comment, event: WPAnalyticsEvent) { let properties = defaultProperties(comment: comment) guard let blog = comment.blog else { WPAnalytics.track(event, properties: properties) return } WPAnalytics.track(event, properties: properties, blog: blog) } static func trackCommentEditorOpened(block: FormattableCommentContent) { WPAnalytics.track(.commentEditorOpened, properties: [ Constants.context: CommentAnalytics.trackingContext(), WPAppAnalyticsKeyBlogID: block.metaSiteID?.intValue ?? 0, WPAppAnalyticsKeyCommentID: block.metaCommentID?.intValue ?? 0 ]) } static func trackCommentEdited(block: FormattableCommentContent) { WPAnalytics.track(.commentEdited, properties: [ Constants.context: CommentAnalytics.trackingContext(), WPAppAnalyticsKeyBlogID: block.metaSiteID?.intValue ?? 0, WPAppAnalyticsKeyCommentID: block.metaCommentID?.intValue ?? 0 ]) } }
gpl-2.0
80c632bce5923b185116675e67e5b9a6
33.882353
104
0.681563
5.025424
false
false
false
false
yarshure/Surf
Surf/TextFieldCell.swift
1
1183
// // TextFieldCell.swift // Surf // // Created by kiwi on 15/11/23. // Copyright © 2015年 yarshure. All rights reserved. // import UIKit import SFSocket import XRuler class TextFieldCell: UITableViewCell,UITextFieldDelegate { @IBOutlet weak var textField: UITextField! @IBOutlet weak var cellLabel: UILabel? var valueChanged: ((UITextField) -> Void)? func textFieldDidEndEditing(_ textField: UITextField) { valueChanged?(textField) } func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return true } func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { valueChanged?(textField) return true } deinit{ } func wwdcStyle(){ let style = ProxyGroupSettings.share.wwdcStyle if style { textField.textColor = UIColor.white cellLabel?.textColor = UIColor.white }else { textField.textColor = UIColor.black cellLabel?.textColor = UIColor.black } } }
bsd-3-clause
bc5902d9c24319c4e537994356d6ee4d
24.106383
129
0.631356
5.108225
false
false
false
false
damouse/Silvery
SilveryTests/StructAssignmentTests.swift
1
1283
// // StructAssignmentTests.swift // Silvery // // Created by Mickey Barboi on 6/21/16. // Copyright © 2016 I. All rights reserved. // import XCTest @testable import Silvery // Why the repetition on properties here? Based on the size in memory of a given type // things can get a little screwy. This ordering of properties tests those specific bugs // Floats and Booleans are the real culprits struct Pigeon: Silvery { var str1 = "str1" var int1 = 123456 var bool1 = true var bool2 = false var bool3 = true var str2 = "str2" var flt1: Float = 111.111 var flt2: Float = 222.222 var flt3: Float = 333.333 var str3 = "str3" var double1: Double = 111.111 var double2: Double = 222.222 var double3: Double = 333.333 var str4 = "str4" } // Triggers a swift assignment bug, on hold class StructAssignmentTests: XCTestCase { var d = Pigeon() func testString() { // d["str1"] = "str1-new" // d["str2"] = "str2-new" // d["str3"] = "str3-new" // d["str4"] = "str4-new" // XCTAssert(d.str1 == "str1-new") // XCTAssert(d.str2 == "str2-new") // XCTAssert(d.str3 == "str3-new") // XCTAssert(d.str4 == "str4-new") } }
mit
faa64034af2bda56f4d7e45759b413da
22.327273
88
0.588924
3.253807
false
true
false
false
toohotz/IQKeyboardManager
Demo/Swift_Demo/ViewController/TextSelectionViewController.swift
1
3234
// // TextSelectionViewController.swift // IQKeyboardManager // // Created by InfoEnum02 on 20/04/15. // Copyright (c) 2015 Iftekhar. All rights reserved. // import UIKit class TextSelectionViewController : UIViewController, UITableViewDelegate, UITableViewDataSource, UIPopoverPresentationControllerDelegate { @IBOutlet var tableView : UITableView! let _data = ["Hello", "This is a demo code", "Issue #56", "With mutiple cells", "And some useless text.", "Hello", "This is a demo code", "Issue #56", "With mutiple cells", "And some useless text.", "Hello", "This is a demo code", "Issue #56", "With mutiple cells", "And some useless text."] func tableView(tableView: UITableView, heightForRowAtIndexPath: NSIndexPath) -> CGFloat { return tableView.rowHeight } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return _data.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let identifier = "\(indexPath.section) \(indexPath.row)" var cell = tableView.dequeueReusableCellWithIdentifier(identifier) if cell == nil { cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: identifier) cell?.selectionStyle = UITableViewCellSelectionStyle.None cell?.backgroundColor = UIColor.clearColor() let textView = UITextView(frame: CGRectMake(5,7,135,30)) textView.autoresizingMask = [UIViewAutoresizing.FlexibleHeight, UIViewAutoresizing.FlexibleWidth] textView.backgroundColor = UIColor.clearColor() textView.text = _data[indexPath.row] textView.dataDetectorTypes = UIDataDetectorTypes.All textView.scrollEnabled = false textView.editable = false cell?.contentView.addSubview(textView) } return cell! } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if let identifier = segue.identifier { if identifier == "SettingsNavigationController" { let controller = segue.destinationViewController controller.modalPresentationStyle = .Popover controller.popoverPresentationController?.barButtonItem = sender as? UIBarButtonItem let heightWidth = max(CGRectGetWidth(UIScreen.mainScreen().bounds), CGRectGetHeight(UIScreen.mainScreen().bounds)); controller.preferredContentSize = CGSizeMake(heightWidth, heightWidth) controller.popoverPresentationController?.delegate = self } } } func adaptivePresentationStyleForPresentationController(controller: UIPresentationController) -> UIModalPresentationStyle { return .None } func prepareForPopoverPresentation(popoverPresentationController: UIPopoverPresentationController) { self.view.endEditing(true) } override func shouldAutorotate() -> Bool { return true } }
mit
18ee147fa75748758cbe62a8fd8ce7e0
38.925926
139
0.657699
6.033582
false
false
false
false
carambalabs/Paparajote
Example/Tests/Providers/UnsplashProviderSpec.swift
1
3399
import Foundation import Quick import Nimble import NSURL_QueryDictionary @testable import Paparajote class UnsplashProviderSpec: QuickSpec { override func spec() { var subject: UnsplashProvider! var clientId: String! var clientSecret: String! var redirectUri: String! var scope: [String]! beforeEach { clientId = "client_id" clientSecret = "client_secret" redirectUri = "redirect://works" scope = ["scope1", "scope2"] subject = UnsplashProvider(clientId: clientId, clientSecret: clientSecret, redirectUri: redirectUri, scope: scope) } describe("-authorization") { it("should return the correct url") { let expected = "https://unsplash.com/oauth/authorize?response_type=code&scope=scope1%20scope2&redirect_uri=redirect%3A%2F%2Fworks&client_id=client_id" expect(subject.authorization().absoluteString) == expected } } describe("-authentication") { context("when there's no code in the url") { it("should return nil") { let url = URL(string: "\(redirectUri!)?state=abc")! expect(subject.authentication(url)).to(beNil()) } } context("when it has code and state") { var request: URLRequest! beforeEach { let url = URL(string: "\(redirectUri!)?code=abc&state")! request = subject.authentication(url) } it("should return a request with the correct URL") { let expected = "https://unsplash.com/oauth/token?client_secret=client_secret&grant_type=authorization_code&code=abc&client_id=client_id&redirect_uri=redirect%3A%2F%2Fworks" expect(request.url?.absoluteString) == expected } it("should return a request with the a JSON Accept header") { expect(request.value(forHTTPHeaderField: "Accept")) == "application/json" } it("should return a request with the POST method") { expect(request.httpMethod) == "POST" } } } describe("-sessionAdapter") { context("when the data has not the correct format") { it("should return nil") { let dictionary: [String: Any] = [:] let data = try! JSONSerialization.data(withJSONObject: dictionary, options: []) expect(subject.sessionAdapter(data, URLResponse())).to(beNil()) } } context("when the data has the correct format") { it("should return the session") { let dictionary = ["access_token": "tooooken"] let data = try! JSONSerialization.data(withJSONObject: dictionary, options: []) expect(subject.sessionAdapter(data, URLResponse())?.accessToken) == "tooooken" } } } } }
mit
cd80f8a078874a33cb562c3b9554e663
38.988235
192
0.506914
5.302652
false
false
false
false
googleads/googleads-mobile-ios-examples
Swift/admob/NativeAdvancedExample/NativeAdvancedExample/ViewController.swift
1
8303
// // 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 GoogleMobileAds import UIKit class ViewController: UIViewController { /// The view that holds the native ad. @IBOutlet weak var nativeAdPlaceholder: UIView! /// Indicates whether videos should start muted. @IBOutlet weak var startMutedSwitch: UISwitch! /// The refresh ad button. @IBOutlet weak var refreshAdButton: UIButton! /// Displays the current status of video assets. @IBOutlet weak var videoStatusLabel: UILabel! /// The SDK version label. @IBOutlet weak var versionLabel: UILabel! /// The height constraint applied to the ad view, where necessary. var heightConstraint: NSLayoutConstraint? /// The ad loader. You must keep a strong reference to the GADAdLoader during the ad loading /// process. var adLoader: GADAdLoader! /// The native ad view that is being presented. var nativeAdView: GADNativeAdView! /// The ad unit ID. let adUnitID = "ca-app-pub-3940256099942544/3986624511" override func viewDidLoad() { super.viewDidLoad() versionLabel.text = GADMobileAds.sharedInstance().sdkVersion guard let nibObjects = Bundle.main.loadNibNamed("NativeAdView", owner: nil, options: nil), let adView = nibObjects.first as? GADNativeAdView else { assert(false, "Could not load nib file for adView") } setAdView(adView) refreshAd(nil) } func setAdView(_ view: GADNativeAdView) { // Remove the previous ad view. nativeAdView = view nativeAdPlaceholder.addSubview(nativeAdView) nativeAdView.translatesAutoresizingMaskIntoConstraints = false // Layout constraints for positioning the native ad view to stretch the entire width and height // of the nativeAdPlaceholder. let viewDictionary = ["_nativeAdView": nativeAdView!] self.view.addConstraints( NSLayoutConstraint.constraints( withVisualFormat: "H:|[_nativeAdView]|", options: NSLayoutConstraint.FormatOptions(rawValue: 0), metrics: nil, views: viewDictionary) ) self.view.addConstraints( NSLayoutConstraint.constraints( withVisualFormat: "V:|[_nativeAdView]|", options: NSLayoutConstraint.FormatOptions(rawValue: 0), metrics: nil, views: viewDictionary) ) } // MARK: - Actions /// Refreshes the native ad. @IBAction func refreshAd(_ sender: AnyObject!) { refreshAdButton.isEnabled = false videoStatusLabel.text = "" adLoader = GADAdLoader( adUnitID: adUnitID, rootViewController: self, adTypes: [.native], options: nil) adLoader.delegate = self adLoader.load(GADRequest()) } /// Returns a `UIImage` representing the number of stars from the given star rating; returns `nil` /// if the star rating is less than 3.5 stars. func imageOfStars(from starRating: NSDecimalNumber?) -> UIImage? { guard let rating = starRating?.doubleValue else { return nil } if rating >= 5 { return UIImage(named: "stars_5") } else if rating >= 4.5 { return UIImage(named: "stars_4_5") } else if rating >= 4 { return UIImage(named: "stars_4") } else if rating >= 3.5 { return UIImage(named: "stars_3_5") } else { return nil } } } extension ViewController: GADVideoControllerDelegate { func videoControllerDidEndVideoPlayback(_ videoController: GADVideoController) { videoStatusLabel.text = "Video playback has ended." } } extension ViewController: GADAdLoaderDelegate { func adLoader(_ adLoader: GADAdLoader, didFailToReceiveAdWithError error: Error) { print("\(adLoader) failed with error: \(error.localizedDescription)") refreshAdButton.isEnabled = true } } extension ViewController: GADNativeAdLoaderDelegate { func adLoader(_ adLoader: GADAdLoader, didReceive nativeAd: GADNativeAd) { refreshAdButton.isEnabled = true // Set ourselves as the native ad delegate to be notified of native ad events. nativeAd.delegate = self // Deactivate the height constraint that was set when the previous video ad loaded. heightConstraint?.isActive = false // Populate the native ad view with the native ad assets. // The headline and mediaContent are guaranteed to be present in every native ad. (nativeAdView.headlineView as? UILabel)?.text = nativeAd.headline nativeAdView.mediaView?.mediaContent = nativeAd.mediaContent // Some native ads will include a video asset, while others do not. Apps can use the // GADVideoController's hasVideoContent property to determine if one is present, and adjust their // UI accordingly. let mediaContent = nativeAd.mediaContent if mediaContent.hasVideoContent { // By acting as the delegate to the GADVideoController, this ViewController receives messages // about events in the video lifecycle. mediaContent.videoController.delegate = self videoStatusLabel.text = "Ad contains a video asset." } else { videoStatusLabel.text = "Ad does not contain a video." } // This app uses a fixed width for the GADMediaView and changes its height to match the aspect // ratio of the media it displays. if let mediaView = nativeAdView.mediaView, nativeAd.mediaContent.aspectRatio > 0 { heightConstraint = NSLayoutConstraint( item: mediaView, attribute: .height, relatedBy: .equal, toItem: mediaView, attribute: .width, multiplier: CGFloat(1 / nativeAd.mediaContent.aspectRatio), constant: 0) heightConstraint?.isActive = true } // These assets are not guaranteed to be present. Check that they are before // showing or hiding them. (nativeAdView.bodyView as? UILabel)?.text = nativeAd.body nativeAdView.bodyView?.isHidden = nativeAd.body == nil (nativeAdView.callToActionView as? UIButton)?.setTitle(nativeAd.callToAction, for: .normal) nativeAdView.callToActionView?.isHidden = nativeAd.callToAction == nil (nativeAdView.iconView as? UIImageView)?.image = nativeAd.icon?.image nativeAdView.iconView?.isHidden = nativeAd.icon == nil (nativeAdView.starRatingView as? UIImageView)?.image = imageOfStars(from: nativeAd.starRating) nativeAdView.starRatingView?.isHidden = nativeAd.starRating == nil (nativeAdView.storeView as? UILabel)?.text = nativeAd.store nativeAdView.storeView?.isHidden = nativeAd.store == nil (nativeAdView.priceView as? UILabel)?.text = nativeAd.price nativeAdView.priceView?.isHidden = nativeAd.price == nil (nativeAdView.advertiserView as? UILabel)?.text = nativeAd.advertiser nativeAdView.advertiserView?.isHidden = nativeAd.advertiser == nil // In order for the SDK to process touch events properly, user interaction should be disabled. nativeAdView.callToActionView?.isUserInteractionEnabled = false // Associate the native ad view with the native ad object. This is // required to make the ad clickable. // Note: this should always be done after populating the ad views. nativeAdView.nativeAd = nativeAd } } // MARK: - GADNativeAdDelegate implementation extension ViewController: GADNativeAdDelegate { func nativeAdDidRecordClick(_ nativeAd: GADNativeAd) { print("\(#function) called") } func nativeAdDidRecordImpression(_ nativeAd: GADNativeAd) { print("\(#function) called") } func nativeAdWillPresentScreen(_ nativeAd: GADNativeAd) { print("\(#function) called") } func nativeAdWillDismissScreen(_ nativeAd: GADNativeAd) { print("\(#function) called") } func nativeAdDidDismissScreen(_ nativeAd: GADNativeAd) { print("\(#function) called") } func nativeAdWillLeaveApplication(_ nativeAd: GADNativeAd) { print("\(#function) called") } }
apache-2.0
ebb935424fa03638aa47d15852770561
34.482906
101
0.715404
4.646335
false
false
false
false
HocTran/CoreDataNotification
Example/CoreDataNotification/DataController.swift
1
1892
// // DataController.swift // CoreDataNotification // // Created by HocTran on 11/30/16. // Copyright © 2016 Hoc Tran. All rights reserved. // import UIKit import UIKit import CoreData class DataController: NSObject { static var `default` = DataController() var managedObjectContext: NSManagedObjectContext private override init() { // This resource is the same name as your xcdatamodeld contained in your project. guard let modelURL = Bundle.main.url(forResource: "CoreDataNotification", withExtension:"momd") else { fatalError("Error loading model from bundle") } // The managed object model for the application. It is a fatal error for the application not to be able to find and load its model. guard let mom = NSManagedObjectModel(contentsOf: modelURL) else { fatalError("Error initializing mom from: \(modelURL)") } let psc = NSPersistentStoreCoordinator(managedObjectModel: mom) managedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType) managedObjectContext.persistentStoreCoordinator = psc // DispatchQueue.global(qos: .background).async { let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask) let docUrl = urls[urls.endIndex - 1] let storeUrl = docUrl.appendingPathComponent("CoreDataNotification.sqlite") do { try psc.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: storeUrl, options: nil) } catch { fatalError("Error migrating store: \(error)") } // } } func save() { do { try managedObjectContext.save() } catch { print(error) } } }
mit
4aa58de42f7d52438a555b696802b2e2
33.381818
139
0.631941
5.296919
false
false
false
false
sindanar/PDStrategy
Example/PDStrategy/PDStrategy/FRCTableCell.swift
1
628
// // FRCTableCell.swift // PDStrategy // // Created by Pavel Deminov on 08/11/2017. // Copyright © 2017 Pavel Deminov. All rights reserved. // import UIKit class FRCTableCell: PDTableViewCell { var titleLabel: PDTitleLabel! override func setup() { selectionStyle = .none weak var wSelf = self TitleBuilder.addTitle(to: contentView, with: { (titleLabel) in wSelf?.titleLabel = titleLabel; }) } override func updateUI() { let item = self.itemInfo if let managed = item { titleLabel.text = managed.pdTitle } } }
mit
82179bcde8a499a9ee4bd03f6348931e
20.62069
70
0.599681
4.071429
false
false
false
false
mlibai/XZKit
XZKit/Code/Networking/XZAPIError.swift
1
4664
// // APIError.swift // HTTP // // Created by Xezun on 2018/7/3. // Copyright © 2018年 XEZUN INC. All rights reserved. // import Foundation extension APIError { /// 接口请求没有发生错,如果没有错误,请不要抛出异常,包括 noError 。 public static let noError = APIError(code: -0, message: "No error.") /// 错误码 -1 ,未定义的错误。 public static let undefined = APIError(code: -1, message: "An undefined error occurred.") /// 错误码 -2 ,请求被取消了。 public static let cancelled = APIError(code: -2, message: "The request was cancelled.") /// 错误码 -3 ,请求被忽略了。 public static let ignored = APIError(code: -3, message: "The request was ignored.") /// 错误码 -4 ,请求超截止时间,非网络响应的超时。 public static let overtime = APIError(code: -4, message: "The request is out of the limited time.") /// 错误码 -100 ,因为无网络而发生的错误。 /// - Note: 建议网络错误 -100 ~ -199 。 public static let unreachable = APIError(code: -100, message: "The network was unreachable.") /// 错误码 - 200 ,无效的接口请求。 /// - Note: 建议 request 错误 -200 ~ -299 。 public static let invalidRequest = APIError(code: -200, message: "The api request is invalid.") /// 错误码 -300 ,请求结果无法解析。 /// - Note: 建议 response 错误 -300 ~ -399 。 public static let unexpectedResponse = APIError(code: -300, message: "The response data can not be parsed.") } /// 描述接口请求、解析过程中产生的错误。 /// - Note: 根据 HTTP 规范,HTTP 状态码在 100 ~ 999 之间。 /// - Note: 本框架内部错误在 -1 ~ -999 之间,请参见预定义的枚举。 /// - Note: 业务逻辑错误码,建议定义在上述范围之外的数值。 /// - Note: 如果错误码相同,即表示为相同的错误。 public struct APIError: Error, CustomStringConvertible { /// APIError 错误码。 public let code: Int /// APIError 错误信息描述。 public let message: String /// APIError 初始化。 /// /// - Parameters: /// - code: 错误码 /// - message: 描述 public init(code: Int, message: String) { self.code = code self.message = message } /// 错误描述信息。 public var description: String { return "XZKit.APIError(code: \(code), message: \(message))" } } extension APIError: Equatable { public static func ==(lhs: APIError, rhs: APIError) -> Bool { return lhs.code == rhs.code } /// 提供通过 APIError.code 与 APIError 直接比较的方法。 /// /// - Parameters: /// - lhs: Error Code. /// - rhs: APIError /// - Returns: The number is equal to the error code or not. public static func ==(lhs: Int, rhs: APIError) -> Bool { return lhs == rhs.code } } extension APIError: _ObjectiveCBridgeable { /// 将任意 Error 转换为 APIError 。 /// - 如果待转换的 Error 不是 APIError ,则将其转换为 NSError 然后使用 code、description 属性创建 APIError 。 /// /// - Parameter error: 任意的 Error 对象。 public init(_ error: Error) { if let apiError = error as? APIError { self = apiError } else { let nsError = error as NSError self = APIError.init(code: nsError.code, message: nsError.localizedDescription) } } public typealias _ObjectiveCType = NSError /// APIError 的错误域,在桥接到 Objective-C NSError 时使用。 public static let Domain = "com.xezun.XZKit.Networking" public func _bridgeToObjectiveC() -> NSError { return NSError.init(domain: APIError.Domain, code: code, userInfo: [NSLocalizedDescriptionKey: message]) } public static func _forceBridgeFromObjectiveC(_ source: NSError, result: inout APIError?) { result = APIError.init(code: source.code, message: source.localizedDescription) } public static func _conditionallyBridgeFromObjectiveC(_ source: NSError, result: inout APIError?) -> Bool { _forceBridgeFromObjectiveC(source, result: &result) return true } public static func _unconditionallyBridgeFromObjectiveC(_ source: NSError?) -> APIError { if let nsError = source { return APIError.init(code: nsError.code, message: nsError.localizedDescription) } return APIError.noError } }
mit
035638b399c455ea906000f24765893b
29.18797
112
0.616438
3.827455
false
false
false
false
soheilbm/SwiftStructures
Source/Factories/Trie.swift
10
3337
// // Trie.swift // SwiftStructures // // Created by Wayne Bishop on 10/14/14. // Copyright (c) 2014 Arbutus Software Inc. All rights reserved. // import Foundation public class Trie { private var root: TrieNode! init(){ root = TrieNode() } //finds all words based on the prefix func findWord(keyword: String) -> Array<String>! { if (keyword.length == 0){ return nil } var current: TrieNode = root var wordList: Array<String>! = Array<String>() while (keyword.length != current.level) { var childToUse: TrieNode! let searchKey: String = keyword.substringToIndex(current.level + 1) print("looking for prefix: \(searchKey)..") //iterate through any children for child in current.children { if (child.key == searchKey) { childToUse = child current = childToUse break } } if childToUse == nil { return nil } } //end while //retrieve the keyword and any decendants if ((current.key == keyword) && (current.isFinal)) { wordList.append(current.key) } //include only children that are words for child in current.children { if (child.isFinal == true) { wordList.append(child.key) } } return wordList } //end function //builds a iterative tree of dictionary content func addWord(keyword: String) { if keyword.length == 0 { return } var current: TrieNode = root while(keyword.length != current.level) { var childToUse: TrieNode! let searchKey: String = keyword.substringToIndex(current.level + 1) //println("current has \(current.children.count) children..") //iterate through the node children for child in current.children { if (child.key == searchKey) { childToUse = child break } } //create a new node if (childToUse == nil) { childToUse = TrieNode() childToUse.key = searchKey childToUse.level = current.level + 1 current.children.append(childToUse) } current = childToUse } //end while //add final end of word check if (keyword.length == current.level) { current.isFinal = true print("end of word reached!") return } } //end function }
mit
44d28c7477d4d09cafe71b8abcad68b4
21.402685
79
0.421936
6.191095
false
false
false
false
edragoev1/pdfjet
Sources/PDFjet/QRMath.swift
1
1367
/** * Copyright 2009 Kazuhiko Arase URL: http://www.d-project.com/ Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php The word "QR Code" is registered trademark of DENSO WAVE INCORPORATED http://www.denso-wave.com/qrcode/faqpatent-e.html */ import Foundation /** * QRMath * @author Kazuhiko Arase */ class QRMath { static let singleton = QRMath() private static var EXP_TABLE = [Int](repeating: 0, count: 256) private static var LOG_TABLE = [Int](repeating: 0, count: 256) private init() { for i in 0..<8 { QRMath.EXP_TABLE[i] = (1 << i) } for i in 8..<256 { QRMath.EXP_TABLE[i] = QRMath.EXP_TABLE[i - 4] ^ QRMath.EXP_TABLE[i - 5] ^ QRMath.EXP_TABLE[i - 6] ^ QRMath.EXP_TABLE[i - 8] } for i in 0..<255 { QRMath.LOG_TABLE[QRMath.EXP_TABLE[i]] = i } } public func glog(_ n: Int) -> Int { if n < 1 { Swift.print("log(" + String(describing: n) + ")") } return QRMath.LOG_TABLE[n] } public func gexp(_ i: Int) -> Int { var n = i while n < 0 { n += 255 } while n >= 256 { n -= 255 } return QRMath.EXP_TABLE[n] } }
mit
06f4c650340eda5a6d5a97030a335eb9
21.048387
66
0.503292
3.326034
false
false
false
false
vtongcoder/iOS-9-Sampler
iOS9Sampler/SampleViewControllers/StringTransformViewController.swift
110
3254
// // StringTransformViewController.swift // iOS9Sampler // // Created by Shuichi Tsutsumi on 9/16/15. // Copyright © 2015 Shuichi Tsutsumi. All rights reserved. // // Thanks to: // http://nshipster.com/ios9/ import UIKit class StringTransformViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate { @IBOutlet weak var kanaLabel: UILabel! @IBOutlet weak var widthSwitch: UISwitch! @IBOutlet weak var transformedLabel: UILabel! @IBOutlet weak var picker: UIPickerView! var items: [String] = [ NSStringTransformToLatin, NSStringTransformLatinToKatakana, NSStringTransformLatinToHiragana, NSStringTransformLatinToHangul, NSStringTransformLatinToArabic, NSStringTransformLatinToHebrew, NSStringTransformLatinToThai, NSStringTransformLatinToCyrillic, NSStringTransformLatinToGreek ] var orgKana = "" override func viewDidLoad() { super.viewDidLoad() orgKana = kanaLabel.text! self.pickerView(picker, didSelectRow: 0, inComponent: 0) } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } // ========================================================================= // MARK: - UIPickerViewDataSource func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int { return 1 } func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return items.count } // ========================================================================= // MARK: - UIPickerViewDelegate func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { let item = items[row] // strip the prefix var title: String let toIndex = item.rangeOfString("To")?.endIndex if toIndex != nil { // example: ")kCFStringTransformToLatin" title = item.substringFromIndex(toIndex!) } else { // example: ")kCFStringTransformLatinKatakana" let latinIndex = item.rangeOfString("Latin")!.endIndex title = item.substringFromIndex(latinIndex) } return title } func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { transformedLabel.text = "Hello, world!".stringByApplyingTransform(items[row], reverse: false) } // ========================================================================= // MARK: - Actions @IBAction func hiraganaToKatakanaSwitchChanged(sender: UISwitch) { kanaLabel.text = kanaLabel.text!.stringByApplyingTransform(NSStringTransformHiraganaToKatakana, reverse: !sender.on) widthSwitch.enabled = sender.on } @IBAction func widthSwitchChanged(sender: UISwitch) { kanaLabel.text = kanaLabel.text!.stringByApplyingTransform(NSStringTransformFullwidthToHalfwidth, reverse: !sender.on) } }
mit
49f9ada2bc8af72860bb2e2e8eac38df
28.572727
126
0.609591
5.385762
false
false
false
false
Kalvin126/BatteryNotifier
BatteryNotifier Widget/ListRowViewController.swift
1
1819
// // ListRowViewController.swift // BatteryNotifier Widget // // Created by Kalvin Loc on 3/24/16. // Copyright © 2016 Red Panda. All rights reserved. // import Cocoa final class ListRowViewController: NSViewController { // MARK: Children @IBOutlet private var deviceImageView: NSImageView! @IBOutlet private var nameField: NSTextField! @IBOutlet private var batteryLevelField: NSTextField! @IBOutlet private var batteryView: NSView! private var batteryViewController: BatteryViewController? // MARK: NSViewController override var nibName: String? { "ListRowViewController" } override func loadView() { super.loadView() guard let controller = MainStoryBoard.instantiateController(with: .batteryViewController), let batteryController = controller as? BatteryViewController else { fatalError(#function + " - Could not instantiate BatteryViewController") } self.batteryViewController = batteryController batteryView.addSubview(batteryViewController!.view, positioned: .above, relativeTo: nil) guard let dictionary = representedObject as? [String: AnyObject], let device = Device(dictionary: dictionary) else { return } let image = NSImage(named: device.deviceClass) ?? NSImage(named: "iPhone") deviceImageView.image = image nameField.cell?.title = device.name batteryLevelField.cell?.title = "\(device.currentBatteryCapacity)%" batteryViewController?.displayedDevice = device batteryViewController?.whiteThemeOnly = true } override func viewDidLayout() { super.viewDidLayout() var battFrame = batteryView.frame battFrame.origin = .zero batteryViewController!.view.frame = battFrame } }
gpl-3.0
af6c64b6fb73f8f865439872c92b9802
29.813559
98
0.69912
5.036011
false
false
false
false
sacrelee/iOSDev
Demos/Demo_SketchpadSwift/Demo_SketchpadSwift/DrawingView.swift
1
3342
// // DrawingView.swift // Demo_SketchpadSwift // // Created by SACRELEE on 16/2/2. // Copyright © 2016年 SACRELEE. All rights reserved. // import UIKit import SnapKit class DrawingView: UIView { var lineChanged = false var lineModels = [LineModel]() var willDraw:() -> Void = {_ in } let fm = FMDBManager.defaultManager init() { super.init(frame: CGRectZero) self.backgroundColor = UIColor.whiteColor() let panGr = UIPanGestureRecognizer.init(target: self, action:#selector(DrawingView.panInView(_:))) self.addGestureRecognizer(panGr) } func canSaveData() -> Bool{ if self.lineModels.count != 0 && lineChanged == true { return true } return false } func saveData() -> Bool{ if fm.saveLineModels(lineModels: self.lineModels) { print("data saved!") lineChanged = false return true } print("data save error!") return false } func readData(){ if let tmpModels = fm.getLineModelArray() { if tmpModels.count != 0 { self.lineModels = tmpModels self.setNeedsLayout() print("data read!") return } print("null data!") return } print("read data error!") } func clearData(){ lineModels.removeAll() self.setNeedsDisplay() } func panInView( pan:UIPanGestureRecognizer){ if pan.state == .Began{ self.willDraw() lineChanged = true lineModels.append(LineModel.init()) } let lastLM = lineModels.last! lastLM.points.append(pan.locationInView(self)) if pan.state == .Ended{ print("\(lastLM.points)") } self.setNeedsDisplay() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func drawRect(rect: CGRect) { let contextRef = UIGraphicsGetCurrentContext() CGContextScaleCTM( contextRef, 1, 1) for line in lineModels { ConfigManager.colorArray[line.colorIndex].set() CGContextSetLineWidth( contextRef, line.width) let firstPoint = line.points[0] CGContextBeginPath( contextRef) CGContextMoveToPoint( contextRef, firstPoint.x, firstPoint.y) var lastPoint = firstPoint for i in 0 ..< line.points.count { let currentPoint = line.points[i] CGContextAddQuadCurveToPoint( contextRef, lastPoint.x, lastPoint.y, ( currentPoint.x + lastPoint.x) / 2.0, ( currentPoint.y + lastPoint.y ) / 2.0) lastPoint = currentPoint } CGContextAddLineToPoint( contextRef, lastPoint.x, lastPoint.y) CGContextStrokePath( contextRef) } } /* // Only override drawRect: if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func drawRect(rect: CGRect) { // Drawing code } */ }
apache-2.0
d65197c4c14d8983415e307217fb72f9
26.146341
163
0.551363
4.991031
false
false
false
false
overtake/TelegramSwift
Telegram-Mac/ForumTopicEmojiSelectRowItem.swift
1
2072
// // ForumTopicEmojiSelectRowItem.swift // Telegram // // Created by Mike Renoir on 27.09.2022. // Copyright © 2022 Telegram. All rights reserved. // import Foundation import TGUIKit final class ForumTopicEmojiSelectRowItem : GeneralRowItem { let getView: ()->NSView let context: AccountContext init(_ initialSize: NSSize, stableId: AnyHashable, context: AccountContext, getView: @escaping()->NSView, viewType: GeneralViewType) { self.getView = getView self.context = context super.init(initialSize, stableId: stableId, viewType: viewType) } override func viewClass() -> AnyClass { return ForumTopicEmojiSelectRowView.self } override var height: CGFloat { if let table = self.table { var height: CGFloat = 0 table.enumerateItems(with: { item in if item != self { height += item.height } return true }) return table.frame.height - height } return 250 } override var instantlyResize: Bool { return true } override var reloadOnTableHeightChanged: Bool { return true } } private final class ForumTopicEmojiSelectRowView: GeneralContainableRowView { required init(frame frameRect: NSRect) { super.init(frame: frameRect) } override func layout() { super.layout() guard let item = item as? ForumTopicEmojiSelectRowItem else { return } let view = item.getView() view.frame = self.containerView.bounds } override func set(item: TableRowItem, animated: Bool = false) { super.set(item: item, animated: animated) guard let item = item as? ForumTopicEmojiSelectRowItem else { return } let view = item.getView() addSubview(view) needsLayout = true } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
gpl-2.0
d49cc808f642736c2df720d131eb1a73
25.551282
138
0.60309
4.827506
false
false
false
false
saeta/penguin
Sources/PenguinPipeline/Pipeline/SequencePipelineIterator.swift
1
2236
// Copyright 2020 Penguin Authors // // 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 Dispatch public struct SequencePipelineIterator<T: Sequence>: PipelineIteratorProtocol { public typealias Element = T.Element typealias UnderlyingIterator = T.Iterator init(underlying: T, name: String) { self.underlying = underlying.makeIterator() self.queue = DispatchQueue(label: "PenguinParallel.PipelineSequence.\(name)") } public mutating func next() throws -> Element? { // Ensure access to the underlying iterator is thread safe. return queue.sync { underlying.next() } } var underlying: UnderlyingIterator let queue: DispatchQueue } public struct SequencePipelineSequence<T: Sequence>: PipelineSequence { public typealias Element = T.Element typealias UnderlyingIterator = T.Iterator init(underlying: T, name: String) { self.underlying = underlying self.name = name } public func makeIterator() -> SequencePipelineIterator<T> { SequencePipelineIterator(underlying: underlying, name: name) } let underlying: T let name: String } extension Sequence { public func asPipelineSequence( name: String? = nil, file: StaticString = #file, function: StaticString = #function, line: Int = #line ) -> SequencePipelineSequence<Self> { return SequencePipelineSequence(underlying: self, name: name ?? "\(file):\(line):\(function).") } public func makePipelineIterator( name: String? = nil, file: StaticString = #file, function: StaticString = #function, line: Int = #line ) -> SequencePipelineIterator<Self> { return SequencePipelineIterator(underlying: self, name: name ?? "\(file):\(line):\(function)") } }
apache-2.0
8612caf9e01b5fe0b8c42fb35b6436bb
29.630137
99
0.716905
4.375734
false
false
false
false
wikimedia/wikipedia-ios
WMF Framework/ExtensionViewController.swift
1
1497
import UIKit open class ExtensionViewController: UIViewController, Themeable { public final var theme: Theme = Theme.widgetLight open func apply(theme: Theme) { self.theme = theme } var isFirstLayout = true open override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() updateThemeFromTraitCollection(force: isFirstLayout) isFirstLayout = false } private func updateThemeFromTraitCollection(force: Bool = false) { let compatibleTheme = Theme.widgetThemeCompatible(with: traitCollection) guard theme !== compatibleTheme else { if force { apply(theme: theme) } return } apply(theme: compatibleTheme) } override open func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { super.traitCollectionDidChange(previousTraitCollection) updateThemeFromTraitCollection() } public func openAppInActivity(with activityType: WMFUserActivityType) { self.extensionContext?.open(NSUserActivity.wmf_baseURLForActivity(of: activityType)) } public func openApp(with url: URL?, fallback fallbackURL: URL? = nil) { guard let wikipediaSchemeURL = url?.replacingSchemeWithWikipediaScheme ?? fallbackURL else { openAppInActivity(with: .explore) return } self.extensionContext?.open(wikipediaSchemeURL) } }
mit
47f1668ed8c0c8ed255c8eafecd254cd
32.266667
100
0.667335
5.483516
false
false
false
false