repo_name
stringlengths 7
91
| path
stringlengths 8
658
| copies
stringclasses 125
values | size
stringlengths 3
6
| content
stringlengths 118
674k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6.09
99.2
| line_max
int64 17
995
| alpha_frac
float64 0.3
0.9
| ratio
float64 2
9.18
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
lyft/SwiftLint | Source/SwiftLintFramework/Rules/SwitchCaseOnNewlineRule.swift | 1 | 3914 | import Foundation
import SourceKittenFramework
private func wrapInSwitch(_ str: String) -> String {
return "switch foo {\n \(str)\n}\n"
}
public struct SwitchCaseOnNewlineRule: ASTRule, ConfigurationProviderRule, OptInRule {
public var configuration = SeverityConfiguration(.warning)
public init() {}
public static let description = RuleDescription(
identifier: "switch_case_on_newline",
name: "Switch Case on Newline",
description: "Cases inside a switch should always be on a newline",
kind: .style,
nonTriggeringExamples: [
"/*case 1: */return true",
"//case 1:\n return true",
"let x = [caseKey: value]",
"let x = [key: .default]",
"if case let .someEnum(value) = aFunction([key: 2]) { }",
"guard case let .someEnum(value) = aFunction([key: 2]) { }",
"for case let .someEnum(value) = aFunction([key: 2]) { }",
"enum Environment {\n case development\n}",
"enum Environment {\n case development(url: URL)\n}",
"enum Environment {\n case development(url: URL) // staging\n}"
] + [
"case 1:\n return true",
"default:\n return true",
"case let value:\n return true",
"case .myCase: // error from network\n return true",
"case let .myCase(value) where value > 10:\n return false",
"case let .myCase(value)\n where value > 10:\n return false",
"case let .myCase(code: lhsErrorCode, description: _)\n where lhsErrorCode > 10:\n return false",
"case #selector(aFunction(_:)):\n return false\n"
].map(wrapInSwitch),
triggeringExamples: [
"↓case 1: return true",
"↓case let value: return true",
"↓default: return true",
"↓case \"a string\": return false",
"↓case .myCase: return false // error from network",
"↓case let .myCase(value) where value > 10: return false",
"↓case #selector(aFunction(_:)): return false\n",
"↓case let .myCase(value)\n where value > 10: return false",
"↓case .first,\n .second: return false"
].map(wrapInSwitch)
)
public func validate(file: File, kind: StatementKind,
dictionary: [String: SourceKitRepresentable]) -> [StyleViolation] {
guard kind == .case,
let offset = dictionary.offset,
let length = dictionary.length,
let lastElement = dictionary.elements.last,
let lastElementOffset = lastElement.offset,
let lastElementLength = lastElement.length,
case let start = lastElementOffset + lastElementLength,
case let rangeLength = offset + length - start,
case let byteRange = NSRange(location: start, length: rangeLength),
let firstToken = firstNonCommentToken(inByteRange: byteRange, file: file),
let (tokenLine, _) = file.contents.bridge().lineAndCharacter(forByteOffset: firstToken.offset),
let (caseEndLine, _) = file.contents.bridge().lineAndCharacter(forByteOffset: start),
tokenLine == caseEndLine else {
return []
}
return [
StyleViolation(ruleDescription: type(of: self).description,
severity: configuration.severity,
location: Location(file: file, byteOffset: offset))
]
}
private func firstNonCommentToken(inByteRange byteRange: NSRange, file: File) -> SyntaxToken? {
return file.syntaxMap.tokens(inByteRange: byteRange).first { token -> Bool in
guard let kind = SyntaxKind(rawValue: token.type) else {
return false
}
return !SyntaxKind.commentKinds.contains(kind)
}
}
}
| mit | 7885adaf7305a454eeffafbc2b279a00 | 44.302326 | 109 | 0.584959 | 4.638095 | false | false | false | false |
kosicki123/eidolon | Kiosk/Bid Fulfillment/BidDetailsPreviewView.swift | 1 | 3455 | import UIKit
import Artsy_UILabels
import Artsy_UIButtons
import UIImageViewAligned
public class BidDetailsPreviewView: UIView {
dynamic var bidDetails: BidDetails?
dynamic let artworkImageView = UIImageViewAligned()
dynamic let artistNameLabel = ARSansSerifLabel()
dynamic let artworkTitleLabel = ARSerifLabel()
dynamic let currentBidPriceLabel = ARSerifLabel()
override public func awakeFromNib() {
self.backgroundColor = UIColor.whiteColor()
artistNameLabel.numberOfLines = 1
artworkTitleLabel.numberOfLines = 1
currentBidPriceLabel.numberOfLines = 1
artworkImageView.alignRight = true
artworkImageView.alignBottom = true
artworkImageView.contentMode = .ScaleAspectFit
artistNameLabel.font = UIFont.sansSerifFontWithSize(14)
currentBidPriceLabel.font = UIFont.serifBoldFontWithSize(14)
RACObserve(self, "bidDetails.saleArtwork.artwork").subscribeNext { [weak self] (artwork) -> Void in
if let url = (artwork as? Artwork)?.images?.first?.thumbnailURL() {
self?.artworkImageView.sd_setImageWithURL(url)
} else {
self?.artworkImageView.image = nil
}
}
RAC(self, "artistNameLabel.text") <~ RACObserve(self, "bidDetails.saleArtwork.artwork").map({ (artwork) -> AnyObject! in
return (artwork as? Artwork)?.artists?.first?.name
}).mapNilToEmptyString()
RAC(self, "artworkTitleLabel.attributedText") <~ RACObserve(self, "bidDetails.saleArtwork.artwork").map({ (artwork) -> AnyObject! in
if let artwork = artwork as? Artwork {
return artwork.titleAndDate
} else {
return nil
}
}).mapNilToEmptyAttributedString()
RAC(self, "currentBidPriceLabel.text") <~ RACObserve(self, "bidDetails").map({ (bidDetails) -> AnyObject! in
if let cents = (bidDetails as? BidDetails)?.bidAmountCents {
return "Your bid: " + NSNumberFormatter.currencyStringForCents(cents)
}
return nil
}).mapNilToEmptyString()
for subview in [artworkImageView, artistNameLabel, artworkTitleLabel, currentBidPriceLabel] {
self.addSubview(subview)
}
self.constrainHeight("60")
artworkImageView.alignTop("0", leading: "0", bottom: "0", trailing: nil, toView: self)
artworkImageView.constrainWidth("84")
artworkImageView.constrainHeight("60")
artistNameLabel.alignAttribute(.Top, toAttribute: .Top, ofView: self, predicate: "0")
artistNameLabel.constrainHeight("16")
artworkTitleLabel.alignAttribute(.Top, toAttribute: .Bottom, ofView: artistNameLabel, predicate: "8")
artworkTitleLabel.constrainHeight("16")
currentBidPriceLabel.alignAttribute(.Top, toAttribute: .Bottom, ofView: artworkTitleLabel, predicate: "4")
currentBidPriceLabel.constrainHeight("16")
UIView.alignAttribute(.Leading, ofViews: [artistNameLabel, artworkTitleLabel, currentBidPriceLabel], toAttribute:.Trailing, ofViews: [artworkImageView, artworkImageView, artworkImageView], predicate: "20")
UIView.alignAttribute(.Trailing, ofViews: [artistNameLabel, artworkTitleLabel, currentBidPriceLabel], toAttribute:.Trailing, ofViews: [self, self, self], predicate: "0")
}
}
| mit | ca66394bc7cef28250c5b26ede013841 | 43.294872 | 213 | 0.668596 | 5.30722 | false | false | false | false |
Koalappp/Alamofire | Source/ResponseSerialization.swift | 1 | 14541 | //
// ResponseSerialization.swift
//
// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
// MARK: ResponseSerializer
/**
The type in which all response serializers must conform to in order to serialize a response.
*/
public protocol ResponseSerializerType {
/// The type of serialized object to be created by this `ResponseSerializerType`.
associatedtype SerializedObject
/// The type of error to be created by this `ResponseSerializer` if serialization fails.
associatedtype ErrorObject: ErrorType
/**
A closure used by response handlers that takes a request, response, data and error and returns a result.
*/
var serializeResponse: (NSURLRequest?, NSHTTPURLResponse?, NSData?, NSError?) -> ALResult<SerializedObject, ErrorObject> { get }
}
// MARK: -
/**
A generic `ResponseSerializerType` used to serialize a request, response, and data into a serialized object.
*/
public struct ResponseSerializer<Value, Error: ErrorType>: ResponseSerializerType {
/// The type of serialized object to be created by this `ResponseSerializer`.
public typealias SerializedObject = Value
/// The type of error to be created by this `ResponseSerializer` if serialization fails.
public typealias ErrorObject = Error
/**
A closure used by response handlers that takes a request, response, data and error and returns a result.
*/
public var serializeResponse: (NSURLRequest?, NSHTTPURLResponse?, NSData?, NSError?) -> ALResult<Value, Error>
/**
Initializes the `ResponseSerializer` instance with the given serialize response closure.
- parameter serializeResponse: The closure used to serialize the response.
- returns: The new generic response serializer instance.
*/
public init(serializeResponse: (NSURLRequest?, NSHTTPURLResponse?, NSData?, NSError?) -> ALResult<Value, Error>) {
self.serializeResponse = serializeResponse
}
}
// MARK: - Default
extension Request {
/**
Adds a handler to be called once the request has finished.
- parameter queue: The queue on which the completion handler is dispatched.
- parameter completionHandler: The code to be executed once the request has finished.
- returns: The request.
*/
public func response(
queue queue: dispatch_queue_t? = nil,
completionHandler: (NSURLRequest?, NSHTTPURLResponse?, NSData?, NSError?) -> Void)
-> Self
{
delegate.queue.addOperationWithBlock {
dispatch_async(queue ?? dispatch_get_main_queue()) {
completionHandler(self.request, self.response, self.delegate.data, self.delegate.error)
}
}
return self
}
/**
Adds a handler to be called once the request has finished.
- parameter queue: The queue on which the completion handler is dispatched.
- parameter responseSerializer: The response serializer responsible for serializing the request, response,
and data.
- parameter completionHandler: The code to be executed once the request has finished.
- returns: The request.
*/
public func response<T: ResponseSerializerType>(
queue queue: dispatch_queue_t? = nil,
responseSerializer: T,
completionHandler: Response<T.SerializedObject, T.ErrorObject> -> Void)
-> Self
{
delegate.queue.addOperationWithBlock {
let result = responseSerializer.serializeResponse(
self.request,
self.response,
self.delegate.data,
self.delegate.error
)
let requestCompletedTime = self.endTime ?? CFAbsoluteTimeGetCurrent()
let initialResponseTime = self.delegate.initialResponseTime ?? requestCompletedTime
let timeline = Timeline(
requestStartTime: self.startTime ?? CFAbsoluteTimeGetCurrent(),
initialResponseTime: initialResponseTime,
requestCompletedTime: requestCompletedTime,
serializationCompletedTime: CFAbsoluteTimeGetCurrent()
)
let response = Response<T.SerializedObject, T.ErrorObject>(
request: self.request,
response: self.response,
data: self.delegate.data,
result: result,
timeline: timeline
)
dispatch_async(queue ?? dispatch_get_main_queue()) { completionHandler(response) }
}
return self
}
}
// MARK: - Data
extension Request {
/**
Creates a response serializer that returns the associated data as-is.
- returns: A data response serializer.
*/
public static func dataResponseSerializer() -> ResponseSerializer<NSData, NSError> {
return ResponseSerializer { _, response, data, error in
guard error == nil else { return .Failure(error!) }
if let response = response where response.statusCode == 204 { return .Success(NSData()) }
guard let validData = data else {
let failureReason = "Data could not be serialized. Input data was nil."
let error = Error.error(code: .DataSerializationFailed, failureReason: failureReason)
return .Failure(error)
}
return .Success(validData)
}
}
/**
Adds a handler to be called once the request has finished.
- parameter completionHandler: The code to be executed once the request has finished.
- returns: The request.
*/
public func responseData(
queue queue: dispatch_queue_t? = nil,
completionHandler: Response<NSData, NSError> -> Void)
-> Self
{
return response(queue: queue, responseSerializer: Request.dataResponseSerializer(), completionHandler: completionHandler)
}
}
// MARK: - String
extension Request {
/**
Creates a response serializer that returns a string initialized from the response data with the specified
string encoding.
- parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the server
response, falling back to the default HTTP default character set, ISO-8859-1.
- returns: A string response serializer.
*/
public static func stringResponseSerializer(
encoding encoding: NSStringEncoding? = nil)
-> ResponseSerializer<String, NSError>
{
return ResponseSerializer { _, response, data, error in
guard error == nil else { return .Failure(error!) }
if let response = response where response.statusCode == 204 { return .Success("") }
guard let validData = data else {
let failureReason = "String could not be serialized. Input data was nil."
let error = Error.error(code: .StringSerializationFailed, failureReason: failureReason)
return .Failure(error)
}
var convertedEncoding = encoding
if let encodingName = response?.textEncodingName where convertedEncoding == nil {
convertedEncoding = CFStringConvertEncodingToNSStringEncoding(
CFStringConvertIANACharSetNameToEncoding(encodingName)
)
}
let actualEncoding = convertedEncoding ?? NSISOLatin1StringEncoding
if let string = String(data: validData, encoding: actualEncoding) {
return .Success(string)
} else {
let failureReason = "String could not be serialized with encoding: \(actualEncoding)"
let error = Error.error(code: .StringSerializationFailed, failureReason: failureReason)
return .Failure(error)
}
}
}
/**
Adds a handler to be called once the request has finished.
- parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the
server response, falling back to the default HTTP default character set,
ISO-8859-1.
- parameter completionHandler: A closure to be executed once the request has finished.
- returns: The request.
*/
public func responseString(
queue queue: dispatch_queue_t? = nil,
encoding: NSStringEncoding? = nil,
completionHandler: Response<String, NSError> -> Void)
-> Self
{
return response(
queue: queue,
responseSerializer: Request.stringResponseSerializer(encoding: encoding),
completionHandler: completionHandler
)
}
}
// MARK: - JSON
extension Request {
/**
Creates a response serializer that returns a JSON object constructed from the response data using
`NSJSONSerialization` with the specified reading options.
- parameter options: The JSON serialization reading options. `.AllowFragments` by default.
- returns: A JSON object response serializer.
*/
public static func JSONResponseSerializer(
options options: NSJSONReadingOptions = .AllowFragments)
-> ResponseSerializer<AnyObject, NSError>
{
return ResponseSerializer { _, response, data, error in
guard error == nil else { return .Failure(error!) }
if let response = response where response.statusCode == 204 { return .Success(NSNull()) }
guard let validData = data where validData.length > 0 else {
let failureReason = "JSON could not be serialized. Input data was nil or zero length."
let error = Error.error(code: .JSONSerializationFailed, failureReason: failureReason)
return .Failure(error)
}
do {
let JSON = try NSJSONSerialization.JSONObjectWithData(validData, options: options)
return .Success(JSON)
} catch {
return .Failure(error as NSError)
}
}
}
/**
Adds a handler to be called once the request has finished.
- parameter options: The JSON serialization reading options. `.AllowFragments` by default.
- parameter completionHandler: A closure to be executed once the request has finished.
- returns: The request.
*/
public func responseJSON(
queue queue: dispatch_queue_t? = nil,
options: NSJSONReadingOptions = .AllowFragments,
completionHandler: Response<AnyObject, NSError> -> Void)
-> Self
{
return response(
queue: queue,
responseSerializer: Request.JSONResponseSerializer(options: options),
completionHandler: completionHandler
)
}
}
// MARK: - Property List
extension Request {
/**
Creates a response serializer that returns an object constructed from the response data using
`NSPropertyListSerialization` with the specified reading options.
- parameter options: The property list reading options. `NSPropertyListReadOptions()` by default.
- returns: A property list object response serializer.
*/
public static func propertyListResponseSerializer(
options options: NSPropertyListReadOptions = NSPropertyListReadOptions())
-> ResponseSerializer<AnyObject, NSError>
{
return ResponseSerializer { _, response, data, error in
guard error == nil else { return .Failure(error!) }
if let response = response where response.statusCode == 204 { return .Success(NSNull()) }
guard let validData = data where validData.length > 0 else {
let failureReason = "Property list could not be serialized. Input data was nil or zero length."
let error = Error.error(code: .PropertyListSerializationFailed, failureReason: failureReason)
return .Failure(error)
}
do {
let plist = try NSPropertyListSerialization.propertyListWithData(validData, options: options, format: nil)
return .Success(plist)
} catch {
return .Failure(error as NSError)
}
}
}
/**
Adds a handler to be called once the request has finished.
- parameter options: The property list reading options. `0` by default.
- parameter completionHandler: A closure to be executed once the request has finished. The closure takes 3
arguments: the URL request, the URL response, the server data and the result
produced while creating the property list.
- returns: The request.
*/
public func responsePropertyList(
queue queue: dispatch_queue_t? = nil,
options: NSPropertyListReadOptions = NSPropertyListReadOptions(),
completionHandler: Response<AnyObject, NSError> -> Void)
-> Self
{
return response(
queue: queue,
responseSerializer: Request.propertyListResponseSerializer(options: options),
completionHandler: completionHandler
)
}
}
| mit | ab79259b3fa069c6db5ba54abbceb7e8 | 37.468254 | 132 | 0.642253 | 5.566998 | false | false | false | false |
sabyapradhan/IBM-Ready-App-for-Banking | HatchReadyApp/apps/Hatch/iphone/native/Hatch/Controllers/Watson/WatsonBestPlanViewController.swift | 1 | 7460 | /*
Licensed Materials - Property of IBM
© Copyright IBM Corporation 2015. All Rights Reserved.
*/
import UIKit
/**
* This view controller is 4/5 of the Watson questionnaire, and presents the user with the best bank plan for them, and allows them to either accept or refuse to switch to this recommended account. It also will initiate the MobileFirst Platform call to receive all available offers and generate a WatsonTradeoffSolution from the bank. The user may also tap to view all account options.
*/
class WatsonBestPlanViewController: UIViewController {
@IBOutlet var whiteView: UIView!
@IBOutlet var backButton: UIButton!
@IBOutlet var menuButton: UIButton!
@IBOutlet var animationImage: UIImageView!
@IBOutlet var accountLabel: UILabel!
var watsonChoice : [Int] = [-1,-1,-1]
var coverView : UIView!
//@IBOutlet weak var menuBar: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
menuButton.addTarget(self.navigationController, action: "menuButtonTapped:", forControlEvents: UIControlEvents.TouchUpInside)
backButton.addTarget(self.navigationController, action: "backButtonTapped:", forControlEvents: UIControlEvents.TouchUpInside)
backButton.addTarget(self, action: "backButtonTapped", forControlEvents: UIControlEvents.TouchDown)
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.coverView = UIView(frame: self.view.frame)
self.coverView.backgroundColor = UIColor.greenHatch()
self.view.addSubview(self.coverView)
self.accountLabel.text = ""
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
MILLoadViewManager.sharedInstance.show()
formatWatsonProblem()
}
/**
This method will push to the next view controller in the UIPageViewController
:param: sender
*/
@IBAction func tappedYes(sender: AnyObject) {
//transition to next view
var viewControllerDestination = self.storyboard?.instantiateViewControllerWithIdentifier("finish") as! UIViewController
self.navigationController?.pushViewController(viewControllerDestination, animated: true)
}
/**
This method will push to the next view controller in the UIPageViewController
:param: sender
*/
@IBAction func tappedNo(sender: AnyObject) {
MenuViewController.goToDashboard()
}
/**
This method will display the all offers page
:param: sender
*/
@IBAction func tappedAccountOptions(sender: AnyObject) {
let storyboard = UIStoryboard(name: "Watson", bundle: nil)
let nativeViewController = storyboard.instantiateViewControllerWithIdentifier("AllOffersNativeViewController") as! NativeViewController
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
appDelegate.hybridViewController.isFirstInstance = true
WL.sharedInstance().sendActionToJS("changePage", withData: ["route":"offers"]);
self.navigationController?.pushViewController(nativeViewController, animated: true)
}
/**
This method will fetch the list of available offers and call gotOffers upon completion
*/
func formatWatsonProblem() {
OffersDataManager.sharedInstance.fetchOffersData(gotOffers)
}
/**
This method is called when the list of offers is returned from MobileFirst Platform. A Watson problem is then created and sent to watson in order to receive a Watson Tradeoff Solution.
:param: offers Offers dictionary received from MobileFirst Platform
*/
func gotOffers(offers : [NSObject: AnyObject]) {
let offerArray : [Offer] = Offer.parseJsonArray(offers) //make all offers into an array of Offer objects
var problem = [NSObject : AnyObject]()
problem = ProblemJSONHelper.formatProblemJSON(offerArray, response: watsonChoice) //send this JSON that contains Watson Problem back to WL
var singleProblemArray : Array<AnyObject> = []
singleProblemArray.append(problem)
WatsonDataManager.sharedInstance.fetchWatsonData(singleProblemArray,callback: gotWatsonSolution)
}
/**
This method is called when the Watson Tradeoff Solution has been received. The resolution is parsed and the recommended bank account (offer) is displayed to the user.
:param: solution The solution dictionary returned from MobileFirst Platform
*/
func gotWatsonSolution (solution : [NSObject : AnyObject]) {
let resolution = Resolution(jsonDict: solution)
let solutionArray = resolution.solutions as [Solution]
var chosenOffer : String = ""
for solution in solutionArray {
if (solution.status == "FRONT") {
chosenOffer = solution.solutionRef
break
}
}
var attributedString : NSMutableAttributedString = NSMutableAttributedString(string: "")
switch chosenOffer {
case "offer0" :
attributedString = NSMutableAttributedString(string: "BUSINESS BASIC\nCHECKING ACCOUNT")
case "offer1" :
attributedString = NSMutableAttributedString(string:"BUSINESS SELECT\nCHECKING ACCOUNT")
case "offer2" :
attributedString = NSMutableAttributedString(string:"BUSINESS ADVANTAGE\nCHECKING ACCOUNT")
case "offer3" :
attributedString = NSMutableAttributedString(string: "BUSINESS BASIC\nSAVINGS ACCOUNT")
case "offer4" :
attributedString = NSMutableAttributedString(string:"BUSINESS SELECT\nSAVINGS ACCOUNT")
case "offer5" :
attributedString = NSMutableAttributedString(string:"BUSINESS ADVANTAGE\nSAVINGS ACCOUNT")
default : ""
attributedString = NSMutableAttributedString(string:"")
}
accountLabel.attributedText = attributedString
Utils.setUpViewKern(self.view)
self.coverView.removeFromSuperview()
MILLoadViewManager.sharedInstance.hide(callback: self.startAnimation)
}
/**
This method will animate an egg rolling to reveal the suggested Account offer after pausing
*/
func startAnimation () {
self.accountLabel.hidden = false
self.animationImage.hidden = false
var timer = NSTimer.scheduledTimerWithTimeInterval(0.35, target: self, selector: Selector("beginAnimation"), userInfo: nil, repeats: false)
}
/**
This method will animate an egg rolling to reveal the suggested Account offer
*/
func beginAnimation () {
var imageArray : [UIImage] = []
for (var i = 1; i < 100; i++) {
let image : UIImage = UIImage(named: "hatchegg\(i)")!
imageArray.append(image)
}
self.animationImage.animationImages = imageArray
self.animationImage.animationDuration = 3.00
self.animationImage.animationRepeatCount = 1
self.animationImage.image = imageArray.last
self.animationImage.startAnimating()
self.whiteView.hidden = false
}
/**
This method will hide the animation of the egg rolling when the user has pressed back
*/
func backButtonTapped(){
self.animationImage.hidden = true
}
}
| epl-1.0 | 955885560b32a46c07946c85c3191589 | 39.102151 | 385 | 0.683604 | 5.362329 | false | false | false | false |
qiscus/qiscus-sdk-ios | Qiscus/Qiscus/Library/QLoadingViewController.swift | 1 | 2821 | //
// QLoadingViewController.swift
// QiscusSDK
//
// Created by Ahmad Athaullah on 12/16/16.
// Copyright © 2016 Ahmad Athaullah. All rights reserved.
//
import UIKit
open class QLoadingViewController: UIViewController {
open static let sharedInstance = QLoadingViewController()
@IBOutlet weak var loadingImage: UIImageView!
@IBOutlet weak var loadingLabel: UILabel!
@IBOutlet weak var percentageLabel: UILabel!
open var percentage:Float = 0
open var showPercentage = false
open var showText = false
open var isPresence = false
open var isBlocking = false
open var interuptLoadingAction:()->Void = ({})
open var dismissImmediately: Bool = false
fileprivate init() {
super.init(nibName: "QLoadingViewController", bundle: Qiscus.bundle)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override open func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.setNavigationBarHidden(true , animated: false)
self.loadingLabel.isHidden = !showText
self.percentageLabel.isHidden = !showText
}
override open func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.navigationController?.setNavigationBarHidden(true , animated: false)
self.isPresence = true
var images: [UIImage] = []
for i in 0...11 {
images.append(Qiscus.image(named: "loading\(i+1)")!)
}
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(QLoadingViewController.onTapLoading))
self.view.addGestureRecognizer(tap)
self.loadingImage.animationImages = images
self.loadingImage.animationDuration = 1
self.loadingImage.animationRepeatCount = 0
self.loadingImage.startAnimating()
}
override open func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
self.isPresence = false
}
override open func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@objc open func onTapLoading() {
if !self.isBlocking{
self.dismiss(animated: true, completion: {
self.interuptLoadingAction()
})
}
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit | 2f69df774ccd633e60acfdc7a334d62e | 32.975904 | 134 | 0.661702 | 5.062837 | false | false | false | false |
contentful-labs/Wunderschnell | Phone App/AppDelegate.swift | 1 | 5096 | //
// AppDelegate.swift
// WatchButton
//
// Created by Boris Bügling on 09/05/15.
// Copyright (c) 2015 Boris Bügling. All rights reserved.
//
import Cube
import Keys
import MMWormhole
import WatchConnectivity
import UIKit
// Change the used sphere.io project here
let SphereIOProject = "ecomhack-demo-67"
private extension Array {
func randomItem() -> Element {
let index = Int(arc4random_uniform(UInt32(self.count)))
return self[index]
}
}
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, WCSessionDelegate {
private let beaconController = BeaconController()
private let keys = WatchbuttonKeys()
private var sphereClient: SphereIOClient!
private let wormhole = MMWormhole(applicationGroupIdentifier: AppGroupIdentifier, optionalDirectory: DirectoryIdentifier)
var selectedProduct: [String:AnyObject]?
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
WCSession.defaultSession().delegate = self
WCSession.defaultSession().activateSession()
// TODO: WCSession.defaultSession().reachable
PayPalMobile.initializeWithClientIdsForEnvironments([ PayPalEnvironmentSandbox: WatchbuttonKeys().payPalSandboxClientId()])
beaconController.beaconCallback = { (beacon, _) in
self.wormhole.passMessageObject(true, identifier: Reply.BeaconRanged.rawValue)
}
beaconController.outOfRangeCallback = {
self.wormhole.passMessageObject(false, identifier: Reply.BeaconRanged.rawValue)
}
beaconController.refresh()
return true
}
func initializeSphereClient() {
if sphereClient == nil {
sphereClient = SphereIOClient(clientId: keys.sphereIOClientId(), clientSecret: keys.sphereIOClientSecret(), project: SphereIOProject)
}
}
func session(session: WCSession, didReceiveMessage message: [String : AnyObject], replyHandler: ([String : AnyObject]) -> Void) {
if let command = message[CommandIdentifier] as? String {
handleCommand(command, replyHandler)
} else {
fatalError("Invalid WatchKit extension request :(")
}
// Keep the phone app running a bit for demonstration purposes
UIApplication.sharedApplication().beginBackgroundTaskWithExpirationHandler() {}
}
// MARK: - Helpers
func fetchSelectedProduct(completion: () -> ()) {
initializeSphereClient()
if selectedProduct != nil {
completion()
return
}
sphereClient.fetchProductData() { (result) in
if let value = result.value, results = value["results"] as? [[String:AnyObject]] {
self.selectedProduct = results.randomItem()
completion()
} else {
fatalError("Failed to retrieve products from Sphere.IO")
}
}
}
private func handleCommand(command: String, _ reply: (([String : AnyObject]) -> Void)) {
initializeSphereClient()
switch(Command(rawValue: command)!) {
case .GetProduct:
fetchSelectedProduct() {
if let product = self.selectedProduct {
reply([Reply.Product.rawValue: product])
}
return
}
break
case .MakeOrder:
fetchSelectedProduct() {
self.sphereClient.quickOrder(product: self.selectedProduct!, to:retrieveShippingAddress()) { (result) in
if let order = result.value {
let pp = Product(self.selectedProduct!)
let amount = pp.price["amount"]!
let currency = pp.price["currency"]!
let client = PayPalClient(clientId: self.keys.payPalSandboxClientId(), clientSecret: self.keys.payPalSandboxClientSecret(), code: retrieveRefreshToken())
client.pay(retrievePaymentId(), currency, amount) { (paid) in
reply([Reply.Paid.rawValue: paid])
self.wormhole.passMessageObject(paid, identifier: Reply.Paid.rawValue)
self.sphereClient.setPaymentState(paid ? .Paid : .Failed, forOrder: order) { (result) in
//println("Payment state result: \(result)")
if let order = result.value {
self.sphereClient.setState(.Complete, forOrder: order) { (result) in
print("Ordered successfully.")
}
} else {
fatalError("Failed to set order to complete state.")
}
}
}
}
}
}
break
default:
break
}
}
}
| mit | a4064ff7f7272ae179adf6e0b0753a9e | 35.913043 | 177 | 0.585198 | 5.367756 | false | false | false | false |
motylevm/skstylekit | Sources/SKTextView.swift | 1 | 2495 | //
// Copyright (c) 2016 Mikhail Motylev https://twitter.com/mikhail_motylev
//
// 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
open class SKTextView: UITextView {
// MARK: - Private properties
private var hasExternalAttributedText: Bool = false
// MARK: - Style properties
@IBInspectable open var styleName: String? {
get {
return style?.name
}
set {
style = StyleKit.style(withName: newValue)
}
}
open var style: SKStyle? {
didSet {
if oldValue != style {
applyCurrentStyle(includeTextStyle: !hasExternalAttributedText && text != nil)
}
}
}
// MARK: - Style application
private func applyCurrentStyle(includeTextStyle: Bool) {
if includeTextStyle {
style?.apply(textView: self, text: text)
hasExternalAttributedText = false
}
else {
style?.apply(view: self)
}
}
// MARK: - Overridden properties
override open var text: String? {
didSet {
applyCurrentStyle(includeTextStyle: true)
}
}
override open var attributedText: NSAttributedString? {
didSet {
hasExternalAttributedText = attributedText != nil
}
}
}
| mit | e91b701730bb5020562a478ab32521dd | 30.987179 | 94 | 0.624048 | 4.950397 | false | false | false | false |
webim/webim-client-sdk-ios | WebimClientLibrary/Backend/WebimActionsImpl.swift | 1 | 28252 | //
// WebimActionsImpl.swift
// WebimClientLibrary
//
// Created by Nikita Lazarev-Zubov on 11.08.17.
// Copyright © 2017 Webim. 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
/**
Class that is responsible for history storage when it is set to memory mode.
- author:
Nikita Lazarev-Zubov
- copyright:
2017 Webim
*/
final class WebimActionsImpl {
// MARK: - Constants
private enum ChatMode: String {
case online = "online"
}
private enum Action: String {
case closeChat = "chat.close"
case geoResponse = "geo_response"
case rateOperator = "chat.operator_rate_select"
case respondSentryCall = "chat.action_request.call_sentry_action_request"
case sendMessage = "chat.message"
case deleteMessage = "chat.delete_message"
case sendChatHistory = "chat.send_chat_history"
case setDeviceToken = "set_push_token"
case setPrechat = "chat.set_prechat_fields"
case setVisitorTyping = "chat.visitor_typing"
case startChat = "chat.start"
case surveyAnswer = "survey.answer"
case surveyCancel = "survey.cancel"
case chatRead = "chat.read_by_visitor"
case widgetUpdate = "widget.update"
case keyboardResponse = "chat.keyboard_response"
case sendSticker = "sticker"
case clearHistory = "chat.clear_history"
case reaction = "chat.react_message"
}
// MARK: - Properties
private let baseURL: String
let actionRequestLoop: ActionRequestLoop
// MARK: - Initialization
init(baseURL: String,
actionRequestLoop: ActionRequestLoop
) {
self.baseURL = baseURL
self.actionRequestLoop = actionRequestLoop
}
}
extension WebimActionsImpl: WebimActions {
// MARK: - Methods
func send(message: String,
clientSideID: String,
dataJSONString: String?,
isHintQuestion: Bool?,
dataMessageCompletionHandler: DataMessageCompletionHandler? = nil,
editMessageCompletionHandler: EditMessageCompletionHandler? = nil,
sendMessageCompletionHandler: SendMessageCompletionHandler? = nil) {
var dataToPost = [Parameter.actionn.rawValue: Action.sendMessage.rawValue,
Parameter.clientSideID.rawValue: clientSideID,
Parameter.message.rawValue: message] as [String: Any]
if let isHintQuestion = isHintQuestion {
dataToPost[Parameter.hintQuestion.rawValue] = isHintQuestion
}
if let dataJSONString = dataJSONString {
dataToPost[Parameter.data.rawValue] = dataJSONString
}
let urlString = baseURL + ServerPathSuffix.doAction.rawValue
actionRequestLoop.enqueue(request: WebimRequest(httpMethod: .post,
primaryData: dataToPost,
messageID: clientSideID,
contentType: ContentType.urlEncoded.rawValue,
baseURLString: urlString,
dataMessageCompletionHandler: dataMessageCompletionHandler,
editMessageCompletionHandler: editMessageCompletionHandler,
sendMessageCompletionHandler: sendMessageCompletionHandler))
}
func send(file: Data,
filename: String,
mimeType: String,
clientSideID: String,
completionHandler: SendFileCompletionHandler? = nil,
uploadFileToServerCompletionHandler: UploadFileToServerCompletionHandler? = nil) {
let dataToPost = [Parameter.chatMode.rawValue: ChatMode.online.rawValue,
Parameter.clientSideID.rawValue: clientSideID] as [String: Any]
let urlString = baseURL + ServerPathSuffix.uploadFile.rawValue
let boundaryString = NSUUID().uuidString
actionRequestLoop.enqueue(request: WebimRequest(httpMethod: .post,
primaryData: dataToPost,
messageID: clientSideID,
filename: filename,
mimeType: mimeType,
fileData: file,
boundaryString: boundaryString,
contentType: (ContentType.multipartBody.rawValue + boundaryString),
baseURLString: urlString,
sendFileCompletionHandler: completionHandler,
uploadFileToServerCompletionHandler: uploadFileToServerCompletionHandler))
}
func sendFiles(message: String,
clientSideID: String,
isHintQuestion: Bool?,
sendFilesCompletionHandler: SendFilesCompletionHandler?) {
var dataToPost = [Parameter.actionn.rawValue: Action.sendMessage.rawValue,
Parameter.clientSideID.rawValue: clientSideID,
Parameter.message.rawValue: message,
Parameter.kind.rawValue: "file_visitor"] as [String: Any]
if let isHintQuestion = isHintQuestion {
dataToPost[Parameter.hintQuestion.rawValue] = isHintQuestion
}
let urlString = baseURL + ServerPathSuffix.doAction.rawValue
actionRequestLoop.enqueue(request: WebimRequest(httpMethod: .post,
primaryData: dataToPost,
messageID: clientSideID,
contentType: ContentType.urlEncoded.rawValue,
baseURLString: urlString,
sendFilesCompletionHandler: sendFilesCompletionHandler))
}
func replay(message: String,
clientSideID: String,
quotedMessageID: String) {
let dataToPost = [Parameter.actionn.rawValue: Action.sendMessage.rawValue,
Parameter.clientSideID.rawValue: clientSideID,
Parameter.message.rawValue: message,
Parameter.quote.rawValue: getQuotedMessage(repliedMessageId: quotedMessageID)] as [String: Any]
let urlString = baseURL + ServerPathSuffix.doAction.rawValue
actionRequestLoop.enqueue(request: WebimRequest(httpMethod: .post,
primaryData: dataToPost,
messageID: clientSideID,
contentType: ContentType.urlEncoded.rawValue,
baseURLString: urlString))
}
private func getQuotedMessage(repliedMessageId: String) -> String {
return "{\"ref\":{\"msgId\":\"\(repliedMessageId)\",\"msgChannelSideId\":null,\"chatId\":null}}";
}
func delete(clientSideID: String,
completionHandler: DeleteMessageCompletionHandler?) {
let dataToPost = [Parameter.actionn.rawValue: Action.deleteMessage.rawValue,
Parameter.clientSideID.rawValue: clientSideID] as [String: Any]
let urlString = baseURL + ServerPathSuffix.doAction.rawValue
actionRequestLoop.enqueue(request: WebimRequest(httpMethod: .post,
primaryData: dataToPost,
messageID: clientSideID,
contentType: ContentType.urlEncoded.rawValue,
baseURLString: urlString,
deleteMessageCompletionHandler: completionHandler))
}
func deleteUploadedFile(fileGuid: String,
completionHandler: DeleteUploadedFileCompletionHandler?) {
let dataToPost = [Parameter.guid.rawValue: fileGuid] as [String: Any]
let urlString = baseURL + ServerPathSuffix.fileDelete.rawValue
actionRequestLoop.enqueue(request: WebimRequest(httpMethod: .get,
primaryData: dataToPost,
contentType: ContentType.urlEncoded.rawValue,
baseURLString: urlString,
deleteUploadedFileCompletionHandler: completionHandler))
}
func startChat(withClientSideID clientSideID: String,
firstQuestion: String? = nil,
departmentKey: String? = nil,
customFields: String? = nil) {
var dataToPost = [Parameter.actionn.rawValue: Action.startChat.rawValue,
Parameter.forceOnline.rawValue: true,
Parameter.clientSideID.rawValue: clientSideID] as [String: Any]
if let firstQuestion = firstQuestion {
dataToPost[Parameter.firstQuestion.rawValue] = firstQuestion
}
if let departmentKey = departmentKey {
dataToPost[Parameter.departmentKey.rawValue] = departmentKey
}
if let custom_fields = customFields {
dataToPost[Parameter.customFields.rawValue] = custom_fields
}
let urlString = baseURL + ServerPathSuffix.doAction.rawValue
actionRequestLoop.enqueue(request: WebimRequest(httpMethod: .post,
primaryData: dataToPost,
contentType: ContentType.urlEncoded.rawValue,
baseURLString: urlString))
}
func closeChat() {
let dataToPost = [Parameter.actionn.rawValue: Action.closeChat.rawValue] as [String: Any]
let urlString = baseURL + ServerPathSuffix.doAction.rawValue
actionRequestLoop.enqueue(request: WebimRequest(httpMethod: .post,
primaryData: dataToPost,
contentType: ContentType.urlEncoded.rawValue,
baseURLString: urlString))
}
func set(visitorTyping: Bool,
draft: String?,
deleteDraft: Bool) {
var dataToPost = [Parameter.actionn.rawValue: Action.setVisitorTyping.rawValue,
Parameter.deleteDraft.rawValue: deleteDraft ? "1" : "0", // true / false
Parameter.visitorTyping.rawValue: visitorTyping ? "1" : "0"] as [String: Any] // true / false
if let draft = draft {
dataToPost[Parameter.draft.rawValue] = draft
}
let urlString = baseURL + ServerPathSuffix.doAction.rawValue
actionRequestLoop.enqueue(request: WebimRequest(httpMethod: .post,
primaryData: dataToPost,
contentType: ContentType.urlEncoded.rawValue,
baseURLString: urlString))
}
func set(prechatFields: String) {
let dataToPost = [Parameter.actionn.rawValue: Action.setPrechat.rawValue,
Parameter.prechat.rawValue: prechatFields] as [String: Any]
let urlString = baseURL + ServerPathSuffix.doAction.rawValue
actionRequestLoop.enqueue(request: WebimRequest(httpMethod: .post,
primaryData: dataToPost,
contentType: ContentType.urlEncoded.rawValue,
baseURLString: urlString))
}
func requestHistory(since: String?,
completion: @escaping (_ data: Data?) throws -> ()) {
var dataToPost = [String: Any]()
if let since = since {
dataToPost[Parameter.since.rawValue] = since
}
let urlString = baseURL + ServerPathSuffix.getHistory.rawValue
actionRequestLoop.enqueue(request: WebimRequest(httpMethod: .get,
primaryData: dataToPost,
baseURLString: urlString,
historyRequestCompletionHandler: completion))
}
func requestHistory(beforeMessageTimestamp: Int64,
completion: @escaping (_ data: Data?) throws -> ()) {
let dataToPost = [Parameter.beforeTimestamp.rawValue: beforeMessageTimestamp] as [String: Any]
let urlString = baseURL + ServerPathSuffix.getHistory.rawValue
actionRequestLoop.enqueue(request: WebimRequest(httpMethod: .get,
primaryData: dataToPost,
baseURLString: urlString,
historyRequestCompletionHandler: completion))
}
func rateOperatorWith(id: String?,
rating: Int,
visitorNote: String?,
completionHandler: RateOperatorCompletionHandler?) {
var dataToPost = [Parameter.actionn.rawValue: Action.rateOperator.rawValue,
Parameter.rating.rawValue: String(rating)] as [String: Any]
if let id = id {
dataToPost[Parameter.operatorID.rawValue] = id
}
if let visitorNote = visitorNote {
dataToPost[Parameter.visitorNote.rawValue] = visitorNote
}
let urlString = baseURL + ServerPathSuffix.doAction.rawValue
actionRequestLoop.enqueue(request: WebimRequest(httpMethod: .post,
primaryData: dataToPost,
contentType: ContentType.urlEncoded.rawValue,
baseURLString: urlString,
rateOperatorCompletionHandler: completionHandler))
}
func respondSentryCall(id: String) {
let dataToPost = [Parameter.actionn.rawValue: Action.respondSentryCall.rawValue,
Parameter.clientSideID.rawValue: id] as [String: Any]
let urlString = baseURL + ServerPathSuffix.doAction.rawValue
actionRequestLoop.enqueue(request: WebimRequest(httpMethod: .post,
primaryData: dataToPost,
contentType: ContentType.urlEncoded.rawValue,
baseURLString: urlString))
}
func searchMessagesBy(query: String, completion: @escaping (_ data: Data?) throws -> ()) {
let pageId = self.actionRequestLoop.authorizationData?.getPageID() ?? ""
let authToken = self.actionRequestLoop.authorizationData?.getAuthorizationToken() ?? ""
let parameterDictionary: [String: String] = [Parameter.pageID.rawValue: pageId, Parameter.query.rawValue: query, Parameter.authorizationToken.rawValue:authToken]
let urlString = baseURL + ServerPathSuffix.search.rawValue
actionRequestLoop.enqueue(request: WebimRequest(httpMethod: .get,
primaryData: parameterDictionary,
baseURLString: urlString,
searchMessagesCompletionHandler: completion))
}
func update(deviceToken: String) {
let dataToPost = [Parameter.actionn.rawValue: Action.setDeviceToken.rawValue,
Parameter.deviceToken.rawValue: deviceToken] as [String: Any]
let urlString = baseURL + ServerPathSuffix.doAction.rawValue
actionRequestLoop.enqueue(request: WebimRequest(httpMethod: .post,
primaryData: dataToPost,
contentType: ContentType.urlEncoded.rawValue,
baseURLString: urlString))
}
func setChatRead() {
let dataToPost = [Parameter.actionn.rawValue: Action.chatRead.rawValue] as [String: Any]
let urlString = baseURL + ServerPathSuffix.doAction.rawValue
actionRequestLoop.enqueue(request: WebimRequest(httpMethod: .post,
primaryData: dataToPost,
contentType: ContentType.urlEncoded.rawValue,
baseURLString: urlString))
}
func updateWidgetStatusWith(data: String) {
let dataToPost = [Parameter.actionn.rawValue: Action.widgetUpdate.rawValue,
Parameter.data.rawValue: data] as [String: Any]
let urlString = baseURL + ServerPathSuffix.doAction.rawValue
actionRequestLoop.enqueue(request: WebimRequest(httpMethod: .post,
primaryData: dataToPost,
contentType: ContentType.urlEncoded.rawValue,
baseURLString: urlString))
}
func sendKeyboardRequest(buttonId: String,
messageId: String,
completionHandler: SendKeyboardRequestCompletionHandler?) {
let dataToPost = [Parameter.actionn.rawValue: Action.keyboardResponse.rawValue,
Parameter.buttonId.rawValue: buttonId,
Parameter.requestMessageId.rawValue: messageId] as [String: Any]
let urlString = baseURL + ServerPathSuffix.doAction.rawValue
actionRequestLoop.enqueue(request: WebimRequest(httpMethod: .post,
primaryData: dataToPost,
messageID: messageId,
contentType: ContentType.urlEncoded.rawValue,
baseURLString: urlString,
keyboardResponseCompletionHandler: completionHandler))
}
func sendDialogTo(emailAddress: String,
completionHandler: SendDialogToEmailAddressCompletionHandler?) {
let dataToPost = [Parameter.actionn.rawValue: Action.sendChatHistory.rawValue,
Parameter.email.rawValue: emailAddress] as [String: Any]
let urlString = baseURL + ServerPathSuffix.doAction.rawValue
actionRequestLoop.enqueue(request: WebimRequest(httpMethod: .post,
primaryData: dataToPost,
contentType: ContentType.urlEncoded.rawValue,
baseURLString: urlString,
sendDialogToEmailAddressCompletionHandler: completionHandler))
}
func sendSticker(stickerId: Int,
clientSideId: String,
completionHandler: SendStickerCompletionHandler? = nil) {
let dataToPost = [
Parameter.actionn.rawValue: Action.sendSticker.rawValue,
Parameter.stickerId.rawValue: stickerId,
Parameter.clientSideID.rawValue: clientSideId
] as [String: Any]
let urlString = baseURL + ServerPathSuffix.doAction.rawValue
actionRequestLoop.enqueue(request: WebimRequest(
httpMethod: .post,
primaryData: dataToPost,
contentType: ContentType.urlEncoded.rawValue,
baseURLString: urlString,
sendStickerCompletionHandler: completionHandler
))
}
func sendReaction(reaction: ReactionString,
clientSideId: String,
completionHandler: ReactionCompletionHandler?) {
let react: String
switch reaction {
case .like:
react = "like"
case .dislike:
react = "dislike"
}
let dataToPost = [
Parameter.actionn.rawValue: Action.reaction.rawValue,
Parameter.reaction.rawValue: react,
Parameter.clientSideID.rawValue: clientSideId
] as [String: Any]
let urlString = baseURL + ServerPathSuffix.doAction.rawValue
actionRequestLoop.enqueue(request: WebimRequest(
httpMethod: .post,
primaryData: dataToPost,
contentType: ContentType.urlEncoded.rawValue,
baseURLString: urlString,
reacionCompletionHandler: completionHandler
))
}
func sendQuestionAnswer(surveyID: String,
formID: Int,
questionID: Int,
surveyAnswer: String,
sendSurveyAnswerCompletionHandler: SendSurveyAnswerCompletionHandlerWrapper?) {
let dataToPost = [Parameter.actionn.rawValue: Action.surveyAnswer.rawValue,
Parameter.surveyID.rawValue: surveyID,
Parameter.surveyFormID.rawValue: formID,
Parameter.surveyQuestionID.rawValue: questionID,
Parameter.surveyAnswer.rawValue: surveyAnswer] as [String: Any]
let urlString = baseURL + ServerPathSuffix.doAction.rawValue
actionRequestLoop.enqueue(request: WebimRequest(httpMethod: .post,
primaryData: dataToPost,
contentType: ContentType.urlEncoded.rawValue,
baseURLString: urlString,
sendSurveyAnswerCompletionHandler: sendSurveyAnswerCompletionHandler))
}
func closeSurvey(surveyID: String,
surveyCloseCompletionHandler: SurveyCloseCompletionHandler?) {
let dataToPost = [Parameter.actionn.rawValue: Action.surveyAnswer.rawValue,
Parameter.surveyID.rawValue: surveyID] as [String: Any]
let urlString = baseURL + ServerPathSuffix.doAction.rawValue
actionRequestLoop.enqueue(request: WebimRequest(httpMethod: .post,
primaryData: dataToPost,
contentType: ContentType.urlEncoded.rawValue,
baseURLString: urlString,
surveyCloseCompletionHandler: surveyCloseCompletionHandler))
}
func getOnlineStatus(location: String,
completion: @escaping (_ data: Data?) throws -> ()) {
let dataToPost = [Parameter.location.rawValue: location] as [String: Any]
let urlString = baseURL + ServerPathSuffix.getOnlineStatus.rawValue
actionRequestLoop.enqueue(request: WebimRequest(httpMethod: .get,
primaryData: dataToPost,
contentType: ContentType.urlEncoded.rawValue,
baseURLString: urlString,
locationStatusRequestCompletionHandler: completion))
}
func clearHistory() {
let dataToPost = [Parameter.actionn.rawValue: Action.clearHistory.rawValue] as [String: Any]
let urlString = baseURL + ServerPathSuffix.doAction.rawValue
actionRequestLoop.enqueue(request: WebimRequest(httpMethod: .post,
primaryData: dataToPost,
contentType: ContentType.urlEncoded.rawValue,
baseURLString: urlString))
}
func getRawConfig(forLocation location: String, completion: @escaping (Data?) throws -> ()) {
let dataToPost = [String: Any]()
let urlString = baseURL + ServerPathSuffix.getConfig.rawValue + "/\(location)"
actionRequestLoop.enqueue(request: WebimRequest(httpMethod: .get,
primaryData: dataToPost,
contentType: ContentType.urlEncoded.rawValue,
baseURLString: urlString,
locationSettingsCompletionHandler: completion))
}
func sendGeolocation(latitude: Double, longitude: Double, completionHandler: GeolocationCompletionHandler?) {
let dataToPost = [Parameter.actionn.rawValue: Action.geoResponse.rawValue,
Parameter.latitude.rawValue: latitude,
Parameter.longitude.rawValue: longitude] as [String: Any]
let urlString = baseURL + ServerPathSuffix.doAction.rawValue
actionRequestLoop.enqueue(request: WebimRequest(httpMethod: .post,
primaryData: dataToPost,
contentType: ContentType.urlEncoded.rawValue,
baseURLString: urlString,
geolocationCompletionHandler: completionHandler))
}
}
| mit | ceab6ace96abbaffb14e287722549a38 | 50.836697 | 169 | 0.533857 | 6.273817 | false | false | false | false |
josve05a/wikipedia-ios | Wikipedia/Code/WMFArticlePreviewViewController.swift | 2 | 2948 | import UIKit
open class WMFArticlePreviewViewController: ExtensionViewController {
public var titleTextStyle: DynamicTextStyle = .headline
public var titleTextColor: UIColor = .black {
didSet {
titleLabel.textColor = titleTextColor
}
}
@objc public var titleHTML: String? {
didSet {
updateTitle()
}
}
private func updateTitle() {
titleLabel.attributedText = titleHTML?.byAttributingHTML(with: titleTextStyle, matching: traitCollection)
}
@IBOutlet weak open var marginWidthConstraint: NSLayoutConstraint!
@IBOutlet weak open var imageView: UIImageView!
@IBOutlet weak open var subtitleLabel: UILabel!
@IBOutlet weak open var titleLabel: UILabel!
@IBOutlet weak open var rankLabel: UILabel!
@IBOutlet weak open var separatorView: UIView!
@IBOutlet weak open var viewCountAndSparklineContainerView: UIView!
@IBOutlet weak open var viewCountLabel: UILabel!
@IBOutlet weak open var sparklineView: WMFSparklineView!
@IBOutlet var imageWidthConstraint: NSLayoutConstraint!
@IBOutlet var titleLabelTrailingConstraint: NSLayoutConstraint!
public required init() {
super.init(nibName: "WMFArticlePreviewViewController", bundle: Bundle.wmf)
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
open override func viewDidLoad() {
rankLabel.textColor = .wmf_darkGray
separatorView.backgroundColor = .wmf_darkGray
imageView.accessibilityIgnoresInvertColors = true
updateFonts()
}
open override func awakeFromNib() {
collapseImageAndWidenLabels = true
}
private func updateFonts() {
updateTitle()
}
open override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
updateFonts()
}
@objc open var collapseImageAndWidenLabels: Bool = true {
didSet {
imageWidthConstraint.constant = collapseImageAndWidenLabels ? 0 : 86
titleLabelTrailingConstraint.constant = collapseImageAndWidenLabels ? 0 : 8
self.imageView.alpha = self.collapseImageAndWidenLabels ? 0 : 1
self.view.layoutIfNeeded()
}
}
public override func apply(theme: Theme) {
super.apply(theme: theme)
guard viewIfLoaded != nil else {
return
}
titleTextColor = theme.colors.primaryText
subtitleLabel.textColor = theme.colors.secondaryText
rankLabel.textColor = theme.colors.secondaryText
viewCountLabel.textColor = theme.colors.overlayText
viewCountAndSparklineContainerView.backgroundColor = theme.colors.overlayBackground
separatorView.backgroundColor = theme.colors.border
sparklineView.apply(theme: theme)
}
}
| mit | 3514c8a79735fdd5cb03e3715a245f3b | 34.095238 | 113 | 0.687585 | 5.449168 | false | false | false | false |
kaushaldeo/Olympics | Olympics/ViewControllers/KDWinnersViewController.swift | 1 | 8755 | //
// KDWinnersViewController.swift
// Olympics
//
// Created by Kaushal Deo on 8/6/16.
// Copyright © 2016 Scorpion Inc. All rights reserved.
//
import UIKit
import CoreData
class KDWinnersViewController: UITableViewController, NSFetchedResultsControllerDelegate {
var country : Country!
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
self.navigationItem.backBarButtonItem = UIBarButtonItem(title:" ", style: .Plain, target: nil, action: nil)
self.addBackButton()
self.tableView.backgroundView = nil
self.tableView.backgroundColor = UIColor.backgroundColor()
self.tableView.registerNib(UINib(nibName: "KDWinnerHeaderView", bundle: nil), forHeaderFooterViewReuseIdentifier: "kHeaderView")
self.navigationItem.title = "Breakdown"
self.tableView.rowHeight = UITableViewAutomaticDimension
self.tableView.estimatedRowHeight = 64.0
KDAPIManager.sharedInstance.medal(self.country) { [weak self] (error) in
if let strongSelf = self {
var message = "ResultError".localized("")
if let nserror = error {
//strongSelf.process(nserror)
message = ""
}
else {
//TODO: Stamp the time on refresh control
}
strongSelf.fetchedResultsController.update()
strongSelf.tableView.reloadData()
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return self.fetchedResultsController.sections?.count ?? 0
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let sectionInfo = self.fetchedResultsController.sections![section]
return sectionInfo.numberOfObjects
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! KDWinnerViewCell
// Configure the cell...
cell.setWinner(self.fetchedResultsController.objectAtIndexPath(indexPath) as! Winner)
return cell
}
/*
// 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: Table View Delegate Method
override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerView = tableView.dequeueReusableHeaderFooterViewWithIdentifier("kHeaderView") as! KDWinnerHeaderView
headerView.nameLabel.text = self.country.name
headerView.goldLabel.text = "\(self.country.gold)"
headerView.silverLabel.text = "\(self.country.silver)"
headerView.brozeLabel.text = "\(self.country.bronze)"
if let text = self.country.alias?.lowercaseString {
headerView.iconView.image = UIImage(named: "Images/\(text).png")
}
return headerView
}
override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
if let text = self.country.name {
return max(50, text.size(UIFont.systemFontOfSize(15), width:CGRectGetWidth(tableView.frame) - 221.0).height + 30)
}
return 50.0
}
/*
// 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: - Fetched results controller
lazy var fetchedResultsController: NSFetchedResultsController = {
let context = NSManagedObjectContext.mainContext()
let fetchRequest = NSFetchRequest()
// Edit the entity name as appropriate.
let entity = NSEntityDescription.entityForName("Winner", inManagedObjectContext: context)
fetchRequest.entity = entity
// Set the batch size to a suitable number.
fetchRequest.fetchBatchSize = 20
fetchRequest.sortDescriptors = [NSSortDescriptor(key: "medal", ascending: true)]
fetchRequest.predicate = NSPredicate(format: "team.country = %@ OR athlete.country = %@",self.country,self.country)
// Edit the section name key path and cache name if appropriate.
// nil for section name key path means "no sections".
var fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext:context, sectionNameKeyPath: nil, cacheName: nil)
fetchedResultsController.delegate = self
fetchedResultsController.update()
return fetchedResultsController
}()
func controllerWillChangeContent(controller: NSFetchedResultsController) {
self.tableView.beginUpdates()
}
func controller(controller: NSFetchedResultsController, didChangeSection sectionInfo: NSFetchedResultsSectionInfo, atIndex sectionIndex: Int, forChangeType type: NSFetchedResultsChangeType) {
switch type {
case .Insert:
self.tableView.insertSections(NSIndexSet(index: sectionIndex), withRowAnimation: .Fade)
case .Delete:
self.tableView.deleteSections(NSIndexSet(index: sectionIndex), withRowAnimation: .Fade)
default:
return
}
}
func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?) {
switch type {
case .Insert:
tableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: .Fade)
case .Delete:
tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Fade)
case .Update:
tableView.reloadRowsAtIndexPaths([indexPath!], withRowAnimation: .Fade)
case .Move:
tableView.moveRowAtIndexPath(indexPath!, toIndexPath: newIndexPath!)
}
}
func controllerDidChangeContent(controller: NSFetchedResultsController) {
self.tableView.endUpdates()
}
/*
// Implementing the above methods to update the table view in response to individual changes may have performance implications if a large number of changes are made simultaneously. If this proves to be an issue, you can instead just implement controllerDidChangeContent: which notifies the delegate that all section and object changes have been processed.
func controllerDidChangeContent(controller: NSFetchedResultsController) {
// In the simplest, most efficient, case, reload the table view.
self.tableView.reloadData()
}
*/
}
| apache-2.0 | 9ea5e6ef1945d381f2d82689c7e4429a | 38.972603 | 360 | 0.667923 | 5.843792 | false | false | false | false |
tbergmen/TableViewModel | Example/Tests/TableRowSpec.swift | 1 | 3222 | /*
Copyright (c) 2016 Tunca Bergmen <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
import Foundation
import UIKit
import Quick
import Nimble
import TableViewModel
class TableRowSpec: QuickSpec {
override func spec() {
describe("TableRow") {
var bundle: NSBundle!
var tableRow: TableRow!
var tableView: UITableView!
beforeEach {
bundle = NSBundle(forClass: self.dynamicType)
tableView = UITableView()
tableRow = TableRow(cellIdentifier: "SampleCell1", inBundle: bundle)
}
context("when asked for the cell") {
var cell: UITableViewCell!
beforeEach {
cell = tableRow.cellForTableView(tableView)
}
it("returns the correct cell") {
let label = cell!.contentView.subviews[0] as! UILabel
expect(label.text) == "SampleCell1"
}
it("registers the cell as a reusable cell in the table view") {
let cell = tableView.dequeueReusableCellWithIdentifier("SampleCell1")
expect(cell).toNot(beNil())
}
}
// TODO: test always fails because dequeueReusableCellWithIdentifier
// returns a different instance every time
// context("when the cell is already registered as a reusable cell") {
// beforeEach {
// let nib: UINib = UINib(nibName: "SampleCell1", bundle: bundle)
// tableView.registerNib(nib, forCellReuseIdentifier: "SampleCell1")
// }
//
// context("when asked for the cell") {
// var cell: UITableViewCell!
//
// beforeEach {
// cell = tableRow.cellForTableView(tableView)
// }
//
// it("dequeues the reusable cell") {
// var dequeued = tableView.dequeueReusableCellWithIdentifier("SampleCell1")
// expect(cell) === dequeued
// }
// }
// }
}
}
} | mit | 12c9abc07462b0b7348b57a45826fbc9 | 36.476744 | 99 | 0.604283 | 5.196774 | false | false | false | false |
yuezaixz/UPillow | UPillow/Classes/ViewCotrollers/ConnectViewController.swift | 1 | 11450 | //
// ConnectViewController.swift
// UPillow
//
// Created by 吴迪玮 on 2017/8/4.
// Copyright © 2017年 Podoon. All rights reserved.
//
import UIKit
let kPillowSearchTimes = 30
class ConnectViewController: UIViewController,WDCentralManageDelegate,UITableViewDelegate,UITableViewDataSource,PillowDiscoveryCellDelegate,WDPeriphealDelegate {
@IBOutlet weak var topShadowView: UIView!
@IBOutlet weak var pillowSearchContainer: UIView!
@IBOutlet weak var pillowSearchView: UIView!
@IBOutlet weak var pillowSearchViewYellow: UIView!
@IBOutlet weak var pillowSearchViewPurple: UIView!
@IBOutlet weak var pillowStopSearchView: UIView!
@IBOutlet weak var searchAgainLab: UILabel!
@IBOutlet weak var searchBtn: UIButton!
@IBOutlet weak var pillowSearchTableView: UITableView!
@IBOutlet weak var currentPillowContainerView: UIView!
@IBOutlet weak var pillowSearchStatusLab: UILabel!
@IBOutlet weak var rssiLevelImageView: UIImageView!
@IBOutlet weak var rssiLabel: UILabel!
@IBOutlet weak var rssiDescriptorLabel: UILabel!
@IBOutlet weak var deviceNameLabel: UILabel!
@IBOutlet weak var connectLab: UILabel!
@IBOutlet weak var connectedImageView: UIImageView!
@IBOutlet weak var pillowFoundHeadView: UIView!
@IBOutlet weak var disConnectBtn: UIButton!
private var isSearch:Bool = false
private var currentPeer:WDPeripheal?
private var readRSSITimer:Timer?
override func viewDidLoad() {
super.viewDidLoad()
self.topShadowView.layer.shadowColor = UIColor.black.cgColor//shadowColor阴影颜色
self.topShadowView.layer.shadowOffset = CGSize.init(width: 0.0, height: 0.8) //shadowOffset阴影偏移x,y向(上/下)偏移(-/+)2
self.topShadowView.layer.shadowOpacity = 1.0//阴影透明度,默认0
self.topShadowView.layer.shadowRadius = 5.0//阴影半径
WDCentralManage.shareInstance.delegate = self
// pillowSearchTableView.register(PillowDiscoveryCell.self, forCellReuseIdentifier: PillowDiscoveryCellIdentifier)
pillowSearchTableView.dataSource = self
pillowSearchTableView.delegate = self
pillowSearchTableView.tableFooterView = UIView.init()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if let currentPeer = WDCentralManage.shareInstance.currentPeer {
self.currentPeer = currentPeer
self.currentPeer?.delegate = self
loadConnectedWDPeer(currentPeer)
startReadRSSI()
}
self.perform(#selector(scan), with: nil, afterDelay: 0.2)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
stopRSSITimer()
}
//MARK:Bluetooth
@objc private func scan() {
startSearchAnimation()
WDCentralManage.shareInstance.scanWithConfiguration(WDCBConfigurationFactory.pillowConfiguration, duration: 30)
}
//MARK:Search Animations
private func startSearchAnimation() {
isSearch = true
self.searchBtn.isUserInteractionEnabled = false
self.pillowSearchView.isHidden = false
self.pillowSearchViewYellow.isHidden = false
self.pillowSearchViewPurple.isHidden = false
self.pillowStopSearchView.isHidden = true
self.pillowSearchView.layer.add(self.setAnimationWithDuration(3.5), forKey: "rotationAnimation")
self.pillowSearchViewYellow.layer.add(self.setAnimationWithDuration(4.5), forKey: "rotationAnimation")
self.pillowSearchViewPurple.layer.add(self.setAnimationWithDuration(5.0), forKey: "rotationAnimation")
}
private func interrupt() {
isSearch = false
self.searchBtn.isUserInteractionEnabled = true
self.pillowSearchView.layer.removeAllAnimations()
self.pillowSearchViewYellow.layer.removeAllAnimations()
self.pillowSearchViewPurple.layer.removeAllAnimations()
self.searchAgainLab.text = "点击重试"
self.pillowSearchView.isHidden = true
self.pillowSearchViewYellow.isHidden = true
self.pillowSearchViewPurple.isHidden = true
self.pillowStopSearchView.isHidden = false
if WDCentralManage.shareInstance.bluetoothState == .poweredOff {
self.noticeError("蓝牙开关未开启", autoClear: true, autoClearTime: 2)
} else if let _ = WDCentralManage.shareInstance.currentPeer, WDCentralManage.shareInstance.discoveries.count > 0 {
//TODO 未连接
}
self.searchAgainLab.text = "点击重试"
}
private func stopRSSITimer() {
if let currentTimer = readRSSITimer {
currentTimer.invalidate()
}
readRSSITimer = nil
}
private func startReadRSSI() {
if let _ = self.currentPeer {
stopRSSITimer()
readRSSITimer = Timer.scheduledTimer(timeInterval: TimeInterval(2), target: self, selector: #selector(readRSSI), userInfo: nil, repeats: true)
}
}
@objc private func readRSSI() {
if let currentPeer = self.currentPeer {
currentPeer.startReadRSSI()
}
}
func setAnimationWithDuration(_ duration:Double) -> CABasicAnimation {
let rotationAnimation = CABasicAnimation.init(keyPath: "transform.rotation.z")
rotationAnimation.toValue = Double.pi * 2.0
rotationAnimation.duration = CFTimeInterval(duration)
rotationAnimation.isCumulative = true
rotationAnimation.repeatCount = Float(kPillowSearchTimes)
return rotationAnimation
}
private func loadConnectingDiscovery(_ discovery:WDDiscovery) {
currentPillowContainerView.isHidden = false
disConnectBtn.isEnabled = false
connectLab.text = "连接中"
deviceNameLabel.text = discovery.name
self.rssiLabel.isHidden = true
self.rssiDescriptorLabel.isHidden = true
}
private func loadConnectedWDPeer(_ peer:WDPeripheal) {
currentPillowContainerView.isHidden = false
disConnectBtn.isEnabled = true
connectLab.text = "断开"
deviceNameLabel.text = peer.name
self.rssiLabel.isHidden = true
self.rssiDescriptorLabel.isHidden = true
}
private func clearCurrentPeer() {
self.currentPillowContainerView.isHidden = true
}
private func loadRSSI(_ rssi:Int) {
if rssi < 0 {
self.rssiLabel.isHidden = false
self.rssiDescriptorLabel.isHidden = false
if rssi > -30 {
self.rssiLabel.text = "100%"
}else{
self.rssiLabel.text = "\(rssi + 130)%";
}
if rssi >= -70 {
self.rssiLabel.textColor = Specs.color.insoleRSSILevelGreen
self.rssiLevelImageView.image = UIImage.init(named: "icon_rssi_level_4")
}else if rssi < -70 && rssi >= -80 {
self.rssiLabel.textColor = Specs.color.insoleRSSILevelYellow
self.rssiLevelImageView.image = UIImage.init(named: "icon_rssi_level_3")
}else if rssi < -80 && rssi > -90 {
self.rssiLabel.textColor = Specs.color.insoleRSSILevelYellow
self.rssiLevelImageView.image = UIImage.init(named: "icon_rssi_level_2")
}else{
self.rssiLabel.textColor = Specs.color.insoleRSSILevelRed
self.rssiLevelImageView.image = UIImage.init(named: "icon_rssi_level_1")
}
} else {
self.rssiDescriptorLabel.isHidden = true
self.rssiLabel.isHidden = true
}
}
//MARK:UITableViewDelegate,UITableViewDatasource
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return WDCentralManage.shareInstance.discoveries.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell:PillowDiscoveryCell = pillowSearchTableView.dequeueReusableCell(withIdentifier: PillowDiscoveryCell.identifier, for: indexPath) as! PillowDiscoveryCell
let discovery = WDCentralManage.shareInstance.discoveries[indexPath.row]
cell.loadByDevice(discovery,at: indexPath)
cell.loadRSSI(discovery.RSSI)
cell.delegate = self
return cell
}
//MARK:Actions
@IBAction func actionSearch(_ sender: UIButton) {
startSearchAnimation()
WDCentralManage.shareInstance.scanWithConfiguration(WDCBConfigurationFactory.pillowConfiguration, duration: 15)
}
@IBAction func actionDisconnectCurrent(_ sender: UIButton) {
stopRSSITimer()
WDCentralManage.shareInstance.disconnectCurrentPeer()
self.clearCurrentPeer()
startSearchAnimation()
WDCentralManage.shareInstance.scanWithConfiguration(WDCBConfigurationFactory.pillowConfiguration, duration: 15)
}
@IBAction func actionDismiss(_ sender: UIButton) {
self.dismiss(animated: true, completion: nil)
}
//MARK:PillowDiscoveryCellDelegate
func connectDiscovery(_ discovery:WDDiscovery, at indexPath:IndexPath){
WDCentralManage.shareInstance.interruptScan()//停止搜索
interrupt()//停止搜索的动画
WDCentralManage.shareInstance.connect(discovery: discovery)
self.loadConnectingDiscovery(discovery)
self.pleaseWait(txt:"连接中")
self.pillowSearchTableView.reloadData()
}
//MARK:WDCentralManageDelegate
func scanTimeout() {
interrupt()
}
func discoverys(_ discoverys: [WDDiscovery]) {
if let lastPeerUUIDStr = WDCentralManage.shareInstance.lastPeerUUIDStr() {
for discovery in discoverys {
if discovery.remotePeripheral.identifier.uuidString == lastPeerUUIDStr {
WDCentralManage.shareInstance.connect(discovery: discovery)
self.pleaseWait(txt:"自动连接中")
break
}
}
}
pillowSearchTableView.reloadData()
}
func didConnected(for peripheal: WDPeripheal) {
peripheal.delegate = self
currentPeer = peripheal
self.loadConnectedWDPeer(peripheal)
self.clearAllNotice()
self.noticeSuccess("连接成功", autoClear: true, autoClearTime: 2)
self.pillowSearchTableView.reloadData()
}
func didDisConnected(for peripheal: WDPeripheal) {
self.clearCurrentPeer()
self.clearAllNotice()
self.noticeError("断开连接", autoClear: true, autoClearTime: 2)
}
func failConnected(for uuidStr: String) {
self.clearCurrentPeer()
self.clearAllNotice()
self.noticeError("连接失败", autoClear: true, autoClearTime: 2)
}
//MARK:WDPeripheralDelegate
func didFoundCharacteristic(_ peripheral:WDPeripheal){
startReadRSSI()
}
func wdPeripheral(_ peripheral:WDPeripheal, received receivedData:Data){
}
func wdPeripheral(_ peripheral:WDPeripheal, rssi:Int){
self.loadRSSI(rssi)
}
//MARK:other
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
| gpl-3.0 | 3a623898d9eea658c7c97b6a9b5d13b8 | 36.729097 | 168 | 0.667317 | 4.57276 | false | false | false | false |
joerocca/GitHawk | Classes/Utility/AlertAction.swift | 1 | 4974 | //
// AlertActions.swift
// Freetime
//
// Created by Ivan Magda on 25/09/2017.
// Copyright © 2017 Ryan Nystrom. All rights reserved.
//
import UIKit
import SafariServices
typealias AlertActionBlock = (UIAlertAction) -> Void
// MARK: AlertActions -
struct AlertAction {
// MARK: Properties
let rootViewController: UIViewController?
let title: String?
let style: UIAlertActionStyle
// MARK: Init
init(_ builder: AlertActionBuilder) {
rootViewController = builder.rootViewController
title = builder.title
style = builder.style ?? .default
}
// MARK: Public
func get(_ handler: AlertActionBlock? = nil) -> UIAlertAction {
return UIAlertAction(title: self.title, style: self.style, handler: handler)
}
func share(_ items: [Any],
activities: [UIActivity]?,
buildActivityBlock: ((UIActivityViewController) -> Void)?) -> UIAlertAction {
return UIAlertAction(title: NSLocalizedString("Share", comment: ""), style: .default) { _ in
let activityController = UIActivityViewController(activityItems: items, applicationActivities: activities)
buildActivityBlock?(activityController)
self.rootViewController?.present(activityController, animated: trueUnlessReduceMotionEnabled)
}
}
func view(client: GithubClient, repo: RepositoryDetails) -> UIAlertAction {
return UIAlertAction(title: String.localizedStringWithFormat("View %@", repo.name), style: .default) { _ in
let repoViewController = RepositoryViewController(client: client, repo: repo)
self.rootViewController?.show(repoViewController, sender: nil)
}
}
func view(owner: String, url: URL) -> UIAlertAction {
return UIAlertAction(title: String.localizedStringWithFormat("View @%@", owner), style: .default) { _ in
self.rootViewController?.presentSafari(url: url)
}
}
func newIssue(issueController: NewIssueTableViewController) -> UIAlertAction {
return UIAlertAction(title: Constants.Strings.newIssue, style: .default) { _ in
let nav = UINavigationController(rootViewController: issueController)
nav.modalPresentationStyle = .formSheet
self.rootViewController?.present(nav, animated: trueUnlessReduceMotionEnabled)
}
}
// MARK: Static
static func cancel(_ handler: AlertActionBlock? = nil) -> UIAlertAction {
return UIAlertAction(title: Constants.Strings.cancel, style: .cancel, handler: handler)
}
static func ok(_ handler: AlertActionBlock? = nil) -> UIAlertAction {
return UIAlertAction(title: Constants.Strings.ok, style: .default, handler: handler)
}
static func no(_ handler: AlertActionBlock? = nil) -> UIAlertAction {
return UIAlertAction(title: Constants.Strings.no, style: .cancel, handler: handler)
}
static func yes(_ handler: AlertActionBlock? = nil) -> UIAlertAction {
return UIAlertAction(title: Constants.Strings.yes, style: .default, handler: handler)
}
static func goBack(_ handler: AlertActionBlock? = nil) -> UIAlertAction {
return UIAlertAction(title: NSLocalizedString("Go back", comment: ""), style: .cancel, handler: handler)
}
static func discard(_ handler: AlertActionBlock? = nil) -> UIAlertAction {
return UIAlertAction(title: NSLocalizedString("Discard", comment: ""), style: .destructive, handler: handler)
}
static func delete(_ handler: AlertActionBlock? = nil) -> UIAlertAction {
return UIAlertAction(title: NSLocalizedString("Delete", comment: ""), style: .destructive, handler: handler)
}
static func toggleIssue(_ status: IssueStatus, handler: AlertActionBlock? = nil) -> UIAlertAction {
let title = status == .open
? NSLocalizedString("Close", comment: "")
: NSLocalizedString("Reopen", comment: "")
return UIAlertAction(title: title, style: .destructive, handler: handler)
}
static func toggleLocked(_ locked: Bool, handler: AlertActionBlock? = nil) -> UIAlertAction {
let title = locked
? NSLocalizedString("Unlock", comment: "")
: NSLocalizedString("Lock", comment: "")
return UIAlertAction(title: title, style: .destructive, handler: handler)
}
static func login(_ handler: AlertActionBlock? = nil) -> UIAlertAction {
return UIAlertAction(title: Constants.Strings.signin, style: .default, handler: handler)
}
static func markAll(_ handler: AlertActionBlock? = nil) -> UIAlertAction {
return UIAlertAction(title: NSLocalizedString("Mark all Read", comment: ""), style: .destructive, handler: handler)
}
static func clearAll(_ handler: AlertActionBlock? = nil) -> UIAlertAction {
return UIAlertAction(title: Constants.Strings.clearAll, style: .destructive, handler: handler)
}
}
| mit | b743a8fd223e4e0aab9670a24b85821b | 38.15748 | 123 | 0.672431 | 4.977978 | false | false | false | false |
OmarBizreh/IOSTrainingApp | IOSTrainingApp/ViewController.swift | 1 | 2209 | //
// ViewController.swift
// IOSTrainingApp
//
// Created by Omar Bizreh on 2/6/16.
// Copyright © 2016 Omar Bizreh. All rights reserved.
//
import UIKit
import KYDrawerController
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet var lblTitle: UILabel!
@IBOutlet var tableView: UITableView!
@IBOutlet var viewHeader: UIView!
private let cellIdentifier = "reuseCell"
private let headersArray: [String] = ["Controls", "General"]
private var drawerView: KYDrawerController?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
//self.viewHeader.backgroundColor = UIColor(patternImage: UIImage(named: "header_image.jpg")!)
self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: self.cellIdentifier)
self.drawerView = (UIApplication.sharedApplication().windows[0].rootViewController as! KYDrawerController)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 2
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0 {
return 3
}else{
return 2
}
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(self.cellIdentifier)
if indexPath.section == 0 {
cell?.textLabel?.text = "Hello World"
}
else{
cell?.textLabel?.text = "Hello World"
}
return cell!
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
self.drawerView?.setDrawerState(.Closed, animated: true)
}
func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return self.headersArray[section]
}
}
| mit | b30b20fb19b49c1be94eec77530c0e63 | 31.470588 | 114 | 0.667572 | 5.158879 | false | false | false | false |
listen-li/DYZB | DYZB/DYZB/Classes/Main/View/PageContentView.swift | 1 | 5571 | //
// PageContentView.swift
// DYZB
//
// Created by admin on 17/7/17.
// Copyright © 2017年 smartFlash. All rights reserved.
//
import UIKit
protocol PageContentViewDelegate : class {
func pageContentView(contentView : PageContentView, progress : CGFloat, sourceIndex : Int, targetIndex : Int)
}
class PageContentView: UIView {
//Mark:- 自定义属性
var childVcs : [UIViewController]
weak var parentViewController : UIViewController?
var startOffsetX : CGFloat = 0
var isForbidScrollDelegate : Bool = false
weak var delegate : PageContentViewDelegate?
//Mark: - 懒加载属性
lazy var collectionView : UICollectionView = {[weak self] in
//1.创建layout
let layout = UICollectionViewFlowLayout()
layout.itemSize = (self?.bounds.size)!
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = 0
layout.scrollDirection = .horizontal
//2.创建UIcollectionViw
let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout:layout)
collectionView.showsHorizontalScrollIndicator = false
collectionView.isPagingEnabled = true
collectionView.bounces = false
collectionView.dataSource = self
collectionView.delegate = self
collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "ContentCellID")
return collectionView
}()
//Mark:- 自定义构造函数
init(frame : CGRect,childVcs : [UIViewController], parentViewController : UIViewController?) {
self.childVcs = childVcs
self.parentViewController = parentViewController
super.init(frame:frame)
//设置UI
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
//MARk:- 设置UI界面
extension PageContentView{
func setupUI(){
//1.将所有的自控制器添加父控制器中
for childVc in childVcs {
parentViewController?.addChildViewController(childVc)
}
//2.添加UICollectionView,用于在cell中存放控制器的View
addSubview(collectionView)
collectionView.frame = bounds
}
}
//Mark:- 遵守UICollectionViewDataSource
extension PageContentView : UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return childVcs.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
//1.创建cell
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ContentCellID", for: indexPath)
//2.给cell设置内容
for view in cell.contentView.subviews {
view.removeFromSuperview()
}
let childVc = childVcs[indexPath.item]
childVc.view.frame = cell.contentView.bounds
cell.contentView.addSubview(childVc.view)
return cell
}
}
//Mark:- 遵守UICollectionViewDelegate
extension PageContentView : UICollectionViewDelegate{
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
isForbidScrollDelegate = false
startOffsetX = scrollView.contentOffset.x
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
//0.判断是否点击事件
if isForbidScrollDelegate {
return
}
//1.定义我们需要的数据
var progress : CGFloat = 0
var sourceIndex : Int = 0
var targetIndex : Int = 0
//2.判断是左滑还是右滑
let currentOffsetX = scrollView.contentOffset.x
let scrollViewW = scrollView.bounds.width
if currentOffsetX > startOffsetX {//左滑
//1.计算progress
progress = currentOffsetX / scrollViewW - floor(currentOffsetX / scrollViewW)
//2.计算sourceIndex
sourceIndex = Int(currentOffsetX / scrollViewW)
//3.计算targetIndex
targetIndex = sourceIndex + 1
if targetIndex >= childVcs.count {
targetIndex = childVcs.count - 1
}
//4.如果完全滑过去
if currentOffsetX - startOffsetX == scrollViewW {
progress = 1
targetIndex = sourceIndex
}
}else{
//1.计算progress
progress = 1 - (currentOffsetX / scrollViewW - floor(currentOffsetX / scrollViewW))
//2.计算targetIndex
targetIndex = Int(currentOffsetX / scrollViewW)
//3.计算sourceIndex
sourceIndex = targetIndex + 1
if sourceIndex >= childVcs.count {
sourceIndex = childVcs.count - 1
}
}
//3.将progress、sourceIndex、targetIndex传递给titleView
delegate?.pageContentView(contentView: self, progress: progress, sourceIndex: sourceIndex, targetIndex: targetIndex)
}
}
//Mark:- 对外暴露的方法
extension PageContentView{
func setCurrentIndex(currentIndex : Int){
//1.记录需要禁止执行代理方法
isForbidScrollDelegate = true
//2.滚动正确的位置
let offsetX = CGFloat(currentIndex) * collectionView.frame.width
collectionView.setContentOffset(CGPoint(x:offsetX,y:0), animated: false)
}
}
| mit | 1342ab040d9736ea6a55d8bf31abab33 | 31.380368 | 124 | 0.636226 | 5.71831 | false | false | false | false |
Bouke/HAP | Sources/HAP/Utils/Event.swift | 1 | 2571 | // swiftlint:disable unused_optional_binding
import Foundation
import VaporHTTP
struct Event {
enum Error: Swift.Error {
case characteristicWithoutAccessory
}
var status: HTTPResponseStatus
var body: Data
var headers: [String: String] = [:]
init(status: HTTPResponseStatus, body: Data, mimeType: String) {
self.status = status
self.body = body
headers["Content-Length"] = "\(body.count)"
headers["Content-Type"] = mimeType
}
init?(deserialize data: Data) {
let scanner = DataScanner(data: data)
let space = " ".data(using: .utf8)!
let newline = "\r\n".data(using: .utf8)!
let headerSeparator = ": ".data(using: .utf8)!
guard
let _ = scanner.scan("EVENT/1.0 "),
let statusCode = scanner.scanUpTo(" ").flatMap({ Int($0) }),
let _ = scanner.scan(space),
let _ = scanner.scanUpTo("\r\n"),
let _ = scanner.scan(newline)
else {
return nil
}
self.status = HTTPResponseStatus(statusCode: statusCode)
while true {
if let _ = scanner.scan(newline) {
break
}
guard
let key = scanner.scanUpTo(": "),
let _ = scanner.scan(headerSeparator),
let value = scanner.scanUpTo("\r\n"),
let _ = scanner.scan(newline)
else {
return nil
}
headers[key] = value
}
body = data[scanner.scanLocation..<data.endIndex]
}
func serialized() -> Data {
// @todo should set additional headers here as well?
let headers = self.headers.map({ "\($0): \($1)\r\n" }).joined()
return "EVENT/1.0 \(status.code) \(status.reasonPhrase)\r\n\(headers)\r\n".data(using: .utf8)! + body
}
init(valueChangedOfCharacteristics characteristics: [Characteristic]) throws {
var payload = [[String: Any]]()
for char in characteristics {
guard let aid = char.service?.accessory?.aid else {
throw Error.characteristicWithoutAccessory
}
payload.append(["aid": aid, "iid": char.iid, "value": char.getValue() ?? NSNull()])
}
let serialized = ["characteristics": payload]
guard let body = try? JSONSerialization.data(withJSONObject: serialized, options: []) else {
abort()
}
self.init(status: .ok, body: body, mimeType: "application/hap+json")
}
}
| mit | 328a3f5d3335a4817aa6c31368017953 | 34.219178 | 109 | 0.547647 | 4.432759 | false | false | false | false |
wenghengcong/Coderpursue | BeeFun/BeeFun/View/Stars/BFStarContentView.swift | 1 | 8483 | //
// BFStarContentView.swift
// BeeFun
//
// Created by WengHengcong on 26/09/2017.
// Copyright © 2017 JungleSong. All rights reserved.
//
import UIKit
import ObjectMapper
class BFStarContentView: UIView, UITableViewDelegate, UITableViewDataSource, MJRefreshManagerAction {
//Reload View
let reloadViewTag = 19999
// 重试提醒
var reloadTip = "Wake up your connection!".localized
// 重试提醒的图片
var reloadImage = "network_error_1"
//重试加载按钮的title
var reloadActionTitle = "Try Again".localized
//Reload View
let emptyViewTag = 19998
// 无数据提醒
var emptyTip = "Empty now,star repositories and tag it".localized
// 无数据提醒的图片
var emptyImage = "empty_data"
// 无数据按钮的title
var emptyActionTitle = "Explore more".localized
/// 是否显示空白视图
var showEmpty = false
// MARK: - View
var tableView: UITableView = UITableView()
let refreshManager = MJRefreshManager()
// MARK: - Data
/// 当前页面所对应的tag
var tagTitle: String?
var starReposData: [ObjRepos] = []
var reposPageVal = 1
var reposPerpage = 15
var sortVal: String = "created"
var directionVal: String = "desc"
override init(frame: CGRect) {
super.init(frame: frame)
setupTableView()
}
convenience init(frame: CGRect, tag: String) {
self.init(frame: frame)
self.tagTitle = tag
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setupTableView() {
tableView.frame = self.bounds
tableView.dataSource = self
tableView.delegate = self
tableView.separatorStyle = .none
refreshManager.delegate = self
tableView.mj_header = refreshManager.header()
tableView.mj_footer = refreshManager.footer()
tableView.backgroundColor = UIColor.white
if #available(iOS 11, *) {
tableView.estimatedRowHeight = 0
tableView.estimatedSectionHeaderHeight = 0
tableView.estimatedSectionFooterHeight = 0
}
addSubview(tableView)
}
/// 当前页面是否已经拉取到数据
func hasData() -> Bool {
return starReposData.count > 0
}
/// 重新加载本页面数据
///
/// - Parameter force: 是否需要强制去请求去拿网络数据
func reloadNetworkData(force: Bool) {
if UserManager.shared.isLogin {//已登录
tableView.mj_footer.isHidden = false
if force {
requestFirstPage()
} else {
if !hasData() {
requestFirstPage()
}
}
} else {
clearAllData()
//加载未登录的页面
tableView.mj_footer.isHidden = true
}
}
private func clearAllData() {
starReposData.removeAll()
tableView.reloadData()
}
private func requestFirstPage() {
reposPageVal = 1
svc_getStaredReposRequest(reposPageVal)
}
private func requestNextPage() {
reposPageVal += 1
svc_getStaredReposRequest(reposPageVal)
}
}
// MARK: - Refresh
extension BFStarContentView {
func headerRefresh() {
tableView.mj_header.endRefreshing()
requestFirstPage()
}
func footerRefresh() {
tableView.mj_footer.endRefreshing()
requestNextPage()
}
}
// MARK: - empty and network error
extension BFStarContentView: BFPlaceHolderViewDelegate {
func showReloadView() {
removeReloadView()
tableView.isHidden = true
let placeReloadView = BFPlaceHolderView(frame: self.frame, tip: reloadTip, image: reloadImage, actionTitle: reloadActionTitle)
placeReloadView.placeHolderActionDelegate = self
placeReloadView.tag = reloadViewTag
insertSubview(placeReloadView, at: 0)
self.bringSubview(toFront: placeReloadView)
}
func removeReloadView() {
if let reloadView = viewWithTag(reloadViewTag) {
reloadView.removeFromSuperview()
}
tableView.isHidden = false
}
func didAction(place: BFPlaceHolderView) {
self.reloadNetworkData(force: true)
}
}
extension BFStarContentView {
/// Get stared repos
@objc private func svc_getStaredReposRequest(_ pageVal: Int) {
if DeviceType.isPad {
reposPerpage = 25
}
if tagTitle == nil || tagTitle?.length == 0 {
return
}
let hud = JSMBHUDBridge.showHud(view: self)
BeeFunProvider.sharedProvider.request(BeeFunAPI.repos(tag: tagTitle!, language: "all", page: pageVal, perpage: reposPerpage, sort: "starred_at", direction: "desc")) { (result) in
self.showEmpty = false
hud.hide(animated: true)
switch result {
case let .success(response):
do {
if let allRepos: GetReposResponse = Mapper<GetReposResponse>().map(JSONObject: try response.mapJSON()) {
if let code = allRepos.codeEnum, code == BFStatusCode.bfOk {
if let data = allRepos.data {
DispatchQueue.main.async {
self.hanldeStaredRepoResponse(repos: data)
}
}
}
}
} catch {
self.showReloadView()
}
case .failure:
self.showReloadView()
}
}
}
private func hanldeStaredRepoResponse(repos: [ObjRepos]) {
removeReloadView()
if reposPageVal == 1 {
self.starReposData.removeAll()
self.starReposData = repos
} else {
self.starReposData += repos
}
if starReposData.count == 0 {
showEmpty = true
} else {
showEmpty = false
}
tableView.reloadData()
}
}
// MARK: - TableViewdatasource
extension BFStarContentView: BFEmptyDataCellDelegate {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return showEmpty ? 1 : starReposData.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let row = indexPath.row
if !showEmpty {
let cellId = "BFRepositoryTypeOneCellIdentifier"
var cell = tableView.dequeueReusableCell(withIdentifier: cellId) as? BFRepositoryTypeOneCell
if cell == nil {
cell = (BFRepositoryTypeOneCell.cellFromNibNamed("BFRepositoryTypeOneCell") as? BFRepositoryTypeOneCell)
}
if !starReposData.isBeyond(index: row) {
cell?.setBothEndsLines(row, all: starReposData.count)
let repos = starReposData[row]
cell!.objRepos = repos
}
return cell!
} else {
let cellId = "BFEmptyStarDataCell"
var cell = tableView.dequeueReusableCell(withIdentifier: cellId) as? BFEmptyDataCell
if cell == nil {
cell = BFEmptyDataCell(style: .default, reuseIdentifier: cellId)
cell?.display(tip: emptyTip, imageName: emptyImage, actionTitle: emptyActionTitle)
}
cell?.delegate = self
return cell!
}
}
func didClickEmptyAction(cell: BFEmptyDataCell) {
BFTabbarManager.shared.goto(index: 0)
}
}
// MARK: - Tableview delegate
extension BFStarContentView {
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if showEmpty {
return height
}
return 85
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if showEmpty {
return
}
tableView.deselectRow(at: indexPath, animated: true)
let row = indexPath.row
if !starReposData.isBeyond(index: row) {
let repos = starReposData[row]
JumpManager.shared.jumpReposDetailView(repos: repos, from: .star)
}
}
}
| mit | 7d06780f3b1797403d9e3e34050055f1 | 29.109091 | 186 | 0.583696 | 4.734134 | false | false | false | false |
ewhitley/CDAKit | CDAKit/health-data-standards/lib/models/cda_identifier.swift | 1 | 3040 | //
// cda_identifier.swift
// CDAKit
//
// Created by Eric Whitley on 11/30/15.
// Copyright © 2015 Eric Whitley. All rights reserved.
//
import Foundation
import Mustache
/**
CDA Identifier
Usually takes the form of a "root" (required) and an "extension" (identifier) (optional).
[Additional information](http://www.cdapro.com/know/24985)
**Examples:**
[Source](https://github.com/chb/sample_ccdas/blob/master/EMERGE/Patient-673.xml)
```
<id root="db734647-fc99-424c-a864-7e3cda82e703"/>
```
or
```
<!-- Fake ID using HL7 example OID. -->
<id extension="998991" root="2.16.840.1.113883.19.5.99999.2"/>
<!-- Fake Social Security Number using the actual SSN OID. -->
<id extension="111-00-2330" root="2.16.840.1.113883.4.1"/>
```
*/
public class CDAKCDAIdentifier: Equatable, Hashable, CDAKJSONInstantiable, CustomStringConvertible {
// MARK: CDA properties
///CDA Root
public var root: String?
///CDA Extension
public var extension_id: String?
public var hashValue: Int {
return "\(root)\(extension_id)".hashValue
}
///Attempts to return a simplified compound version of the Root and Extension
public var as_string: String {
get {
var r = ""
var e = ""
if let root = root {
r = root
}
if let extension_id = extension_id {
e = extension_id
}
return "\(r)\(r.characters.count > 0 && e.characters.count > 0 ? " " : "")\(e)"
}
}
// MARK: Standard properties
///Debugging description
public var description: String {
return "CDAKCDAIdentifier => root: \(root), extension_id: \(extension_id)"
}
// MARK: - Initializers
public init(root: String? = nil, extension_id: String? = nil) {
self.root = root
self.extension_id = extension_id
}
// MARK: - Deprecated - Do not use
///Do not use - will be removed. Was used in HDS Ruby.
required public init(event: [String:Any?]) {
initFromEventList(event)
}
///Do not use - will be removed. Was used in HDS Ruby.
private func initFromEventList(event: [String:Any?]) {
for (key, value) in event {
CDAKUtility.setProperty(self, property: key, value: value)
}
}
}
public func == (lhs: CDAKCDAIdentifier, rhs: CDAKCDAIdentifier) -> Bool {
return lhs.hashValue == rhs.hashValue
//self.root == comparison_object.root && self.extension == comparison_object.extension
}
extension CDAKCDAIdentifier: MustacheBoxable {
// MARK: - Mustache marshalling
public var mustacheBox: MustacheBox {
return Box([
"root": self.root,
"extension": self.extension_id,
"as_string": self.as_string
])
}
}
extension CDAKCDAIdentifier: CDAKJSONExportable {
// MARK: - JSON Generation
///Dictionary for JSON data
public var jsonDict: [String: AnyObject] {
var dict: [String: AnyObject] = [:]
if let root = root {
dict["root"] = root
}
if let extension_id = extension_id {
dict["extension"] = extension_id
}
return dict
}
} | mit | bde131ba7df355aeffe1fca778e0b601 | 22.937008 | 100 | 0.636064 | 3.648259 | false | false | false | false |
kelvin13/noise | tests/noise/tests.swift | 1 | 9860 | import Noise
import PNG
extension UInt8
{
init<T>(clamping value:T) where T:BinaryFloatingPoint
{
self.init(Swift.max(0, Swift.min(255, value)))
}
}
func color_noise_png(r_noise:Noise, g_noise:Noise, b_noise:Noise,
width:Int, height:Int, value_offset:(r:Double, g:Double, b:Double), invert:Bool = false, path:String)
{
let domain:Domain2D = .init(samples_x: width, samples_y: height)
let rgba:[PNG.RGBA<UInt8>] = domain.map
{
(p:(x:Double, y:Double)) in
let r:UInt8 = .init(clamping: r_noise.evaluate(p.x, p.y) + value_offset.r),
g:UInt8 = .init(clamping: g_noise.evaluate(p.x, p.y) + value_offset.g),
b:UInt8 = .init(clamping: b_noise.evaluate(p.x, p.y) + value_offset.b)
if invert
{
return .init(.max - r, .max - g, .max - b)
}
else
{
return .init(r, g, b)
}
}
do
{
try PNG.encode(rgba: rgba, size: (width, height), as: .rgb8, path: path)
}
catch
{
print(error)
}
}
func banner_classic3d(width:Int, height:Int, seed:Int)
{
color_noise_png(r_noise: ClassicNoise3D(amplitude: 1.6 * 0.5*255, frequency: 0.01, seed: seed),
g_noise: ClassicNoise3D(amplitude: 1.6 * 0.5*255, frequency: 0.005, seed: seed + 1),
b_noise: ClassicNoise3D(amplitude: 1.6 * 0.5*255, frequency: 0.0025, seed: seed + 2),
width: width,
height: height,
value_offset: (0.65*255, 0.65*255, 0.65*255),
path: "tests/banner_classic3d.png")
}
/*
func banner_simplex2d(width:Int, height:Int, seed:Int)
{
color_noise_png(r_noise: SimplexNoise2D(amplitude: 0.5*255, frequency: 0.015, seed: seed),
g_noise: SimplexNoise2D(amplitude: 0.5*255, frequency: 0.0075, seed: seed + 1),
b_noise: SimplexNoise2D(amplitude: 0.5*255, frequency: 0.00375, seed: seed + 2),
width: width,
height: height,
value_offset: (0.65*255, 0.65*255, 0.65*255),
path: "tests/banner_simplex2d.png")
}
*/
func banner_supersimplex2d(width:Int, height:Int, seed:Int)
{
color_noise_png(r_noise: GradientNoise2D(amplitude: 0.5*255, frequency: 0.01, seed: seed),
g_noise: GradientNoise2D(amplitude: 0.5*255, frequency: 0.005, seed: seed + 1),
b_noise: GradientNoise2D(amplitude: 0.5*255, frequency: 0.0025, seed: seed + 2),
width: width,
height: height,
value_offset: (0.65*255, 0.65*255, 0.65*255),
path: "tests/banner_supersimplex2d.png")
}
func banner_supersimplex3d(width:Int, height:Int, seed:Int)
{
color_noise_png(r_noise: GradientNoise3D(amplitude: 0.5*255, frequency: 0.01, seed: seed),
g_noise: GradientNoise3D(amplitude: 0.5*255, frequency: 0.005, seed: seed + 1),
b_noise: GradientNoise3D(amplitude: 0.5*255, frequency: 0.0025, seed: seed + 2),
width: width,
height: height,
value_offset: (0.65*255, 0.65*255, 0.65*255),
path: "tests/banner_supersimplex3d.png")
}
func banner_cell2d(width:Int, height:Int, seed:Int)
{
color_noise_png(r_noise: CellNoise2D(amplitude: 3*255, frequency: 0.03, seed: seed),
g_noise: CellNoise2D(amplitude: 3*255, frequency: 0.015, seed: seed + 1),
b_noise: CellNoise2D(amplitude: 3*255, frequency: 0.0075, seed: seed + 2),
width: width,
height: height,
value_offset: (0, 0, 0),
invert: true,
path: "tests/banner_cell2d.png")
}
func banner_cell3d(width:Int, height:Int, seed:Int)
{
color_noise_png(r_noise: CellNoise3D(amplitude: 3*255, frequency: 0.03, seed: seed),
g_noise: CellNoise3D(amplitude: 3*255, frequency: 0.015, seed: seed + 1),
b_noise: CellNoise3D(amplitude: 3*255, frequency: 0.0075, seed: seed + 2),
width: width,
height: height,
value_offset: (0, 0, 0),
invert: true,
path: "tests/banner_cell3d.png")
}
func banner_FBM(width:Int, height:Int, seed:Int)
{
color_noise_png(r_noise: FBM<CellNoise3D> (CellNoise3D(amplitude: 10*255, frequency: 0.01, seed: seed + 2), octaves: 7, persistence: 0.75),
g_noise: FBM<GradientNoise3D>(GradientNoise3D(amplitude: 300, frequency: 0.005, seed: seed + 3), octaves: 7, persistence: 0.75),
b_noise: FBM<GradientNoise2D>(GradientNoise2D(amplitude: 300, frequency: 0.005), octaves: 7, persistence: 0.75),
width: width,
height: height,
value_offset: (0, 150, 150),
invert: false,
path: "tests/banner_FBM.png")
}
func circle_at(cx:Double, cy:Double, r:Double, width:Int, height:Int, _ f:(Int, Int, Double) -> ())
{
// get bounding box
let x1:Int = max(0 , Int(cx - r)),
x2:Int = min(width - 1 , Int((cx + r).rounded(.up))),
y1:Int = max(0 , Int(cy - r)),
y2:Int = min(height - 1, Int((cy + r).rounded(.up)))
for y in y1 ... y2
{
let dy:Double = Double(y) - cy
for x in x1 ... x2
{
let dx:Double = Double(x) - cx,
dr:Double = (dx*dx + dy*dy).squareRoot()
f(x, y, min(1, max(0, 1 - dr + r - 0.5)))
}
}
}
func banner_disk2d(width:Int, height:Int, seed:Int)
{
var poisson:DiskSampler2D = .init(seed: seed)
var rgba:[PNG.RGBA<UInt8>] = .init(repeating: .init(.max), count: width * height)
//let points = poisson.generate(radius: 20, width: width, height: height, k: 80)
@inline(__always)
func _dots(_ points:[(x:Double, y:Double)], color: (r:UInt8, g:UInt8, b:UInt8))
{
for point:(x:Double, y:Double) in points
{
circle_at(cx: point.x, cy: point.y, r: 10, width: width, height: height)
{
(x:Int, y:Int, v:Double) in
let i:Int = y * width + x
rgba[i].r = .init(clamping: Int(rgba[i].r) - Int(Double(color.r) * v))
rgba[i].g = .init(clamping: Int(rgba[i].g) - Int(Double(color.g) * v))
rgba[i].b = .init(clamping: Int(rgba[i].b) - Int(Double(color.b) * v))
}
}
}
_dots(poisson.generate(radius: 35, width: width, height: height, k: 80, seed: (10, 10)), color: (0, 210, 70))
_dots(poisson.generate(radius: 25, width: width, height: height, k: 80, seed: (45, 15)), color: (0, 10, 235))
_dots(poisson.generate(radius: 30, width: width, height: height, k: 80, seed: (15, 45)), color: (225, 20, 0))
do
{
try PNG.encode(rgba: rgba, size: (width, height), as: .rgb8, path: "tests/banner_disk2d.png")
}
catch
{
print(error)
}
}
func banner_voronoi2d(width:Int, height:Int, seed:Int)
{
let voronoi:CellNoise2D = CellNoise2D(amplitude: 255, frequency: 0.025, seed: seed)
let r:PermutationTable = PermutationTable(seed: seed),
g:PermutationTable = PermutationTable(seed: seed + 1),
b:PermutationTable = PermutationTable(seed: seed + 2)
let domain:Domain2D = .init(samples_x: width, samples_y: height)
let rgba:[PNG.RGBA<UInt8>] = domain.map
{
(p:(x:Double, y:Double)) in
@inline(__always)
func _supersample(_ x:Double, _ y:Double) -> (r:UInt8, g:UInt8, b:UInt8)
{
let (point, _):((Int, Int), Double) = voronoi.closest_point(Double(x), Double(y))
let r:UInt8 = r.hash(point.0, point.1),
g:UInt8 = g.hash(point.0, point.1),
b:UInt8 = b.hash(point.0, point.1),
peak:UInt8 = max(r, max(g, b)),
saturate:Double = .init(UInt8.max) / .init(peak)
return (.init(.init(r) * saturate), .init(.init(g) * saturate), .init(.init(b) * saturate))
}
var r:Int = 0,
g:Int = 0,
b:Int = 0
let supersamples:[(Double, Double)] = [(0, 0), (0, 0.4), (0.4, 0), (-0.4, 0), (0, -0.4),
(-0.25, -0.25), (0.25, 0.25), (-0.25, 0.25), (0.25, -0.25)]
for (dx, dy):(Double, Double) in supersamples
{
let contribution:(r:UInt8, g:UInt8, b:UInt8) = _supersample(p.x + dx, p.y + dy)
r += .init(contribution.r)
g += .init(contribution.g)
b += .init(contribution.b)
}
return .init( .init(r / supersamples.count),
.init(g / supersamples.count),
.init(b / supersamples.count))
}
do
{
try PNG.encode(rgba: rgba, size: (width, height), as: .rgb8, path: "tests/banner_voronoi2d.png")
}
catch
{
print(error)
}
}
public
func banners(width:Int, ratio:Double)
{
let height:Int = Int(Double(width) / ratio)
banner_classic3d (width: width, height: height, seed: 6)
//banner_simplex2d (width: width, height: height, seed: 6)
banner_supersimplex2d(width: width, height: height, seed: 8)
banner_supersimplex3d(width: width, height: height, seed: 2)
banner_cell2d (width: width, height: height, seed: 0)
banner_cell3d (width: width, height: height, seed: 0)
banner_voronoi2d (width: width, height: height, seed: 3)
banner_FBM (width: width, height: height, seed: 2)
banner_disk2d (width: width, height: height, seed: 0)
}
| gpl-3.0 | bb2fbdc728656ed3ec0dfa928d14f390 | 38.126984 | 148 | 0.535193 | 3.11434 | false | false | false | false |
radvansky-tomas/NutriFacts | nutri-facts/nutri-facts/Libraries/iOSCharts/Classes/Renderers/HorizontalBarChartRenderer.swift | 6 | 19147 | //
// HorizontalBarChartRenderer.swift
// Charts
//
// Created by Daniel Cohen Gindi on 4/3/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
//
import Foundation
import CoreGraphics.CGBase
import UIKit.UIFont
public class HorizontalBarChartRenderer: BarChartRenderer
{
private var xOffset: CGFloat = 0.0;
private var yOffset: CGFloat = 0.0;
public override init(delegate: BarChartRendererDelegate?, animator: ChartAnimator?, viewPortHandler: ChartViewPortHandler)
{
super.init(delegate: delegate, animator: animator, viewPortHandler: viewPortHandler);
}
internal override func drawDataSet(#context: CGContext, dataSet: BarChartDataSet, index: Int)
{
CGContextSaveGState(context);
var barData = delegate!.barChartRendererData(self);
var trans = delegate!.barChartRenderer(self, transformerForAxis: dataSet.axisDependency);
var drawBarShadowEnabled: Bool = delegate!.barChartIsDrawBarShadowEnabled(self);
var dataSetOffset = (barData.dataSetCount - 1);
var groupSpace = barData.groupSpace;
var groupSpaceHalf = groupSpace / 2.0;
var barSpace = dataSet.barSpace;
var barSpaceHalf = barSpace / 2.0;
var containsStacks = dataSet.isStacked;
var isInverted = delegate!.barChartIsInverted(self, axis: dataSet.axisDependency);
var entries = dataSet.yVals as! [BarChartDataEntry];
var barWidth: CGFloat = 0.5;
var phaseY = _animator.phaseY;
var barRect = CGRect();
var barShadow = CGRect();
var y: Float;
// do the drawing
for (var j = 0, count = Int(ceil(CGFloat(dataSet.entryCount) * _animator.phaseX)); j < count; j++)
{
var e = entries[j];
// calculate the x-position, depending on datasetcount
var x = CGFloat(e.xIndex + j * dataSetOffset) + CGFloat(index)
+ groupSpace * CGFloat(j) + groupSpaceHalf;
var vals = e.values;
if (!containsStacks || vals == nil)
{
y = e.value;
var bottom = x - barWidth + barSpaceHalf;
var top = x + barWidth - barSpaceHalf;
var right = isInverted ? (y <= 0.0 ? CGFloat(y) : 0) : (y >= 0.0 ? CGFloat(y) : 0);
var left = isInverted ? (y >= 0.0 ? CGFloat(y) : 0) : (y <= 0.0 ? CGFloat(y) : 0);
// multiply the height of the rect with the phase
if (right > 0)
{
right *= phaseY;
}
else
{
left *= phaseY;
}
barRect.origin.x = left;
barRect.size.width = right - left;
barRect.origin.y = top;
barRect.size.height = bottom - top;
trans.rectValueToPixel(&barRect);
if (!viewPortHandler.isInBoundsLeft(barRect.origin.x + barRect.size.width))
{
continue;
}
if (!viewPortHandler.isInBoundsRight(barRect.origin.x))
{
break;
}
// if drawing the bar shadow is enabled
if (drawBarShadowEnabled)
{
barShadow.origin.x = viewPortHandler.contentLeft;
barShadow.origin.y = barRect.origin.y;
barShadow.size.width = viewPortHandler.contentWidth;
barShadow.size.height = barRect.size.height;
CGContextSetFillColorWithColor(context, dataSet.barShadowColor.CGColor);
CGContextFillRect(context, barShadow);
}
// Set the color for the currently drawn value. If the index is out of bounds, reuse colors.
CGContextSetFillColorWithColor(context, dataSet.colorAt(j).CGColor);
CGContextFillRect(context, barRect);
}
else
{
var all = e.value;
// if drawing the bar shadow is enabled
if (drawBarShadowEnabled)
{
y = e.value;
var bottom = x - barWidth + barSpaceHalf;
var top = x + barWidth - barSpaceHalf;
var right = isInverted ? (y <= 0.0 ? CGFloat(y) : 0) : (y >= 0.0 ? CGFloat(y) : 0);
var left = isInverted ? (y >= 0.0 ? CGFloat(y) : 0) : (y <= 0.0 ? CGFloat(y) : 0);
// multiply the height of the rect with the phase
if (right > 0)
{
right *= phaseY;
}
else
{
left *= phaseY;
}
barRect.origin.x = left;
barRect.size.width = right - left;
barRect.origin.y = top;
barRect.size.height = bottom - top;
trans.rectValueToPixel(&barRect);
barShadow.origin.x = viewPortHandler.contentLeft;
barShadow.origin.y = barRect.origin.y;
barShadow.size.width = viewPortHandler.contentWidth;
barShadow.size.height = barRect.size.height;
CGContextSetFillColorWithColor(context, dataSet.barShadowColor.CGColor);
CGContextFillRect(context, barShadow);
}
// fill the stack
for (var k = 0; k < vals.count; k++)
{
all -= vals[k];
y = vals[k] + all;
var bottom = x - barWidth + barSpaceHalf;
var top = x + barWidth - barSpaceHalf;
var right = y >= 0.0 ? CGFloat(y) : 0.0;
var left = y <= 0.0 ? CGFloat(y) : 0.0;
// multiply the height of the rect with the phase
if (right > 0)
{
right *= phaseY;
}
else
{
left *= phaseY;
}
barRect.origin.x = left;
barRect.size.width = right - left;
barRect.origin.y = top;
barRect.size.height = bottom - top;
trans.rectValueToPixel(&barRect);
if (k == 0 && !viewPortHandler.isInBoundsLeft(barRect.origin.x + barRect.size.width))
{
// Skip to next bar
break;
}
// avoid drawing outofbounds values
if (!viewPortHandler.isInBoundsRight(barRect.origin.x))
{
break;
}
// Set the color for the currently drawn value. If the index is out of bounds, reuse colors.
CGContextSetFillColorWithColor(context, dataSet.colorAt(k).CGColor);
CGContextFillRect(context, barRect);
}
}
}
CGContextRestoreGState(context);
}
internal override func prepareBarHighlight(#x: CGFloat, y: Float, barspacehalf: CGFloat, from: Float, trans: ChartTransformer, inout rect: CGRect)
{
let barWidth: CGFloat = 0.5;
var top = x - barWidth + barspacehalf;
var bottom = x + barWidth - barspacehalf;
var left = y >= from ? CGFloat(y) : CGFloat(from);
var right = y <= from ? CGFloat(y) : CGFloat(from);
rect.origin.x = left;
rect.origin.y = top;
rect.size.width = right - left;
rect.size.height = bottom - top;
trans.rectValueToPixelHorizontal(&rect, phaseY: _animator.phaseY);
}
public override func getTransformedValues(#trans: ChartTransformer, entries: [BarChartDataEntry], dataSetIndex: Int) -> [CGPoint]
{
return trans.generateTransformedValuesHorizontalBarChart(entries, dataSet: dataSetIndex, barData: delegate!.barChartRendererData(self)!, phaseY: _animator.phaseY);
}
public override func drawValues(#context: CGContext)
{
// if values are drawn
if (passesCheck())
{
var barData = delegate!.barChartRendererData(self);
var defaultValueFormatter = delegate!.barChartDefaultRendererValueFormatter(self);
var dataSets = barData.dataSets;
var drawValueAboveBar = delegate!.barChartIsDrawValueAboveBarEnabled(self);
var drawValuesForWholeStackEnabled = delegate!.barChartIsDrawValuesForWholeStackEnabled(self);
var textAlign = drawValueAboveBar ? NSTextAlignment.Left : NSTextAlignment.Right;
let valueOffsetPlus: CGFloat = 5.0;
var posOffset: CGFloat;
var negOffset: CGFloat;
for (var i = 0, count = barData.dataSetCount; i < count; i++)
{
var dataSet = dataSets[i];
if (!dataSet.isDrawValuesEnabled)
{
continue;
}
var isInverted = delegate!.barChartIsInverted(self, axis: dataSet.axisDependency);
var valueFont = dataSet.valueFont;
var valueTextColor = dataSet.valueTextColor;
var yOffset = -valueFont.lineHeight / 2.0;
var formatter = dataSet.valueFormatter;
if (formatter === nil)
{
formatter = defaultValueFormatter;
}
var trans = delegate!.barChartRenderer(self, transformerForAxis: dataSet.axisDependency);
var entries = dataSet.yVals as! [BarChartDataEntry];
var valuePoints = getTransformedValues(trans: trans, entries: entries, dataSetIndex: i);
// if only single values are drawn (sum)
if (!drawValuesForWholeStackEnabled)
{
for (var j = 0, count = Int(ceil(CGFloat(valuePoints.count) * _animator.phaseX)); j < count; j++)
{
if (!viewPortHandler.isInBoundsX(valuePoints[j].x))
{
continue;
}
if (!viewPortHandler.isInBoundsTop(valuePoints[j].y))
{
break;
}
if (!viewPortHandler.isInBoundsBottom(valuePoints[j].y))
{
continue;
}
var val = entries[j].value;
var valueText = formatter!.stringFromNumber(val)!;
// calculate the correct offset depending on the draw position of the value
var valueTextWidth = valueText.sizeWithAttributes([NSFontAttributeName: valueFont]).width;
posOffset = (drawValueAboveBar ? valueOffsetPlus : -(valueTextWidth + valueOffsetPlus));
negOffset = (drawValueAboveBar ? -(valueTextWidth + valueOffsetPlus) : valueOffsetPlus);
if (isInverted)
{
posOffset = -posOffset - valueTextWidth;
negOffset = -negOffset - valueTextWidth;
}
drawValue(
context: context,
value: valueText,
xPos: valuePoints[j].x + (val >= 0.0 ? posOffset : negOffset),
yPos: valuePoints[j].y + yOffset,
font: valueFont,
align: .Left,
color: valueTextColor);
}
}
else
{
// if each value of a potential stack should be drawn
for (var j = 0, count = Int(ceil(CGFloat(valuePoints.count) * _animator.phaseX)); j < count; j++)
{
var e = entries[j];
var vals = e.values;
// we still draw stacked bars, but there is one non-stacked in between
if (vals == nil)
{
if (!viewPortHandler.isInBoundsX(valuePoints[j].x))
{
continue;
}
if (!viewPortHandler.isInBoundsTop(valuePoints[j].y))
{
break;
}
if (!viewPortHandler.isInBoundsBottom(valuePoints[j].y))
{
continue;
}
var val = e.value;
var valueText = formatter!.stringFromNumber(val)!;
// calculate the correct offset depending on the draw position of the value
var valueTextWidth = valueText.sizeWithAttributes([NSFontAttributeName: valueFont]).width;
posOffset = (drawValueAboveBar ? valueOffsetPlus : -(valueTextWidth + valueOffsetPlus));
negOffset = (drawValueAboveBar ? -(valueTextWidth + valueOffsetPlus) : valueOffsetPlus);
if (isInverted)
{
posOffset = -posOffset - valueTextWidth;
negOffset = -negOffset - valueTextWidth;
}
drawValue(
context: context,
value: valueText,
xPos: valuePoints[j].x + (val >= 0.0 ? posOffset : negOffset),
yPos: valuePoints[j].y + yOffset,
font: valueFont,
align: .Left,
color: valueTextColor);
}
else
{
var transformed = [CGPoint]();
var cnt = 0;
var add = e.value;
for (var k = 0; k < vals.count; k++)
{
add -= vals[cnt];
transformed.append(CGPoint(x: (CGFloat(vals[cnt]) + CGFloat(add)) * _animator.phaseY, y: 0.0));
cnt++;
}
trans.pointValuesToPixel(&transformed);
for (var k = 0; k < transformed.count; k++)
{
var val = vals[k];
var valueText = formatter!.stringFromNumber(val)!;
// calculate the correct offset depending on the draw position of the value
var valueTextWidth = valueText.sizeWithAttributes([NSFontAttributeName: valueFont]).width;
posOffset = (drawValueAboveBar ? valueOffsetPlus : -(valueTextWidth + valueOffsetPlus));
negOffset = (drawValueAboveBar ? -(valueTextWidth + valueOffsetPlus) : valueOffsetPlus);
if (isInverted)
{
posOffset = -posOffset - valueTextWidth;
negOffset = -negOffset - valueTextWidth;
}
var x = transformed[k].x + (val >= 0 ? posOffset : negOffset);
var y = valuePoints[j].y;
if (!viewPortHandler.isInBoundsX(x))
{
continue;
}
if (!viewPortHandler.isInBoundsTop(y))
{
break;
}
if (!viewPortHandler.isInBoundsBottom(y))
{
continue;
}
drawValue(context: context,
value: valueText,
xPos: x,
yPos: y + yOffset,
font: valueFont,
align: .Left,
color: valueTextColor);
}
}
}
}
}
}
}
internal override func passesCheck() -> Bool
{
var barData = delegate!.barChartRendererData(self);
if (barData === nil)
{
return false;
}
return CGFloat(barData.yValCount) < CGFloat(delegate!.barChartRendererMaxVisibleValueCount(self)) * viewPortHandler.scaleY;
}
} | gpl-2.0 | 600683209eb93a86109567efd7ba0817 | 42.321267 | 171 | 0.425706 | 6.692415 | false | false | false | false |
hughbe/swift | validation-test/stdlib/Data.swift | 6 | 2159 | // RUN: %target-run-simple-swift
// REQUIRES: executable_test
// REQUIRES: objc_interop
import StdlibUnittest
import StdlibCollectionUnittest
import Foundation
var DataTestSuite = TestSuite("Data")
DataTestSuite.test("Data.Iterator semantics") {
// Empty data
checkSequence([], Data())
// Small data
checkSequence([1,2,4,8,16], Data(bytes: [1,2,4,8,16]))
// Boundary conditions
checkSequence([5], Data(bytes: [5]))
checkSequence(1...31, Data(bytes: Array(1...31)))
checkSequence(1...32, Data(bytes: Array(1...32)))
checkSequence(1...33, Data(bytes: Array(1...33)))
// Large data
var data = Data(count: 65535)
data.withUnsafeMutableBytes { (ptr: UnsafeMutablePointer<UInt8>) -> () in
for i in 0..<data.count {
ptr[i] = UInt8(i % 23)
}
}
checkSequence((0..<65535).lazy.map({ UInt8($0 % 23) }), data)
}
DataTestSuite.test("associated types") {
typealias Subject = Data
expectRandomAccessCollectionAssociatedTypes(
collectionType: Subject.self,
iteratorType: Data.Iterator.self,
subSequenceType: Subject.self,
indexType: Int.self,
indexDistanceType: Int.self,
indicesType: CountableRange<Int>.self)
}
DataTestSuite.test("Data SubSequence") {
let array: [UInt8] = [0, 1, 2, 3, 4, 5, 6, 7]
var data = Data(bytes: array)
// FIXME: Iteration over Data slices is currently broken:
// [SR-4292] Foundation.Data.copyBytes is zero-based.
// Data.Iterator assumes it is not.
// checkRandomAccessCollection(array, data)
for i in 0..<data.count {
for j in i..<data.count {
var dataSlice = data[i..<j]
let arraySlice = array[i..<j]
if dataSlice.count > 0 {
expectEqual(dataSlice.startIndex, i)
expectEqual(dataSlice.endIndex, j)
// FIXME: Iteration over Data slices is currently broken:
// [SR-4292] Foundation.Data.copyBytes is zero-based.
// Data.Iterator assumes it is not.
// expectEqual(dataSlice[i], arraySlice[i])
dataSlice[i] = 0xFF
expectEqual(dataSlice.startIndex, i)
expectEqual(dataSlice.endIndex, j)
}
}
}
}
runAllTests()
| apache-2.0 | 7fc06d5fe74634427926aafc312e3bac | 27.407895 | 75 | 0.648912 | 3.671769 | false | true | false | false |
liuxuan30/Charts | Source/Charts/Charts/ChartViewBase.swift | 2 | 37355 | //
// ChartViewBase.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
//
// Based on https://github.com/PhilJay/MPAndroidChart/commit/c42b880
import Foundation
import CoreGraphics
#if canImport(UIKit)
import UIKit
#endif
#if canImport(Cocoa)
import Cocoa
#endif
@objc
public protocol ChartViewDelegate
{
/// Called when a value has been selected inside the chart.
///
/// - Parameters:
/// - entry: The selected Entry.
/// - highlight: The corresponding highlight object that contains information about the highlighted position such as dataSetIndex etc.
@objc optional func chartValueSelected(_ chartView: ChartViewBase, entry: ChartDataEntry, highlight: Highlight)
/// Called when a user stops panning between values on the chart
@objc optional func chartViewDidEndPanning(_ chartView: ChartViewBase)
// Called when nothing has been selected or an "un-select" has been made.
@objc optional func chartValueNothingSelected(_ chartView: ChartViewBase)
// Callbacks when the chart is scaled / zoomed via pinch zoom gesture.
@objc optional func chartScaled(_ chartView: ChartViewBase, scaleX: CGFloat, scaleY: CGFloat)
// Callbacks when the chart is moved / translated via drag gesture.
@objc optional func chartTranslated(_ chartView: ChartViewBase, dX: CGFloat, dY: CGFloat)
// Callbacks when Animator stops animating
@objc optional func chartView(_ chartView: ChartViewBase, animatorDidStop animator: Animator)
}
open class ChartViewBase: NSUIView, ChartDataProvider, AnimatorDelegate
{
// MARK: - Properties
/// - Returns: The object representing all x-labels, this method can be used to
/// acquire the XAxis object and modify it (e.g. change the position of the
/// labels)
@objc open var xAxis: XAxis
{
return _xAxis
}
/// The default IValueFormatter that has been determined by the chart considering the provided minimum and maximum values.
internal var _defaultValueFormatter: IValueFormatter? = DefaultValueFormatter(decimals: 0)
/// object that holds all data that was originally set for the chart, before it was modified or any filtering algorithms had been applied
internal var _data: ChartData?
/// Flag that indicates if highlighting per tap (touch) is enabled
private var _highlightPerTapEnabled = true
/// If set to true, chart continues to scroll after touch up
@objc open var dragDecelerationEnabled = true
/// Deceleration friction coefficient in [0 ; 1] interval, higher values indicate that speed will decrease slowly, for example if it set to 0, it will stop immediately.
/// 1 is an invalid value, and will be converted to 0.999 automatically.
private var _dragDecelerationFrictionCoef: CGFloat = 0.9
/// if true, units are drawn next to the values in the chart
internal var _drawUnitInChart = false
/// The object representing the labels on the x-axis
internal var _xAxis: XAxis!
/// The `Description` object of the chart.
/// This should have been called just "description", but
@objc open var chartDescription: Description?
/// The legend object containing all data associated with the legend
internal var _legend: Legend!
/// delegate to receive chart events
@objc open weak var delegate: ChartViewDelegate?
/// text that is displayed when the chart is empty
@objc open var noDataText = "No chart data available."
/// Font to be used for the no data text.
@objc open var noDataFont = NSUIFont.systemFont(ofSize: 12)
/// color of the no data text
@objc open var noDataTextColor: NSUIColor = .labelOrBlack
/// alignment of the no data text
@objc open var noDataTextAlignment: NSTextAlignment = .left
internal var _legendRenderer: LegendRenderer!
/// object responsible for rendering the data
@objc open var renderer: DataRenderer?
@objc open var highlighter: IHighlighter?
/// object that manages the bounds and drawing constraints of the chart
internal var _viewPortHandler: ViewPortHandler!
/// object responsible for animations
internal var _animator: Animator!
/// flag that indicates if offsets calculation has already been done or not
private var _offsetsCalculated = false
/// array of Highlight objects that reference the highlighted slices in the chart
internal var _indicesToHighlight = [Highlight]()
/// `true` if drawing the marker is enabled when tapping on values
/// (use the `marker` property to specify a marker)
@objc open var drawMarkers = true
/// - Returns: `true` if drawing the marker is enabled when tapping on values
/// (use the `marker` property to specify a marker)
@objc open var isDrawMarkersEnabled: Bool { return drawMarkers }
/// The marker that is displayed when a value is clicked on the chart
@objc open var marker: IMarker?
private var _interceptTouchEvents = false
/// An extra offset to be appended to the viewport's top
@objc open var extraTopOffset: CGFloat = 0.0
/// An extra offset to be appended to the viewport's right
@objc open var extraRightOffset: CGFloat = 0.0
/// An extra offset to be appended to the viewport's bottom
@objc open var extraBottomOffset: CGFloat = 0.0
/// An extra offset to be appended to the viewport's left
@objc open var extraLeftOffset: CGFloat = 0.0
@objc open func setExtraOffsets(left: CGFloat, top: CGFloat, right: CGFloat, bottom: CGFloat)
{
extraLeftOffset = left
extraTopOffset = top
extraRightOffset = right
extraBottomOffset = bottom
}
// MARK: - Initializers
public override init(frame: CGRect)
{
super.init(frame: frame)
initialize()
}
public required init?(coder aDecoder: NSCoder)
{
super.init(coder: aDecoder)
initialize()
}
deinit
{
self.removeObserver(self, forKeyPath: "bounds")
self.removeObserver(self, forKeyPath: "frame")
}
internal func initialize()
{
#if os(iOS)
self.backgroundColor = NSUIColor.clear
#endif
_animator = Animator()
_animator.delegate = self
_viewPortHandler = ViewPortHandler(width: bounds.size.width, height: bounds.size.height)
chartDescription = Description()
_legend = Legend()
_legendRenderer = LegendRenderer(viewPortHandler: _viewPortHandler, legend: _legend)
_xAxis = XAxis()
self.addObserver(self, forKeyPath: "bounds", options: .new, context: nil)
self.addObserver(self, forKeyPath: "frame", options: .new, context: nil)
}
// MARK: - ChartViewBase
/// The data for the chart
open var data: ChartData?
{
get
{
return _data
}
set
{
_data = newValue
_offsetsCalculated = false
guard let _data = _data else
{
setNeedsDisplay()
return
}
// calculate how many digits are needed
setupDefaultFormatter(min: _data.getYMin(), max: _data.getYMax())
for set in _data.dataSets
{
if set.needsFormatter || set.valueFormatter === _defaultValueFormatter
{
set.valueFormatter = _defaultValueFormatter
}
}
// let the chart know there is new data
notifyDataSetChanged()
}
}
/// Clears the chart from all data (sets it to null) and refreshes it (by calling setNeedsDisplay()).
@objc open func clear()
{
_data = nil
_offsetsCalculated = false
_indicesToHighlight.removeAll()
lastHighlighted = nil
setNeedsDisplay()
}
/// Removes all DataSets (and thereby Entries) from the chart. Does not set the data object to nil. Also refreshes the chart by calling setNeedsDisplay().
@objc open func clearValues()
{
_data?.clearValues()
setNeedsDisplay()
}
/// - Returns: `true` if the chart is empty (meaning it's data object is either null or contains no entries).
@objc open func isEmpty() -> Bool
{
guard let data = _data else { return true }
if data.entryCount <= 0
{
return true
}
else
{
return false
}
}
/// Lets the chart know its underlying data has changed and should perform all necessary recalculations.
/// It is crucial that this method is called everytime data is changed dynamically. Not calling this method can lead to crashes or unexpected behaviour.
@objc open func notifyDataSetChanged()
{
fatalError("notifyDataSetChanged() cannot be called on ChartViewBase")
}
/// Calculates the offsets of the chart to the border depending on the position of an eventual legend or depending on the length of the y-axis and x-axis labels and their position
internal func calculateOffsets()
{
fatalError("calculateOffsets() cannot be called on ChartViewBase")
}
/// calcualtes the y-min and y-max value and the y-delta and x-delta value
internal func calcMinMax()
{
fatalError("calcMinMax() cannot be called on ChartViewBase")
}
/// calculates the required number of digits for the values that might be drawn in the chart (if enabled), and creates the default value formatter
internal func setupDefaultFormatter(min: Double, max: Double)
{
// check if a custom formatter is set or not
var reference = Double(0.0)
if let data = _data , data.entryCount >= 2
{
reference = fabs(max - min)
}
else
{
let absMin = fabs(min)
let absMax = fabs(max)
reference = absMin > absMax ? absMin : absMax
}
if _defaultValueFormatter is DefaultValueFormatter
{
// setup the formatter with a new number of digits
let digits = reference.decimalPlaces
(_defaultValueFormatter as? DefaultValueFormatter)?.decimals
= digits
}
}
open override func draw(_ rect: CGRect)
{
let optionalContext = NSUIGraphicsGetCurrentContext()
guard let context = optionalContext else { return }
let frame = self.bounds
if _data === nil && noDataText.count > 0
{
context.saveGState()
defer { context.restoreGState() }
let paragraphStyle = NSMutableParagraphStyle.default.mutableCopy() as! NSMutableParagraphStyle
paragraphStyle.minimumLineHeight = noDataFont.lineHeight
paragraphStyle.lineBreakMode = .byWordWrapping
paragraphStyle.alignment = noDataTextAlignment
ChartUtils.drawMultilineText(
context: context,
text: noDataText,
point: CGPoint(x: frame.width / 2.0, y: frame.height / 2.0),
attributes:
[.font: noDataFont,
.foregroundColor: noDataTextColor,
.paragraphStyle: paragraphStyle],
constrainedToSize: self.bounds.size,
anchor: CGPoint(x: 0.5, y: 0.5),
angleRadians: 0.0)
return
}
if !_offsetsCalculated
{
calculateOffsets()
_offsetsCalculated = true
}
}
/// Draws the description text in the bottom right corner of the chart (per default)
internal func drawDescription(context: CGContext)
{
// check if description should be drawn
guard
let description = chartDescription,
description.isEnabled,
let descriptionText = description.text,
descriptionText.count > 0
else { return }
let position = description.position ?? CGPoint(x: bounds.width - _viewPortHandler.offsetRight - description.xOffset,
y: bounds.height - _viewPortHandler.offsetBottom - description.yOffset - description.font.lineHeight)
var attrs = [NSAttributedString.Key : Any]()
attrs[NSAttributedString.Key.font] = description.font
attrs[NSAttributedString.Key.foregroundColor] = description.textColor
ChartUtils.drawText(
context: context,
text: descriptionText,
point: position,
align: description.textAlign,
attributes: attrs)
}
// MARK: - Accessibility
open override func accessibilityChildren() -> [Any]? {
return renderer?.accessibleChartElements
}
// MARK: - Highlighting
/// The array of currently highlighted values. This might an empty if nothing is highlighted.
@objc open var highlighted: [Highlight]
{
return _indicesToHighlight
}
/// Set this to false to prevent values from being highlighted by tap gesture.
/// Values can still be highlighted via drag or programmatically.
/// **default**: true
@objc open var highlightPerTapEnabled: Bool
{
get { return _highlightPerTapEnabled }
set { _highlightPerTapEnabled = newValue }
}
/// `true` if values can be highlighted via tap gesture, `false` ifnot.
@objc open var isHighLightPerTapEnabled: Bool
{
return highlightPerTapEnabled
}
/// Checks if the highlight array is null, has a length of zero or if the first object is null.
///
/// - Returns: `true` if there are values to highlight, `false` ifthere are no values to highlight.
@objc open func valuesToHighlight() -> Bool
{
return !_indicesToHighlight.isEmpty
}
/// Highlights the values at the given indices in the given DataSets. Provide
/// null or an empty array to undo all highlighting.
/// This should be used to programmatically highlight values.
/// This method *will not* call the delegate.
@objc open func highlightValues(_ highs: [Highlight]?)
{
// set the indices to highlight
_indicesToHighlight = highs ?? [Highlight]()
if _indicesToHighlight.isEmpty
{
self.lastHighlighted = nil
}
else
{
self.lastHighlighted = _indicesToHighlight[0]
}
// redraw the chart
setNeedsDisplay()
}
/// Highlights any y-value at the given x-value in the given DataSet.
/// Provide -1 as the dataSetIndex to undo all highlighting.
/// This method will call the delegate.
///
/// - Parameters:
/// - x: The x-value to highlight
/// - dataSetIndex: The dataset index to search in
/// - dataIndex: The data index to search in (only used in CombinedChartView currently)
@objc open func highlightValue(x: Double, dataSetIndex: Int, dataIndex: Int = -1)
{
highlightValue(x: x, dataSetIndex: dataSetIndex, dataIndex: dataIndex, callDelegate: true)
}
/// Highlights the value at the given x-value and y-value in the given DataSet.
/// Provide -1 as the dataSetIndex to undo all highlighting.
/// This method will call the delegate.
///
/// - Parameters:
/// - x: The x-value to highlight
/// - y: The y-value to highlight. Supply `NaN` for "any"
/// - dataSetIndex: The dataset index to search in
/// - dataIndex: The data index to search in (only used in CombinedChartView currently)
@objc open func highlightValue(x: Double, y: Double, dataSetIndex: Int, dataIndex: Int = -1)
{
highlightValue(x: x, y: y, dataSetIndex: dataSetIndex, dataIndex: dataIndex, callDelegate: true)
}
/// Highlights any y-value at the given x-value in the given DataSet.
/// Provide -1 as the dataSetIndex to undo all highlighting.
///
/// - Parameters:
/// - x: The x-value to highlight
/// - dataSetIndex: The dataset index to search in
/// - dataIndex: The data index to search in (only used in CombinedChartView currently)
/// - callDelegate: Should the delegate be called for this change
@objc open func highlightValue(x: Double, dataSetIndex: Int, dataIndex: Int = -1, callDelegate: Bool)
{
highlightValue(x: x, y: .nan, dataSetIndex: dataSetIndex, dataIndex: dataIndex, callDelegate: callDelegate)
}
/// Highlights the value at the given x-value and y-value in the given DataSet.
/// Provide -1 as the dataSetIndex to undo all highlighting.
///
/// - Parameters:
/// - x: The x-value to highlight
/// - y: The y-value to highlight. Supply `NaN` for "any"
/// - dataSetIndex: The dataset index to search in
/// - dataIndex: The data index to search in (only used in CombinedChartView currently)
/// - callDelegate: Should the delegate be called for this change
@objc open func highlightValue(x: Double, y: Double, dataSetIndex: Int, dataIndex: Int = -1, callDelegate: Bool)
{
guard let data = _data else
{
Swift.print("Value not highlighted because data is nil")
return
}
if dataSetIndex < 0 || dataSetIndex >= data.dataSetCount
{
highlightValue(nil, callDelegate: callDelegate)
}
else
{
highlightValue(Highlight(x: x, y: y, dataSetIndex: dataSetIndex, dataIndex: dataIndex), callDelegate: callDelegate)
}
}
/// Highlights the values represented by the provided Highlight object
/// This method *will not* call the delegate.
///
/// - Parameters:
/// - highlight: contains information about which entry should be highlighted
@objc open func highlightValue(_ highlight: Highlight?)
{
highlightValue(highlight, callDelegate: false)
}
/// Highlights the value selected by touch gesture.
@objc open func highlightValue(_ highlight: Highlight?, callDelegate: Bool)
{
var entry: ChartDataEntry?
var h = highlight
if h == nil
{
self.lastHighlighted = nil
_indicesToHighlight.removeAll(keepingCapacity: false)
}
else
{
// set the indices to highlight
entry = _data?.entryForHighlight(h!)
if entry == nil
{
h = nil
_indicesToHighlight.removeAll(keepingCapacity: false)
}
else
{
_indicesToHighlight = [h!]
}
}
if callDelegate, let delegate = delegate
{
if let h = h
{
// notify the listener
delegate.chartValueSelected?(self, entry: entry!, highlight: h)
}
else
{
delegate.chartValueNothingSelected?(self)
}
}
// redraw the chart
setNeedsDisplay()
}
/// - Returns: The Highlight object (contains x-index and DataSet index) of the
/// selected value at the given touch point inside the Line-, Scatter-, or
/// CandleStick-Chart.
@objc open func getHighlightByTouchPoint(_ pt: CGPoint) -> Highlight?
{
if _data === nil
{
Swift.print("Can't select by touch. No data set.")
return nil
}
return self.highlighter?.getHighlight(x: pt.x, y: pt.y)
}
/// The last value that was highlighted via touch.
@objc open var lastHighlighted: Highlight?
// MARK: - Markers
/// draws all MarkerViews on the highlighted positions
internal func drawMarkers(context: CGContext)
{
// if there is no marker view or drawing marker is disabled
guard
let marker = marker
, isDrawMarkersEnabled &&
valuesToHighlight()
else { return }
for i in 0 ..< _indicesToHighlight.count
{
let highlight = _indicesToHighlight[i]
guard let
set = data?.getDataSetByIndex(highlight.dataSetIndex),
let e = _data?.entryForHighlight(highlight)
else { continue }
let entryIndex = set.entryIndex(entry: e)
if entryIndex > Int(Double(set.entryCount) * _animator.phaseX)
{
continue
}
let pos = getMarkerPosition(highlight: highlight)
// check bounds
if !_viewPortHandler.isInBounds(x: pos.x, y: pos.y)
{
continue
}
// callbacks to update the content
marker.refreshContent(entry: e, highlight: highlight)
// draw the marker
marker.draw(context: context, point: pos)
}
}
/// - Returns: The actual position in pixels of the MarkerView for the given Entry in the given DataSet.
@objc open func getMarkerPosition(highlight: Highlight) -> CGPoint
{
return CGPoint(x: highlight.drawX, y: highlight.drawY)
}
// MARK: - Animation
/// The animator responsible for animating chart values.
@objc open var chartAnimator: Animator!
{
return _animator
}
/// Animates the drawing / rendering of the chart on both x- and y-axis with the specified animation time.
/// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart.
///
/// - Parameters:
/// - xAxisDuration: duration for animating the x axis
/// - yAxisDuration: duration for animating the y axis
/// - easingX: an easing function for the animation on the x axis
/// - easingY: an easing function for the animation on the y axis
@objc open func animate(xAxisDuration: TimeInterval, yAxisDuration: TimeInterval, easingX: ChartEasingFunctionBlock?, easingY: ChartEasingFunctionBlock?)
{
_animator.animate(xAxisDuration: xAxisDuration, yAxisDuration: yAxisDuration, easingX: easingX, easingY: easingY)
}
/// Animates the drawing / rendering of the chart on both x- and y-axis with the specified animation time.
/// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart.
///
/// - Parameters:
/// - xAxisDuration: duration for animating the x axis
/// - yAxisDuration: duration for animating the y axis
/// - easingOptionX: the easing function for the animation on the x axis
/// - easingOptionY: the easing function for the animation on the y axis
@objc open func animate(xAxisDuration: TimeInterval, yAxisDuration: TimeInterval, easingOptionX: ChartEasingOption, easingOptionY: ChartEasingOption)
{
_animator.animate(xAxisDuration: xAxisDuration, yAxisDuration: yAxisDuration, easingOptionX: easingOptionX, easingOptionY: easingOptionY)
}
/// Animates the drawing / rendering of the chart on both x- and y-axis with the specified animation time.
/// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart.
///
/// - Parameters:
/// - xAxisDuration: duration for animating the x axis
/// - yAxisDuration: duration for animating the y axis
/// - easing: an easing function for the animation
@objc open func animate(xAxisDuration: TimeInterval, yAxisDuration: TimeInterval, easing: ChartEasingFunctionBlock?)
{
_animator.animate(xAxisDuration: xAxisDuration, yAxisDuration: yAxisDuration, easing: easing)
}
/// Animates the drawing / rendering of the chart on both x- and y-axis with the specified animation time.
/// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart.
///
/// - Parameters:
/// - xAxisDuration: duration for animating the x axis
/// - yAxisDuration: duration for animating the y axis
/// - easingOption: the easing function for the animation
@objc open func animate(xAxisDuration: TimeInterval, yAxisDuration: TimeInterval, easingOption: ChartEasingOption)
{
_animator.animate(xAxisDuration: xAxisDuration, yAxisDuration: yAxisDuration, easingOption: easingOption)
}
/// Animates the drawing / rendering of the chart on both x- and y-axis with the specified animation time.
/// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart.
///
/// - Parameters:
/// - xAxisDuration: duration for animating the x axis
/// - yAxisDuration: duration for animating the y axis
@objc open func animate(xAxisDuration: TimeInterval, yAxisDuration: TimeInterval)
{
_animator.animate(xAxisDuration: xAxisDuration, yAxisDuration: yAxisDuration)
}
/// Animates the drawing / rendering of the chart the x-axis with the specified animation time.
/// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart.
///
/// - Parameters:
/// - xAxisDuration: duration for animating the x axis
/// - easing: an easing function for the animation
@objc open func animate(xAxisDuration: TimeInterval, easing: ChartEasingFunctionBlock?)
{
_animator.animate(xAxisDuration: xAxisDuration, easing: easing)
}
/// Animates the drawing / rendering of the chart the x-axis with the specified animation time.
/// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart.
///
/// - Parameters:
/// - xAxisDuration: duration for animating the x axis
/// - easingOption: the easing function for the animation
@objc open func animate(xAxisDuration: TimeInterval, easingOption: ChartEasingOption)
{
_animator.animate(xAxisDuration: xAxisDuration, easingOption: easingOption)
}
/// Animates the drawing / rendering of the chart the x-axis with the specified animation time.
/// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart.
///
/// - Parameters:
/// - xAxisDuration: duration for animating the x axis
@objc open func animate(xAxisDuration: TimeInterval)
{
_animator.animate(xAxisDuration: xAxisDuration)
}
/// Animates the drawing / rendering of the chart the y-axis with the specified animation time.
/// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart.
///
/// - Parameters:
/// - yAxisDuration: duration for animating the y axis
/// - easing: an easing function for the animation
@objc open func animate(yAxisDuration: TimeInterval, easing: ChartEasingFunctionBlock?)
{
_animator.animate(yAxisDuration: yAxisDuration, easing: easing)
}
/// Animates the drawing / rendering of the chart the y-axis with the specified animation time.
/// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart.
///
/// - Parameters:
/// - yAxisDuration: duration for animating the y axis
/// - easingOption: the easing function for the animation
@objc open func animate(yAxisDuration: TimeInterval, easingOption: ChartEasingOption)
{
_animator.animate(yAxisDuration: yAxisDuration, easingOption: easingOption)
}
/// Animates the drawing / rendering of the chart the y-axis with the specified animation time.
/// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart.
///
/// - Parameters:
/// - yAxisDuration: duration for animating the y axis
@objc open func animate(yAxisDuration: TimeInterval)
{
_animator.animate(yAxisDuration: yAxisDuration)
}
// MARK: - Accessors
/// The current y-max value across all DataSets
open var chartYMax: Double
{
return _data?.yMax ?? 0.0
}
/// The current y-min value across all DataSets
open var chartYMin: Double
{
return _data?.yMin ?? 0.0
}
open var chartXMax: Double
{
return _xAxis._axisMaximum
}
open var chartXMin: Double
{
return _xAxis._axisMinimum
}
open var xRange: Double
{
return _xAxis.axisRange
}
/// - Note: (Equivalent of getCenter() in MPAndroidChart, as center is already a standard in iOS that returns the center point relative to superview, and MPAndroidChart returns relative to self)*
/// The center point of the chart (the whole View) in pixels.
@objc open var midPoint: CGPoint
{
let bounds = self.bounds
return CGPoint(x: bounds.origin.x + bounds.size.width / 2.0, y: bounds.origin.y + bounds.size.height / 2.0)
}
/// The center of the chart taking offsets under consideration. (returns the center of the content rectangle)
open var centerOffsets: CGPoint
{
return _viewPortHandler.contentCenter
}
/// The Legend object of the chart. This method can be used to get an instance of the legend in order to customize the automatically generated Legend.
@objc open var legend: Legend
{
return _legend
}
/// The renderer object responsible for rendering / drawing the Legend.
@objc open var legendRenderer: LegendRenderer!
{
return _legendRenderer
}
/// The rectangle that defines the borders of the chart-value surface (into which the actual values are drawn).
@objc open var contentRect: CGRect
{
return _viewPortHandler.contentRect
}
/// - Returns: The ViewPortHandler of the chart that is responsible for the
/// content area of the chart and its offsets and dimensions.
@objc open var viewPortHandler: ViewPortHandler!
{
return _viewPortHandler
}
/// - Returns: The bitmap that represents the chart.
@objc open func getChartImage(transparent: Bool) -> NSUIImage?
{
NSUIGraphicsBeginImageContextWithOptions(bounds.size, isOpaque || !transparent, NSUIScreen.nsuiMain?.nsuiScale ?? 1.0)
guard let context = NSUIGraphicsGetCurrentContext()
else { return nil }
let rect = CGRect(origin: CGPoint(x: 0, y: 0), size: bounds.size)
if isOpaque || !transparent
{
// Background color may be partially transparent, we must fill with white if we want to output an opaque image
context.setFillColor(NSUIColor.white.cgColor)
context.fill(rect)
if let backgroundColor = self.backgroundColor
{
context.setFillColor(backgroundColor.cgColor)
context.fill(rect)
}
}
nsuiLayer?.render(in: context)
let image = NSUIGraphicsGetImageFromCurrentImageContext()
NSUIGraphicsEndImageContext()
return image
}
public enum ImageFormat
{
case jpeg
case png
}
/// Saves the current chart state with the given name to the given path on
/// the sdcard leaving the path empty "" will put the saved file directly on
/// the SD card chart is saved as a PNG image, example:
/// saveToPath("myfilename", "foldername1/foldername2")
///
/// - Parameters:
/// - to: path to the image to save
/// - format: the format to save
/// - compressionQuality: compression quality for lossless formats (JPEG)
/// - Returns: `true` if the image was saved successfully
open func save(to path: String, format: ImageFormat, compressionQuality: Double) -> Bool
{
guard let image = getChartImage(transparent: format != .jpeg) else { return false }
let imageData: Data?
switch (format)
{
case .png: imageData = NSUIImagePNGRepresentation(image)
case .jpeg: imageData = NSUIImageJPEGRepresentation(image, CGFloat(compressionQuality))
}
guard let data = imageData else { return false }
do
{
try data.write(to: URL(fileURLWithPath: path), options: .atomic)
}
catch
{
return false
}
return true
}
internal var _viewportJobs = [ViewPortJob]()
open override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?)
{
if keyPath == "bounds" || keyPath == "frame"
{
let bounds = self.bounds
if (_viewPortHandler !== nil &&
(bounds.size.width != _viewPortHandler.chartWidth ||
bounds.size.height != _viewPortHandler.chartHeight))
{
_viewPortHandler.setChartDimens(width: bounds.size.width, height: bounds.size.height)
// This may cause the chart view to mutate properties affecting the view port -- lets do this
// before we try to run any pending jobs on the view port itself
notifyDataSetChanged()
// Finish any pending viewport changes
while (!_viewportJobs.isEmpty)
{
let job = _viewportJobs.remove(at: 0)
job.doJob()
}
}
}
}
@objc open func removeViewportJob(_ job: ViewPortJob)
{
if let index = _viewportJobs.firstIndex(where: { $0 === job })
{
_viewportJobs.remove(at: index)
}
}
@objc open func clearAllViewportJobs()
{
_viewportJobs.removeAll(keepingCapacity: false)
}
@objc open func addViewportJob(_ job: ViewPortJob)
{
if _viewPortHandler.hasChartDimens
{
job.doJob()
}
else
{
_viewportJobs.append(job)
}
}
/// **default**: true
/// `true` if chart continues to scroll after touch up, `false` ifnot.
@objc open var isDragDecelerationEnabled: Bool
{
return dragDecelerationEnabled
}
/// Deceleration friction coefficient in [0 ; 1] interval, higher values indicate that speed will decrease slowly, for example if it set to 0, it will stop immediately.
/// 1 is an invalid value, and will be converted to 0.999 automatically.
///
/// **default**: true
@objc open var dragDecelerationFrictionCoef: CGFloat
{
get
{
return _dragDecelerationFrictionCoef
}
set
{
var val = newValue
if val < 0.0
{
val = 0.0
}
if val >= 1.0
{
val = 0.999
}
_dragDecelerationFrictionCoef = val
}
}
/// The maximum distance in screen pixels away from an entry causing it to highlight.
/// **default**: 500.0
open var maxHighlightDistance: CGFloat = 500.0
/// the number of maximum visible drawn values on the chart only active when `drawValuesEnabled` is enabled
open var maxVisibleCount: Int
{
return Int(INT_MAX)
}
// MARK: - AnimatorDelegate
open func animatorUpdated(_ chartAnimator: Animator)
{
setNeedsDisplay()
}
open func animatorStopped(_ chartAnimator: Animator)
{
delegate?.chartView?(self, animatorDidStop: chartAnimator)
}
// MARK: - Touches
open override func nsuiTouchesBegan(_ touches: Set<NSUITouch>, withEvent event: NSUIEvent?)
{
if !_interceptTouchEvents
{
super.nsuiTouchesBegan(touches, withEvent: event)
}
}
open override func nsuiTouchesMoved(_ touches: Set<NSUITouch>, withEvent event: NSUIEvent?)
{
if !_interceptTouchEvents
{
super.nsuiTouchesMoved(touches, withEvent: event)
}
}
open override func nsuiTouchesEnded(_ touches: Set<NSUITouch>, withEvent event: NSUIEvent?)
{
if !_interceptTouchEvents
{
super.nsuiTouchesEnded(touches, withEvent: event)
}
}
open override func nsuiTouchesCancelled(_ touches: Set<NSUITouch>?, withEvent event: NSUIEvent?)
{
if !_interceptTouchEvents
{
super.nsuiTouchesCancelled(touches, withEvent: event)
}
}
}
| apache-2.0 | 6fa6f96325b4b866096f792a1412f39f | 34.849328 | 199 | 0.620158 | 5.201197 | false | false | false | false |
hironytic/Moltonf-iOS | Moltonf/ViewModel/StoryWatchingViewModel.swift | 1 | 6391 | //
// StoryWatchingViewModel.swift
// Moltonf
//
// Copyright (c) 2016 Hironori Ichimiya <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
import RxSwift
import RxCocoa
fileprivate typealias R = Resource
public struct StoryWatchingViewModelElementList {
let items: [IStoryElementViewModel]
let shouldScrollToTop: Bool
}
public protocol IStoryWatchingViewModel: IViewModel {
var titleLine: Observable<String> { get }
var currentPeriodTextLine: Observable<String?> { get }
var elementListLine: Observable<StoryWatchingViewModelElementList> { get }
var selectPeriodAction: AnyObserver<Void> { get }
var leaveWatchingAction: AnyObserver<Void> { get }
}
public class StoryWatchingViewModel: ViewModel, IStoryWatchingViewModel {
public var titleLine: Observable<String> { get { return _storyWatching.titleLine } }
public private(set) var currentPeriodTextLine: Observable<String?>
public private(set) var elementListLine: Observable<StoryWatchingViewModelElementList>
public private(set) var selectPeriodAction: AnyObserver<Void>
public private(set) var leaveWatchingAction: AnyObserver<Void>
private let _factory: Factory
private let _storyWatching: IStoryWatching
private let _selectPeriodAction = ActionObserver<Void>()
private let _leaveWatchingAction = ActionObserver<Void>()
class Factory {
func storyEventViewModel(storyEvent: StoryEvent) -> IStoryEventViewModel {
return StoryEventViewModel(storyEvent: storyEvent)
}
func talkViewModel(talk: Talk) -> ITalkViewModel {
return TalkViewModel(talk: talk)
}
func selectPeriodViewModel(storyWatching: IStoryWatching) -> ISelectPeriodViewModel {
return SelectPeriodViewModel(storyWatching: storyWatching)
}
}
public convenience init(storyWatching: IStoryWatching) {
self.init(storyWatching: storyWatching, factory: Factory())
}
init(storyWatching: IStoryWatching, factory: Factory) {
_factory = factory
_storyWatching = storyWatching
currentPeriodTextLine = type(of: self).configureCurrentPeriodTextLine(_storyWatching.currentPeriodLine)
elementListLine = type(of: self).configureElementListLine(storyElementListLine: _storyWatching.storyElementListLine, factory: _factory)
selectPeriodAction = _selectPeriodAction.asObserver()
leaveWatchingAction = _leaveWatchingAction.asObserver()
super.init()
_selectPeriodAction.handler = { [weak self] in self?.selectPeriod() }
_leaveWatchingAction.handler = { [weak self] in self?.leaveWatching() }
}
private static func configureCurrentPeriodTextLine(_ currentPeriodLine: Observable<Period>) -> Observable<String?> {
return currentPeriodLine
.map { period in
return { () -> String in
switch period.type {
case .prologue:
return ResourceUtils.getString(R.String.periodPrologue)
case .epilogue:
return ResourceUtils.getString(R.String.periodEpilogue)
case .progress:
return ResourceUtils.getString(format: R.String.periodDayFormat, period.day)
}
}()
}
.map { ResourceUtils.getString(format: R.String.periodSelectFormat, $0) }
.asDriver(onErrorJustReturn: nil).asObservable()
}
private static func configureElementListLine(storyElementListLine: Observable<StoryWatchingElementList>, factory: Factory)
-> Observable<StoryWatchingViewModelElementList>
{
return storyElementListLine
.map { elementList in
let items = elementList.elements
.map { element -> IStoryElementViewModel in
if let storyEvent = element as? StoryEvent {
return factory.storyEventViewModel(storyEvent: storyEvent)
} else if let talk = element as? Talk {
return factory.talkViewModel(talk: talk)
} else {
fatalError()
}
}
return StoryWatchingViewModelElementList(items: items, shouldScrollToTop: elementList.shouldScrollToTop)
}
.asDriver(onErrorJustReturn: StoryWatchingViewModelElementList(items: [], shouldScrollToTop: false)).asObservable()
}
private func selectPeriod() {
let selectPeriodViewModel = _factory.selectPeriodViewModel(storyWatching: _storyWatching)
selectPeriodViewModel.onResult = { [weak self] result in
self?.processSelectPeriodViewModelResult(result)
}
sendMessage(TransitionMessage(viewModel: selectPeriodViewModel))
}
private func processSelectPeriodViewModelResult(_ result: SelectPeriodViewModelResult) {
switch result {
case .selected(let periodReference):
_storyWatching.selectPeriodAction.onNext(periodReference)
default:
break
}
}
private func leaveWatching() {
sendMessage(DismissingMessage())
}
}
| mit | ad305190d1527cea933ef444fe51a558 | 42.182432 | 143 | 0.675481 | 5.108713 | false | false | false | false |
guoc/spi | SPiKeyboard/TastyImitationKeyboard/CatboardBanner.swift | 1 | 2087 | //
// CatboardBanner.swift
// TastyImitationKeyboard
//
// Created by Alexei Baboulevitch on 10/5/14.
// Copyright (c) 2014 Apple. All rights reserved.
//
import UIKit
/*
This is the demo banner. The banner is needed so that the top row popups have somewhere to go. Might as well fill it
with something (or leave it blank if you like.)
*/
class CatboardBanner: ExtraView {
var catSwitch: UISwitch = UISwitch()
var catLabel: UILabel = UILabel()
required init(globalColors: GlobalColors.Type?, darkMode: Bool, solidColorMode: Bool) {
super.init(globalColors: globalColors, darkMode: darkMode, solidColorMode: solidColorMode)
self.addSubview(self.catSwitch)
self.addSubview(self.catLabel)
self.catSwitch.isOn = UserDefaults.standard.bool(forKey: kCatTypeEnabled)
self.catSwitch.transform = CGAffineTransform(scaleX: 0.75, y: 0.75)
self.catSwitch.addTarget(self, action: #selector(respondToSwitch), for: UIControlEvents.valueChanged)
self.updateAppearance()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func setNeedsLayout() {
super.setNeedsLayout()
}
override func layoutSubviews() {
super.layoutSubviews()
self.catSwitch.center = self.center
self.catLabel.center = self.center
self.catLabel.frame.origin = CGPoint(x: self.catSwitch.frame.origin.x + self.catSwitch.frame.width + 8, y: self.catLabel.frame.origin.y)
}
func respondToSwitch() {
UserDefaults.standard.set(self.catSwitch.isOn, forKey: kCatTypeEnabled)
self.updateAppearance()
}
override func updateAppearance() {
super.updateAppearance()
if self.catSwitch.isOn {
self.catLabel.text = "😺"
self.catLabel.alpha = 1
}
else {
self.catLabel.text = "🐱"
self.catLabel.alpha = 0.5
}
self.catLabel.sizeToFit()
}
}
| bsd-3-clause | d7a1757bcf8b1de20f4517a1fb20077b | 29.15942 | 144 | 0.641519 | 4.238289 | false | false | false | false |
naoty/flock | Sources/flock/main.swift | 1 | 1284 | //
// main.swift
// flock
//
// Created by Naoto Kaneko on 2017/02/25.
// Copyright (c) 2017 Naoto Kaneko. All rights reserved.
//
import Foundation
import PathKit
let version = "0.1.0"
func main() {
let command = makeCommand(arguments: [String](CommandLine.arguments.dropFirst()))
let result = command.run()
switch result {
case let .success(message):
print(message)
exit(0)
case let .failure(error):
print(error.message)
exit(Int32(error.code))
}
}
func makeCommand(arguments: [String]) -> Command {
guard let firstArgument = arguments.first else {
let paths = allSourcePaths(directoryPath: ".")
return MainCommand(paths: paths)
}
switch firstArgument {
case "--help", "-h":
return HelpCommand()
case "--version", "-v":
return VersionCommand(version: version)
default:
let paths = allSourcePaths(directoryPath: firstArgument)
return MainCommand(paths: paths)
}
}
func allSourcePaths(directoryPath: String) -> [String] {
let absolutePath = Path(directoryPath).absolute()
do {
return try absolutePath.recursiveChildren().filter({ $0.extension == "swift" }).map({ $0.string })
} catch {
return []
}
}
main()
| mit | 91ed41dae176f41de62ebbf385aa4638 | 22.345455 | 106 | 0.626168 | 3.975232 | false | false | false | false |
IdeasOnCanvas/Ashton | Sources/Ashton/AshtonHTMLWriter.swift | 1 | 12867 | //
// AshtonHTMLWriter.swift
// Ashton
//
// Created by Michael Schwarz on 16.09.17.
// Copyright © 2017 Michael Schwarz. All rights reserved.
//
import Foundation
#if os(iOS)
import UIKit
#elseif os(macOS)
import AppKit
#endif
final class AshtonHTMLWriter {
func encode(_ attributedString: NSAttributedString) -> Ashton.HTML {
let string = attributedString.string
let paragraphRanges = self.getParagraphRanges(from: string)
var html = String()
for paragraphRange in paragraphRanges {
var paragraphContent = String()
let nsParagraphRange = NSRange(paragraphRange, in: string)
var paragraphTag = HTMLTag(defaultName: .p, attributes: [:], ignoreParagraphStyles: false)
// We use `attributedString.string as NSString` casts and NSRange ranges in the block because
// we experienced outOfBounds crashes when converting NSRange to Range and using it on swift string
attributedString.enumerateAttributes(in: nsParagraphRange,
options: .longestEffectiveRangeNotRequired, using: { attributes, nsrange, _ in
let paragraphStyle = attributes.filter { $0.key == .paragraphStyle }
paragraphTag.addAttributes(paragraphStyle)
let nsString = attributedString.string as NSString
if nsParagraphRange.length == nsrange.length {
paragraphTag.addAttributes(attributes)
paragraphContent += String(nsString.substring(with: nsrange)).htmlEscaped
} else {
var tag = HTMLTag(defaultName: .span, attributes: attributes, ignoreParagraphStyles: true)
paragraphContent += tag.parseOpenTag()
paragraphContent += String(nsString.substring(with: nsrange)).htmlEscaped
paragraphContent += tag.makeCloseTag()
}
})
html += paragraphTag.parseOpenTag() + paragraphContent + paragraphTag.makeCloseTag()
}
return html
}
}
// MARK: - Private
private extension AshtonHTMLWriter {
func getParagraphRanges(from string: String) -> [Range<String.Index>] {
var (paragraphStart, paragraphEnd, contentsEnd) = (string.startIndex, string.startIndex, string.startIndex)
var ranges = [Range<String.Index>]()
let length = string.endIndex
while paragraphEnd < length {
string.getParagraphStart(¶graphStart, end: ¶graphEnd, contentsEnd: &contentsEnd, for: paragraphEnd...paragraphEnd)
ranges.append(paragraphStart..<contentsEnd)
}
return ranges
}
}
private struct HTMLTag {
enum Name: String {
case p
case span
case a
func openTag(with attributes: String...) -> String {
var attributesString = ""
for attribute in attributes {
if attribute.isEmpty { continue }
attributesString += " " + attribute
}
return "<\(self.rawValue)\(attributesString)>"
}
func closeTag() -> String {
return "</\(self.rawValue)>"
}
}
private var hasParsedLinks: Bool = false
// MARK: - Properties
let defaultName: Name
var attributes: [NSAttributedString.Key: Any]
let ignoreParagraphStyles: Bool
init(defaultName: Name, attributes: [NSAttributedString.Key: Any], ignoreParagraphStyles: Bool) {
self.defaultName = defaultName
self.attributes = attributes
self.ignoreParagraphStyles = ignoreParagraphStyles
}
mutating func addAttributes(_ attributes: [NSAttributedString.Key: Any]?) {
attributes?.forEach { (key, value) in
self.attributes[key] = value
}
}
mutating func parseOpenTag() -> String {
guard !self.attributes.isEmpty else { return self.defaultName.openTag() }
var styles: [String: String] = [:]
var cocoaStyles: [String: String] = [:]
var links = ""
self.attributes.forEach { key, value in
switch key {
case .backgroundColor:
guard let color = value as? Color else { return }
styles["background-color"] = self.makeCSSrgba(for: color)
case .foregroundColor:
guard let color = value as? Color else { return }
styles["color"] = self.makeCSSrgba(for: color)
case .underlineStyle:
guard let intValue = value as? Int else { return }
guard let underlineStyle = Mappings.UnderlineStyle.encode[intValue] else { return }
styles["text-decoration"] = (styles["text-decoration"] ?? "").stringByAppendingAttributeValue("underline")
cocoaStyles["-cocoa-underline"] = underlineStyle
case .underlineColor:
guard let color = value as? Color else { return }
cocoaStyles["-cocoa-underline-color"] = self.makeCSSrgba(for: color)
case .strikethroughColor:
guard let color = value as? Color else { return }
cocoaStyles["-cocoa-strikethrough-color"] = self.makeCSSrgba(for: color)
case .strikethroughStyle:
guard let intValue = value as? Int else { return }
guard let underlineStyle = Mappings.UnderlineStyle.encode[intValue] else { return }
styles["text-decoration"] = "line-through".stringByAppendingAttributeValue(styles["text-decoration"])
cocoaStyles["-cocoa-strikethrough"] = underlineStyle
case .font:
guard let font = value as? Font else { return }
let fontDescriptor = font.fontDescriptor
var fontStyle = ""
#if os(iOS)
if fontDescriptor.symbolicTraits.contains(.traitBold) {
fontStyle += "bold "
}
if fontDescriptor.symbolicTraits.contains(.traitItalic) {
fontStyle += "italic "
}
#elseif os(macOS)
if fontDescriptor.symbolicTraits.contains(.bold) {
fontStyle += "bold "
}
if fontDescriptor.symbolicTraits.contains(.italic) {
fontStyle += "italic "
}
#endif
if let fontFeatures = fontDescriptor.object(forKey: .featureSettings) as? [[String: Any]] {
let features = fontFeatures.compactMap { feature in
guard let typeID = feature[FontDescriptor.FeatureKey.cpTypeIdentifier.rawValue] else { return nil }
guard let selectorID = feature[FontDescriptor.FeatureKey.selectorIdentifier.rawValue] else { return nil }
return "\(typeID)/\(selectorID)"
}.sorted(by: <).joined(separator: " ")
if features.isEmpty == false {
cocoaStyles["-cocoa-font-features"] = features
}
}
fontStyle += String(format: "%gpx ", fontDescriptor.pointSize)
fontStyle += "\"\(font.cpFamilyName)\""
styles["font"] = fontStyle
cocoaStyles["-cocoa-font-postscriptname"] = "\"\(fontDescriptor.cpPostscriptName)\""
case .paragraphStyle:
guard self.ignoreParagraphStyles == false else { return }
guard let paragraphStyle = value as? NSParagraphStyle else { return }
guard let alignment = Mappings.TextAlignment.encode[paragraphStyle.alignment] else { return }
styles["text-align"] = alignment
case .baselineOffset:
guard let offset = value as? Float else { return }
cocoaStyles["-cocoa-baseline-offset"] = String(format: "%.0f", offset)
case NSAttributedString.Key(rawValue: "NSSuperScript"):
guard let offset = value as? Int, offset != 0 else { return }
let verticalAlignment = offset > 0 ? "super" : "sub"
styles["vertical-align"] = verticalAlignment
cocoaStyles["-cocoa-vertical-align"] = String(offset)
case .link:
let link: String
switch value {
case let urlString as String:
link = urlString
case let url as URL:
link = url.absoluteString
default:
return
}
links = "href='\(link.htmlEscaped)'"
self.hasParsedLinks = true
default:
break
}
}
if styles.isEmpty && cocoaStyles.isEmpty && links.isEmpty {
return self.defaultName.openTag()
}
var openTag = ""
var styleAttributes = ""
do {
let separator = "; "
let styleDictionaryTransform: ([String: String]) -> [String] = { return $0.sorted(by: <).map { "\($0): \($1)" } }
let styleString = (styleDictionaryTransform(styles) + styleDictionaryTransform(cocoaStyles)).joined(separator: separator)
if styleString.isEmpty == false {
styleAttributes = "style='\(styleString)\(separator)'"
}
}
if self.hasParsedLinks {
if self.defaultName == .p {
openTag += self.defaultName.openTag(with: styleAttributes)
openTag += Name.a.openTag(with: links)
} else {
openTag += Name.a.openTag(with: styleAttributes, links)
}
} else {
openTag += self.defaultName.openTag(with: styleAttributes)
}
return openTag
}
func makeCloseTag() -> String {
if self.hasParsedLinks {
if self.defaultName == .p {
return Name.a.closeTag() + self.defaultName.closeTag()
} else {
return Name.a.closeTag()
}
} else {
return self.defaultName.closeTag()
}
}
// MARK: - Private
private func compareStyleTags(tags: (tag1: String, tag2: String)) -> Bool {
return tags.tag1 > tags.tag2
}
private func makeCSSrgba(for color: Color) -> String {
var (red, green, blue): (CGFloat, CGFloat, CGFloat)
let alpha = color.cgColor.alpha
if color.cgColor.numberOfComponents == 2 {
let monochromeValue = color.cgColor.components?[0] ?? 0
(red, green, blue) = (monochromeValue, monochromeValue, monochromeValue)
} else if color.cgColor.numberOfComponents == 4 {
var cgColor = color.cgColor
if let sRGBColorSpace = CGColorSpace(name: CGColorSpace.sRGB) {
if let convertedCGColor = color.cgColor.converted(to: sRGBColorSpace, intent: .defaultIntent, options: nil) {
cgColor = convertedCGColor
}
}
red = cgColor.components?[0] ?? 0
green = cgColor.components?[1] ?? 0
blue = cgColor.components?[2] ?? 0
} else {
(red, green, blue) = (0, 0, 0)
}
let r = Int((red * 255.0).rounded())
let g = Int((green * 255.0).rounded())
let b = Int((blue * 255.0).rounded())
return "rgba(\(r), \(g), \(b), \(String(format: "%.6f", alpha)))"
}
}
// MARK: - String
private extension String {
var htmlEscaped: String {
guard self.contains(where: { Character.mapping[$0] != nil }) else { return self }
return self.reduce("") { $0 + $1.escaped }
}
func stringByAppendingAttributeValue(_ value: String?) -> String {
guard let value = value, value.isEmpty == false else { return self }
if self.isEmpty {
return value
} else {
return self + " " + value
}
}
}
private extension Character {
static let mapping: [Character: String] = [
"&": "&",
"\"": """,
"'": "'",
"<": "<",
">": ">",
"\n": "<br />"
]
var escaped: String {
return Character.mapping[self] ?? String(self)
}
}
| mit | 035a9be6bc4466a3aa79b44c82e8f835 | 37.520958 | 146 | 0.539173 | 5.215241 | false | false | false | false |
nielstj/GLChat | GLChatPlayground.playground/Pages/Styleable.xcplaygroundpage/Contents.swift | 1 | 1008 | //: [Previous](@previous)
import UIKit
import GLChat
import PlaygroundSupport
struct BaseStyles {
static func roundCornerStyle(_ view: UIView) {
view.layer.cornerRadius = 12.0
view.layer.masksToBounds = true
}
static func blueBackground(_ view: UIView) {
view.backgroundColor = UIColor.blue
}
static func normalTextFont(_ label: UILabel) {
label.font = UIFont.systemFont(ofSize: 12.0)
}
static func multipleLineLabel(_ label: UILabel) {
label.numberOfLines = 0
}
static func whiteTextLabel(_ label: UILabel) {
label.textColor = UIColor.white
}
}
let rect = CGRect(x: 0, y: 0, width: 100, height: 100)
let label = BubbleLabel(frame: rect)
label.text = "Lorem Ipsum dorem"
label.apply(styles: [BaseStyles.blueBackground,
BaseStyles.roundCornerStyle,
BaseStyles.multipleLineLabel,
BaseStyles.whiteTextLabel])
PlaygroundPage.current.liveView = label
//: [Next](@next)
| mit | dca963ae1f482d55d149cdcfae2ba305 | 22.44186 | 54 | 0.657738 | 4.097561 | false | false | false | false |
mleiv/PhoneNumberFormatter | PhoneNumberFormatter/PhoneNumberFormatter/ViewController.swift | 1 | 1895 | //
// ViewController.swift
// PhoneNumberFormatter
//
// Created by Emily Ivie on 7/20/15.
// Copyright (c) 2015 Emily Ivie. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var phone1: UITextField!
@IBOutlet weak var phone2: UITextField!
@IBOutlet weak var validationResponse: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
formatField(phone1)
formatField(phone2)
}
var phoneFormatter = PhoneNumberFormatter() // (reset when loading different data into fields, with .reset() or new struct)
/**
Wired up to be called every time the field is edited.
*/
@IBAction func formatField(_ sender: UITextField) {
if let text = sender.text {
if sender == phone1 {
sender.text = phoneFormatter.format(text)
} else {
//multiple phone numbers being validated at once require an additional unique hash parameter so we can keep them straight
sender.text = phoneFormatter.format(text, hash: sender.hash)
}
}
}
@IBAction func checkIsValid(_ sender: AnyObject) {
validationResponse.isHidden = true
var message = String()
if phone1.text?.isEmpty == false {
if let text = phone1.text , !phoneFormatter.isValid(text) {
message += "Phone 1 is invalid.\n"
} else {
message += "Phone 1 is valid.\n"
}
}
if phone2.text?.isEmpty == false {
if let text = phone2.text , !phoneFormatter.isValid(text) {
message += "Phone 2 is invalid.\n"
} else {
message += "Phone 2 is valid.\n"
}
}
validationResponse.text = message
validationResponse.isHidden = false
}
}
| mit | 352d7de034ebc300eb0bfc4e16b9ce10 | 29.564516 | 137 | 0.58153 | 4.610706 | false | false | false | false |
Xibarr/TimeManagerr | TimeManagerr.swift | 1 | 4311 | //
// TimeManager.swift
//
//
// Created by Xibarr on 26/01/16.
// Copyright © 2016 Xibarr. All rights reserved.
//
// 1 - The TimeManager is used determine the period of the day on a device (Morning, Lunch, Afternoon, etc).
//
// 2 - You can also use to return the value .Dark at night and .Bright during day time. It can be used to adapt your app theme.
//
// 3 - Use currentTime() to return the current Time as a Tuple ex: for 19:29:05 (19, 29, 5)
import Foundation
class TimeManagerr {
// Singletons are cool
static let sharedInstance = TimeManagerr()
// MARK: - Properties
// Modify this tuple to adapt when to return .Dark or .Bright
// Return Bright between Sunrise and Sunset (e.g: from 8:00 to 18:59)
private var sun = (sunrise: 8, sunset: 19)
private var date: NSDate // current date
private var calendar: NSCalendar // user calendar
private var formatter: NSDateFormatter
var currentPeriod: timePeriod { return self.getCurrentPeriod() }
var currentDarkness: darkOrBright { return self.getCurrentDarkness() }
private init() {
date = NSDate()
calendar = NSCalendar.currentCalendar()
formatter = NSDateFormatter()
}
// MARK: - Public Enums
// Time periods of the day
enum timePeriod {
case Morning
case Lunch
case Afternoon
case Dinner
case Evening
case Night
case Unknown
}
// Dark or Bright?
// Can be used to change your app theme
enum darkOrBright { // Doesn't work well on Northpole
case Dark
case Bright
}
// MARK: - Private Functions
// Refresh the date
private func refresh() {
date = NSDate()
}
// Return the time period of the day
private func getCurrentPeriod() -> timePeriod {
refresh()
let time = currentTime()
switch time.hour {
case 5..<12:
return .Morning
case 12..<14:
return .Lunch
case 14..<19:
return .Afternoon
case 19..<21:
return .Dinner
case 21..<22:
return .Evening
default:
return .Night
}
}
// Return dark or bright
// from 8:00am to 6:59pm returns Bright
private func getCurrentDarkness() -> darkOrBright {
refresh()
let time = currentTime()
switch time.hour {
case sun.sunrise..<sun.sunset:
return .Bright
default:
return .Dark
}
}
// MARK: - Time related functions
// Return current Time as a Tuple ex: for 19:29:05 (19, 29, 5)
func currentTime() -> (hour: Int, minute: Int, second: Int) {
let components = self.calendar.components([.Hour, .Minute, .Second], fromDate: self.date)
let hour = components.hour
let minute = components.minute
let second = components.second
return (hour,minute,second)
}
// Similar function but using a custom Date
func currentTime(fromDate date: NSDate) -> (hour: Int, minute: Int, second: Int) {
let components = self.calendar.components([.Hour, .Minute, .Second], fromDate: date)
let hour = components.hour
let minute = components.minute
let second = components.second
return (hour,minute,second)
}
// MARK: - Extra
// Return current time into string, "10:56 PM" or "22:56"
private func timeToString(show24h: Bool = false) -> String {
formatter.timeStyle = .ShortStyle
let time = self.formatter.stringFromDate(self.date)
formatter.dateFormat = "HH:mm"
let time24h = formatter.stringFromDate(date)
return (show24h ? time24h : time)
}
private func timeToString(fromDate date: NSDate, show24h: Bool = false) -> String {
formatter.timeStyle = .ShortStyle
let time = self.formatter.stringFromDate(date)
formatter.dateFormat = "HH:mm"
let time24h = formatter.stringFromDate(date)
return (show24h ? time24h : time)
}
}
| gpl-3.0 | 10ff190042ef4ba5c143184ab0c57915 | 26.106918 | 127 | 0.576798 | 4.498956 | false | false | false | false |
jopamer/swift | tools/SwiftSyntax/SwiftcInvocation.swift | 2 | 7015 | //===------- SwiftcInvocation.swift - Utilities for invoking swiftc -------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// This file provides the logic for invoking swiftc to parse Swift files.
//===----------------------------------------------------------------------===//
import Foundation
#if os(macOS)
import Darwin
#elseif os(Linux)
import Glibc
#endif
/// The result of process execution, containing the exit status code,
/// stdout, and stderr
struct ProcessResult {
/// The process exit code. A non-zero exit code usually indicates failure.
let exitCode: Int
/// The contents of the process's stdout as Data.
let stdoutData: Data
/// The contents of the process's stderr as Data.
let stderrData: Data
/// The contents of the process's stdout, assuming the data was UTF-8 encoded.
var stdout: String {
return String(data: stdoutData, encoding: .utf8)!
}
/// The contents of the process's stderr, assuming the data was UTF-8 encoded.
var stderr: String {
return String(data: stderrData, encoding: .utf8)!
}
/// Whether or not this process had a non-zero exit code.
var wasSuccessful: Bool {
return exitCode == 0
}
}
/// Runs the provided executable with the provided arguments and returns the
/// contents of stdout and stderr as Data.
/// - Parameters:
/// - executable: The full file URL to the executable you're running.
/// - arguments: A list of strings to pass to the process as arguments.
/// - Returns: A ProcessResult containing stdout, stderr, and the exit code.
func run(_ executable: URL, arguments: [String] = []) -> ProcessResult {
// Use an autoreleasepool to prevent memory- and file-descriptor leaks.
return autoreleasepool {
() -> ProcessResult in
let stdoutPipe = Pipe()
var stdoutData = Data()
stdoutPipe.fileHandleForReading.readabilityHandler = { file in
stdoutData.append(file.availableData)
}
let stderrPipe = Pipe()
var stderrData = Data()
stderrPipe.fileHandleForReading.readabilityHandler = { file in
stderrData.append(file.availableData)
}
let process = Process()
process.terminationHandler = { process in
stdoutPipe.fileHandleForReading.readabilityHandler = nil
stderrPipe.fileHandleForReading.readabilityHandler = nil
}
process.launchPath = executable.path
process.arguments = arguments
process.standardOutput = stdoutPipe
process.standardError = stderrPipe
process.launch()
process.waitUntilExit()
return ProcessResult(exitCode: Int(process.terminationStatus),
stdoutData: stdoutData,
stderrData: stderrData)
}
}
/// Finds the dylib or executable which the provided address falls in.
/// - Parameter dsohandle: A pointer to a symbol in the object file you're
/// looking for. If not provided, defaults to the
/// caller's `#dsohandle`, which will give you the
/// object file the caller resides in.
/// - Returns: A File URL pointing to the object where the provided address
/// resides. This may be a dylib, shared object, static library,
/// or executable. If unable to find the appropriate object, returns
/// `nil`.
func findFirstObjectFile(for dsohandle: UnsafeRawPointer = #dsohandle) -> URL? {
var info = dl_info()
if dladdr(dsohandle, &info) == 0 {
return nil
}
let path = String(cString: info.dli_fname)
return URL(fileURLWithPath: path)
}
enum InvocationError: Error, CustomStringConvertible {
case couldNotFindSwiftc
case couldNotFindSDK
var description: String {
switch self {
case .couldNotFindSwiftc:
return "could not locate swift compiler binary"
case .couldNotFindSDK:
return "could not locate macOS SDK"
}
}
}
struct SwiftcRunner {
/// Gets the `swiftc` binary packaged alongside this library.
/// - Returns: The path to `swiftc` relative to the path of this library
/// file, or `nil` if it could not be found.
/// - Note: This makes assumptions about your Swift installation directory
/// structure. Importantly, it assumes that the directory tree is
/// shaped like this:
/// ```
/// install_root/
/// - bin/
/// - swiftc
/// - lib/
/// - swift/
/// - ${target}/
/// - libswiftSwiftSyntax.[dylib|so]
/// ```
static func locateSwiftc() -> URL? {
guard let libraryPath = findFirstObjectFile() else { return nil }
let swiftcURL = libraryPath.deletingLastPathComponent()
.deletingLastPathComponent()
.deletingLastPathComponent()
.deletingLastPathComponent()
.appendingPathComponent("bin")
.appendingPathComponent("swiftc")
guard FileManager.default.fileExists(atPath: swiftcURL.path) else {
return nil
}
return swiftcURL
}
#if os(macOS)
/// The location of the macOS SDK, or `nil` if it could not be found.
static let macOSSDK: String? = {
let url = URL(fileURLWithPath: "/usr/bin/env")
let result = run(url, arguments: ["xcrun", "--show-sdk-path"])
guard result.wasSuccessful else { return nil }
let toolPath = result.stdout.trimmingCharacters(in: .whitespacesAndNewlines)
if toolPath.isEmpty { return nil }
return toolPath
}()
#endif
/// Internal static cache of the Swiftc path.
static let _swiftcURL: URL? = SwiftcRunner.locateSwiftc()
/// The URL where the `swiftc` binary lies.
let swiftcURL: URL
/// The source file being parsed.
let sourceFile: URL
/// Creates a SwiftcRunner that will parse and emit the syntax
/// tree for a provided source file.
/// - Parameter sourceFile: The URL to the source file you're trying
/// to parse.
init(sourceFile: URL) throws {
guard let url = SwiftcRunner._swiftcURL else {
throw InvocationError.couldNotFindSwiftc
}
self.swiftcURL = url
self.sourceFile = sourceFile
}
/// Invokes swiftc with the provided arguments.
func invoke() throws -> ProcessResult {
var arguments = ["-frontend", "-emit-syntax"]
arguments.append(sourceFile.path)
#if os(macOS)
guard let sdk = SwiftcRunner.macOSSDK else {
throw InvocationError.couldNotFindSDK
}
arguments.append("-sdk")
arguments.append(sdk)
#endif
return run(swiftcURL, arguments: arguments)
}
}
| apache-2.0 | b14aa2ac9d40fb679a619ce095564992 | 33.900498 | 80 | 0.639202 | 4.682911 | false | false | false | false |
huonw/swift | test/Interpreter/synthesized_extension_conformances.swift | 2 | 8924 | // RUN: %empty-directory(%t)
// RUN: %target-build-swift %s -o %t/a.out -module-name main -swift-version 4
// RUN: %target-run %t/a.out
// REQUIRES: executable_test
// REQUIRES: objc_interop
import Foundation
#if FOUNDATION_XCTEST
import XCTest
class TestSuper : XCTestCase { }
#else
import StdlibUnittest
class TestSuper { }
#endif
struct SInt: Codable, Equatable, Hashable {
var x: Int
}
struct SFloat {
var y: Float
}
extension SFloat: Equatable {}
extension SFloat: Hashable {}
extension SFloat: Codable {}
struct SGeneric<T, U> {
var t: T
var u: U
}
extension SGeneric: Equatable where T: Equatable, U: Equatable {}
extension SGeneric: Hashable where T: Hashable, U: Hashable {}
extension SGeneric: Codable where T: Codable, U: Codable {}
enum EGeneric<T> {
case a(T), b(Int), c
}
extension EGeneric: Equatable where T: Equatable {}
extension EGeneric: Hashable where T: Hashable {}
enum NoValues {
case a, b, c
}
extension NoValues: CaseIterable {}
// Cache some values, and make them all have the same width (within a type) for
// formatting niceness.
let SIOne = SInt(x: 1)
let SITwo = SInt(x: 2)
let SFOne = SFloat(y: 1.0)
let SFTwo = SFloat(y: 2.0)
let SFInf = SFloat(y: .infinity)
let SFNan = SFloat(y: .nan)
let SGOneOne = SGeneric(t: SIOne, u: SFOne)
let SGTwoOne = SGeneric(t: SITwo, u: SFOne)
let SGTwoTwo = SGeneric(t: SITwo, u: SFTwo)
let SGOneInf = SGeneric(t: SIOne, u: SFInf)
let SGOneNan = SGeneric(t: SIOne, u: SFNan)
let EGaOne: EGeneric<SInt> = .a(SIOne)
let EGaTwo: EGeneric<SInt> = .a(SITwo)
let EGbOne: EGeneric<SInt> = .b(1)
let EGbTwo: EGeneric<SInt> = .b(2)
let EGc___: EGeneric<SInt> = .c
func debugDescription<T>(_ value: T) -> String {
if let debugDescribable = value as? CustomDebugStringConvertible {
return debugDescribable.debugDescription
} else if let describable = value as? CustomStringConvertible {
return describable.description
} else {
return "\(value)"
}
}
func testEquatableHashable<T: Equatable & Hashable>(cases: [Int: (T, T, Bool, Bool)]) {
for (testLine, (lhs, rhs, equal, hashEqual)) in cases {
expectEqual(lhs == rhs, equal,
"\(#file):\(testLine) LHS <\(debugDescription(lhs))> == RHS <\(debugDescription(rhs))> doesn't match <\(equal)>")
let lhsHash = lhs.hashValue
let rhsHash = rhs.hashValue
expectEqual(lhsHash == rhsHash, hashEqual,
"\(#file):\(testLine) LHS <\(debugDescription(lhs)).hashValue> (\(lhsHash)) == RHS <\(debugDescription(rhs)).hashValue> (\(rhsHash)) doesn't match <\(hashEqual)>")
}
}
class TestEquatableHashable : TestSuper {
lazy var int: [Int: (SInt, SInt, Bool, Bool)] = [
#line : (SIOne, SIOne, true, true),
#line : (SIOne, SITwo, false, false),
#line : (SITwo, SIOne, false, false),
#line : (SITwo, SITwo, true, true),
]
func test_SInt() {
testEquatableHashable(cases: int)
}
lazy var float: [Int: (SFloat, SFloat, Bool, Bool)] = [
#line : (SFOne, SFOne, true, true),
#line : (SFOne, SFTwo, false, false),
#line : (SFTwo, SFOne, false, false),
#line : (SFTwo, SFTwo, true, true),
#line : (SFInf, SFInf, true, true),
#line : (SFInf, SFOne, false, false),
// A bit-based hasher is likely to hash these to the same thing.
#line : (SFNan, SFNan, false, true),
#line : (SFNan, SFOne, false, false),
]
func test_SFloat() {
testEquatableHashable(cases: float)
}
lazy var generic: [Int: (SGeneric<SInt, SFloat>, SGeneric<SInt, SFloat>, Bool, Bool)] = [
#line : (SGOneOne, SGOneOne, true, true),
#line : (SGOneOne, SGTwoOne, false, false),
#line : (SGOneOne, SGTwoTwo, false, false),
#line : (SGTwoOne, SGTwoOne, true, true),
#line : (SGTwoOne, SGTwoTwo, false, false),
#line : (SGTwoTwo, SGTwoTwo, true, true),
#line : (SGOneInf, SGOneInf, true, true),
#line : (SGOneInf, SGOneOne, false, false),
#line : (SGOneInf, SGTwoOne, false, false),
#line : (SGOneInf, SGTwoTwo, false, false),
// As above, a bit-based hasher is likely to hash these to the same thing
#line : (SGOneNan, SGOneNan, false, true),
#line : (SGOneNan, SGOneOne, false, false),
#line : (SGOneNan, SGTwoOne, false, false),
#line : (SGOneNan, SGTwoTwo, false, false),
#line : (SGOneNan, SGOneInf, false, false)
]
func test_SGeneric() {
testEquatableHashable(cases: generic)
}
lazy var egeneric: [Int: (EGeneric<SInt>, EGeneric<SInt>, Bool, Bool)] = [
#line : (EGaOne, EGaOne, true, true),
#line : (EGaOne, EGaTwo, false, false),
#line : (EGaOne, EGbOne, false, false),
#line : (EGaOne, EGbTwo, false, false),
#line : (EGaOne, EGc___, false, false),
#line : (EGbOne, EGaOne, false, false),
#line : (EGbOne, EGaTwo, false, false),
#line : (EGbOne, EGbOne, true, true),
#line : (EGbOne, EGbTwo, false, false),
#line : (EGbOne, EGc___, false, false),
#line : (EGc___, EGaOne, false, false),
#line : (EGc___, EGaTwo, false, false),
#line : (EGc___, EGbOne, false, false),
#line : (EGc___, EGbTwo, false, false),
#line : (EGc___, EGc___, true, true),
]
func test_EGeneric() {
testEquatableHashable(cases: egeneric)
}
}
func expectRoundTripEquality<T : Codable>(of value: T, lineNumber: Int) where T : Equatable {
let inf = "INF", negInf = "-INF", nan = "NaN"
let encoder = JSONEncoder()
encoder.nonConformingFloatEncodingStrategy = .convertToString(positiveInfinity: inf,
negativeInfinity: negInf,
nan: nan)
let data: Data
do {
data = try encoder.encode(value)
} catch {
fatalError("\(#file):\(lineNumber): Unable to encode \(T.self) <\(debugDescription(value))>: \(error)")
}
let decoder = JSONDecoder()
decoder.nonConformingFloatDecodingStrategy = .convertFromString(positiveInfinity: inf,
negativeInfinity: negInf,
nan: nan)
let decoded: T
do {
decoded = try decoder.decode(T.self, from: data)
} catch {
fatalError("\(#file):\(lineNumber): Unable to decode \(T.self) <\(debugDescription(value))>: \(error)")
}
expectEqual(value, decoded, "\(#file):\(lineNumber): Decoded \(T.self) <\(debugDescription(decoded))> not equal to original <\(debugDescription(value))>")
}
class TestCodable : TestSuper {
lazy var int: [Int: SInt] = [
#line : SIOne,
#line : SITwo,
]
func test_SInt() {
for (testLine, value) in int {
expectRoundTripEquality(of: value, lineNumber: testLine)
}
}
lazy var float: [Int : SFloat] = [
#line : SFOne,
#line : SFTwo,
#line : SFInf,
// This won't compare equal to itself
// #line : SFNan
]
func test_SFloat() {
for (testLine, value) in float {
expectRoundTripEquality(of: value, lineNumber: testLine)
}
}
lazy var generic : [Int : SGeneric<SInt, SFloat>] = [
#line : SGOneOne,
#line : SGTwoOne,
#line : SGTwoTwo,
#line : SGOneInf,
// As above, this won't compare equal to itself
// #line : SGOneNan,
]
func test_SGeneric() {
for (testLine, value) in generic {
expectRoundTripEquality(of: value, lineNumber: testLine)
}
}
}
class TestCaseIterable : TestSuper {
func test_allCases() {
expectEqual(NoValues.allCases, [.a, .b, .c])
}
}
#if !FOUNDATION_XCTEST
var equatableHashable = [
"TestEquatableHashable.test_SInt": TestEquatableHashable.test_SInt,
"TestEquatableHashable.test_SFloat": TestEquatableHashable.test_SFloat,
"TestEquatableHashable.test_SGeneric": TestEquatableHashable.test_SGeneric,
"TestEquatableHashable.test_EGeneric": TestEquatableHashable.test_EGeneric,
]
var EquatableHashableTests = TestSuite("TestEquatableHashable")
for (name, test) in equatableHashable {
EquatableHashableTests.test(name) { test(TestEquatableHashable())() }
}
var codable = [
"TestCodable.test_SInt": TestCodable.test_SInt,
"TestCodable.test_SFloat": TestCodable.test_SFloat,
"TestCodable.test_SGeneric": TestCodable.test_SGeneric,
]
var CodableTests = TestSuite("TestCodable")
for (name, test) in codable {
CodableTests.test(name) { test(TestCodable())() }
}
var caseIterable = [
"TestCaseIterable.test_allCases": TestCaseIterable.test_allCases,
]
var CaseIterableTests = TestSuite("TestCaseIterable")
for (name, test) in caseIterable {
CaseIterableTests.test(name) { test(TestCaseIterable())() }
}
runAllTests()
#endif
| apache-2.0 | ce319b982ce2020eeff4ff6922e6d61c | 30.985663 | 183 | 0.613962 | 3.469673 | false | true | false | false |
faimin/ZDOpenSourceDemo | ZDOpenSourceSwiftDemo/Pods/Hero/Sources/Parser/Nodes.swift | 10 | 2281 | //
// Nodes.swift
// Kaleidoscope
//
// Created by Matthew Cheok on 15/11/15.
// Copyright © 2015 Matthew Cheok. All rights reserved.
//
import Foundation
public class ExprNode: CustomStringConvertible, Equatable {
public var range: CountableRange<Int> = 0..<0
public let name: String
public var description: String {
return "ExprNode(name: \"\(name)\")"
}
public init(name: String) {
self.name = name
}
}
public func == (lhs: ExprNode, rhs: ExprNode) -> Bool {
return lhs.description == rhs.description
}
public class NumberNode: ExprNode {
public let value: Float
public override var description: String {
return "NumberNode(value: \(value))"
}
public init(value: Float) {
self.value = value
super.init(name: "\(value)")
}
}
public class VariableNode: ExprNode {
public override var description: String {
return "VariableNode(name: \"\(name)\")"
}
}
public class BinaryOpNode: ExprNode {
public let lhs: ExprNode
public let rhs: ExprNode
public override var description: String {
return "BinaryOpNode(name: \"\(name)\", lhs: \(lhs), rhs: \(rhs))"
}
public init(name: String, lhs: ExprNode, rhs: ExprNode) {
self.lhs = lhs
self.rhs = rhs
super.init(name: "\(name)")
}
}
public class CallNode: ExprNode {
public let arguments: [ExprNode]
public override var description: String {
return "CallNode(name: \"\(name)\", arguments: \(arguments))"
}
public init(name: String, arguments: [ExprNode]) {
self.arguments = arguments
super.init(name: "\(name)")
}
}
public class PrototypeNode: ExprNode {
public let argumentNames: [String]
public override var description: String {
return "PrototypeNode(name: \"\(name)\", argumentNames: \(argumentNames))"
}
public init(name: String, argumentNames: [String]) {
self.argumentNames = argumentNames
super.init(name: "\(name)")
}
}
public class FunctionNode: ExprNode {
public let prototype: PrototypeNode
public let body: ExprNode
public override var description: String {
return "FunctionNode(prototype: \(prototype), body: \(body))"
}
public init(prototype: PrototypeNode, body: ExprNode) {
self.prototype = prototype
self.body = body
super.init(name: "\(prototype.name)")
}
}
| mit | 055bc6e93851581e0dd68f303d200c7d | 24.617978 | 78 | 0.673684 | 3.787375 | false | false | false | false |
zhenghuadong11/firstGitHub | 旅游app_useSwift/旅游app_useSwift/MYSetUpViewController.swift | 1 | 1988 | //
// MYSetUpViewController.swift
// 旅游app_useSwift
//
// Created by zhenghuadong on 16/4/17.
// Copyright © 2016年 zhenghuadong. All rights reserved.
//
import Foundation
import UIKit
class MYSetUpViewController: UIViewController,UITableViewDelegate,UITableViewDataSource{
var _tableView = UITableView()
override func viewDidLoad() {
let titleLabel = UILabel()
titleLabel.text = "设置"
titleLabel.frame = CGRectMake(0, 0, 100, 30)
titleLabel.textAlignment = NSTextAlignment.Center
titleLabel.textColor = UIColor.init(red: CGFloat(3*16+3)/256, green: CGFloat(3*16+3)/256, blue: CGFloat(3*16+3)/256, alpha: 1.0)
self.navigationItem.titleView = titleLabel
_tableView.frame = self.view.bounds
_tableView.bounces = false
_tableView.delegate = self
_tableView.dataSource = self
self.view.addSubview(_tableView)
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 2
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell:UITableViewCell?
if indexPath.row == 0
{ var setUpcell = MYSetUpTableViewCell.setUpTableViewWithTableView(tableView)
setUpcell.textLabel?.text = "背景音乐"
cell = setUpcell
}
else if indexPath .row == 1
{
var setUpLoginCell = MYSetUpLoginTableViewCell.setUpLoginTableViewCellWithTableView(tableView)
// = NSBundle.mainBundle().loadNibNamed("MYSetUpLoginTableViewCell", owner: self, options: nil).first as! MYSetUpLoginTableViewCell
cell = setUpLoginCell
}
print(cell)
return cell!
}
// func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
// return 1000
// }
} | apache-2.0 | 0b701fecd95034b309ff3a933d3b01f6 | 32.389831 | 142 | 0.647029 | 4.654846 | false | false | false | false |
brightec/CustomCollectionViewLayout | CustomCollectionLayout/CustomCollectionViewLayout.swift | 1 | 5373 | //
// CustomCollectionViewLayout.swift
// CustomCollectionLayout
//
// Created by JOSE MARTINEZ on 15/12/2014.
// Copyright (c) 2014 brightec. All rights reserved.
//
import UIKit
class CustomCollectionViewLayout: UICollectionViewLayout {
let numberOfColumns = 8
var shouldPinFirstColumn = true
var shouldPinFirstRow = true
var itemAttributes = [[UICollectionViewLayoutAttributes]]()
var itemsSize = [CGSize]()
var contentSize: CGSize = .zero
override func prepare() {
guard let collectionView = collectionView else {
return
}
if collectionView.numberOfSections == 0 {
return
}
if itemAttributes.count != collectionView.numberOfSections {
generateItemAttributes(collectionView: collectionView)
return
}
for section in 0..<collectionView.numberOfSections {
for item in 0..<collectionView.numberOfItems(inSection: section) {
if section != 0 && item != 0 {
continue
}
let attributes = layoutAttributesForItem(at: IndexPath(item: item, section: section))!
if section == 0 {
var frame = attributes.frame
frame.origin.y = collectionView.contentOffset.y
attributes.frame = frame
}
if item == 0 {
var frame = attributes.frame
frame.origin.x = collectionView.contentOffset.x
attributes.frame = frame
}
}
}
}
override var collectionViewContentSize: CGSize {
return contentSize
}
override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
return itemAttributes[indexPath.section][indexPath.row]
}
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
var attributes = [UICollectionViewLayoutAttributes]()
for section in itemAttributes {
let filteredArray = section.filter { obj -> Bool in
return rect.intersects(obj.frame)
}
attributes.append(contentsOf: filteredArray)
}
return attributes
}
override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool {
return true
}
}
// MARK: - Helpers
extension CustomCollectionViewLayout {
func generateItemAttributes(collectionView: UICollectionView) {
if itemsSize.count != numberOfColumns {
calculateItemSizes()
}
var column = 0
var xOffset: CGFloat = 0
var yOffset: CGFloat = 0
var contentWidth: CGFloat = 0
itemAttributes = []
for section in 0..<collectionView.numberOfSections {
var sectionAttributes: [UICollectionViewLayoutAttributes] = []
for index in 0..<numberOfColumns {
let itemSize = itemsSize[index]
let indexPath = IndexPath(item: index, section: section)
let attributes = UICollectionViewLayoutAttributes(forCellWith: indexPath)
attributes.frame = CGRect(x: xOffset, y: yOffset, width: itemSize.width, height: itemSize.height).integral
if section == 0 && index == 0 {
// First cell should be on top
attributes.zIndex = 1024
} else if section == 0 || index == 0 {
// First row/column should be above other cells
attributes.zIndex = 1023
}
if section == 0 {
var frame = attributes.frame
frame.origin.y = collectionView.contentOffset.y
attributes.frame = frame
}
if index == 0 {
var frame = attributes.frame
frame.origin.x = collectionView.contentOffset.x
attributes.frame = frame
}
sectionAttributes.append(attributes)
xOffset += itemSize.width
column += 1
if column == numberOfColumns {
if xOffset > contentWidth {
contentWidth = xOffset
}
column = 0
xOffset = 0
yOffset += itemSize.height
}
}
itemAttributes.append(sectionAttributes)
}
if let attributes = itemAttributes.last?.last {
contentSize = CGSize(width: contentWidth, height: attributes.frame.maxY)
}
}
func calculateItemSizes() {
itemsSize = []
for index in 0..<numberOfColumns {
itemsSize.append(sizeForItemWithColumnIndex(index))
}
}
func sizeForItemWithColumnIndex(_ columnIndex: Int) -> CGSize {
var text: NSString
switch columnIndex {
case 0:
text = "MMM-99"
default:
text = "Content"
}
let size: CGSize = text.size(attributes: [NSFontAttributeName: UIFont.systemFont(ofSize: 14.0)])
let width: CGFloat = size.width + 16
return CGSize(width: width, height: 30)
}
}
| mit | e8ff6c6f468549ed77ca403a68448139 | 29.528409 | 122 | 0.559836 | 5.752677 | false | false | false | false |
carabina/DDMathParser | MathParser/Evaluator.swift | 2 | 3026 | //
// Evaluator.swift
// DDMathParser
//
// Created by Dave DeLong on 8/20/15.
//
//
import Foundation
public enum EvaluationError: ErrorType {
case UnknownFunction(String)
case UnknownVariable(String)
case DivideByZero
case InvalidArguments
}
public enum FunctionRegistrationError: ErrorType {
case FunctionAlreadyExists(String)
case FunctionDoesNotExist(String)
}
public struct Evaluator {
public enum AngleMode {
case Radians
case Degrees
}
public static let defaultEvaluator = Evaluator()
private let functionSet: FunctionSet
public var angleMeasurementMode = AngleMode.Radians
public var functionOverrider: FunctionOverrider?
public var functionResolver: FunctionResolver?
public var variableResolver: VariableResolver?
public init(caseSensitive: Bool = false) {
functionSet = FunctionSet(caseSensitive: caseSensitive)
}
public func evaluate(expression: Expression, substitutions: Substitutions = [:]) throws -> Double {
switch expression.kind {
case .Number(let d):
return d
case .Variable(let s):
return try evaluateVariable(s, substitutions: substitutions)
case .Function(let f, let args):
return try evaluateFunction(f, arguments: args, substitutions: substitutions)
}
}
public func registerFunction(function: Function) throws {
try functionSet.registerFunction(function)
}
public func registerAlias(alias: String, forFunctionName name: String) throws {
try functionSet.addAlias(alias, forFunctionName: name)
}
private func evaluateVariable(name: String, substitutions: Substitutions) throws -> Double {
if let value = substitutions[name] { return value }
// substitutions were insufficient
// use the variable resolver
if let resolved = variableResolver?.resolveVariable(name) {
return resolved
}
throw EvaluationError.UnknownVariable(name)
}
private func evaluateFunction(name: String, arguments: Array<Expression>, substitutions: Substitutions) throws -> Double {
// check for function overrides
if let value = try functionOverrider?.overrideFunction(name, arguments: arguments, substitutions: substitutions, evaluator: self) {
return value
}
if let function = functionSet.evaluatorForName(name) {
return try function(arguments, substitutions, self)
}
// a function with this name does not exist
// use the function resolver
let normalized = functionSet.normalize(name)
if let value = try functionResolver?.resolveFunction(normalized, arguments: arguments, substitutions: substitutions, evaluator: self) {
return value
}
throw EvaluationError.UnknownFunction(normalized)
}
}
| mit | 440f2f86a6a940acb12144bc6eedbe36 | 31.191489 | 143 | 0.660939 | 5.280977 | false | false | false | false |
rhcad/ShapeAnimation-Swift | ShapeAnimation/Animation/AnimationPrivate.swift | 3 | 3332 | //
// AnimationPrivate.swift
// ShapeAnimation
//
// Created by Zhang Yungui on 15/1/20.
// Copyright (c) 2015 github.com/rhcad. All rights reserved.
//
import SwiftGraphics
private var stopping = 0
internal class AnimationDelagate : NSObject {
internal var didStart:((CAAnimation!) -> Void)?
internal var didStop :(() -> Void)?
internal var willStop :(() -> Void)?
internal var finished = true
override internal func animationDidStart(anim:CAAnimation) {
didStart?(anim)
didStart = nil
}
override internal func animationDidStop(anim:CAAnimation, finished:Bool) {
self.finished = finished
if finished {
willStop?()
didStop?()
} else {
stopping++
willStop?()
didStop?()
stopping--
}
willStop = nil
didStop = nil
}
internal class func groupDidStop(completion:() -> Void, finished:Bool) {
if finished {
completion()
} else {
stopping++
completion()
stopping--
}
}
}
public extension CAAnimation {
public var didStart:((CAAnimation!) -> Void)? {
get {
let delegate = self.delegate as? AnimationDelagate
return delegate?.didStart
}
set {
if let delegate = self.delegate as? AnimationDelagate {
delegate.didStart = newValue
}
else if newValue != nil {
let delegate = AnimationDelagate()
delegate.didStart = newValue
self.delegate = delegate
}
}
}
public var didStop:(() -> Void)? {
get {
let delegate = self.delegate as? AnimationDelagate
return delegate?.didStop
}
set {
if let delegate = self.delegate as? AnimationDelagate {
delegate.didStop = newValue
}
else if newValue != nil {
let delegate = AnimationDelagate()
delegate.didStop = newValue
self.delegate = delegate
}
}
}
public var willStop:(() -> Void)? {
get {
let delegate = self.delegate as? AnimationDelagate
return delegate?.willStop
}
set {
if let delegate = self.delegate as? AnimationDelagate {
delegate.willStop = newValue
}
else if newValue != nil {
let delegate = AnimationDelagate()
delegate.willStop = newValue
self.delegate = delegate
}
}
}
internal var finished:Bool {
get {
if let delegate = self.delegate as? AnimationDelagate {
return delegate.finished
}
return true
}
set {
if let delegate = self.delegate as? AnimationDelagate {
delegate.finished = newValue
}
else {
let delegate = AnimationDelagate()
delegate.finished = finished
self.delegate = delegate
}
}
}
internal class var isStopping:Bool { return stopping > 0 }
}
| bsd-2-clause | c67089964cbc2f799cf5d2ffa4874f99 | 25.870968 | 78 | 0.510204 | 5.480263 | false | false | false | false |
kronik/ScalePicker | ScalePicker/ScalePicker.swift | 2 | 18420 | //
// ScalePicker.swift
// Dmitry Klimkin
//
// Created by Dmitry Klimkin on 12/11/15.
// Copyright © 2016 Dmitry Klimkin. All rights reserved.
//
import Foundation
import UIKit
public typealias ValueFormatter = (CGFloat) -> NSAttributedString
public typealias ValueChangeHandler = (CGFloat) -> Void
public enum ScalePickerValuePosition {
case Top
case Left
}
public protocol ScalePickerDelegate {
func didChangeScaleValue(picker: ScalePicker, value: CGFloat)
func didBeginChangingValue(picker: ScalePicker)
func didEndChangingValue(picker: ScalePicker)
}
@IBDesignable
public class ScalePicker: UIView, SlidePickerDelegate {
public var delegate: ScalePickerDelegate?
public var valueChangeHandler: ValueChangeHandler = {(value: CGFloat) in
}
public var valuePosition = ScalePickerValuePosition.Top {
didSet {
layoutSubviews()
}
}
@IBInspectable
public var title: String = "" {
didSet {
titleLabel.text = title
}
}
@IBInspectable
public var gradientMaskEnabled: Bool = false {
didSet {
picker.gradientMaskEnabled = gradientMaskEnabled
}
}
@IBInspectable
public var invertValues: Bool = false {
didSet {
picker.invertValues = invertValues
}
}
@IBInspectable
public var trackProgress: Bool = false {
didSet {
progressView.alpha = trackProgress ? 1.0 : 0.0
}
}
@IBInspectable
public var invertProgress: Bool = false {
didSet {
layoutProgressView(currentProgress)
}
}
@IBInspectable
public var fillSides: Bool = false {
didSet {
picker.fillSides = fillSides
}
}
@IBInspectable
public var elasticCurrentValue: Bool = false
@IBInspectable
public var highlightCenterTick: Bool = true {
didSet {
picker.highlightCenterTick = highlightCenterTick
}
}
@IBInspectable
public var allTicksWithSameSize: Bool = false {
didSet {
picker.allTicksWithSameSize = allTicksWithSameSize
}
}
@IBInspectable
public var showCurrentValue: Bool = false {
didSet {
valueLabel.alpha = showCurrentValue ? 1.0 : 0.0
showTickLabels = !showTickLabels
showTickLabels = !showTickLabels
}
}
@IBInspectable
public var blockedUI: Bool = false {
didSet {
picker.blockedUI = blockedUI
}
}
@IBInspectable
public var numberOfTicksBetweenValues: UInt = 4 {
didSet {
picker.numberOfTicksBetweenValues = numberOfTicksBetweenValues
reset()
}
}
@IBInspectable
public var minValue: CGFloat = -3.0 {
didSet {
picker.minValue = minValue
reset()
}
}
@IBInspectable
public var maxValue: CGFloat = 3.0 {
didSet {
picker.maxValue = maxValue
reset()
}
}
@IBInspectable
public var spaceBetweenTicks: CGFloat = 10.0 {
didSet {
picker.spaceBetweenTicks = spaceBetweenTicks
reset()
}
}
@IBInspectable
public var centerViewWithLabelsYOffset: CGFloat = 15.0 {
didSet {
updateCenterViewOffset()
}
}
@IBInspectable
public var centerViewWithoutLabelsYOffset: CGFloat = 15.0 {
didSet {
updateCenterViewOffset()
}
}
@IBInspectable
public var pickerOffset: CGFloat = 0.0 {
didSet {
layoutSubviews()
}
}
@IBInspectable
public var tickColor: UIColor = UIColor.whiteColor() {
didSet {
picker.tickColor = tickColor
centerImageView.image = centerArrowImage?.tintImage(tickColor)
titleLabel.textColor = tickColor
}
}
@IBInspectable
public var progressColor: UIColor = UIColor.whiteColor() {
didSet {
progressView.backgroundColor = progressColor
}
}
@IBInspectable
public var progressViewSize: CGFloat = 3.0 {
didSet {
progressView.frame = CGRectMake(0, 0, progressViewSize, progressViewSize)
progressView.layer.cornerRadius = progressViewSize / 2
layoutProgressView(currentProgress)
}
}
@IBInspectable
public var centerArrowImage: UIImage? {
didSet {
centerImageView.image = centerArrowImage
reset()
}
}
@IBInspectable
public var showTickLabels: Bool = true {
didSet {
picker.showTickLabels = showTickLabels
updateCenterViewOffset()
layoutSubviews()
}
}
@IBInspectable
public var snapEnabled: Bool = false {
didSet {
picker.snapEnabled = snapEnabled
}
}
@IBInspectable
public var showPlusForPositiveValues: Bool = true {
didSet {
picker.showPlusForPositiveValues = showPlusForPositiveValues
}
}
@IBInspectable
public var fireValuesOnScrollEnabled: Bool = true {
didSet {
picker.fireValuesOnScrollEnabled = fireValuesOnScrollEnabled
}
}
@IBInspectable
public var bounces: Bool = false {
didSet {
picker.bounces = bounces
}
}
@IBInspectable
public var sidePadding: CGFloat = 0.0 {
didSet {
layoutSubviews()
}
}
public var currentTransform: CGAffineTransform = CGAffineTransformIdentity {
didSet {
applyCurrentTransform()
}
}
public func applyCurrentTransform() {
picker.currentTransform = currentTransform
if valuePosition == .Left {
valueLabel.transform = currentTransform
}
}
public var values: [CGFloat]? {
didSet {
guard let values = values where values.count > 1 else { return; }
picker.values = values
maxValue = values[values.count - 1]
minValue = values[0]
initialValue = values[0]
}
}
public var valueFormatter: ValueFormatter = {(value: CGFloat) -> NSAttributedString in
let attrs = [NSForegroundColorAttributeName: UIColor.whiteColor(),
NSFontAttributeName: UIFont.systemFontOfSize(15.0)]
return NSMutableAttributedString(string: value.format(".2"), attributes: attrs)
}
public var rightView: UIView? {
willSet(newRightView) {
if let view = rightView {
view.removeFromSuperview()
}
}
didSet {
if let view = rightView {
addSubview(view)
}
layoutSubviews()
}
}
public var leftView: UIView? {
willSet(newLeftView) {
if let view = leftView {
view.removeFromSuperview()
}
}
didSet {
if let view = leftView {
addSubview(view)
}
layoutSubviews()
}
}
private let centerImageView = UIImageView(frame: CGRectMake(0, 0, 10, 10))
private let centerView = UIView(frame: CGRectMake(0, 0, 10, 10))
private let titleLabel = UILabel()
private let valueLabel = UILabel()
private var currentProgress: CGFloat = 0.5
private var progressView = UIView()
private var initialValue: CGFloat = 0.0
private var picker: SlidePicker!
private var shouldUpdatePicker: Bool = true
private var notifyOnChanges: Bool = true
private var timer: NSTimer?
public var currentValue: CGFloat = 0.0 {
didSet {
if shouldUpdatePicker {
picker.scrollToValue(currentValue, animated: true)
}
valueLabel.attributedText = valueFormatter(currentValue)
layoutValueLabel()
updateProgressAsync()
}
}
public func updateCurrentValue(value: CGFloat, animated: Bool, notify: Bool = false) {
shouldUpdatePicker = false
notifyOnChanges = false
picker.scrollToValue(value, animated: animated, reload: false, complete: { [unowned self] in
self.currentValue = value
if notify {
self.delegate?.didChangeScaleValue(self, value: value)
self.valueChangeHandler(value)
}
self.scheduleTimer()
})
}
private func scheduleTimer() {
timer?.invalidate()
timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: #selector(ScalePicker.onTimer), userInfo: nil, repeats: false)
}
internal func onTimer() {
self.shouldUpdatePicker = true
self.notifyOnChanges = true
}
private func updateProgressAsync() {
let popTime = dispatch_time(DISPATCH_TIME_NOW, Int64(1.0 * CGFloat(NSEC_PER_SEC)))
dispatch_after(popTime, dispatch_get_main_queue()) {
self.picker.updateCurrentProgress()
if self.trackProgress {
UIView.animateWithDuration(0.3, delay: 0.0, usingSpringWithDamping: 1.0, initialSpringVelocity: 0.0, options: .CurveEaseInOut, animations: { () -> Void in
self.progressView.alpha = 1.0
}, completion: nil)
}
}
}
public override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
public func commonInit() {
userInteractionEnabled = true
titleLabel.textColor = tickColor
titleLabel.textAlignment = .Center
titleLabel.font = UIFont.systemFontOfSize(13.0)
addSubview(titleLabel)
valueLabel.textColor = tickColor
valueLabel.textAlignment = .Center
valueLabel.font = UIFont.systemFontOfSize(13.0)
addSubview(valueLabel)
centerImageView.contentMode = .Center
centerImageView.center = CGPointMake(centerView.frame.size.width / 2, centerView.frame.size.height / 2 + 5)
centerView.addSubview(centerImageView)
picker = SlidePicker(frame: CGRectMake(sidePadding, 0, frame.size.width - sidePadding * 2, frame.size.height))
picker.numberOfTicksBetweenValues = numberOfTicksBetweenValues
picker.minValue = minValue
picker.maxValue = maxValue
picker.delegate = self
picker.snapEnabled = snapEnabled
picker.showTickLabels = showTickLabels
picker.highlightCenterTick = highlightCenterTick
picker.bounces = bounces
picker.tickColor = tickColor
picker.centerView = centerView
picker.spaceBetweenTicks = spaceBetweenTicks
updateCenterViewOffset()
addSubview(picker)
progressView.frame = CGRectMake(0, 0, progressViewSize, progressViewSize)
progressView.backgroundColor = UIColor.whiteColor()
progressView.alpha = 0.0
progressView.layer.masksToBounds = true
progressView.layer.cornerRadius = progressViewSize / 2
addSubview(progressView)
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(ScalePicker.onDoubleTap(_:)))
tapGesture.numberOfTapsRequired = 2
addGestureRecognizer(tapGesture)
}
public override func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
layoutSubviews()
reset()
}
public override func layoutSubviews() {
super.layoutSubviews()
picker.frame = CGRectMake(sidePadding, pickerOffset,
frame.size.width - sidePadding * 2, frame.size.height)
picker.layoutSubviews()
let xOffset = gradientMaskEnabled ? picker.frame.size.width * 0.05 : 0.0
if let view = rightView {
view.center = CGPointMake(frame.size.width - xOffset - sidePadding / 2, picker.center.y + 5)
}
if let view = leftView {
if valuePosition == .Left {
view.center = CGPointMake(xOffset + sidePadding / 2, ((frame.size.height / 2) + view.frame.height / 4))
} else {
view.center = CGPointMake(xOffset + sidePadding / 2, picker.center.y + 5)
}
}
titleLabel.frame = CGRectMake(xOffset, 5, sidePadding, frame.size.height)
if valuePosition == .Top {
valueLabel.frame = CGRectMake(sidePadding, 5,
frame.width - sidePadding * 2, frame.size.height / 4.0)
} else {
layoutValueLabel()
}
}
public func onDoubleTap(recognizer: UITapGestureRecognizer) {
updateCurrentValue(initialValue, animated: true, notify: true)
}
public func reset(notify: Bool = false) {
updateCurrentValue(initialValue, animated: false, notify: notify)
}
public func increaseValue() {
picker.increaseValue()
}
public func decreaseValue() {
picker.decreaseValue()
}
public func setInitialCurrentValue(value: CGFloat) {
shouldUpdatePicker = false
currentValue = value
initialValue = value
picker.scrollToValue(value, animated: false)
shouldUpdatePicker = true
progressView.alpha = 0.0
}
public func didSelectValue(value: CGFloat) {
shouldUpdatePicker = false
if notifyOnChanges && (value != currentValue) {
currentValue = value
delegate?.didChangeScaleValue(self, value: value)
valueChangeHandler(value)
}
shouldUpdatePicker = true
}
public func didBeginChangingValue() {
delegate?.didBeginChangingValue(self)
}
public func didEndChangingValue() {
delegate?.didEndChangingValue(self)
}
public func didChangeContentOffset(offset: CGFloat, progress: CGFloat) {
layoutProgressView(progress)
guard elasticCurrentValue else { return }
let minScale: CGFloat = 0.0
let maxScale: CGFloat = 0.25
let maxOffset: CGFloat = 50.0
var offsetShift: CGFloat = 0.0
var scaleShift: CGFloat = 1.0
var offsetValue = offset
if offset < 0 {
scaleShift = -maxScale
offsetShift = 50.0
offsetValue = offset + offsetShift
}
var value = min(maxScale, max(minScale, offsetValue * (maxScale / maxOffset)))
value += scaleShift
if offset < 0 {
if value < 0 {
if invertValues {
value = fabs(value) + 1
} else {
value += 1
}
}
} else {
if invertValues {
value = 1 - (value - scaleShift)
}
}
valueLabel.transform = CGAffineTransformScale(currentTransform, value, value)
}
private func updateCenterViewOffset() {
picker.centerViewOffsetY = showTickLabels ? centerViewWithLabelsYOffset : centerViewWithoutLabelsYOffset
}
private func layoutProgressView(progress: CGFloat) {
currentProgress = progress
let updatedProgress = invertProgress ? 1.0 - progress : progress
let xOffset = gradientMaskEnabled ? picker.frame.origin.x + (picker.frame.size.width * 0.1) : picker.frame.origin.x
let progressWidth = gradientMaskEnabled ? picker.frame.size.width * 0.8 : picker.frame.size.width
let scaledValue = progressWidth * updatedProgress
var yOffset = pickerOffset + 4 + frame.size.height / 3
if title.isEmpty && valuePosition == .Left {
yOffset -= 6
}
progressView.center = CGPointMake(xOffset + scaledValue, yOffset)
}
private func layoutValueLabel() {
let text = valueLabel.attributedText
guard let textValue = text else { return }
let textWidth = valueWidth(textValue)
var signOffset: CGFloat = 0
if textValue.string.containsString("+") || textValue.string.containsString("-") {
signOffset = 2
}
let xOffset = gradientMaskEnabled ? picker.frame.size.width * 0.05 : 0.0
if valuePosition == .Left {
if let view = leftView {
valueLabel.frame = CGRectMake(view.center.x - signOffset - textWidth / 2, (frame.size.height / 2) - 20, textWidth, 16)
} else {
valueLabel.frame = CGRectMake(sidePadding, 5, textWidth, frame.size.height)
valueLabel.center = CGPointMake(xOffset + sidePadding / 2, frame.size.height / 2 + 5)
}
} else {
valueLabel.frame = CGRectMake(0, 5, textWidth, frame.size.height - 10)
valueLabel.center = CGPointMake(xOffset + sidePadding / 2, frame.size.height / 2 - 5)
}
}
private func valueWidth(text: NSAttributedString) -> CGFloat {
let rect = text.boundingRectWithSize(CGSizeMake(1024, frame.size.width), options: NSStringDrawingOptions.UsesLineFragmentOrigin, context: nil)
return rect.width + 10
}
}
private extension Double {
func format(f: String) -> String {
return String(format: "%\(f)f", self)
}
}
private extension Float {
func format(f: String) -> String {
return String(format: "%\(f)f", self)
}
}
private extension CGFloat {
func format(f: String) -> String {
return String(format: "%\(f)f", self)
}
} | mit | 8065e19132b59a314de851946688e7a3 | 27.646967 | 170 | 0.578262 | 5.217847 | false | false | false | false |
konduruvijaykumar/ios-sample-apps | CoreLocationDemoApp/CoreLocationDemoApp/ViewController.swift | 1 | 5391 | //
// ViewController.swift
// CoreLocationDemoApp
//
// Created by Vijay Konduru on 06/02/17.
// Copyright © 2017 PJay. All rights reserved.
//
// https://www.youtube.com/watch?v=kkVI3njOlqU
// http://www.appcoda.com/how-to-get-current-location-iphone-user/
// http://stackoverflow.com/questions/24062509/location-services-not-working-in-ios-8
// http://nevan.net/2014/09/core-location-manager-changes-in-ios-8/
import UIKit
import CoreLocation
class ViewController: UIViewController, CLLocationManagerDelegate {
let locationManager = CLLocationManager();
@IBOutlet weak var longitudeLabel: UILabel!
@IBOutlet weak var latitudeLabel: UILabel!
@IBOutlet weak var addressText: UITextView!
var addressDetails: String = "";
var latitudeData: Double = 0.0;
var longitudeData: Double = 0.0;
var didWeReceiveUpdate: Bool = false;
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.locationManager.delegate = self;
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
// Not necessary for this app
//self.locationManager.requestAlwaysAuthorization();
self.locationManager.requestWhenInUseAuthorization();
// Start on click on button to get information
//self.locationManager.startUpdatingLocation();
}
@IBAction func getMyLocation(_ sender: Any) {
self.locationManager.startUpdatingLocation();
// reset data on click of get my location again or at start
self.addressDetails = "";
self.latitudeData = 0.0;
self.longitudeData = 0.0;
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// location manager delegate methods
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
//print("\(manager.location?.coordinate.latitude)");
//print("\(manager.location?.coordinate.longitude)");
// We can try this to solve multiple values of location data coming -- Not sure give it a try
//locations.first;
CLGeocoder().reverseGeocodeLocation(manager.location!, completionHandler: {
(placemarks, error) -> Void in
if(error != nil){
print("Error: \(error)");
return;
}
// Looks like this method is called so many times before it stops updating, this is causing a lot of problem. Let put some hack to avoid so many calls
if(placemarks != nil && (placemarks!.count) > 0 && !self.didWeReceiveUpdate){
let pm = placemarks![0];
self.didWeReceiveUpdate = true;
self.displayLocationInfo(placemark: pm);
return;
}
})
}
func displayLocationInfo(placemark: CLPlacemark){
self.locationManager.stopUpdatingLocation();
if(self.locationManager.location != nil){
// Note: The below hack of checking with 0.0 and "" for lat, long and address is not required. As we solved the problem using didWeReceiveUpdate variable.
//if(latitudeData == 0.0){
//print(self.locationManager.location!.coordinate.latitude);
latitudeData = self.locationManager.location!.coordinate.latitude;
self.latitudeLabel.text = "\(latitudeData)";
//}
//if(longitudeData == 0.0){
//print(self.locationManager.location!.coordinate.longitude);
longitudeData = self.locationManager.location!.coordinate.longitude;
self.longitudeLabel.text = "\(longitudeData)";
//}
}
//if(self.addressDetails == ""){
//print(placemark.name!);
//print(placemark.thoroughfare!); // Avoiding due to some data repeat
//print(placemark.subThoroughfare!); // Not Imp
//print(placemark.locality!);
//print(placemark.administrativeArea!);
//print(placemark.postalCode!);
//print(placemark.country!);
// Note: the address is some times coming as old value, but lat, long values change. Please verify
self.addressDetails = "\(checkNil(anyObj: placemark.name))\n\(checkNil(anyObj: placemark.locality))\n\(checkNil(anyObj: placemark.administrativeArea))\n\(checkNil(anyObj: placemark.postalCode))\n\(checkNil(anyObj: placemark.country))";
//addressDetails += checkNil(anyObj: placemark.name)+"\n";
//addressDetails += checkNil(anyObj: placemark.location)+"\n";
//addressDetails += checkNil(anyObj: placemark.administrativeArea)+"\n";
//addressDetails += checkNil(anyObj: placemark.postalCode)+"\n";
//addressDetails += checkNil(anyObj: placemark.country);
print(addressDetails);
self.addressText.text = self.addressDetails;
//}
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print("Error: " + error.localizedDescription);
}
func checkNil(anyObj: Any?) -> String{
if(anyObj != nil){
return "\(anyObj!)";
}else{
return "";
}
}
}
| apache-2.0 | d9b8f142a1a8b5d6a4544c41a3ab35d9 | 39.526316 | 243 | 0.633766 | 4.765694 | false | false | false | false |
justindhill/Facets | Facets/View Controllers/Quick Assign/OZLQuickAssignViewController.swift | 1 | 7557 | //
// OZLQuickAssignViewController.swift
// Facets
//
// Created by Justin Hill on 12/24/15.
// Copyright © 2015 Justin Hill. All rights reserved.
//
import UIKit
@objc protocol OZLQuickAssignDelegate {
func quickAssignController(_ quickAssign: OZLQuickAssignViewController, didChangeAssigneeInIssue issue: OZLModelIssue, from: OZLModelUser?, to: OZLModelUser?)
}
@objc class OZLQuickAssignViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate {
let CellReuseIdentifier = "reuseIdentifier"
var canonicalMemberships: RLMResults<AnyObject>?
var filteredMemberships: RLMResults<AnyObject>?
var issueModel: OZLModelIssue?
weak var delegate: OZLQuickAssignDelegate?
convenience init(issueModel: OZLModelIssue) {
self.init(nibName: nil, bundle: nil)
self.issueModel = issueModel
// Reset the change dictionary in case it has already been modified
self.issueModel?.modelDiffingEnabled = false
self.issueModel?.modelDiffingEnabled = true
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
override func loadView() {
self.view = OZLQuickAssignView(frame: CGRect(x: 0, y: 0, width: 320, height: 568))
}
override func viewDidLoad() {
if let view = self.view as? OZLQuickAssignView {
if self.popoverPresentationController?.sourceView == nil {
self.preferredContentSize = CGSize(width: 320, height: 350)
}
view.cancelButton.addTarget(self, action: #selector(dismissQuickAssignView), for: .touchUpInside)
view.backgroundColor = UIColor.white
view.tableView.dataSource = self
view.tableView.delegate = self
view.tableView.register(UITableViewCell.self, forCellReuseIdentifier:CellReuseIdentifier)
view.filterField.delegate = self
NotificationCenter.default.addObserver(self, selector: #selector(OZLQuickAssignViewController.keyboardWillShowOrHide(_:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(OZLQuickAssignViewController.keyboardWillShowOrHide(_:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
guard let issueModel = self.issueModel, let projectId = issueModel.projectId else {
assertionFailure("Issue model wasn't set on OZLQuickAssignViewController before its view was loaded.");
return
}
self.canonicalMemberships = OZLModelMembership.objects(with: NSPredicate(format: "%K = %ld", "projectId", projectId))
self.filteredMemberships = self.canonicalMemberships
}
}
@objc func dismissQuickAssignView() {
self.presentingViewController?.dismiss(animated: true, completion: nil)
}
@objc func keyboardWillShowOrHide(_ notification: Notification) {
if let view = self.view as? OZLQuickAssignView {
if let keyboardFrameValue = notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue {
let keyboardFrame = keyboardFrameValue.cgRectValue
if notification.name == NSNotification.Name.UIKeyboardWillShow && view.filterField.isFirstResponder {
let tableBottomOffset = view.frame.size.height - view.tableView.bottom
view.tableView.contentInset = UIEdgeInsetsMake(0, 0, keyboardFrame.size.height - tableBottomOffset, 0)
if self.popoverPresentationController?.sourceView == nil {
self.preferredContentSize = CGSize(width: 320, height: 450)
}
} else {
view.tableView.contentInset = UIEdgeInsets.zero
if self.popoverPresentationController?.sourceView == nil {
self.preferredContentSize = CGSize(width: 320, height: 350)
}
}
}
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if let memberships = self.filteredMemberships {
return Int(memberships.count)
}
return 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: CellReuseIdentifier, for: indexPath)
if let membership = self.filteredMemberships?[UInt(indexPath.row)] as? OZLModelMembership {
cell.textLabel?.text = membership.user.name
}
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if let view = self.view as? OZLQuickAssignView, let issueModel = self.issueModel {
if let newAssignee = self.filteredMemberships?.object(at: UInt(indexPath.row)) as? OZLModelMembership {
let oldAssignee = issueModel.assignedTo
issueModel.assignedTo = newAssignee.user
view.showLoadingOverlay()
weak var weakSelf = self
OZLNetwork.sharedInstance().update(issueModel, withParams: nil, completion: { (success, error) -> Void in
view.hideLoadingOverlay()
if let weakSelf = weakSelf, error == nil {
weakSelf.presentingViewController?.dismiss(animated: true, completion: nil)
weakSelf.delegate?.quickAssignController(weakSelf, didChangeAssigneeInIssue: issueModel, from: oldAssignee, to: newAssignee.user)
} else {
let alert = UIAlertController(title: "Error", message: "Couldn't set assignee.", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { (action) -> Void in
weakSelf?.presentingViewController?.dismiss(animated: true, completion: nil)
}))
weakSelf?.present(alert, animated: true, completion: nil)
}
})
}
}
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if string == "\n" {
textField.resignFirstResponder()
} else if let view = self.view as? OZLQuickAssignView,
let resultString = (textField.text as NSString?)?.replacingCharacters(in: range, with: string) {
self.filteredMemberships = self.canonicalMemberships?.objects(with: NSPredicate(format: "%K CONTAINS[c] %@", "user.name", resultString))
view.tableView.reloadData()
}
return true
}
func textFieldShouldClear(_ textField: UITextField) -> Bool {
if let view = self.view as? OZLQuickAssignView {
self.filteredMemberships = self.canonicalMemberships
view.tableView.reloadData()
}
return true
}
}
| mit | c81ff0d22c3740a9ae6d6ab72f0ee6b0 | 44.245509 | 193 | 0.625066 | 5.592894 | false | false | false | false |
yokochie/EchoServer-Sample | EchoServer/main.swift | 1 | 2298 |
import Darwin
let DEFAULT_PORT = 7000
let DEFAULT_BACKLOG = 128
var loop: UnsafeMutablePointer<uv_loop_t> = nil
var addr = sockaddr_in()
func alloc_buffer(handle: UnsafeMutablePointer<uv_handle_t>, suggested_size: size_t, buf: UnsafeMutablePointer<uv_buf_t>) {
buf.memory.base = UnsafeMutablePointer<CChar>.alloc(suggested_size)
buf.memory.len = suggested_size
}
func echo_write(req: UnsafeMutablePointer<uv_write_t>, status: CInt) {
if status != 0 {
print("Write error \(uv_strerror(status))")
}
req.destroy()
}
func echo_read(client: UnsafeMutablePointer<uv_stream_t>, nread: ssize_t, buf: UnsafePointer<uv_buf_t>) {
if nread < 0 {
if nread != ssize_t(UV_EOF.rawValue) {
print("Read error \(uv_err_name(CInt(nread)))")
}
uv_close(UnsafeMutablePointer<uv_handle_t>(client), nil)
} else if nread > 0 {
let req = UnsafeMutablePointer<uv_write_t>.alloc(sizeof(uv_write_t))
var wrbuf = uv_buf_init(buf.memory.base, UInt32(nread))
uv_write(req, client, &wrbuf, 1, echo_write)
}
if buf.memory.base != nil {
buf.memory.base.destroy()
}
}
func on_new_connect(server: UnsafeMutablePointer<uv_stream_t>, status: CInt) {
if status < 0 {
print("New connection error \(uv_strerror(status))")
// error!
return
}
let client = UnsafeMutablePointer<uv_tcp_t>.alloc(sizeof(uv_tcp_t))
uv_tcp_init(loop, client)
if uv_accept(server, UnsafeMutablePointer<uv_stream_t>(client)) == 0 {
uv_read_start(UnsafeMutablePointer<uv_stream_t>(client), alloc_buffer, echo_read)
} else {
uv_close(UnsafeMutablePointer<uv_handle_t>(client), nil)
}
}
func main() -> CInt {
loop = uv_default_loop()
var server = uv_tcp_t()
uv_tcp_init(loop, &server)
uv_ip4_addr("0.0.0.0", CInt(DEFAULT_PORT), &addr)
withUnsafePointer(&addr) {
uv_tcp_bind(&server, UnsafePointer<sockaddr>($0), 0)
}
withUnsafePointer(&server) {
let r = uv_listen(UnsafeMutablePointer<uv_stream_t>($0), CInt(DEFAULT_BACKLOG), on_new_connect)
if r != 0 {
print("Listen error \(uv_strerror(r))")
}
}
return uv_run(loop, UV_RUN_DEFAULT)
}
exit(main()) | mit | 31dce827143a630da5f400622739533d | 27.036585 | 123 | 0.619669 | 3.399408 | false | false | false | false |
bitboylabs/selluv-ios | selluv-ios/Pods/XCGLogger/Sources/XCGLogger/LogFormatters/XcodeColorsLogFormatter.swift | 13 | 9135 | //
// XcodeColorsLogFormatter.swift
// XCGLogger: https://github.com/DaveWoodCom/XCGLogger
//
// Created by Dave Wood on 2016-08-30.
// Copyright © 2016 Dave Wood, Cerebral Gardens.
// Some rights reserved: https://github.com/DaveWoodCom/XCGLogger/blob/master/LICENSE.txt
//
#if os(OSX)
import AppKit
#elseif os(iOS) || os(tvOS) || os(watchOS)
import UIKit
#endif
// MARK: - XcodeColorsLogFormatter
/// A log formatter that will add colour codes for the [XcodeColor plug-in](https://github.com/robbiehanson/XcodeColors) to the message
open class XcodeColorsLogFormatter: LogFormatterProtocol, CustomDebugStringConvertible {
/// XcodeColors escape code
public static let escape: String = "\u{001b}["
/// XcodeColors code to reset the foreground colour
public static let resetForeground = "\(escape)fg;"
/// XcodeColors code to reset the background colour
public static let resetBackground = "\(escape)bg;"
/// XcodeColors code to reset both the foreground and background colours
public static let reset: String = "\(escape);"
/// Struct to store RGB values
public struct XcodeColor: CustomStringConvertible {
/// Red component
public var red: Int = 0 {
didSet {
guard red < 0 || red > 255 else { return }
red = 0
}
}
/// Green component
public var green: Int = 0 {
didSet {
guard green < 0 || green > 255 else { return }
green = 0
}
}
/// Blue component
public var blue: Int = 0 {
didSet {
guard blue < 0 || blue > 255 else { return }
blue = 0
}
}
/// Foreground code
public var foregroundCode: String {
return "fg\(red),\(green),\(blue)"
}
/// Background code
public var backgroundCode: String {
return "bg\(red),\(green),\(blue)"
}
public init(red: Int, green: Int, blue: Int) {
self.red = red
self.green = green
self.blue = blue
}
public init(_ red: Int, _ green: Int, _ blue: Int) {
self.red = red
self.green = green
self.blue = blue
}
#if os(OSX)
public init(color: NSColor) {
if let colorSpaceCorrected = color.usingColorSpaceName(NSCalibratedRGBColorSpace) {
self.red = Int(colorSpaceCorrected.redComponent * 255)
self.green = Int(colorSpaceCorrected.greenComponent * 255)
self.blue = Int(colorSpaceCorrected.blueComponent * 255)
}
}
#elseif os(iOS) || os(tvOS) || os(watchOS)
public init(color: UIColor) {
var redComponent: CGFloat = 0
var greenComponent: CGFloat = 0
var blueComponent: CGFloat = 0
var alphaComponent: CGFloat = 0
color.getRed(&redComponent, green: &greenComponent, blue: &blueComponent, alpha:&alphaComponent)
self.red = Int(redComponent * 255)
self.green = Int(greenComponent * 255)
self.blue = Int(blueComponent * 255)
}
#endif
/// Human readable description of this colour (CustomStringConvertible)
public var description: String {
return String(format: "(r: %d, g: %d, b: %d) #%02X%02X%02X", red, green, blue, red, green, blue)
}
/// Preset colour: Red
public static let red: XcodeColor = { return XcodeColor(red: 255, green: 0, blue: 0) }()
/// Preset colour: Green
public static let green: XcodeColor = { return XcodeColor(red: 0, green: 255, blue: 0) }()
/// Preset colour: Blue
public static let blue: XcodeColor = { return XcodeColor(red: 0, green: 0, blue: 255) }()
/// Preset colour: Black
public static let black: XcodeColor = { return XcodeColor(red: 0, green: 0, blue: 0) }()
/// Preset colour: White
public static let white: XcodeColor = { return XcodeColor(red: 255, green: 255, blue: 255) }()
/// Preset colour: Light Grey
public static let lightGrey: XcodeColor = { return XcodeColor(red: 211, green: 211, blue: 211) }()
/// Preset colour: Dark Grey
public static let darkGrey: XcodeColor = { return XcodeColor(red: 169, green: 169, blue: 169) }()
/// Preset colour: Orange
public static let orange: XcodeColor = { return XcodeColor(red: 255, green: 165, blue: 0) }()
/// Preset colour: Purple
public static let purple: XcodeColor = { return XcodeColor(red: 170, green: 0, blue: 170) }()
/// Preset colour: Dark Green
public static let darkGreen: XcodeColor = { return XcodeColor(red: 0, green: 128, blue: 0) }()
/// Preset colour: Cyan
public static let cyan: XcodeColor = { return XcodeColor(red: 0, green: 170, blue: 170) }()
}
/// Internal cache of the XcodeColors codes for each log level
internal var formatStrings: [XCGLogger.Level: String] = [:]
/// Internal cache of the description for each log level
internal var descriptionStrings: [XCGLogger.Level: String] = [:]
public init() {
resetFormatting()
}
/// Set the colours and/or options for a specific log level.
///
/// - Parameters:
/// - level: The log level.
/// - foregroundColor: The text colour of the message. **Default:** Restore default text colour
/// - backgroundColor: The background colour of the message. **Default:** Restore default background colour
///
/// - Returns: Nothing
///
open func colorize(level: XCGLogger.Level, with foregroundColor: XcodeColor? = nil, on backgroundColor: XcodeColor? = nil) {
guard foregroundColor != nil || backgroundColor != nil else {
// neither set, use reset code
formatStrings[level] = XcodeColorsLogFormatter.reset
descriptionStrings[level] = "None"
return
}
var formatString: String = ""
if let foregroundColor = foregroundColor {
formatString += "\(XcodeColorsLogFormatter.escape)fg\(foregroundColor.red),\(foregroundColor.green),\(foregroundColor.blue);"
}
else {
formatString += XcodeColorsLogFormatter.resetForeground
}
if let backgroundColor = backgroundColor {
formatString += "\(XcodeColorsLogFormatter.escape)bg\(backgroundColor.red),\(backgroundColor.green),\(backgroundColor.blue);"
}
else {
formatString += XcodeColorsLogFormatter.resetBackground
}
formatStrings[level] = formatString
descriptionStrings[level] = "\(foregroundColor?.description ?? "Default") on \(backgroundColor?.description ?? "Default")"
}
/// Get the cached XcodeColors codes for the specified log level.
///
/// - Parameters:
/// - level: The log level.
///
/// - Returns: The XcodeColors codes for the specified log level.
///
internal func formatString(for level: XCGLogger.Level) -> String {
return formatStrings[level] ?? XcodeColorsLogFormatter.reset
}
/// Apply a default set of colours.
///
/// - Parameters: None
///
/// - Returns: Nothing
///
open func resetFormatting() {
colorize(level: .verbose, with: .lightGrey)
colorize(level: .debug, with: .darkGrey)
colorize(level: .info, with: .blue)
colorize(level: .warning, with: .orange)
colorize(level: .error, with: .red)
colorize(level: .severe, with: .white, on: .red)
colorize(level: .none)
}
/// Clear all previously set colours. (Sets each log level back to default)
///
/// - Parameters: None
///
/// - Returns: Nothing
///
open func clearFormatting() {
colorize(level: .verbose)
colorize(level: .debug)
colorize(level: .info)
colorize(level: .warning)
colorize(level: .error)
colorize(level: .severe)
colorize(level: .none)
}
// MARK: - LogFormatterProtocol
/// Apply some additional formatting to the message if appropriate.
///
/// - Parameters:
/// - logDetails: The log details.
/// - message: Formatted/processed message ready for output.
///
/// - Returns: message with the additional formatting
///
@discardableResult open func format(logDetails: inout LogDetails, message: inout String) -> String {
message = "\(formatString(for: logDetails.level))\(message)\(XcodeColorsLogFormatter.reset)"
return message
}
// MARK: - CustomDebugStringConvertible
open var debugDescription: String {
get {
var description: String = "\(extractTypeName(self)): "
for level in XCGLogger.Level.all {
description += "\n\t- \(level) > \(descriptionStrings[level] ?? "None")"
}
return description
}
}
}
| mit | 0336331343a211a68e2f4d1bfc831219 | 34.540856 | 137 | 0.593606 | 4.601511 | false | false | false | false |
NoryCao/zhuishushenqi | zhuishushenqi/NewVersion/Community/ZSDynamicHeaderView.swift | 1 | 8311 | //
// ZSDynamicHeaderView.swift
// zhuishushenqi
//
// Created by yung on 2019/7/6.
// Copyright © 2019 QS. All rights reserved.
//
import UIKit
protocol ZSDynamicHeaderViewDelegate:class {
func headerView(headerView:ZSDynamicHeaderView, clickIcon:UIButton)
func headerView(headerView:ZSDynamicHeaderView, clickFocus:UIButton)
func headerView(headerView:ZSDynamicHeaderView, clickFocusCount:UIButton)
func headerView(headerView:ZSDynamicHeaderView, clickFans:UIButton)
}
class ZSDynamicHeaderView: UITableViewHeaderFooterView {
lazy var iconView:UIButton = {
let imageView = UIButton(type: .custom)
imageView.addTarget(self, action: #selector(iconAction(btn:)), for: .touchUpInside)
imageView.layer.cornerRadius = 32
imageView.layer.masksToBounds = true
return imageView
}()
lazy var focusButton:UIButton = {
let button = UIButton(type: .custom)
button.layer.cornerRadius = 14
button.layer.masksToBounds = true
button.backgroundColor = UIColor.init(red: 0.93, green: 0.28, blue: 0.27, alpha: 1)
button.setTitle("关注", for: .normal)
button.titleLabel?.font = UIFont.systemFont(ofSize: 15)
button.addTarget(self, action: #selector(focusAction(btn:)), for: .touchUpInside)
return button
}()
lazy var nickNameLabe:UILabel = {
let label = UILabel(frame: .zero)
label.textColor = UIColor(red: 0.2, green: 0.2, blue: 0.2, alpha: 1)
label.font = UIFont.systemFont(ofSize: 16)
return label
}()
lazy var levelLabel:UILabel = {
let label = UILabel(frame: .zero)
label.textColor = UIColor.init(red: 0.64, green: 0.64, blue: 0.64, alpha: 1)
label.font = UIFont.systemFont(ofSize: 9)
label.textAlignment = .center
label.layer.cornerRadius = 6.5
label.layer.borderColor = UIColor.darkGray.cgColor
label.layer.borderWidth = 0.5
return label
}()
lazy var focusLabel:UILabel = {
let label = UILabel(frame: .zero)
label.textColor = UIColor.init(red: 0.6, green: 0.6, blue: 0.6, alpha: 1)
label.font = UIFont.systemFont(ofSize: 10)
label.text = "关注"
return label
}()
lazy var focusCountLabel:UILabel = {
let label = UILabel(frame: .zero)
label.textColor = UIColor.init(red: 0.2, green: 0.2, blue: 0.2, alpha: 1)
label.font = UIFont.systemFont(ofSize: 14)
return label
}()
lazy var focusCountButton:UIButton = {
let button = UIButton(type: .custom)
button.titleLabel?.font = UIFont.systemFont(ofSize: 15)
button.addTarget(self, action: #selector(focusCountAction(btn:)), for: .touchUpInside)
return button
}()
lazy var fansLabel:UILabel = {
let label = UILabel(frame: .zero)
label.textColor = UIColor.init(red: 0.6, green: 0.6, blue: 0.6, alpha: 1)
label.font = UIFont.systemFont(ofSize: 10)
label.text = "粉丝"
return label
}()
lazy var fansCountLabel:UILabel = {
let label = UILabel(frame: .zero)
label.textColor = UIColor.init(red: 0.2, green: 0.2, blue: 0.2, alpha: 1)
label.font = UIFont.systemFont(ofSize: 14)
return label
}()
lazy var fansCountButton:UIButton = {
let button = UIButton(type: .custom)
button.titleLabel?.font = UIFont.systemFont(ofSize: 15)
button.addTarget(self, action: #selector(fansAction(btn:)), for: .touchUpInside)
return button
}()
weak var delegate:ZSDynamicHeaderViewDelegate?
var type:UserDynamicType = .dynamic {
didSet {
type == .dynamic ? focusButton.setTitle("关注", for: .normal) : focusButton.setTitle("编辑", for: .normal)
}
}
var focusState:Bool = false {
didSet {
if type == .dynamic {
focusState ? focusSelected():focusUnSelected()
}
}
}
override init(reuseIdentifier: String?) {
super.init(reuseIdentifier: reuseIdentifier)
backgroundColor = UIColor.white
contentView.backgroundColor = UIColor.white
contentView.addSubview(iconView)
contentView.addSubview(focusButton)
contentView.addSubview(nickNameLabe)
contentView.addSubview(levelLabel)
contentView.addSubview(focusLabel)
contentView.addSubview(focusCountLabel)
contentView.addSubview(focusCountButton)
contentView.addSubview(fansLabel)
contentView.addSubview(fansCountLabel)
contentView.addSubview(fansCountButton)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
iconView.frame = CGRect(x: 15, y: 34, width: 64, height: 64)
focusButton.frame = CGRect(x: bounds.width - 60 - 16, y: 30, width: 60, height: 28)
let nickNameWidth = nickNameLabe.sizeThatFits(CGSize(width: CGFloat.greatestFiniteMagnitude, height: 20)).width
nickNameLabe.frame = CGRect(x: iconView.frame.maxX + 20, y: 32, width: nickNameWidth, height: 20)
let levelWidth = levelLabel.sizeThatFits(CGSize(width: CGFloat.greatestFiniteMagnitude, height: 13)).width + 10
levelLabel.frame = CGRect(x: nickNameLabe.frame.maxX + 3, y: 35.5, width: levelWidth, height: 13)
let focusWidth = focusCountLabel.sizeThatFits(CGSize(width: CGFloat.greatestFiniteMagnitude, height: 20)).width
focusCountLabel.frame = CGRect(x: iconView.frame.maxX + 20, y: nickNameLabe.frame.maxY + 20, width: focusWidth, height: 20)
focusLabel.frame = CGRect(x: iconView.frame.maxX + 20, y: focusCountLabel.frame.maxY, width: 40, height: 10)
let focusCountWidth = max(focusCountLabel.frame.maxX - focusCountLabel.frame.minX, focusLabel.frame.maxX - focusLabel.frame.minX)
focusCountButton.frame = CGRect(x: focusCountLabel.frame.minX, y: focusCountLabel.frame.minY, width: focusCountWidth, height: 30)
let fansCountWidth = fansCountLabel.sizeThatFits(CGSize(width: CGFloat.greatestFiniteMagnitude, height: 20)).width
fansCountLabel.frame = CGRect(x: focusCountLabel.frame.maxX + 19, y: nickNameLabe.frame.maxY + 20, width: fansCountWidth, height: 20)
fansLabel.frame = CGRect(x: fansCountLabel.frame.minX, y: fansCountLabel.frame.maxY, width: 40, height: 10)
let fansCountButtonWidth = max(fansCountLabel.frame.maxX - fansCountLabel.frame.minX, fansLabel.frame.maxX - fansLabel.frame.minX)
fansCountButton.frame = CGRect(x: fansCountLabel.frame.minX, y: fansCountLabel.frame.minY, width: fansCountButtonWidth, height: 30)
}
func configure(user:ZSDynaicUser?) {
if let userInfo = user {
iconView.qs_setAvatarWithURLString(urlString: userInfo.avatar)
nickNameLabe.text = userInfo.nickname
levelLabel.text = "lv.\(userInfo.lv)"
focusCountLabel.text = "\(userInfo.followings)"
fansCountLabel.text = "\(userInfo.followers)"
}
}
private func focusSelected() {
self.focusButton.setTitle("已关注", for: .normal)
self.focusButton.setTitleColor(UIColor(red: 0.94, green: 0.94, blue: 0.95, alpha: 1), for: .normal)
self.focusButton.backgroundColor = UIColor(red: 0.75, green: 0.75, blue: 0.76, alpha: 1)
}
private func focusUnSelected() {
self.focusButton.setTitle("关注", for: .normal)
self.focusButton.setTitleColor(UIColor.white, for: .normal)
self.focusButton.backgroundColor = UIColor.init(red: 0.93, green: 0.28, blue: 0.27, alpha: 1)
}
@objc
func iconAction(btn:UIButton) {
delegate?.headerView(headerView: self, clickIcon: btn)
}
@objc
func focusAction(btn:UIButton) {
delegate?.headerView(headerView: self, clickFocus: btn)
}
@objc
func fansAction(btn:UIButton) {
delegate?.headerView(headerView: self, clickFans: btn)
}
@objc
func focusCountAction(btn:UIButton) {
delegate?.headerView(headerView: self, clickFocusCount: btn)
}
}
| mit | 66e08e09a84c23f603e978763a5b06d4 | 39.788177 | 141 | 0.65314 | 4.054848 | false | false | false | false |
hollance/swift-algorithm-club | Insertion Sort/InsertionSort.swift | 1 | 1615 | /// Performs the Insertion sort algorithm to a given array
///
/// - Parameters:
/// - array: the array of elements to be sorted
/// - isOrderedBefore: returns true if the elements provided are in the corect order
/// - Returns: a sorted array containing the same elements
func insertionSort<T>(_ array: [T], _ isOrderedBefore: (T, T) -> Bool) -> [T] {
guard array.count > 1 else { return array }
/// - sortedArray: copy the array to save stability
var sortedArray = array
for index in 1..<sortedArray.count {
var currentIndex = index
let temp = sortedArray[currentIndex]
while currentIndex > 0, isOrderedBefore(temp, sortedArray[currentIndex - 1]) {
sortedArray[currentIndex] = sortedArray[currentIndex - 1]
currentIndex -= 1
}
sortedArray[currentIndex] = temp
}
return sortedArray
}
/// Performs the Insertion sort algorithm to a given array
///
/// - Parameter array: the array to be sorted, containing elements that conform to the Comparable protocol
/// - Returns: a sorted array containing the same elements
func insertionSort<T: Comparable>(_ array: [T]) -> [T] {
guard array.count > 1 else { return array }
var sortedArray = array
for index in 1..<sortedArray.count {
var currentIndex = index
let temp = sortedArray[currentIndex]
while currentIndex > 0, temp < sortedArray[currentIndex - 1] {
sortedArray[currentIndex] = sortedArray[currentIndex - 1]
currentIndex -= 1
}
sortedArray[currentIndex] = temp
}
return sortedArray
}
| mit | 9ba9a78cd9a3ee451f0cf4ab2c6a2c35 | 38.390244 | 106 | 0.656966 | 4.75 | false | false | false | false |
brave/browser-ios | Client/Frontend/Browser/BrowserTrayAnimators.swift | 2 | 15388 | /* 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 UIKit
class TrayToBrowserAnimator: NSObject, UIViewControllerAnimatedTransitioning {
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
guard let vc = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to) else { return }
guard let bvc = (vc as? BraveTopViewController)?.browserViewController else { return }
guard let tabTray = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from) as? TabTrayController else { return }
transitionFromTray(tabTray, toBrowser: bvc, usingContext: transitionContext)
}
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return 0.4
}
}
private extension TrayToBrowserAnimator {
func transitionFromTray(_ tabTray: TabTrayController, toBrowser bvc: BrowserViewController, usingContext transitionContext: UIViewControllerContextTransitioning) {
let container = transitionContext.containerView
guard let selectedTab = bvc.tabManager.selectedTab else { return }
// Bug 1205464 - Top Sites tiles blow up or shrink after rotating
// Force the BVC's frame to match the tab trays since for some reason on iOS 9 the UILayoutContainer in
// the UINavigationController doesn't rotate the presenting view controller
let os = ProcessInfo().operatingSystemVersion
switch (os.majorVersion, os.minorVersion, os.patchVersion) {
case (9, _, _):
bvc.view.frame = UIWindow().frame
default:
break
}
let tabManager = bvc.tabManager
let displayedTabs = tabManager.tabs.displayedTabsForCurrentPrivateMode
guard let expandFromIndex = displayedTabs.index(of: selectedTab) else { return }
// Hide browser components
bvc.toggleSnackBarVisibility(false)
toggleWebViewVisibility(false, usingTabManager: bvc.tabManager)
bvc.homePanelController?.view.isHidden = true
bvc.webViewContainerBackdrop.isHidden = true
// Take a snapshot of the collection view that we can scale/fade out. We don't need to wait for screen updates since it's already rendered on the screen
guard let tabCollectionViewSnapshot = tabTray.collectionView.snapshotView(afterScreenUpdates: false) else { return }
tabTray.collectionView.alpha = 0
tabCollectionViewSnapshot.frame = tabTray.collectionView.frame
container.insertSubview(tabCollectionViewSnapshot, aboveSubview: tabTray.view)
// Create a fake cell to use for the upscaling animation
let startingFrame = calculateCollapsedCellFrameUsingCollectionView(tabTray.collectionView, atIndex: expandFromIndex)
let cell = createTransitionCellFromBrowser(bvc.tabManager.selectedTab, withFrame: startingFrame)
cell.backgroundHolder.layer.cornerRadius = 0
container.insertSubview(getApp().rootViewController.topViewController!.view, aboveSubview: tabCollectionViewSnapshot)
container.insertSubview(cell, aboveSubview: bvc.view)
// Flush any pending layout/animation code in preperation of the animation call
container.layoutIfNeeded()
let finalFrame = calculateExpandedCellFrameFromBVC(bvc)
bvc.footer.alpha = shouldDisplayFooterForBVC(bvc) ? 1 : 0
bvc.urlBar.isTransitioning = true
// Re-calculate the starting transforms for header/footer views in case we switch orientation
resetTransformsForViews([bvc.header, bvc.footer, bvc.footerBackdrop])
transformHeaderFooterForBVC(bvc, toFrame: startingFrame, container: container)
UIView.animate(withDuration: self.transitionDuration(using: transitionContext),
delay: 0, usingSpringWithDamping: 1,
initialSpringVelocity: 0,
options: UIViewAnimationOptions(),
animations:
{
// Scale up the cell and reset the transforms for the header/footers
cell.frame = finalFrame
container.layoutIfNeeded()
cell.titleWrapper.transform = CGAffineTransform(translationX: 0, y: -cell.titleWrapper.frame.height)
bvc.tabTrayDidDismiss(tabTray)
tabCollectionViewSnapshot.transform = CGAffineTransform(scaleX: 0.9, y: 0.9)
tabCollectionViewSnapshot.alpha = 0
// Push out the navigation bar buttons
let buttonOffset = tabTray.addTabButton.frame.width + TabTrayControllerUX.ToolbarButtonOffset
tabTray.addTabButton.transform = CGAffineTransform.identity.translatedBy(x: buttonOffset , y: 0)
#if !BRAVE
tabTray.settingsButton.transform = CGAffineTransform.identity.translatedBy(x: -buttonOffset , y: 0)
tabTray.togglePrivateMode.transform = CGAffineTransform.identity.translatedBy(x: buttonOffset , y: 0)
#endif
}, completion: { finished in
// Remove any of the views we used for the animation
cell.removeFromSuperview()
tabCollectionViewSnapshot.removeFromSuperview()
bvc.footer.alpha = 1
bvc.toggleSnackBarVisibility(true)
toggleWebViewVisibility(true, usingTabManager: bvc.tabManager)
bvc.webViewContainerBackdrop.isHidden = false
bvc.homePanelController?.view.isHidden = false
bvc.urlBar.isTransitioning = false
transitionContext.completeTransition(true)
})
}
}
class BrowserToTrayAnimator: NSObject, UIViewControllerAnimatedTransitioning {
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
guard let vc = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from) else { return }
guard let bvc = (vc as? BraveTopViewController)?.browserViewController else { return }
guard let tabTray = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to) as? TabTrayController else { return }
transitionFromBrowser(bvc, toTabTray: tabTray, usingContext: transitionContext)
}
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return 0.4
}
}
private extension BrowserToTrayAnimator {
func transitionFromBrowser(_ bvc: BrowserViewController, toTabTray tabTray: TabTrayController, usingContext transitionContext: UIViewControllerContextTransitioning) {
let container = transitionContext.containerView
guard let selectedTab = bvc.tabManager.selectedTab else { return }
let tabManager = bvc.tabManager
let displayedTabs = tabManager.tabs.displayedTabsForCurrentPrivateMode
guard let scrollToIndex = displayedTabs.index(of: selectedTab) else { return }
// Insert tab tray below the browser and force a layout so the collection view can get it's frame right
container.insertSubview(tabTray.view, belowSubview: bvc.view)
// Force subview layout on the collection view so we can calculate the correct end frame for the animation
tabTray.view.layoutSubviews()
tabTray.collectionView.scrollToItem(at: IndexPath(item: scrollToIndex, section: 0), at: .centeredVertically, animated: false)
// Build a tab cell that we will use to animate the scaling of the browser to the tab
let expandedFrame = calculateExpandedCellFrameFromBVC(bvc)
let cell = createTransitionCellFromBrowser(bvc.tabManager.selectedTab, withFrame: expandedFrame)
cell.backgroundHolder.layer.cornerRadius = TabTrayControllerUX.CornerRadius
// Take a snapshot of the collection view to perform the scaling/alpha effect
let tabCollectionViewSnapshot = tabTray.collectionView.snapshotView(afterScreenUpdates: true)
tabCollectionViewSnapshot!.frame = tabTray.collectionView.frame
tabCollectionViewSnapshot!.transform = CGAffineTransform(scaleX: 0.9, y: 0.9)
tabCollectionViewSnapshot!.alpha = 0
tabTray.view.addSubview(tabCollectionViewSnapshot!)
container.addSubview(cell)
cell.layoutIfNeeded()
cell.titleWrapper.transform = CGAffineTransform(translationX: 0, y: -cell.titleWrapper.frame.size.height)
// Hide views we don't want to show during the animation in the BVC
bvc.homePanelController?.view.isHidden = true
bvc.toggleSnackBarVisibility(false)
toggleWebViewVisibility(false, usingTabManager: bvc.tabManager)
bvc.urlBar.isTransitioning = true
// Since we are hiding the collection view and the snapshot API takes the snapshot after the next screen update,
// the screenshot ends up being blank unless we set the collection view hidden after the screen update happens.
// To work around this, we dispatch the setting of collection view to hidden after the screen update is completed.
DispatchQueue.main.async {
tabTray.collectionView.isHidden = true
let finalFrame = calculateCollapsedCellFrameUsingCollectionView(tabTray.collectionView,
atIndex: scrollToIndex)
UIView.animate(withDuration: self.transitionDuration(using: transitionContext),
delay: 0, usingSpringWithDamping: 1,
initialSpringVelocity: 0,
options: UIViewAnimationOptions(),
animations:
{
cell.frame = finalFrame
cell.titleWrapper.transform = CGAffineTransform.identity
cell.layoutIfNeeded()
transformHeaderFooterForBVC(bvc, toFrame: finalFrame, container: container)
bvc.urlBar.updateAlphaForSubviews(0)
bvc.footer.alpha = 0
tabCollectionViewSnapshot!.alpha = 1
var viewsToReset: [UIView?] = [tabCollectionViewSnapshot, tabTray.addTabButton]
#if !BRAVE
viewsToReset.append(tabTray.togglePrivateMode)
#endif
resetTransformsForViews(viewsToReset)
}, completion: { finished in
// Remove any of the views we used for the animation
cell.removeFromSuperview()
tabCollectionViewSnapshot!.removeFromSuperview()
tabTray.collectionView.isHidden = false
bvc.toggleSnackBarVisibility(true)
toggleWebViewVisibility(true, usingTabManager: bvc.tabManager)
bvc.homePanelController?.view.isHidden = false
bvc.urlBar.isTransitioning = false
transitionContext.completeTransition(true)
})
}
}
}
private func transformHeaderFooterForBVC(_ bvc: BrowserViewController, toFrame finalFrame: CGRect, container: UIView) {
let footerForTransform = footerTransform(bvc.footer.frame, toFrame: finalFrame, container: container)
let headerForTransform = headerTransform(bvc.header.frame, toFrame: finalFrame, container: container)
bvc.footer.transform = footerForTransform
bvc.footerBackdrop.transform = footerForTransform
bvc.header.transform = headerForTransform
}
private func footerTransform( _ frame: CGRect, toFrame finalFrame: CGRect, container: UIView) -> CGAffineTransform {
let frame = container.convert(frame, to: container)
let endY = finalFrame.maxY - (frame.size.height / 2)
let endX = finalFrame.midX
let translation = CGPoint(x: endX - frame.midX, y: endY - frame.midY)
let scaleX = finalFrame.width / frame.width
var transform = CGAffineTransform.identity
transform = transform.translatedBy(x: translation.x, y: translation.y)
transform = transform.scaledBy(x: scaleX, y: scaleX)
return transform
}
private func headerTransform(_ frame: CGRect, toFrame finalFrame: CGRect, container: UIView) -> CGAffineTransform {
let frame = container.convert(frame, to: container)
let endY = finalFrame.minY + (frame.size.height / 2)
let endX = finalFrame.midX
let translation = CGPoint(x: endX - frame.midX, y: endY - frame.midY)
let scaleX = finalFrame.width / frame.width
var transform = CGAffineTransform.identity
transform = transform.translatedBy(x: translation.x, y: translation.y)
transform = transform.scaledBy(x: scaleX, y: scaleX)
return transform
}
//MARK: Private Helper Methods
private func calculateCollapsedCellFrameUsingCollectionView(_ collectionView: UICollectionView, atIndex index: Int) -> CGRect {
if let attr = collectionView.collectionViewLayout.layoutAttributesForItem(at: IndexPath(item: index, section: 0)) {
return collectionView.convert(attr.frame, to: collectionView.superview)
} else {
return CGRect.zero
}
}
private func calculateExpandedCellFrameFromBVC(_ bvc: BrowserViewController) -> CGRect {
var frame = bvc.webViewContainer.frame
// If we're navigating to a home panel and we were expecting to show the toolbar, add more height to end frame since
// there is no toolbar for home panels
if !bvc.shouldShowFooterForTraitCollection(bvc.traitCollection) {
return frame
} else if AboutUtils.isAboutURL(bvc.tabManager.selectedTab?.url) && bvc.toolbar == nil {
frame.size.height += UIConstants.ToolbarHeight
}
return frame
}
private func shouldDisplayFooterForBVC(_ bvc: BrowserViewController) -> Bool {
return bvc.shouldShowFooterForTraitCollection(bvc.traitCollection) && !AboutUtils.isAboutURL(bvc.tabManager.selectedTab?.url)
}
private func toggleWebViewVisibility(_ show: Bool, usingTabManager tabManager: TabManager) {
for i in 0..<tabManager.tabCount {
let tab = tabManager.tabs.internalTabList[i]
tab.webView?.isHidden = !show
}
}
private func resetTransformsForViews(_ views: [UIView?]) {
for view in views {
// Reset back to origin
view?.transform = CGAffineTransform.identity
}
}
private func transformToolbarsToFrame(_ toolbars: [UIView?], toRect endRect: CGRect) {
for toolbar in toolbars {
// Reset back to origin
toolbar?.transform = CGAffineTransform.identity
// Transform from origin to where we want them to end up
if let toolbarFrame = toolbar?.frame {
toolbar?.transform = CGAffineTransformMakeRectToRect(toolbarFrame, toFrame: endRect)
}
}
}
private func createTransitionCellFromBrowser(_ browser: Browser?, withFrame frame: CGRect) -> TabCell {
let cell = TabCell(frame: frame)
browser?.screenshot(callback: { (image) in
cell.background.image = image
})
cell.titleLbl.text = browser?.displayTitle
if let favIcon = browser?.displayFavicon {
cell.favicon.sd_setImage(with: URL(string: favIcon.url)!)
} else {
var defaultFavicon = UIImage(named: "defaultFavicon")
if browser?.isPrivate ?? false {
defaultFavicon = defaultFavicon?.withRenderingMode(.alwaysTemplate)
cell.favicon.image = defaultFavicon
cell.favicon.tintColor = (browser?.isPrivate ?? false) ? UIColor.white : UIColor.darkGray
} else {
cell.favicon.image = defaultFavicon
}
}
return cell
}
| mpl-2.0 | 6985adb7a6f087ecc5168702869fe3d0 | 47.0875 | 170 | 0.713153 | 5.561258 | false | false | false | false |
dche/FlatColor | Sources/Theory.swift | 1 | 5403 | //
// FlatColor - Theory.swift
//
// Copyright (c) 2016 The FlatColor authors.
// Licensed under MIT License.
import GLMath
public extension Hsb {
/// The complementary color of a HSB color.
public var complement: Hsb {
var c = self
c.hue = mod(self.hue + Float.π, Float.tau)
return c
}
/// Returns a pair of colors that are splited from the complementary color
/// of a HSB color,
///
/// These 2 colors have same distances to the complementary color on the
/// color wheel. In our implementation, this distance is fixed to `30`
/// degrees.
public var splitComplement: (Hsb, Hsb) {
let pi2 = Float.tau
var c1 = self
var c2 = self
c1.hue = mod(self.hue + radians(150), pi2);
c2.hue = mod(self.hue + radians(210), pi2);
return (c1, c2)
}
/// Returns 2 pairs of complementary colors. The first colors of both pairs
/// are the result of a HSB color's `split_complement`.
public var doubleComplement: ((Hsb, Hsb), (Hsb, Hsb)) {
let (c1, c2) = self.splitComplement
return ((c1, c1.complement), (c2, c2.complement))
}
/// Returns other 2 colors of triad colors that includes the receiver.
public var triad: (Hsb, Hsb) {
let a120: Float = radians(120)
var c1 = self
var c2 = self
c1.hue = mod(self.hue + a120, Float.tau);
c2.hue = mod(self.hue + a120 + a120, Float.tau);
return (c1, c2)
}
/// Returns `n` colors that are analogous to the receiver.
///
/// - note:
/// * `[]` is returned if `n` is `0` or negative,
/// * `span` can be larger than `2π`,
/// * `span` can be negative.
public func analog(by n: Int, span: Float) -> [Hsb] {
guard n > 0 else { return [] }
guard !span.isZero else { return [Hsb](repeating: self, count: n) }
let d = span / Float(n)
let h = self.hue
var cs = [self]
for i in 1 ..< n {
var clr = self
clr.hue = h + d * Float(i)
cs.append(clr)
}
return cs
}
/// Returns `n` colors distributed on the color wheel evenly.
///
/// The returned colors have same saturation and brightness as `self`.
/// `self` is the first color in the array.
///
/// If `n` is `0`, an empty array is returned.
public func colorWheel(_ n: Int) -> [Hsb] {
return self.analog(by: n, span: Float.tau)
}
/// Produces a color by adding white to the receiver.
///
/// For `Hsb` color model, adding white means increasing the lightness.
///
/// Parameter `amt` specifies absolute lightness to be added.
public func tinted(_ amount: Float) -> Hsb {
var c = self
c.brightness = self.brightness + amount
return c
}
/// Produces a list of `n` colors whose brightness increase monotonically
/// and evenly.
///
/// If `n` is `0`, returns an empty array. Other wise, the receiver is
/// the first element of the vector and a color with full brightness is
/// the last.
public func tinted(by n: Int) -> [Hsb] {
switch n {
case _ where n < 1:
return []
case 1:
return [self]
default:
let b = self.brightness
let d = (1 - b) / Float(n)
var c = self
var cs = [c]
for i in 1 ..< n - 1 {
c = self
c.brightness = b + d * Float(i)
cs.append(c)
}
c = self
c.brightness = 1
cs.append(c)
return cs
}
}
/// Produces a color by adding black to the receiver.
public func shaded(_ amount: Float) -> Hsb {
var c = self
c.brightness = self.brightness - amount
return c
}
/// Produces`n` colors whose brightness decrease monotonically and evenly.
public func shaded(by n: Int) -> [Hsb] {
switch n {
case _ where n < 1:
return []
case 1:
return [self]
default:
let b = self.brightness
let d = b / Float(n)
var c = self
var cs = [c]
for i in 1 ..< n - 1 {
c = self
c.brightness = b - d * Float(i)
cs.append(c)
}
c = self
c.brightness = 0
cs.append(c)
return cs
}
}
/// Produces a color by adding gray to the receiver, i.e., decreases its
/// saturation.
public func tone(_ amount: Float) -> Hsb {
var c = self
c.saturation = self.saturation - amount
return c
}
/// Produces `n` colors whose saturation decrease monotonically and
/// evenly.
public func tone(by n: Int) -> [Hsb] {
switch n {
case _ where n < 1:
return []
case 1:
return [self]
default:
let s = self.saturation
let d = s / Float(n)
var c = self
var cs = [c]
for i in 1 ..< n - 1 {
c = self
c.saturation = s - d * Float(i)
cs.append(c)
}
c = self
c.saturation = 0
cs.append(c)
return cs
}
}
}
| mit | 18569740e167f4d3d9b9c4297d6c87b5 | 28.353261 | 79 | 0.507128 | 3.95388 | false | false | false | false |
Bouke/LedgerTools | Sources/ledger-import-csv/main.swift | 1 | 5706 | import func LedgerParser.parseLedger
import enum LedgerParser.Token
import struct LedgerParser.Transaction
import Foundation
import func Categorizer.freq
import func Categorizer.train
import typealias Categorizer.History
import func CSV.parse
public struct StderrOutputStream: TextOutputStream {
public mutating func write(_ string: String) { fputs(string, stderr) }
}
public var errStream = StderrOutputStream()
let settings = parseSettings()
let tokens: [Token]
do {
tokens = try parseLedger(filename: (settings.trainFile as NSString).expandingTildeInPath)
} catch {
print("Could not parse ledger file: \(error)", to: &errStream)
exit(1)
}
let transactions = tokens.flatMap { (token: Token) -> Transaction? in
switch token {
case .Transaction(let t): return t
default: return nil
}
}
let ledgerTokenSeparators = CharacterSet(charactersIn: settings.ledgerTokenSeparators)
let originatingAccount = { (t: [Transaction]) -> String in
let f = freq(t.map { $0.postings.map { $0.account } }.joined())
return f.sorted { $0.value >= $1.value }.first?.key ?? "Assets:Banking"
}(transactions)
let descriptionRegex = try! NSRegularExpression(pattern: "Omschrijving: (.+?) IBAN", options: [])
func extractTokens(row: [String]) -> [String] {
var tokens = row[1].components(separatedBy: " ")
if let match = descriptionRegex.matches(in: row[8]).first {
tokens += match.groups.first!.components(separatedBy: " ")
}
return tokens
}
//MARK: Read input, from either stdin (pipe) or file argument.
let inputCSV: Data
if !FileHandle.standardInput.isatty {
inputCSV = FileHandle.standardInput.readDataToEndOfFile()
} else {
// Expect the transaction file as unparsed argument (not matched by flag);
// only one transaction file is expected.
guard cli.unparsedArguments.count == 1 else {
print("Specify exactly one transaction file argument", to: &errStream)
exit(EX_USAGE)
}
guard let data = try? Data(contentsOf: URL(fileURLWithPath: cli.unparsedArguments[0])) else {
print("Could not read transactions file", to: &errStream)
exit(1)
}
inputCSV = data
}
let csvDateFormatter = DateFormatter()
csvDateFormatter.dateFormat = settings.csvDateFormat
let ledgerDateFormatter = DateFormatter()
ledgerDateFormatter.dateFormat = settings.ledgerDateFormat
let minimalColumnCount = [settings.csvDateColumn, settings.csvPayeeColumn,
settings.csvAmountColumn, settings.csvDescriptionColumn].max()!
let csvTokenSeparators = CharacterSet(charactersIn: settings.csvTokenSeparators)
let csvNumberFormatter = NumberFormatter()
csvNumberFormatter.numberStyle = .decimal
csvNumberFormatter.isLenient = true
if let locale = settings.csvLocale {
csvNumberFormatter.locale = Locale(identifier: locale)
}
let ledgerNumberFormatter = NumberFormatter()
ledgerNumberFormatter.numberStyle = .currency
if let locale = settings.ledgerLocale {
ledgerNumberFormatter.locale = Locale(identifier: locale)
}
//MARK: Read history
let (accountHistory, payeeHistory) = { (transactions: [Transaction]) -> (History, History) in
var a = History()
var p = History()
for transaction in transactions {
guard let note = transaction.notes.first(where: { $0.hasPrefix(" CSV: ") }) else { continue }
let csv = note.substring(from: note.index(note.startIndex, offsetBy: 6))
guard let row = (try? CSV.parse(csv.data(using: .utf8)!))?.first else { continue }
guard row.count >= minimalColumnCount else {
print(transaction, to: &errStream)
print("Found a transaction with \(row.count) columns, at least \(minimalColumnCount) expected", to: &errStream)
continue
}
let tokens = extractTokens(row: row)
p.append(transaction.payee, tokens)
for posting in transaction.postings {
guard posting.account != originatingAccount else { continue }
a.append(posting.account, tokens)
}
}
return (a, p)
}(transactions)
let accountCategorizer = train(accountHistory)
let payeeCategorizer = train(payeeHistory)
//MARK: Read input CSV
let rows = try { () throws -> [[String]] in
var rows = try CSV.parse(inputCSV)
rows = Array(rows[settings.csvSkipRows..<rows.endIndex])
if settings.csvReverseRows {
rows = rows.reversed()
}
return rows
}()
for row in rows {
guard row.count >= minimalColumnCount else {
print("Found a row with \(row.count) columns, at least \(minimalColumnCount) expected", to: &errStream)
exit(1)
}
let tokens = extractTokens(row: row)
let account = accountCategorizer(tokens).first?.0 ?? settings.defaultAccount
let payee = payeeCategorizer(tokens).filter({ $0.1 >= 0.2 }).first?.0 ?? row[settings.csvPayeeColumn]
guard var amount = csvNumberFormatter.number(from: row[settings.csvAmountColumn]).flatMap({ $0.decimalValue }) else {
print("Could not parse amount \(row[settings.csvAmountColumn])", to: &errStream)
exit(1)
}
if let csvAmountDebit = settings.csvAmountDebit, row[csvAmountDebit.column] == csvAmountDebit.text {
amount = amount * -1
}
guard let date = csvDateFormatter.date(from: row[settings.csvDateColumn]) else {
print("Could not parse date \(row[settings.csvDateColumn])", to: &errStream)
exit(1)
}
print()
print("\(ledgerDateFormatter.string(from: date)) * \(payee)")
// TODO: write CSV as-is (or escape correctly)
print(" ; CSV: \""+row.joined(separator: "\",\"")+"\"")
print(" \(account)")
print(" \(originatingAccount.pad(65)) \(ledgerNumberFormatter.string(for: amount)!)")
}
| mit | 4c83286396f2dcee9d69fc4a70094226 | 35.113924 | 123 | 0.695058 | 3.981856 | false | false | false | false |
moonknightskye/Luna | Luna/CommandProcessor.swift | 1 | 37213 | //
// CommandProcessor.swift
// Luna
//
// Created by Mart Civil on 2017/03/01.
// Copyright © 2017年 salesforce.com. All rights reserved.
//
import Foundation
import UIKit
import Photos
class CommandProcessor {
private static var QUEUE:[Command] = [Command]();
private class func _queue( command: Command ) {
CommandProcessor.QUEUE.append( command )
switch command.getCommandCode() {
case .NEW_WEB_VIEW:
processNewWebView( command: command )
break
case .LOAD_WEB_VIEW:
processLoadWebView( command: command )
break
case .ANIMATE_WEB_VIEW:
processAnimateWebView( command: command )
break
case .WEB_VIEW_ONLOAD,
.WEB_VIEW_ONLOADED,
.WEB_VIEW_ONLOADING:
checkWebViewEvent( command: command )
break
case .CLOSE_WEB_VIEW:
processCloseWebView( command: command )
break
case .GET_FILE:
processGetFile( command: command )
break
case .GET_HTML_FILE:
processGetHTMLFile( command: command )
break
case .GET_IMAGE_FILE:
processGetImageFile( command: command )
break
case .GET_BASE64_BINARY:
processGetBase64Binary( command: command )
break
case .GET_BASE64_RESIZED:
processGetBase64Resized( command: command )
break
case .MEDIA_PICKER:
checkMediaPicker( command: command )
break
case .CHANGE_ICON:
proccessChangeIcon(command: command)
break
case .MOVE_FILE:
processMoveFile( command: command )
break
case .RENAME_FILE:
processRenameFile( command: command )
break
case .SHAKE_BEGIN:
//checkShakeBegin(command: command)
break
case .SHAKE_END:
//checkShakeEnd(command: command)
break
case .COPY_FILE:
processCopyFile( command: command )
break
case .DELETE_FILE:
processDeleteFile( command: command )
break
case .REMOVE_EVENT_LISTENER:
checkRemoveEventListener(command: command)
break
case .OPEN_WITH_SAFARI:
checkOpenWithSafari( command: command )
break
case .USER_SETTINGS:
checkUserSettings( command: command )
break
case .USER_SETTINGS_STARTUP_HTML:
checkUserSettingsStartupHtml( command: command )
break
case .USER_SETTINGS_DELETE:
checkUserSettingsDelete( command: command )
break
case .USER_SETTINGS_SET:
checkUserSettingsSet( command: command )
break
case .USER_SETTINGS_GET:
checkUserSettingsGet( command: command )
break
case .SCREEN_EDGE_SWIPED:
checkScreenEdgeSwiped( command: command )
break
case .WEB_VIEW_RECIEVEMESSAGE:
checkWebViewRecieveMessage( command: command )
break
case .WEB_VIEW_POSTMESSAGE:
checkWebViewPostMessage( command: command )
break
case .USER_SETTINGS_LUNASETTINGS_HTML:
checkUserSettingsLunaSettingsHtml( command: command )
break
case .USER_NOTIFICATION:
checkUserNotification( command: command )
break
case .USER_NOTIFICATION_SHOWMSG:
checkUserNotificationShowMessage( command: command )
break
case .HTTP_POST:
checkHttpPost( command: command )
break
case .SYSTEM_SETTINGS:
checkSystemSettings( command: command )
break
case .SYSTEM_SETTINGS_SET:
checkSystemSettingsSet( command: command )
break
case .LOGACCESS:
checkLogAccess( command: command )
break
case .SF_SERVICESOS_INIT:
checkSFServiceSOSInit( command: command )
break
case .SF_SERVICESOS_START:
checkSFServiceSOSStart( command: command )
break
case .SF_SERVICESOS_STATECHANGE,
.SF_SERVICESOS_DIDSTOP,
.SF_SERVICESOS_DIDCONNECT:
break
case .SF_SERVICESOS_STOP:
checkSFServiceSOSStop( command: command )
break
case .SF_SERVICELIVEA_INIT:
checkSFServiceLiveAgentInit( command: command )
break
case .SF_SERVICELIVEA_START:
checkSFServiceLiveAgentStart( command: command )
break
case .SF_SERVICELIVEA_ADDPREOBJ:
checkSFServiceLiveAgentAddPrechatObject( command: command )
break
case .SF_SERVICELIVEA_CLEARPREOBJ:
checkSFServiceLiveAgentClearPrechatObject( command: command )
break
case .SF_SERVICELIVEA_STATECHANGE,
.SF_SERVICELIVEA_DIDEND:
break
case .SF_SERVICELIVEA_CHECKAVAIL:
checkSFServiceLiveAgentCheckAvailability( command: command )
break
case .HAPTIC_INIT:
processHapticFeedbackInit(command: command)
break
case .HAPTIC_FEEDBACK:
processHapticFeedbackExecute(command: command)
break
case .EINSTEIN_VISION_INIT:
proccessEinsteinAuth(command: command)
break
case .EINSTEIN_VISION_PREDICT:
proccessEinsteinVisionPredict(command: command)
break
case .BETA_SHOWEINSTEIN_AR:
processShowEinsteinARBeta(command: command)
break
case .OPEN_APP_SETTINGS:
processOpenAppSettings(command: command)
break
case .EINSTEIN_VISION_DATASETS:
proccessEinsteinVisionDatasets(command: command)
break
case .EINSTEIN_VISION_MODELS:
proccessEinsteinVisionModels(command: command)
break
default:
print( "[ERROR] Invalid Command Code: \(command.getCommandCode())" )
command.reject(errorMessage: "Invalid Command Code: \(command.getCommandCode())")
return
}
}
public class func queue( command: Command ) {
var dispatchQos = DispatchQoS.default
switch command.getPriority() {
case .CRITICAL:
DispatchQueue.global(qos: .userInteractive).async(execute: {
DispatchQueue.main.async {
_queue( command: command )
}
})
return
case .HIGH:
dispatchQos = DispatchQoS.userInteractive
break
case .NORMAL:
dispatchQos = DispatchQoS.userInitiated
break
case .LOW:
dispatchQos = DispatchQoS.utility
break
case .BACKGROUND:
dispatchQos = DispatchQoS.background
break
}
DispatchQueue.global(qos: dispatchQos.qosClass).async(execute: {
_queue( command: command )
})
}
public class func getWebViewManager( command: Command ) -> WebViewManager? {
if let wkmanager = WebViewManager.getManager(webview_id: command.getTargetWebViewID()) {
return wkmanager
} else {
command.reject( errorMessage: "[ERROR] No webview with ID of \(command.getTargetWebViewID()) found." )
}
return nil
}
public class func getQueue() -> [Command] {
return CommandProcessor.QUEUE
}
public class func getCommand( commandCode:CommandCode, ifFound:((Command)->()) ) {
for (_, command) in CommandProcessor.getQueue().enumerated() {
if command.getCommandCode() == commandCode {
ifFound( command )
}
}
}
public class func getCommand( commandID:Int, ifFound:((Command)->()) ) {
for (_, command) in CommandProcessor.getQueue().enumerated() {
if command.getCommandID() == commandID {
ifFound( command )
}
}
}
public class func remove( command: Command ) {
for (index, item) in CommandProcessor.QUEUE.enumerated() {
if( item === command) {
CommandProcessor.QUEUE.remove(at: index)
print( "[INFO][REMOVED] COMMAND \(command.getCommandID()) \(command.getCommandCode())" )
}
}
}
private class func processNewWebView( command: Command ) {
checkNewWebView( command: command, onSuccess: { result in
command.resolve( value: result )
}, onFail: { errorMessage in
command.reject( errorMessage: errorMessage )
})
}
private class func checkNewWebView( command: Command, onSuccess:((Int)->()), onFail:((String)->()) ) {
let parameter = (command.getParameter() as AnyObject).value(forKeyPath: "html_file")
var htmlFile:HtmlFile?
switch( parameter ) {
case is HtmlFile:
htmlFile = parameter as? HtmlFile
break
case is NSObject:
htmlFile = HtmlFile( htmlFile: parameter as! NSDictionary )
break
default:
break;
}
if htmlFile != nil {
let wkmanager = WebViewManager( htmlFile: htmlFile! )
if let properties = (command.getParameter() as AnyObject).value(forKeyPath: "property") as? NSDictionary {
wkmanager.getWebview().setProperty(property: properties)
}
onSuccess( wkmanager.getID() )
} else {
onFail( "Please set HTML File" )
}
}
private class func processLoadWebView( command: Command ) {
checkLoadWebView( command: command, onSuccess: { result in
command.resolve( value: result )
}, onFail: { errorMessage in
command.reject( errorMessage: errorMessage )
})
}
private class func checkLoadWebView( command: Command, onSuccess:@escaping ((Bool)->()), onFail:@escaping ((String)->()) ) {
if let wkmanager = CommandProcessor.getWebViewManager(command: command) {
wkmanager.load(onSuccess: {
onSuccess( true )
}, onFail: { (message) in
onFail( message )
})
}
}
private class func processAnimateWebView( command: Command ) {
checkAnimateWebView( command: command, onSuccess: { result in
command.resolve( value: result )
})
}
private class func checkAnimateWebView( command: Command, onSuccess:@escaping((Bool)->()) ) {
if let wkmanager = CommandProcessor.getWebViewManager(command: command) {
let webview = wkmanager.getWebview()
webview.setProperty(
property: (command.getParameter() as AnyObject).value(forKeyPath: "property") as! NSDictionary,
animation: (command.getParameter() as AnyObject).value(forKeyPath: "animation") as? NSDictionary,
onSuccess: { (finished) in
onSuccess( finished )
})
}
}
private class func checkWebViewEvent( command: Command) {
let _ = CommandProcessor.getWebViewManager(command: command)
}
public class func processWebViewOnload( wkmanager: WebViewManager ) {
getCommand(commandCode: CommandCode.WEB_VIEW_ONLOAD) { (command) in
if let webviewId = (command.getParameter() as AnyObject).value(forKeyPath: "webview_id") as? Int {
if webviewId == wkmanager.getID() {
command.update(value: true)
}
}
}
}
public class func processWebViewOnLoaded( wkmanager: WebViewManager, isSuccess:Bool, errorMessage: String?=nil ) {
getCommand(commandCode: CommandCode.WEB_VIEW_ONLOADED) { (command) in
if let webviewId = (command.getParameter() as AnyObject).value(forKeyPath: "webview_id") as? Int {
if webviewId == wkmanager.getID() {
let param = NSMutableDictionary()
param.setValue( isSuccess, forKey: "success")
if isSuccess {
command.update(value: param)
} else {
param.setValue( errorMessage, forKey: "message")
command.update(value: param)
}
}
}
}
}
public class func processWebViewOnLoading( wkmanager: WebViewManager, progress: Double ) {
getCommand(commandCode: CommandCode.WEB_VIEW_ONLOADING) { (command) in
if let webviewId = (command.getParameter() as AnyObject).value(forKeyPath: "webview_id") as? Int {
if webviewId == wkmanager.getID() {
command.update(value:progress)
}
}
}
}
private class func processCloseWebView( command: Command ) {
checkCloseWebView( command: command, onSuccess: { result in
command.resolve( value: result )
})
}
private class func checkCloseWebView( command: Command, onSuccess:@escaping ((Bool)->()) ) {
if let wkmanager = CommandProcessor.getWebViewManager(command: command) {
wkmanager.close(onSuccess: {
onSuccess( true )
})
}
}
private class func checkMediaPicker( command: Command ) {
var isDuplicated = false
getCommand(commandCode: CommandCode.MEDIA_PICKER) { (cmd) in
if cmd !== command {
isDuplicated = true
}
}
if !isDuplicated {
if let type = (command.getParameter() as AnyObject).value(forKeyPath: "from") as? String {
if let pickerType = PickerType(rawValue: type) {
let getPickerController = { (command: Command) -> () in
if !Photos.getMediaPickerController(view: Shared.shared.ViewController, type: pickerType) {
command.reject( errorMessage: "[ERROR] Photos.app is not available" )
}
}
let requestAuthorization = { (command: Command, isRequestAuth: Bool) -> () in
if( isRequestAuth ) {
PHPhotoLibrary.requestAuthorization({(newStatus) in
if newStatus == PHAuthorizationStatus.authorized {
getPickerController( command )
} else {
command.reject(errorMessage: "Not authorized to access Photos app")
}
})
} else {
getPickerController( command )
}
}
if pickerType == .PHOTO_LIBRARY {
requestAuthorization( command, true)
} else {
requestAuthorization( command, false)
}
}
}
} else {
command.reject( errorMessage: "[ERROR] The process is being used by another command" )
}
}
public class func processMediaPicker( media:[String : Any]?=nil, isAllowed:Bool?=true ) {
getCommand(commandCode: CommandCode.MEDIA_PICKER) { (command) in
if media != nil {
if let type = (command.getParameter() as AnyObject).value(forKeyPath: "from") as? String {
if let pickerType = PickerType(rawValue: type) {
switch pickerType {
case PickerType.PHOTO_LIBRARY:
if( isAllowed == true ) {
do {
if let imageURL = media![UIImagePickerControllerImageURL] as? URL, let phasset = media![UIImagePickerControllerPHAsset] as? PHAsset {
let imageFile = try ImageFile( fileId:File.generateID(), localIdentifier:phasset.localIdentifier, assetURL: imageURL)
command.resolve(value: imageFile.toDictionary(), raw: imageFile)
}
} catch let error as NSError {
command.reject(errorMessage: error.localizedDescription)
}
} else {
command.reject(errorMessage: "Not authorized to access Photos App")
}
break
case PickerType.CAMERA:
let exifData = NSMutableDictionary(dictionary: media![UIImagePickerControllerMediaMetadata] as! NSDictionary )
if let takenImage = media![UIImagePickerControllerOriginalImage] as? UIImage {
do {
let imageFile = try ImageFile( fileId:File.generateID(), uiimage:takenImage, exif:exifData, savePath:"CACHE" )
command.resolve(value: imageFile.toDictionary(), raw: imageFile)
} catch let error as NSError {
command.reject( errorMessage: error.localizedDescription )
}
command.resolve(value: true)
} else {
command.reject( errorMessage: "Cannot obtain photo" )
}
break
}
}
}
} else {
command.reject(errorMessage: "User cancelled operation")
}
}
}
private class func processGetImageFile( command: Command ) {
checkGetImageFile( command: command, onSuccess: { result, raw in
command.resolve( value: result, raw: raw )
}, onFail: { errorMessage in
command.reject( errorMessage: errorMessage )
})
}
private class func checkGetImageFile( command:Command, onSuccess:@escaping ((NSDictionary, ImageFile)->()), onFail:@escaping ((String)->()) ) {
let parameter = command.getParameter()
var imageFile:ImageFile?
switch( parameter ) {
case is ImageFile:
imageFile = parameter as? ImageFile
break
case is NSDictionary:
do {
imageFile = try ImageFile( file: parameter as! NSDictionary )
} catch _ as NSError {}
break
default:
break;
}
if imageFile != nil {
onSuccess(imageFile!.toDictionary(), imageFile!)
} else {
command.reject( errorMessage: "Failed to get Image" )
}
}
private class func processGetHTMLFile( command: Command ) {
checkGetHTMLFile( command: command, onSuccess: { result, raw in
command.resolve( value: result, raw: raw )
}, onFail: { errorMessage in
command.reject( errorMessage: errorMessage )
})
}
private class func checkGetHTMLFile( command:Command, onSuccess:@escaping ((NSDictionary, HtmlFile)->()), onFail:@escaping ((String)->()) ) {
do {
let htmlFile = try HtmlFile( file: command.getParameter() as! NSDictionary )
onSuccess(htmlFile.toDictionary(), htmlFile)
} catch let error as NSError {
onFail( error.localizedDescription )
}
}
private class func processGetFile( command: Command ) {
checkGetFile( command: command, onSuccess: { result, raw in
command.resolve( value: result, raw: raw )
}, onFail: { errorMessage in
command.reject( errorMessage: errorMessage )
})
}
private class func checkGetFile( command: Command, onSuccess:@escaping ((NSDictionary, File)->()), onFail:@escaping ((String)->()) ) {
do {
let file = try File( file: command.getParameter() as! NSObject )
onSuccess(file.toDictionary(), file)
} catch let error as NSError {
onFail( error.localizedDescription )
}
}
private class func processGetBase64Binary( command: Command ) {
checkGetBase64Binary( command: command, onSuccess: { result in
command.resolve( value: result )
}, onFail: { errorMessage in
command.reject( errorMessage: errorMessage )
})
}
private class func checkGetBase64Binary( command:Command, onSuccess:@escaping ((Bool)->()), onFail:@escaping ((String)->()) ) {
let parameter = command.getParameter()
var file:File?
switch( parameter ) {
case is File:
file = parameter as? File
break
case is NSDictionary:
if let object_type = (parameter as! NSDictionary).value(forKeyPath: "object_type") as? String {
switch( object_type ) {
case "ImageFile":
file = ImageFile( imageFile: parameter as! NSDictionary )
break
default:
file = File( filedict: parameter as! NSDictionary )
break
}
}
break
default:
break;
}
if file != nil {
file!.getBase64Value(onSuccess: { (base64) in
command.resolve(value: base64)
}, onFail: { (error) in
command.reject( errorMessage: error )
})
} else {
command.reject( errorMessage: "Failed to get Image" )
}
}
private class func processGetBase64Resized( command: Command ) {
checkGetBase64Resized( command: command, onSuccess: { result in
command.resolve( value: result )
}, onFail: { errorMessage in
command.reject( errorMessage: errorMessage )
})
}
private class func checkGetBase64Resized( command:Command, onSuccess:@escaping ((Bool)->()), onFail:@escaping ((String)->()) ) {
let imgParam = (command.getParameter() as? NSObject)?.value(forKeyPath: "image_file")
let option:NSObject = (command.getParameter() as? NSObject)?.value(forKeyPath: "option") as! NSObject
var imageFile:ImageFile?
switch( imgParam ) {
case is ImageFile:
imageFile = imgParam as? ImageFile
break
case is NSDictionary:
imageFile = ImageFile( imageFile: imgParam as! NSDictionary )
break
default:
break;
}
if imageFile != nil {
imageFile!.getBase64Resized( option:option, onSuccess: { (base64) in
command.resolve(value: base64)
}, onFail: { (error) in
command.reject( errorMessage: error )
})
} else {
command.reject( errorMessage: "Failed to get Image" )
}
}
private class func proccessChangeIcon( command: Command ) {
checkChangeIcon( command: command, onSuccess: { result in
command.resolve( value: result )
}, onFail: { errorMessage in
command.reject( errorMessage: errorMessage )
})
}
private class func checkChangeIcon( command: Command, onSuccess:@escaping ((Bool)->()), onFail:@escaping ((String)->()) ) {
if Shared.shared.UIApplication.supportsAlternateIcons {
if let name = (command.getParameter() as AnyObject).value(forKeyPath: "name") as? String {
var iconName:String?
if name != "default" {
iconName = name
}
Shared.shared.UIApplication.setAlternateIconName(iconName) { (error) in
if error != nil {
onFail( error!.localizedDescription )
} else {
onSuccess( true )
}
}
} else {
onFail( FileError.INVALID_PARAMETERS.localizedDescription )
}
} else {
onFail("Device doesn't support alternate icons")
}
}
private class func processMoveFile( command: Command ) {
checkMoveFile( command: command, onSuccess: { result in
command.resolve( value: result )
}, onFail: { errorMessage in
command.reject( errorMessage: errorMessage )
})
}
private class func checkMoveFile( command: Command, onSuccess:@escaping ((String)->()), onFail:@escaping ((String)->()) ) {
let parameter = (command.getParameter() as AnyObject).value(forKeyPath: "file")
var file:File?
switch( parameter ) {
case is File:
file = parameter as? File
break
case is NSDictionary:
do {
file = try File( file: parameter as! NSDictionary )
} catch let error as NSError {
onFail( error.localizedDescription )
return
}
break
default:
break;
}
if file != nil {
let toPath = (command.getParameter() as AnyObject).value(forKeyPath: "to") as? String
let isOverwrite = (command.getParameter() as AnyObject).value(forKeyPath: "isOverwrite") as? Bool
let _ = file!.move(relative: toPath, isOverwrite: isOverwrite, onSuccess: { (newPath) in
onSuccess( newPath.path )
}, onFail: { (error) in
onFail( error )
})
} else {
onFail( "Failed to initialize File" )
}
}
private class func processRenameFile( command: Command ) {
checkRenameFile( command: command, onSuccess: { result in
command.resolve( value: result )
}, onFail: { errorMessage in
command.reject( errorMessage: errorMessage )
})
}
private class func checkRenameFile( command: Command, onSuccess:@escaping ((String)->()), onFail:@escaping ((String)->()) ) {
let parameter = (command.getParameter() as AnyObject).value(forKeyPath: "file")
var file:File?
switch( parameter ) {
case is File:
file = parameter as? File
break
case is NSDictionary:
do {
file = try File( file: parameter as! NSDictionary )
} catch let error as NSError {
onFail( error.localizedDescription )
return
}
break
default:
break;
}
if file != nil {
if let fileName = (command.getParameter() as AnyObject).value(forKeyPath: "filename") as? String {
let _ = file!.rename(fileName: fileName, onSuccess: { (newPath) in
onSuccess( newPath.path )
}, onFail: { (error) in
onFail( error )
})
} else {
onFail( "filename parameter not existent" )
}
} else {
onFail( "Failed to initialize File" )
}
}
private class func processCopyFile( command: Command ) {
checkCopyFile( command: command, onSuccess: { result in
command.resolve( value: result )
}, onFail: { errorMessage in
command.reject( errorMessage: errorMessage )
})
}
private class func checkCopyFile( command: Command, onSuccess:@escaping ((String)->()), onFail:@escaping ((String)->()) ) {
let parameter = (command.getParameter() as AnyObject).value(forKeyPath: "file")
var file:File?
switch( parameter ) {
case is File:
file = parameter as? File
break
case is NSDictionary:
do {
file = try File( file: parameter as! NSDictionary )
} catch let error as NSError {
onFail( error.localizedDescription )
return
}
break
default:
break;
}
if file != nil {
if let to = (command.getParameter() as AnyObject).value(forKeyPath: "to") as? String {
let _ = file!.copy(relative: to, onSuccess: { (newPath) in
onSuccess( newPath.path )
}, onFail: { (error) in
onFail( error )
})
} else {
onFail( "filename parameter not existent" )
}
} else {
onFail( "Failed to initialize File" )
}
}
private class func processDeleteFile( command: Command ) {
checkDeleteFile( command: command, onSuccess: { result in
command.resolve( value: result )
}, onFail: { errorMessage in
command.reject( errorMessage: errorMessage )
})
}
private class func checkDeleteFile( command: Command, onSuccess:@escaping ((Bool)->()), onFail:@escaping ((String)->()) ) {
let parameter = (command.getParameter() as AnyObject).value(forKeyPath: "file")
var file:File?
switch( parameter ) {
case is File:
file = parameter as? File
break
case is NSDictionary:
do {
file = try File( file: parameter as! NSDictionary )
} catch let error as NSError {
onFail( error.localizedDescription )
return
}
break
default:
break;
}
if file != nil {
let _ = file!.delete( onSuccess: { result in
onSuccess( result )
}, onFail: { (error) in
onFail( error )
})
} else {
onFail( "Failed to initialize File" )
}
}
public class func processShakeBegin( ) {
getCommand(commandCode: .SHAKE_BEGIN) { (command) in
command.update(value: true)
}
}
public class func processShakeEnd( ) {
getCommand(commandCode: .SHAKE_END) { (command) in
command.update(value: true)
}
}
private class func checkRemoveEventListener( command: Command ) {
processRemoveEventListener( command: command, onSuccess: { result in
command.resolve( value: result )
}, onFail: { errorMessage in
command.reject( errorMessage: errorMessage )
})
}
private class func processRemoveEventListener( command: Command, onSuccess: ((Int)->()), onFail: ((String)->()) ) {
if let commandCodeVal = (command.getParameter() as! NSDictionary).value(forKey: "evt_command_code") as? Int {
if let evtCommandCode = CommandCode(rawValue: commandCodeVal) {
var count = 0
if let commandID = (command.getParameter() as! NSDictionary).value(forKey: "event_id") as? Int {
getCommand(commandID: commandID) { (evtcommand) in
if evtcommand.getSourceWebViewID() == command.getSourceWebViewID() {
evtcommand.resolve(value: true, raw: true)
count+=1
}
}
} else {
getCommand(commandCode: evtCommandCode) { (evtcommand) in
if evtcommand.getSourceWebViewID() == command.getSourceWebViewID() {
evtcommand.resolve(value: true, raw: true)
count+=1
}
}
}
if count > 0 {
onSuccess( count )
} else {
onFail( "No Event Available" )
}
} else {
onFail( "No Event Available" )
return
}
}
}
private class func checkOpenWithSafari( command: Command ) {
processOpenWithSafari( command: command, onSuccess: { result in
command.resolve( value: result )
}, onFail: { errorMessage in
command.reject( errorMessage: errorMessage )
})
}
private class func processOpenWithSafari( command: Command, onSuccess: @escaping ((Bool)->()), onFail: @escaping ((String)->()) ) {
let parameter = (command.getParameter() as AnyObject).value(forKeyPath: "file")
var htmlFile:HtmlFile?
switch( parameter ) {
case is HtmlFile:
htmlFile = parameter as? HtmlFile
break
case is NSObject:
htmlFile = HtmlFile( htmlFile: parameter as! NSDictionary )
break
default:
break;
}
if htmlFile != nil {
htmlFile!.openWithSafari(onSuccess: onSuccess, onFail: onFail)
} else {
onFail( "Please set HTML File" )
}
}
private class func checkUserSettings( command: Command ) {
procesUserSettings( command: command, onSuccess: { result in
command.resolve( value: result )
}, onFail: { errorMessage in
command.reject( errorMessage: errorMessage )
})
}
private class func procesUserSettings( command: Command, onSuccess: ((NSDictionary)->()), onFail: ((String)->()) ){
onSuccess( UserSettings.instance.getUserSettings() )
}
private class func checkUserSettingsStartupHtml( command: Command ) {
processUserSettingsStartupHtml( command: command, onSuccess: { result, raw in
command.resolve( value: result, raw: raw )
}, onFail: { errorMessage in
command.reject( errorMessage: errorMessage )
})
}
private class func processUserSettingsStartupHtml( command: Command, onSuccess: ((NSDictionary, HtmlFile)->()), onFail: ((String)->()) ){
if let htmlFile = UserSettings.instance.getStartupHtmlFile() {
onSuccess( htmlFile.toDictionary(), htmlFile )
} else {
onFail(FileError.INEXISTENT.localizedDescription)
}
}
private class func checkScreenEdgeSwiped( command: Command ) {
var found = false
var count = 0
let touchesRequired = (command.getParameter() as AnyObject).value(forKeyPath: "touchesRequired") as? Int
let direction = (command.getParameter() as AnyObject).value(forKeyPath: "direction") as? String
getCommand(commandCode: .SCREEN_EDGE_SWIPED) { (cmd) in
let cmdTouchesRequired = (cmd.getParameter() as AnyObject).value(forKeyPath: "touchesRequired") as? Int
let cmdDirection = (cmd.getParameter() as AnyObject).value(forKeyPath: "direction") as? String
if touchesRequired == cmdTouchesRequired && cmdDirection == direction {
count += 1
if count > 1 {
found = true
}
}
}
if !found {
let gestureRecognizer = UISwipeGestureRecognizer()
gestureRecognizer.numberOfTouchesRequired = touchesRequired!
switch touchesRequired! {
case 2:
gestureRecognizer.addTarget(Shared.shared.ViewController, action: #selector( Shared.shared.ViewController.screenEdgeSwipedTwoFingers(_:)))
break
case 3:
gestureRecognizer.addTarget(Shared.shared.ViewController, action: #selector( Shared.shared.ViewController.screenEdgeSwipedThreeFingers(_:)))
break
default:
gestureRecognizer.addTarget(Shared.shared.ViewController, action: #selector( Shared.shared.ViewController.screenEdgeSwipedOneFinger(_:)))
break
}
switch direction!.lowercased() {
case "left":
gestureRecognizer.direction = .left
break
case "up":
gestureRecognizer.direction = .up
break
case "down":
gestureRecognizer.direction = .down
break
default:
gestureRecognizer.direction = .right
break
}
Shared.shared.ViewController.view.addGestureRecognizer(gestureRecognizer)
}
}
public class func processSwipeGesture( swipeDirection: UISwipeGestureRecognizerDirection, touchesRequired:Int ) {
getCommand(commandCode: .SCREEN_EDGE_SWIPED) { (command) in
let ctouchesRequired = (command.getParameter() as AnyObject).value(forKeyPath: "touchesRequired") as? Int
let direction = ((command.getParameter() as AnyObject).value(forKeyPath: "direction") as! String).lowercased()
if( touchesRequired == ctouchesRequired ) {
switch swipeDirection {
case UISwipeGestureRecognizerDirection.left:
if direction == "left" {
command.update(value: true)
}
break
case UISwipeGestureRecognizerDirection.up:
if direction == "up" {
command.update(value: true)
}
break
case UISwipeGestureRecognizerDirection.down:
if direction == "down" {
command.update(value: true)
}
break
default:
if direction == "right" {
command.update(value: true)
}
break
}
}
}
}
}
| gpl-3.0 | e3b3fd21f6bf30d9ef7b34cc4a92c570 | 37.047035 | 169 | 0.55555 | 5.030418 | false | false | false | false |
ktmswzw/jwtSwiftDemoClient | Temp/Book.swift | 1 | 1259 | //
// Book.swift
// Temp
//
// Created by vincent on 4/2/16.
// Copyright © 2016 xecoder. All rights reserved.
//
import Foundation
import SAWaveToast
import ObjectMapper
import AlamofireObjectMapper
public class Book: Mappable
{
var id: String = "";
var content: String = "";
var title: String = "";
var publicDate: NSDate = NSDate();
init(inId:String, inContent:String, inTitle:String, inDate:NSDate)
{
id = inId
content = inContent
title = inTitle
publicDate = inDate
}
public required init?(_ map: Map){
}
//
public func mapping(map: Map) {
id <- map["id"]
content <- map["content"]
title <- map["title"]
publicDate <- map["publicDate"]
}
}
protocol MyAlertMsg{
func alertMsg(str: String ,view: UIViewController, second: NSTimeInterval)
}
extension MyAlertMsg{
func alertMsg(str: String, view: UIViewController, second: NSTimeInterval) {
let waveToast = SAWaveToast(text: str, font: .systemFontOfSize(16), fontColor: .darkGrayColor(), waveColor: .cyanColor(), duration: second)
view.presentViewController(waveToast, animated: false, completion: nil)
}
}
| apache-2.0 | fa9618f73fac1fba0b22ced85e7c7e90 | 20.322034 | 147 | 0.616057 | 4.165563 | false | false | false | false |
iCodesign/ICSTable | ICSTableDemo/ViewController.swift | 1 | 1562 | //
// ViewController.swift
// ICSTableDemo
//
// Created by LEI on 3/29/15.
// Copyright (c) 2015 TouchingApp. All rights reserved.
//
import UIKit
import ICSTable
class ViewController: WTFTable {
var section1: Section?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Add", style: .Plain, target: self, action: "add")
navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Add Row", style: .Plain, target: self, action: "addRow")
var tableManager = Manager()
var section = Section(identifier: "section0", header: "Header", footer: "Footer")
tableManager.addSection(section)
var row = Row(identifier: "basic", type: .Selector(RowSelectorAction.PushTo(BasicViewController.self)), title: "Basic")
section.addRow(row)
row = Row(identifier: "input", type: .Selector(RowSelectorAction.PushTo(InputViewController.self)), title: "Input")
section.addRow(row)
row = Row(identifier: "selector", type: .Selector(RowSelectorAction.PushTo(SelectorViewController.self)), title: "Selector")
section.addRow(row)
row = Row(identifier: "date", type: .Selector(RowSelectorAction.PushTo(DateViewController.self)), title: "Date")
section.addRow(row)
self.manager = tableManager
}
func add() {
}
func addRow() {
}
}
| mit | 86c496a062f5b204fe9db03bb1430641 | 31.541667 | 132 | 0.645967 | 4.291209 | false | false | false | false |
gaoleegin/DamaiPlayBusiness | DamaiPlayBusinessPhone/DamaiPlayBusinessPhone/Classes/Module/ProjectList/DMProjectListViewController.swift | 1 | 3273 | //
// DMProjectListViewController.swift
// DamaiPlayBusinessPhone
//
// Created by 高李军 on 15/11/2.
// Copyright © 2015年 DamaiPlayBusinessPhone. All rights reserved.
//
import UIKit
class DMProjectListViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 10
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("ProjectListCells", forIndexPath: indexPath)
// Configure the cell...
return cell
}
/*
// 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.
}
*/
}
| apache-2.0 | ccf40e3d6aad25e6e23d265ab3ab756f | 33.357895 | 157 | 0.691483 | 5.55102 | false | false | false | false |
GitHubOfJW/JavenKit | JavenKit/JWPhotoBrowserViewController/Controller/JWPhotoBrowserViewController.swift | 1 | 9600 | //
// JWPhotoBrowserViewController.swift
// JWCoreImageBrowser
//
// Created by 朱建伟 on 2016/11/28.
// Copyright © 2016年 zhujianwei. All rights reserved.
//
import UIKit
public class JWPhotoBrowserViewController: UICollectionViewController,UIViewControllerTransitioningDelegate{
let PBReuseIdentifier:String = "reuseIdentifier"
//如果是图片直接调用 不是则下载完成后调用
public typealias JWPhotoCompletionClosure = (UIImage?)->Void
//图片获取
public typealias JWPhotoHanlderClosure = ((Int,UIImageView,@escaping JWPhotoCompletionClosure) -> Void)
//返回对应的View
public typealias JWPhotoSourceViewClosure = (Int)->((UIView?,UIImage?))?
//数组
var photoSource:[JWPhotoBrowerItem] = [JWPhotoBrowerItem]()
//初始化
convenience public init(photoCount:Int,showIndex:Int,thumbnailClosure: @escaping JWPhotoHanlderClosure,bigImageClosure: @escaping JWPhotoHanlderClosure,sourceViewClosure:JWPhotoSourceViewClosure){
//1.初始化布局
let layout:UICollectionViewFlowLayout = UICollectionViewFlowLayout()
layout.scrollDirection = .horizontal
layout.itemSize = UIScreen.main.bounds.size
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = 0
self.init(collectionViewLayout:layout)
//2.创建
self.photoSource.removeAll()
for i:Int in 0..<photoCount
{
let item = JWPhotoBrowerItem()
item.index = i
item.thumbnailClosure = thumbnailClosure
item.bigImageClosure = bigImageClosure
if let source = sourceViewClosure(i){
if let sourceView = source.0{
let rect = sourceView.convert(sourceView.bounds, to: UIApplication.shared.keyWindow)
if rect.intersects(UIScreen.main.bounds){
item.sourceRect = rect
}
//展示页相同
if i == showIndex{
self.presentTransitioning.sourceView = sourceView
}
}
if let sourceImage = source.1{
//展示页相同
if i == showIndex{
self.presentTransitioning.sourceImage = sourceImage
}
}
}
self.photoSource.append(item)
}
self.collectionView?.isPagingEnabled = true
self.collectionView?.backgroundColor = UIColor.clear
collectionView?.reloadData()
IndexPromptLabel.frame = CGRect(x: 10, y: view.bounds.height - 50 , width:100, height: 40)
IndexPromptLabel.textAlignment = NSTextAlignment.center
IndexPromptLabel.layer.cornerRadius = 20
IndexPromptLabel.backgroundColor = UIColor.black
IndexPromptLabel.layer.masksToBounds = true
let m_attr:NSMutableAttributedString = NSMutableAttributedString(string:String(format:"%zd",showIndex < photoCount ? showIndex + 1 : 1), attributes: [NSFontAttributeName:UIFont.systemFont(ofSize: 30),NSForegroundColorAttributeName:UIColor.white])
self.lastAttributeString = NSAttributedString(string: String(format:" / %zd",photoCount), attributes: [NSFontAttributeName:UIFont.systemFont(ofSize: 15),NSForegroundColorAttributeName:UIColor.white])
m_attr.append(self.lastAttributeString!)
IndexPromptLabel.attributedText = m_attr
view.addSubview(IndexPromptLabel)
if showIndex < photoCount{
//滚动到指定的
self.collectionView?.scrollToItem(at:IndexPath(item: showIndex, section: 0), at: UICollectionViewScrollPosition.left, animated: false)
}
}
private var lastAttributeString:NSAttributedString?
var IndexPromptLabel:UILabel = UILabel()
var operationView:UIImageView = UIImageView()
override public func viewDidLoad() {
super.viewDidLoad()
self.collectionView!.register(JWPhotoBrowserCell.self, forCellWithReuseIdentifier: PBReuseIdentifier)
self.transitioningDelegate = self
IndexPromptLabel.isHidden = true
}
override public func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
override public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return photoSource.count
}
override public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
//1.获取cell
let cell:JWPhotoBrowserCell = collectionView.dequeueReusableCell(withReuseIdentifier: PBReuseIdentifier, for: indexPath) as! JWPhotoBrowserCell
//2.设置cell
cell.photoBrowserItem = photoSource[indexPath.item]
weak var weakSelf = self
cell.dismissClosure = {
(item,photoView)->Void in
weakSelf?.dismissTapTransitioning.sourceView = photoView
weakSelf?.dismissTapTransitioning.destinationFrame = item.sourceRect
weakSelf?.dismissTapTransitioning.desinationImage = item.bigImage ?? item.thumbnail
weakSelf?.dismiss(animated: true, completion: {
})
}
//3.返回
return cell
}
override public func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
//1.获取cell
let cell:JWPhotoBrowserCell = cell as! JWPhotoBrowserCell
//2.
cell.handler()
}
override public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
// print("选中了:\(indexPath)")
}
override public func scrollViewDidScroll(_ scrollView: UIScrollView) {
let page = scrollView.contentOffset.x / scrollView.bounds.width
let showIndex:Int = lroundf(Float(page))+1
let m_attr:NSMutableAttributedString = NSMutableAttributedString(string:String(format:"%zd",showIndex), attributes: [NSFontAttributeName:UIFont.systemFont(ofSize: 30),NSForegroundColorAttributeName:UIColor.white])
m_attr.append(self.lastAttributeString!)
IndexPromptLabel.attributedText = m_attr
}
override public func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
IndexPromptLabel.isHidden = false
self.IndexPromptLabel.tag = 0
}
override public func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
if IndexPromptLabel.tag == 0{
IndexPromptLabel.tag = 1
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1, execute:
{
if self.IndexPromptLabel.tag == 1{
UIView.animate(withDuration: 0.25, animations: {
self.IndexPromptLabel.isHidden = true
}, completion: {(finished)->Void in
self.IndexPromptLabel.tag = 1
})
}else{
self.IndexPromptLabel.layer.removeAllAnimations()
}
})
}
}
private override init(collectionViewLayout layout: UICollectionViewLayout) {
super.init(collectionViewLayout: layout)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
//上下滑动退出
var dismissTransitioning:JWPhotoDismissBrowserTransitioning = JWPhotoDismissBrowserTransitioning()
//点击后退出
var dismissTapTransitioning:JWPhotoTapDismissTransioning = JWPhotoTapDismissTransioning()
//弹出
var presentTransitioning:JWPhotoPresentBrowserTransitioning = JWPhotoPresentBrowserTransitioning()
public func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
if self.interactionTransitioning.isStart{
return dismissTransitioning
}else{
return dismissTapTransitioning
}
}
public func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return presentTransitioning
}
var interactionTransitioning:JWPhotoInteractiveTransitioning = JWPhotoInteractiveTransitioning()
public func interactionControllerForDismissal(using animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning?{
return self.interactionTransitioning.isStart ? self.interactionTransitioning : nil
}
override public func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
interactionTransitioning.addPopInteractiveTransition(browserViewController: self)
}
}
| mit | ce273f20493246236d1d35156295aad6 | 33.412409 | 254 | 0.628381 | 5.904195 | false | false | false | false |
antonio081014/LeetCode-CodeBase | Swift/add-two-numbers.swift | 2 | 1614 | /**
* Problem Link: https://leetcode.com/problems/add-two-numbers/
*
*
*
* Definition for singly-linked list.
* public class ListNode {
* public var val: Int
* public var next: ListNode?
* public init(_ val: Int) {
* self.val = val
* self.next = nil
* }
* }
*/
class Solution {
func addTwoNumbers(_ l1: ListNode?, _ l2: ListNode?) -> ListNode? {
var bit = 0
let head = ListNode(0)
var tail = head
var ll1 = l1
var ll2 = l2
while ll1 != nil || ll2 != nil || bit > 0{
var sum = bit
if let x = ll1 {
sum += x.val
ll1 = x.next
}
if let y = ll2 {
sum += y.val
ll2 = y.next
}
tail.next = ListNode(sum % 10)
bit = sum / 10
tail = tail.next!
}
return head.next
}
}
// Wed Mar 25 14:16:12 PDT 2020
class Solution {
///
/// - Complexity: O(max(L1, L2)), where L1 is the length of l1, L2 is the length of l2.
///
func addTwoNumbers(_ l1: ListNode?, _ l2: ListNode?) -> ListNode? {
let root = ListNode(0)
var parent: ListNode? = root
var ll1 = l1
var ll2 = l2
var sum = 0
while ll1 != nil || ll2 != nil || sum > 0 {
sum += ll1?.val ?? 0
sum += ll2?.val ?? 0
ll1 = ll1?.next
ll2 = ll2?.next
parent?.next = ListNode(sum % 10)
parent = parent?.next
sum /= 10
}
return root.next
}
}
| mit | 9d0a550227e7c92968e090dcd0f7de8e | 24.619048 | 91 | 0.449195 | 3.626966 | false | false | false | false |
honghaoz/UW-Quest-iOS | UW Quest/ThirdParty/ExSwift/String.swift | 2 | 10749 | //
// String.swift
// ExSwift
//
// Created by pNre on 03/06/14.
// Copyright (c) 2014 pNre. All rights reserved.
//
import Foundation
public extension String {
/**
String length
*/
var length: Int { return count(self) }
/**
self.capitalizedString shorthand
*/
var capitalized: String { return capitalizedString }
/**
Returns the substring in the given range
:param: range
:returns: Substring in range
*/
subscript (range: Range<Int>) -> String? {
if range.startIndex < 0 || range.endIndex > self.length {
return nil
}
let range = Range(start: advance(startIndex, range.startIndex), end: advance(startIndex, range.endIndex))
return self[range]
}
/**
Equivalent to at. Takes a list of indexes and returns an Array
containing the elements at the given indexes in self.
:param: firstIndex
:param: secondIndex
:param: restOfIndexes
:returns: Charaters at the specified indexes (converted to String)
*/
subscript (firstIndex: Int, secondIndex: Int, restOfIndexes: Int...) -> [String] {
return at([firstIndex, secondIndex] + restOfIndexes)
}
/**
Gets the character at the specified index as String.
If index is negative it is assumed to be relative to the end of the String.
:param: index Position of the character to get
:returns: Character as String or nil if the index is out of bounds
*/
subscript (index: Int) -> String? {
if let char = Array(self).get(index) {
return String(char)
}
return nil
}
/**
Takes a list of indexes and returns an Array containing the elements at the given indexes in self.
:param: indexes Positions of the elements to get
:returns: Array of characters (as String)
*/
func at (indexes: Int...) -> [String] {
return indexes.map { self[$0]! }
}
/**
Takes a list of indexes and returns an Array containing the elements at the given indexes in self.
:param: indexes Positions of the elements to get
:returns: Array of characters (as String)
*/
func at (indexes: [Int]) -> [String] {
return indexes.map { self[$0]! }
}
/**
Returns an array of strings, each of which is a substring of self formed by splitting it on separator.
:param: separator Character used to split the string
:returns: Array of substrings
*/
func explode (separator: Character) -> [String] {
return split(self) { (element: Character) -> Bool in
return element == separator
}
}
/**
Finds any match in self for pattern.
:param: pattern Pattern to match
:param: ignoreCase true for case insensitive matching
:returns: Matches found (as [NSTextCheckingResult])
*/
func matches (pattern: String, ignoreCase: Bool = false) -> [NSTextCheckingResult]? {
if let regex = ExSwift.regex(pattern, ignoreCase: ignoreCase) {
// Using map to prevent a possible bug in the compiler
return regex.matchesInString(self, options: nil, range: NSMakeRange(0, length)).map { $0 as! NSTextCheckingResult }
}
return nil
}
/**
Inserts a substring at the given index in self.
:param: index Where the new string is inserted
:param: string String to insert
:returns: String formed from self inserting string at index
*/
func insert (var index: Int, _ string: String) -> String {
// Edge cases, prepend and append
if index > length {
return self + string
} else if index < 0 {
return string + self
}
return self[0..<index]! + string + self[index..<length]!
}
/**
Strips whitespaces from the beginning of self.
:returns: Stripped string
*/
func ltrimmed () -> String {
return ltrimmed(NSCharacterSet.whitespaceAndNewlineCharacterSet())
}
/**
Strips the specified characters from the beginning of self.
:returns: Stripped string
*/
func ltrimmed (set: NSCharacterSet) -> String {
if let range = rangeOfCharacterFromSet(set.invertedSet) {
return self[range.startIndex..<endIndex]
}
return ""
}
/**
Strips whitespaces from the end of self.
:returns: Stripped string
*/
func rtrimmed () -> String {
return rtrimmed(NSCharacterSet.whitespaceAndNewlineCharacterSet())
}
/**
Strips the specified characters from the end of self.
:returns: Stripped string
*/
func rtrimmed (set: NSCharacterSet) -> String {
if let range = rangeOfCharacterFromSet(set.invertedSet, options: NSStringCompareOptions.BackwardsSearch) {
return self[startIndex..<range.endIndex]
}
return ""
}
/**
Strips whitespaces from both the beginning and the end of self.
:returns: Stripped string
*/
func trimmed () -> String {
return ltrimmed().rtrimmed()
}
/**
Costructs a string using random chars from a given set.
:param: length String length. If < 1, it's randomly selected in the range 0..16
:param: charset Chars to use in the random string
:returns: Random string
*/
static func random (var length len: Int = 0, charset: String = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789") -> String {
if len < 1 {
len = Int.random(max: 16)
}
var result = String()
let max = charset.length - 1
len.times {
result += charset[Int.random(min: 0, max: max)]!
}
return result
}
/**
Parses a string containing a double numerical value into an optional double if the string is a well formed number.
:returns: A double parsed from the string or nil if it cannot be parsed.
*/
func toDouble() -> Double? {
let pattern = "^[-+]?[0-9]*\\.?[0-9]+$"
if let regex = ExSwift.regex(pattern, ignoreCase: true) {
let text = self.trimmed()
let matches = regex.matchesInString(text, options: nil, range: NSMakeRange(0, count(text)))
if matches.isEmpty {
return nil
}
return (self as NSString).doubleValue
}
return nil
}
/**
Parses a string containing a float numerical value into an optional float if the string is a well formed number.
:returns: A float parsed from the string or nil if it cannot be parsed.
*/
func toFloat() -> Float? {
if let val = self.toDouble() {
return Float(val)
}
return nil
}
/**
Parses a string containing a non-negative integer value into an optional UInt if the string is a well formed number.
:returns: A UInt parsed from the string or nil if it cannot be parsed.
*/
func toUInt() -> UInt? {
if let val = self.trimmed().toInt() {
if val < 0 {
return nil
}
return UInt(val)
}
return nil
}
/**
Parses a string containing a boolean value (true or false) into an optional Bool if the string is a well formed.
:returns: A Bool parsed from the string or nil if it cannot be parsed as a boolean.
*/
func toBool() -> Bool? {
let text = self.trimmed().lowercaseString
if text == "true" || text == "false" || text == "yes" || text == "no" {
return (text as NSString).boolValue
}
return nil
}
/**
Parses a string containing a date into an optional NSDate if the string is a well formed.
The default format is yyyy-MM-dd, but can be overriden.
:returns: A NSDate parsed from the string or nil if it cannot be parsed as a date.
*/
func toDate(format : String? = "yyyy-MM-dd") -> NSDate? {
let text = self.trimmed().lowercaseString
var dateFmt = NSDateFormatter()
dateFmt.timeZone = NSTimeZone.defaultTimeZone()
if let fmt = format {
dateFmt.dateFormat = fmt
}
return dateFmt.dateFromString(text)
}
/**
Parses a string containing a date and time into an optional NSDate if the string is a well formed.
The default format is yyyy-MM-dd hh-mm-ss, but can be overriden.
:returns: A NSDate parsed from the string or nil if it cannot be parsed as a date.
*/
func toDateTime(format : String? = "yyyy-MM-dd hh-mm-ss") -> NSDate? {
return toDate(format: format)
}
}
/**
Repeats the string first n times
*/
public func * (first: String, n: Int) -> String {
var result = String()
n.times {
result += first
}
return result
}
// Pattern matching using a regular expression
public func =~ (string: String, pattern: String) -> Bool {
let regex = ExSwift.regex(pattern, ignoreCase: false)!
let matches = regex.numberOfMatchesInString(string, options: nil, range: NSMakeRange(0, string.length))
return matches > 0
}
// Pattern matching using a regular expression
public func =~ (string: String, regex: NSRegularExpression) -> Bool {
let matches = regex.numberOfMatchesInString(string, options: nil, range: NSMakeRange(0, string.length))
return matches > 0
}
// This version also allowes to specify case sentitivity
public func =~ (string: String, options: (pattern: String, ignoreCase: Bool)) -> Bool {
if let matches = ExSwift.regex(options.pattern, ignoreCase: options.ignoreCase)?.numberOfMatchesInString(string, options: nil, range: NSMakeRange(0, string.length)) {
return matches > 0
}
return false
}
// Match against all the alements in an array of String
public func =~ (strings: [String], pattern: String) -> Bool {
let regex = ExSwift.regex(pattern, ignoreCase: false)!
return strings.all { $0 =~ regex }
}
public func =~ (strings: [String], options: (pattern: String, ignoreCase: Bool)) -> Bool {
return strings.all { $0 =~ options }
}
// Match against any element in an array of String
public func |~ (strings: [String], pattern: String) -> Bool {
let regex = ExSwift.regex(pattern, ignoreCase: false)!
return strings.any { $0 =~ regex }
}
public func |~ (strings: [String], options: (pattern: String, ignoreCase: Bool)) -> Bool {
return strings.any { $0 =~ options }
}
| apache-2.0 | 61c5152f6283f6e761b52a582c9b9105 | 28.941504 | 170 | 0.603777 | 4.510701 | false | false | false | false |
HongliYu/firefox-ios | Client/Frontend/Browser/BrowserViewController/BrowserViewController+UIDropInteractionDelegate.swift | 5 | 1421 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Storage
@available(iOS 11.0, *)
extension BrowserViewController: UIDropInteractionDelegate {
func dropInteraction(_ interaction: UIDropInteraction, canHandle session: UIDropSession) -> Bool {
// Prevent tabs from being dragged and dropped into the address bar.
if let localDragSession = session.localDragSession, let item = localDragSession.items.first, let _ = item.localObject {
return false
}
return session.canLoadObjects(ofClass: URL.self)
}
func dropInteraction(_ interaction: UIDropInteraction, sessionDidUpdate session: UIDropSession) -> UIDropProposal {
return UIDropProposal(operation: .copy)
}
func dropInteraction(_ interaction: UIDropInteraction, performDrop session: UIDropSession) {
guard let tab = tabManager.selectedTab else { return }
UnifiedTelemetry.recordEvent(category: .action, method: .drop, object: .url, value: .browser)
_ = session.loadObjects(ofClass: URL.self) { urls in
guard let url = urls.first else {
return
}
self.finishEditingAndSubmit(url, visitType: VisitType.typed, forTab: tab)
}
}
}
| mpl-2.0 | bf9acd994d6041ce1badb47f710e6def | 38.472222 | 127 | 0.68684 | 4.539936 | false | false | false | false |
niunaruto/DeDaoAppSwift | DeDaoSwift/DeDaoSwift/Study/View/DDstudyDailyverseCell.swift | 1 | 4716 | //
// DDstudyDailyverseCell.swift
// DeDaoSwift
//
// Created by niuting on 2017/3/23.
// Copyright © 2017年 niuNaruto. All rights reserved.
//
import UIKit
class DDstudyDailyverseCell: DDBaseTableViewCell {
override func setCellsViewModel(_ model: Any?) {
if let modelT = model as? DDStudyDailyVerseDataModel {
weekLabel.text = modelT.week
dayLabel.text = modelT.day
referer_groupLabel.text = modelT.referer_group
referer_nameLabel.text = modelT.referer_name
fromLabel.text = modelT.from
contentLabel.text = modelT.content
}
}
lazy var weekLabel : UILabel = {
let tempLabel = UILabel()
tempLabel.textColor = UIColor.white
tempLabel.font = UIFont.systemFont(ofSize: 18)
return tempLabel
}()
lazy var dayLabel : UILabel = {
let tempLabel = UILabel()
tempLabel.textColor = UIColor.white
tempLabel.font = UIFont.systemFont(ofSize: 16)
return tempLabel
}()
lazy var referer_groupLabel : UILabel = {
let tempLabel = UILabel()
tempLabel.textColor = UIColor.white
tempLabel.font = UIFont.systemFont(ofSize: 13)
return tempLabel
}()
lazy var referer_nameLabel : UILabel = {
let tempLabel = UILabel()
tempLabel.textColor = UIColor.white
tempLabel.font = UIFont.systemFont(ofSize: 13)
return tempLabel
}()
lazy var fromLabel : UILabel = {
let tempLabel = UILabel()
tempLabel.textColor = UIColor.white
tempLabel.font = UIFont.systemFont(ofSize: 13)
return tempLabel
}()
lazy var contentLabel : UILabel = {
let tempLabel = UILabel()
tempLabel.textColor = UIColor.white
tempLabel.numberOfLines = 0
tempLabel.font = UIFont.systemFont(ofSize: 13)
return tempLabel
}()
override func setUI() {
let backContentView = UIView()
contentView.addSubview(backContentView)
backContentView.snp.makeConstraints { (make) in
make.left.equalToSuperview().offset(10)
make.top.equalToSuperview()
make.right.bottom.equalToSuperview().offset(-10)
}
backContentView.backgroundColor = UIColor.brown
let blodContentView = UIView()
blodContentView.layer.borderColor = UIColor.white.cgColor
blodContentView.layer.borderWidth = 1
blodContentView.layer.masksToBounds = true
blodContentView.backgroundColor = backContentView.backgroundColor
backContentView.addSubview(blodContentView)
blodContentView.snp.makeConstraints { (make) in
make.left.top.equalToSuperview().offset(10)
//make.top.equalToSuperview()
make.right.bottom.equalToSuperview().offset(-10)
}
blodContentView.addSubview(weekLabel)
blodContentView.addSubview(dayLabel)
blodContentView.addSubview(referer_groupLabel)
blodContentView.addSubview(referer_nameLabel)
blodContentView.addSubview(fromLabel)
blodContentView.addSubview(contentLabel)
let viewLine = UIView()
viewLine.backgroundColor = UIColor.white
blodContentView.addSubview(viewLine)
viewLine.snp.makeConstraints { (make) in
make.left.equalTo(weekLabel);
make.height.equalTo(1);
make.right.equalToSuperview().offset(-10)
make.top.equalTo(dayLabel.snp.bottom).offset(10)
}
weekLabel.snp.makeConstraints { (make) in
make.top.left.equalToSuperview().offset(10)
}
dayLabel.snp.makeConstraints { (make) in
make.left.equalTo(weekLabel)
make.top.equalTo(weekLabel.snp.bottom).offset(3)
}
contentLabel.snp.makeConstraints { (make) in
make.left.equalTo(weekLabel)
make.right.equalToSuperview().offset(-10)
make.top.equalTo(viewLine.snp.bottom).offset(10)
}
referer_groupLabel.snp.makeConstraints { (make) in
make.left.equalTo(weekLabel);
make.top.equalTo(contentLabel.snp.bottom).offset(10);
make.bottom.equalToSuperview().offset(-40);//临时代码
}
referer_nameLabel.snp.makeConstraints { (make) in
make.left.equalTo(referer_groupLabel.snp.right).offset(8);
make.centerY.equalTo(referer_groupLabel);
}
}
}
| mit | d4a40a9060d0c2425f9761b7e9a52851 | 30.366667 | 73 | 0.603613 | 4.658416 | false | false | false | false |
davejlong/ResponseDetective | ResponseDetective Tests/Source Files/XMLInterceptorSpec.swift | 1 | 2077 | //
// XMLInterceptorSpec.swift
//
// Copyright (c) 2015 Netguru Sp. z o.o. All rights reserved.
//
import Foundation
import Nimble
import ResponseDetective
import Quick
class XMLInterceptorSpec: QuickSpec {
override func spec() {
describe("XMLInterceptor") {
var stream: BufferOutputStream!
var sut: XMLInterceptor!
let uglyFixtureString = "<foo>\t<bar baz=\"qux\">lorem ipsum</bar\n></foo>"
let uglyFixtureData = uglyFixtureString.dataUsingEncoding(NSUTF8StringEncoding)!
let prettyFixtureString = "<?xml version=\"1.0\"?>\n<foo>\n <bar baz=\"qux\">lorem ipsum</bar>\n</foo>"
let fixtureRequest = RequestRepresentation( {
let mutableRequest = NSMutableURLRequest()
mutableRequest.URL = NSURL(string: "https://httpbin.org/post")!
mutableRequest.HTTPMethod = "POST"
mutableRequest.setValue("application/xml", forHTTPHeaderField: "Content-Type")
mutableRequest.HTTPBody = uglyFixtureData
return mutableRequest
}())!
let fixtureResponse = ResponseRepresentation(NSHTTPURLResponse(
URL: NSURL(string: "https://httpbin.org/post")!,
statusCode: 200,
HTTPVersion: "HTTP/1.1",
headerFields: [
"Content-Type": "text/xml"
]
)!, uglyFixtureData)!
beforeEach {
stream = BufferOutputStream()
sut = XMLInterceptor(outputStream: stream)
}
it("should be able to intercept application/xml requests") {
expect(sut.canInterceptRequest(fixtureRequest)).to(beTrue())
}
it("should be able to intercept text/xml responses") {
expect(sut.canInterceptResponse(fixtureResponse)).to(beTrue())
}
it("should output a correct string when intercepting a application/xml request") {
sut.interceptRequest(fixtureRequest)
expect(stream.buffer).toEventually(contain(prettyFixtureString), timeout: 2, pollInterval: 0.5)
}
it("should output a correct string when intercepting a text/xml response") {
sut.interceptResponse(fixtureResponse)
expect(stream.buffer).toEventually(contain(prettyFixtureString), timeout: 2, pollInterval: 0.5)
}
}
}
}
| mit | f038d20a918d1856e6a9c38b56ef005f | 28.671429 | 107 | 0.711122 | 3.867784 | false | false | false | false |
apple/swift-nio | Sources/NIOCore/Codec.swift | 1 | 36169 | //===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2017-2018 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
/// State of the current decoding process.
public enum DecodingState: Sendable {
/// Continue decoding.
case `continue`
/// Stop decoding until more data is ready to be processed.
case needMoreData
}
/// Common errors thrown by `ByteToMessageDecoder`s.
public enum ByteToMessageDecoderError: Error {
/// More data has been received by a `ByteToMessageHandler` despite the fact that an error has previously been
/// emitted. The associated `Error` is the error previously emitted and the `ByteBuffer` is the extra data that has
/// been received. The common cause for this error to be emitted is the user not having torn down the `Channel`
/// after previously an `Error` has been sent through the pipeline using `fireErrorCaught`.
case dataReceivedInErrorState(Error, ByteBuffer)
/// This error can be thrown by `ByteToMessageDecoder`s if there was unexpectedly some left-over data when the
/// `ByteToMessageDecoder` was removed from the pipeline or the `Channel` was closed.
case leftoverDataWhenDone(ByteBuffer)
}
extension ByteToMessageDecoderError {
// TODO: For NIO 3, make this an enum case (or whatever best way for Errors we have come up with).
/// This error can be thrown by `ByteToMessageDecoder`s if the incoming payload is larger than the max specified.
public struct PayloadTooLargeError: Error {
public init() {}
}
}
/// `ByteToMessageDecoder`s decode bytes in a stream-like fashion from `ByteBuffer` to another message type.
///
/// ### Purpose
///
/// A `ByteToMessageDecoder` provides a simplified API for handling streams of incoming data that can be broken
/// up into messages. This API boils down to two methods: `decode`, and `decodeLast`. These two methods, when
/// implemented, will be used by a `ByteToMessageHandler` paired with a `ByteToMessageDecoder` to decode the
/// incoming byte stream into a sequence of messages.
///
/// The reason this helper exists is to smooth away some of the boilerplate and edge case handling code that
/// is often necessary when implementing parsers in a SwiftNIO `ChannelPipeline`. A `ByteToMessageDecoder`
/// never needs to worry about how inbound bytes will be buffered, as `ByteToMessageHandler` deals with that
/// automatically. A `ByteToMessageDecoder` also never needs to worry about memory exclusivity violations
/// that can occur when re-entrant `ChannelPipeline` operations occur, as `ByteToMessageHandler` will deal with
/// those as well.
///
/// ### Implementing ByteToMessageDecoder
///
/// A type that implements `ByteToMessageDecoder` may implement two methods: decode and decodeLast. Implementations
/// must implement decode: if they do not implement decodeLast, a default implementation will be used that
/// simply calls decode.
///
/// `decode` is the main decoding method, and is the one that will be called most often. `decode` is invoked
/// whenever data is received by the wrapping `ByteToMessageHandler`. It is invoked with a `ByteBuffer` containing
/// all the received data (including any data previously buffered), as well as a `ChannelHandlerContext` that can be
/// used in the `decode` function.
///
/// `decode` is called in a loop by the `ByteToMessageHandler`. This loop continues until one of two cases occurs:
///
/// 1. The input `ByteBuffer` has no more readable bytes (i.e. `.readableBytes == 0`); OR
/// 2. The `decode` method returns `.needMoreData`.
///
/// The reason this method is invoked in a loop is to ensure that the stream-like properties of inbound data are
/// respected. It is entirely possible for `ByteToMessageDecoder` to receive either fewer bytes than a single message,
/// or multiple messages in one go. Rather than have the `ByteToMessageDecoder` handle all of the complexity of this,
/// the logic can be boiled down to a single choice: has the `ByteToMessageDecoder` been able to move the state forward
/// or not? If it has, rather than containing an internal loop it may simply return `.continue` in order to request that
/// `decode` be invoked again immediately. If it has not, it can return `.needMoreData` to ask to be left alone until more
/// data has been returned from the network.
///
/// Essentially, if the next parsing step could not be taken because there wasn't enough data available, return `.needMoreData`.
/// Otherwise, return `.continue`. This will allow a `ByteToMessageDecoder` implementation to ignore the awkward way data
/// arrives from the network, and to just treat it as a series of `decode` calls.
///
/// `decodeLast` is a cousin of `decode`. It is also called in a loop, but unlike with `decode` this loop will only ever
/// occur once: when the `ChannelHandlerContext` belonging to this `ByteToMessageDecoder` is about to become invalidated.
/// This invalidation happens in two situations: when EOF is received from the network, or when the `ByteToMessageDecoder`
/// is being removed from the `ChannelPipeline`. The distinction between these two states is captured by the value of
/// `seenEOF`.
///
/// In this condition, the `ByteToMessageDecoder` must now produce any final messages it can with the bytes it has
/// available. In protocols where EOF is used as a message delimiter, having `decodeLast` called with `seenEOF == true`
/// may produce further messages. In other cases, `decodeLast` may choose to deliver any buffered bytes as "leftovers",
/// either in error messages or via `channelRead`. This can occur if, for example, a protocol upgrade is occurring.
///
/// As with `decode`, `decodeLast` is invoked in a loop. This allows the same simplification as `decode` allows: when
/// a message is completely parsed, the `decodeLast` function can return `.continue` and be re-invoked from the top,
/// rather than containing an internal loop.
///
/// Note that the value of `seenEOF` may change between calls to `decodeLast` in some rare situations.
///
/// ### Implementers Notes
///
/// /// `ByteToMessageHandler` will turn your `ByteToMessageDecoder` into a `ChannelInboundHandler`. `ByteToMessageHandler`
/// also solves a couple of tricky issues for you. Most importantly, in a `ByteToMessageDecoder` you do _not_ need to
/// worry about re-entrancy. Your code owns the passed-in `ByteBuffer` for the duration of the `decode`/`decodeLast` call and
/// can modify it at will.
///
/// If a custom frame decoder is required, then one needs to be careful when implementing
/// one with `ByteToMessageDecoder`. Ensure there are enough bytes in the buffer for a
/// complete frame by checking `buffer.readableBytes`. If there are not enough bytes
/// for a complete frame, return without modifying the reader index to allow more bytes to arrive.
///
/// To check for complete frames without modifying the reader index, use methods like `buffer.getInteger`.
/// You _MUST_ use the reader index when using methods like `buffer.getInteger`.
/// For example calling `buffer.getInteger(at: 0)` is assuming the frame starts at the beginning of the buffer, which
/// is not always the case. Use `buffer.getInteger(at: buffer.readerIndex)` instead.
///
/// If you move the reader index forward, either manually or by using one of `buffer.read*` methods, you must ensure
/// that you no longer need to see those bytes again as they will not be returned to you the next time `decode` is
/// called. If you still need those bytes to come back, consider taking a local copy of buffer inside the function to
/// perform your read operations on.
///
/// The `ByteBuffer` passed in as `buffer` is a slice of a larger buffer owned by the `ByteToMessageDecoder`
/// implementation. Some aspects of this buffer are preserved across calls to `decode`, meaning that any changes to
/// those properties you make in your `decode` method will be reflected in the next call to decode. In particular,
/// moving the reader index forward persists across calls. When your method returns, if the reader index has advanced,
/// those bytes are considered "consumed" and will not be available in future calls to `decode`.
/// Please note, however, that the numerical value of the `readerIndex` itself is not preserved, and may not be the same
/// from one call to the next. Please do not rely on this numerical value: if you need
/// to recall where a byte is relative to the `readerIndex`, use an offset rather than an absolute value.
///
/// ### Using ByteToMessageDecoder
///
/// To add a `ByteToMessageDecoder` to the `ChannelPipeline` use
///
/// channel.pipeline.addHandler(ByteToMessageHandler(MyByteToMessageDecoder()))
///
public protocol ByteToMessageDecoder {
/// The type of the messages this `ByteToMessageDecoder` decodes to.
associatedtype InboundOut
/// Decode from a `ByteBuffer`.
///
/// This method will be called in a loop until either the input `ByteBuffer` has nothing to read left or
/// `DecodingState.needMoreData` is returned. If `DecodingState.continue` is returned and the `ByteBuffer`
/// contains more readable bytes, this method will immediately be invoked again, unless `decodeLast` needs
/// to be invoked instead.
///
/// - parameters:
/// - context: The `ChannelHandlerContext` which this `ByteToMessageDecoder` belongs to.
/// - buffer: The `ByteBuffer` from which we decode.
/// - returns: `DecodingState.continue` if we should continue calling this method or `DecodingState.needMoreData` if it should be called
/// again once more data is present in the `ByteBuffer`.
mutating func decode(context: ChannelHandlerContext, buffer: inout ByteBuffer) throws -> DecodingState
/// Decode from a `ByteBuffer` when no more data is incoming and the `ByteToMessageDecoder` is about to leave
/// the pipeline.
///
/// This method is called in a loop only once, when the `ChannelHandlerContext` goes inactive (i.e. when `channelInactive` is fired or
/// the `ByteToMessageDecoder` is removed from the pipeline).
///
/// Like with `decode`, this method will be called in a loop until either `DecodingState.needMoreData` is returned from the method
/// or until the input `ByteBuffer` has no more readable bytes. If `DecodingState.continue` is returned and the `ByteBuffer`
/// contains more readable bytes, this method will immediately be invoked again.
///
/// - parameters:
/// - context: The `ChannelHandlerContext` which this `ByteToMessageDecoder` belongs to.
/// - buffer: The `ByteBuffer` from which we decode.
/// - seenEOF: `true` if EOF has been seen. Usually if this is `false` the handler has been removed.
/// - returns: `DecodingState.continue` if we should continue calling this method or `DecodingState.needMoreData` if it should be called
/// again when more data is present in the `ByteBuffer`.
mutating func decodeLast(context: ChannelHandlerContext, buffer: inout ByteBuffer, seenEOF: Bool) throws -> DecodingState
/// Called once this `ByteToMessageDecoder` is removed from the `ChannelPipeline`.
///
/// - parameters:
/// - context: The `ChannelHandlerContext` which this `ByteToMessageDecoder` belongs to.
mutating func decoderRemoved(context: ChannelHandlerContext)
/// Called when this `ByteToMessageDecoder` is added to the `ChannelPipeline`.
///
/// - parameters:
/// - context: The `ChannelHandlerContext` which this `ByteToMessageDecoder` belongs to.
mutating func decoderAdded(context: ChannelHandlerContext)
/// Determine if the read bytes in the given `ByteBuffer` should be reclaimed and their associated memory freed.
/// Be aware that reclaiming memory may involve memory copies and so is not free.
///
/// - parameters:
/// - buffer: The `ByteBuffer` to check
/// - return: `true` if memory should be reclaimed, `false` otherwise.
mutating func shouldReclaimBytes(buffer: ByteBuffer) -> Bool
}
/// Some `ByteToMessageDecoder`s need to observe `write`s (which are outbound events). `ByteToMessageDecoder`s which
/// implement the `WriteObservingByteToMessageDecoder` protocol will be notified about every outbound write.
///
/// `WriteObservingByteToMessageDecoder` may only observe a `write` and must not try to transform or block it in any
/// way. After the `write` method returns the `write` will be forwarded to the next outbound handler.
public protocol WriteObservingByteToMessageDecoder: ByteToMessageDecoder {
/// The type of `write`s.
associatedtype OutboundIn
/// `write` is called for every incoming `write` incoming to the corresponding `ByteToMessageHandler`.
///
/// - parameters:
/// - data: The data that was written.
mutating func write(data: OutboundIn)
}
extension ByteToMessageDecoder {
public mutating func decoderRemoved(context: ChannelHandlerContext) {
}
public mutating func decoderAdded(context: ChannelHandlerContext) {
}
/// Default implementation to detect once bytes should be reclaimed.
public func shouldReclaimBytes(buffer: ByteBuffer) -> Bool {
// We want to reclaim in the following cases:
//
// 1. If there is at least 2kB of memory to reclaim
// 2. If the buffer is more than 50% reclaimable memory and is at least
// 1kB in size.
if buffer.readerIndex >= 2048 {
return true
}
return buffer.storageCapacity > 1024 && (buffer.storageCapacity - buffer.readerIndex) < buffer.readerIndex
}
public func wrapInboundOut(_ value: InboundOut) -> NIOAny {
return NIOAny(value)
}
public mutating func decodeLast(context: ChannelHandlerContext, buffer: inout ByteBuffer, seenEOF: Bool) throws -> DecodingState {
while try self.decode(context: context, buffer: &buffer) == .continue {}
return .needMoreData
}
}
private struct B2MDBuffer {
/// `B2MDBuffer`'s internal state, either we're already processing a buffer or we're ready to.
private enum State {
case processingInProgress
case ready
}
/// Can we produce a buffer to be processed right now or not?
enum BufferAvailability {
/// No, because no bytes available
case nothingAvailable
/// No, because we're already processing one
case bufferAlreadyBeingProcessed
/// Yes please, here we go.
case available(ByteBuffer)
}
/// Result of a try to process a buffer.
enum BufferProcessingResult {
/// Could not process a buffer because we are already processing one on the same call stack.
case cannotProcessReentrantly
/// Yes, we did process some.
case didProcess(DecodingState)
}
private var state: State = .ready
private var buffers: CircularBuffer<ByteBuffer> = CircularBuffer(initialCapacity: 4)
private let emptyByteBuffer: ByteBuffer
init(emptyByteBuffer: ByteBuffer) {
assert(emptyByteBuffer.readableBytes == 0)
self.emptyByteBuffer = emptyByteBuffer
}
}
// MARK: B2MDBuffer Main API
extension B2MDBuffer {
/// Start processing some bytes if possible, if we receive a returned buffer (through `.available(ByteBuffer)`)
/// we _must_ indicate the processing has finished by calling `finishProcessing`.
mutating func startProcessing(allowEmptyBuffer: Bool) -> BufferAvailability {
switch self.state {
case .processingInProgress:
return .bufferAlreadyBeingProcessed
case .ready where self.buffers.count > 0:
var buffer = self.buffers.removeFirst()
buffer.writeBuffers(self.buffers)
self.buffers.removeAll(keepingCapacity: self.buffers.capacity < 16) // don't grow too much
if buffer.readableBytes > 0 || allowEmptyBuffer {
self.state = .processingInProgress
return .available(buffer)
} else {
return .nothingAvailable
}
case .ready:
assert(self.buffers.isEmpty)
if allowEmptyBuffer {
self.state = .processingInProgress
return .available(self.emptyByteBuffer)
}
return .nothingAvailable
}
}
mutating func finishProcessing(remainder buffer: inout ByteBuffer) -> Void {
assert(self.state == .processingInProgress)
self.state = .ready
if buffer.readableBytes == 0 && self.buffers.isEmpty {
// fast path, no bytes left and no other buffers, just return
return
}
if buffer.readableBytes > 0 {
self.buffers.prepend(buffer)
} else {
buffer.discardReadBytes()
buffer.writeBuffers(self.buffers)
self.buffers.removeAll(keepingCapacity: self.buffers.capacity < 16) // don't grow too much
self.buffers.append(buffer)
}
}
mutating func append(buffer: ByteBuffer) {
if buffer.readableBytes > 0 {
self.buffers.append(buffer)
}
}
}
// MARK: B2MDBuffer Helpers
private extension ByteBuffer {
mutating func writeBuffers(_ buffers: CircularBuffer<ByteBuffer>) {
guard buffers.count > 0 else {
return
}
var requiredCapacity: Int = self.writerIndex
for buffer in buffers {
requiredCapacity += buffer.readableBytes
}
self.reserveCapacity(requiredCapacity)
for var buffer in buffers {
self.writeBuffer(&buffer)
}
}
}
private extension B2MDBuffer {
func _testOnlyOneBuffer() -> ByteBuffer? {
switch self.buffers.count {
case 0:
return nil
case 1:
return self.buffers.first
default:
let firstIndex = self.buffers.startIndex
var firstBuffer = self.buffers[firstIndex]
for var buffer in self.buffers[self.buffers.index(after: firstIndex)...] {
firstBuffer.writeBuffer(&buffer)
}
return firstBuffer
}
}
}
/// A handler which turns a given `ByteToMessageDecoder` into a `ChannelInboundHandler` that can then be added to a
/// `ChannelPipeline`.
///
/// Most importantly, `ByteToMessageHandler` handles the tricky buffer management for you and flattens out all
/// re-entrancy on `channelRead` that may happen in the `ChannelPipeline`.
public final class ByteToMessageHandler<Decoder: ByteToMessageDecoder> {
public typealias InboundIn = ByteBuffer
public typealias InboundOut = Decoder.InboundOut
private enum DecodeMode {
/// This is a usual decode, ie. not the last chunk
case normal
/// Last chunk
case last
}
private enum RemovalState {
/// Not added to any `ChannelPipeline` yet.
case notAddedToPipeline
/// No one tried to remove this handler.
case notBeingRemoved
/// The user-triggered removal has been started but isn't complete yet. This state will not be entered if the
/// removal is triggered by Channel teardown.
case removalStarted
/// The user-triggered removal is complete. This state will not be entered if the removal is triggered by
/// Channel teardown.
case removalCompleted
/// This handler has been removed from the pipeline.
case handlerRemovedCalled
}
private enum State {
case active
case leftoversNeedProcessing
case done
case error(Error)
var isError: Bool {
switch self {
case .active, .leftoversNeedProcessing, .done:
return false
case .error:
return true
}
}
var isFinalState: Bool {
switch self {
case .active, .leftoversNeedProcessing:
return false
case .done, .error:
return true
}
}
var isActive: Bool {
switch self {
case .done, .error, .leftoversNeedProcessing:
return false
case .active:
return true
}
}
var isLeftoversNeedProcessing: Bool {
switch self {
case .done, .error, .active:
return false
case .leftoversNeedProcessing:
return true
}
}
}
internal private(set) var decoder: Decoder? // only `nil` if we're already decoding (ie. we're re-entered)
private let maximumBufferSize: Int?
private var queuedWrites = CircularBuffer<NIOAny>(initialCapacity: 1) // queues writes received whilst we're already decoding (re-entrant write)
private var state: State = .active {
willSet {
assert(!self.state.isFinalState, "illegal state on state set: \(self.state)") // we can never leave final states
}
}
private var removalState: RemovalState = .notAddedToPipeline
// sadly to construct a B2MDBuffer we need an empty ByteBuffer which we can only get from the allocator, so IUO.
private var buffer: B2MDBuffer!
private var seenEOF: Bool = false
private var selfAsCanDequeueWrites: CanDequeueWrites? = nil
/// @see: ByteToMessageHandler.init(_:maximumBufferSize)
public convenience init(_ decoder: Decoder) {
self.init(decoder, maximumBufferSize: nil)
}
/// Initialize a `ByteToMessageHandler`.
///
/// - parameters:
/// - decoder: The `ByteToMessageDecoder` to decode the bytes into message.
/// - maximumBufferSize: The maximum number of bytes to aggregate in-memory.
public init(_ decoder: Decoder, maximumBufferSize: Int? = nil) {
self.decoder = decoder
self.maximumBufferSize = maximumBufferSize
}
deinit {
if self.removalState != .notAddedToPipeline {
// we have been added to the pipeline, if not, we don't need to check our state.
assert(self.removalState == .handlerRemovedCalled,
"illegal state in deinit: removalState = \(self.removalState)")
assert(self.state.isFinalState, "illegal state in deinit: state = \(self.state)")
}
}
}
#if swift(>=5.7)
@available(*, unavailable)
extension ByteToMessageHandler: Sendable {}
#endif
// MARK: ByteToMessageHandler: Test Helpers
extension ByteToMessageHandler {
internal var cumulationBuffer: ByteBuffer? {
return self.buffer._testOnlyOneBuffer()
}
}
private protocol CanDequeueWrites {
func dequeueWrites()
}
extension ByteToMessageHandler: CanDequeueWrites where Decoder: WriteObservingByteToMessageDecoder {
fileprivate func dequeueWrites() {
while self.queuedWrites.count > 0 {
// self.decoder can't be `nil`, this is only allowed to be called when we're not already on the stack
self.decoder!.write(data: self.unwrapOutboundIn(self.queuedWrites.removeFirst()))
}
}
}
// MARK: ByteToMessageHandler's Main API
extension ByteToMessageHandler {
@inline(__always) // allocations otherwise (reconsider with Swift 5.1)
private func withNextBuffer(allowEmptyBuffer: Bool, _ body: (inout Decoder, inout ByteBuffer) throws -> DecodingState) rethrows -> B2MDBuffer.BufferProcessingResult {
switch self.buffer.startProcessing(allowEmptyBuffer: allowEmptyBuffer) {
case .bufferAlreadyBeingProcessed:
return .cannotProcessReentrantly
case .nothingAvailable:
return .didProcess(.needMoreData)
case .available(var buffer):
var possiblyReclaimBytes = false
var decoder: Decoder? = nil
swap(&decoder, &self.decoder)
assert(decoder != nil) // self.decoder only `nil` if we're being re-entered, but .available means we're not
defer {
swap(&decoder, &self.decoder)
if buffer.readableBytes > 0 && possiblyReclaimBytes {
// we asserted above that the decoder we just swapped back in was non-nil so now `self.decoder` must
// be non-nil.
if self.decoder!.shouldReclaimBytes(buffer: buffer) {
buffer.discardReadBytes()
}
}
self.buffer.finishProcessing(remainder: &buffer)
}
let decodeResult = try body(&decoder!, &buffer)
// If we .continue, there's no point in trying to reclaim bytes because we'll loop again. If we need more
// data on the other hand, we should try to reclaim some of those bytes.
possiblyReclaimBytes = decodeResult == .needMoreData
return .didProcess(decodeResult)
}
}
private func processLeftovers(context: ChannelHandlerContext) {
guard self.state.isActive else {
// we are processing or have already processed the leftovers
return
}
do {
switch try self.decodeLoop(context: context, decodeMode: .last) {
case .didProcess:
self.state = .done
case .cannotProcessReentrantly:
self.state = .leftoversNeedProcessing
}
} catch {
self.state = .error(error)
context.fireErrorCaught(error)
}
}
private func tryDecodeWrites() {
if self.queuedWrites.count > 0 {
// this must succeed because unless we implement `CanDequeueWrites`, `queuedWrites` must always be empty.
self.selfAsCanDequeueWrites!.dequeueWrites()
}
}
private func decodeLoop(context: ChannelHandlerContext, decodeMode: DecodeMode) throws -> B2MDBuffer.BufferProcessingResult {
assert(!self.state.isError)
var allowEmptyBuffer = decodeMode == .last
while (self.state.isActive && self.removalState == .notBeingRemoved) || decodeMode == .last {
let result = try self.withNextBuffer(allowEmptyBuffer: allowEmptyBuffer) { decoder, buffer in
let decoderResult: DecodingState
if decodeMode == .normal {
assert(self.state.isActive, "illegal state for normal decode: \(self.state)")
decoderResult = try decoder.decode(context: context, buffer: &buffer)
} else {
allowEmptyBuffer = false
decoderResult = try decoder.decodeLast(context: context, buffer: &buffer, seenEOF: self.seenEOF)
}
if decoderResult == .needMoreData, let maximumBufferSize = self.maximumBufferSize, buffer.readableBytes > maximumBufferSize {
throw ByteToMessageDecoderError.PayloadTooLargeError()
}
return decoderResult
}
switch result {
case .didProcess(.continue):
self.tryDecodeWrites()
continue
case .didProcess(.needMoreData):
if self.queuedWrites.count > 0 {
self.tryDecodeWrites()
continue // we might have received more, so let's spin once more
} else {
return .didProcess(.needMoreData)
}
case .cannotProcessReentrantly:
return .cannotProcessReentrantly
}
}
return .didProcess(.continue)
}
}
// MARK: ByteToMessageHandler: ChannelInboundHandler
extension ByteToMessageHandler: ChannelInboundHandler {
public func handlerAdded(context: ChannelHandlerContext) {
guard self.removalState == .notAddedToPipeline else {
preconditionFailure("\(self) got readded to a ChannelPipeline but ByteToMessageHandler is single-use")
}
self.removalState = .notBeingRemoved
self.buffer = B2MDBuffer(emptyByteBuffer: context.channel.allocator.buffer(capacity: 0))
// here we can force it because we know that the decoder isn't in use if we're just adding this handler
self.selfAsCanDequeueWrites = self as? CanDequeueWrites // we need to cache this as it allocates.
self.decoder!.decoderAdded(context: context)
}
public func handlerRemoved(context: ChannelHandlerContext) {
// very likely, the removal state is `.notBeingRemoved` or `.removalCompleted` here but we can't assert it
// because the pipeline might be torn down during the formal removal process.
self.removalState = .handlerRemovedCalled
if !self.state.isFinalState {
self.state = .done
}
self.selfAsCanDequeueWrites = nil
// here we can force it because we know that the decoder isn't in use because the removal is always
// eventLoop.execute'd
self.decoder!.decoderRemoved(context: context)
}
/// Calls `decode` until there is nothing left to decode.
public func channelRead(context: ChannelHandlerContext, data: NIOAny) {
let buffer = self.unwrapInboundIn(data)
if case .error(let error) = self.state {
context.fireErrorCaught(ByteToMessageDecoderError.dataReceivedInErrorState(error, buffer))
return
}
self.buffer.append(buffer: buffer)
do {
switch try self.decodeLoop(context: context, decodeMode: .normal) {
case .didProcess:
switch self.state {
case .active:
() // cool, all normal
case .done, .error:
() // fair, all done already
case .leftoversNeedProcessing:
// seems like we received a `channelInactive` or `handlerRemoved` whilst we were processing a read
switch try self.decodeLoop(context: context, decodeMode: .last) {
case .didProcess:
() // expected and cool
case .cannotProcessReentrantly:
preconditionFailure("bug in NIO: non-reentrant decode loop couldn't run \(self), \(self.state)")
}
self.state = .done
}
case .cannotProcessReentrantly:
// fine, will be done later
()
}
} catch {
self.state = .error(error)
context.fireErrorCaught(error)
}
}
/// Call `decodeLast` before forward the event through the pipeline.
public func channelInactive(context: ChannelHandlerContext) {
self.seenEOF = true
self.processLeftovers(context: context)
context.fireChannelInactive()
}
public func userInboundEventTriggered(context: ChannelHandlerContext, event: Any) {
if event as? ChannelEvent == .some(.inputClosed) {
self.seenEOF = true
self.processLeftovers(context: context)
}
context.fireUserInboundEventTriggered(event)
}
}
extension ByteToMessageHandler: ChannelOutboundHandler, _ChannelOutboundHandler where Decoder: WriteObservingByteToMessageDecoder {
public typealias OutboundIn = Decoder.OutboundIn
public func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise<Void>?) {
if self.decoder != nil {
let data = self.unwrapOutboundIn(data)
assert(self.queuedWrites.isEmpty)
self.decoder!.write(data: data)
} else {
self.queuedWrites.append(data)
}
context.write(data, promise: promise)
}
}
/// A protocol for straightforward encoders which encode custom messages to `ByteBuffer`s.
/// To add a `MessageToByteEncoder` to a `ChannelPipeline`, use
/// `channel.pipeline.addHandler(MessageToByteHandler(myEncoder)`.
public protocol MessageToByteEncoder {
associatedtype OutboundIn
/// Called once there is data to encode.
///
/// - parameters:
/// - data: The data to encode into a `ByteBuffer`.
/// - out: The `ByteBuffer` into which we want to encode.
func encode(data: OutboundIn, out: inout ByteBuffer) throws
}
extension ByteToMessageHandler: RemovableChannelHandler {
public func removeHandler(context: ChannelHandlerContext, removalToken: ChannelHandlerContext.RemovalToken) {
precondition(self.removalState == .notBeingRemoved)
self.removalState = .removalStarted
context.eventLoop.execute {
self.processLeftovers(context: context)
assert(!self.state.isLeftoversNeedProcessing, "illegal state: \(self.state)")
switch self.removalState {
case .removalStarted:
self.removalState = .removalCompleted
case .handlerRemovedCalled:
// if we're here, then the channel has also been torn down between the start and the completion of
// the user-triggered removal. That's okay.
()
default:
assertionFailure("illegal removal state: \(self.removalState)")
}
// this is necessary as it'll complete the promise.
context.leavePipeline(removalToken: removalToken)
}
}
}
/// A handler which turns a given `MessageToByteEncoder` into a `ChannelOutboundHandler` that can then be added to a
/// `ChannelPipeline`.
public final class MessageToByteHandler<Encoder: MessageToByteEncoder>: ChannelOutboundHandler {
public typealias OutboundOut = ByteBuffer
public typealias OutboundIn = Encoder.OutboundIn
private enum State {
case notInChannelYet
case operational
case error(Error)
case done
var readyToBeAddedToChannel: Bool {
switch self {
case .notInChannelYet:
return true
case .operational, .error, .done:
return false
}
}
}
private var state: State = .notInChannelYet
private let encoder: Encoder
private var buffer: ByteBuffer? = nil
public init(_ encoder: Encoder) {
self.encoder = encoder
}
}
#if swift(>=5.7)
@available(*, unavailable)
extension MessageToByteHandler: Sendable {}
#endif
extension MessageToByteHandler {
public func handlerAdded(context: ChannelHandlerContext) {
precondition(self.state.readyToBeAddedToChannel,
"illegal state when adding to Channel: \(self.state)")
self.state = .operational
self.buffer = context.channel.allocator.buffer(capacity: 256)
}
public func handlerRemoved(context: ChannelHandlerContext) {
self.state = .done
self.buffer = nil
}
public func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise<Void>?) {
switch self.state {
case .notInChannelYet:
preconditionFailure("MessageToByteHandler.write called before it was added to a Channel")
case .error(let error):
promise?.fail(error)
context.fireErrorCaught(error)
return
case .done:
// let's just ignore this
return
case .operational:
// there's actually some work to do here
break
}
let data = self.unwrapOutboundIn(data)
do {
self.buffer!.clear()
try self.encoder.encode(data: data, out: &self.buffer!)
context.write(self.wrapOutboundOut(self.buffer!), promise: promise)
} catch {
self.state = .error(error)
promise?.fail(error)
context.fireErrorCaught(error)
}
}
}
| apache-2.0 | 5f1f0e7560560b7542882d297a05b0f1 | 42.894417 | 170 | 0.661285 | 4.720569 | false | false | false | false |
watson-developer-cloud/ios-sdk | Sources/DiscoveryV1/Models/SourceOptionsWebCrawl.swift | 1 | 6218 | /**
* (C) Copyright IBM Corp. 2019, 2020.
*
* 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
/**
Object defining which URL to crawl and how to crawl it.
*/
public struct SourceOptionsWebCrawl: Codable, Equatable {
/**
The number of concurrent URLs to fetch. `gentle` means one URL is fetched at a time with a delay between each call.
`normal` means as many as two URLs are fectched concurrently with a short delay between fetch calls. `aggressive`
means that up to ten URLs are fetched concurrently with a short delay between fetch calls.
*/
public enum CrawlSpeed: String {
case gentle = "gentle"
case normal = "normal"
case aggressive = "aggressive"
}
/**
The starting URL to crawl.
*/
public var url: String
/**
When `true`, crawls of the specified URL are limited to the host part of the **url** field.
*/
public var limitToStartingHosts: Bool?
/**
The number of concurrent URLs to fetch. `gentle` means one URL is fetched at a time with a delay between each call.
`normal` means as many as two URLs are fectched concurrently with a short delay between fetch calls. `aggressive`
means that up to ten URLs are fetched concurrently with a short delay between fetch calls.
*/
public var crawlSpeed: String?
/**
When `true`, allows the crawl to interact with HTTPS sites with SSL certificates with untrusted signers.
*/
public var allowUntrustedCertificate: Bool?
/**
The maximum number of hops to make from the initial URL. When a page is crawled each link on that page will also be
crawled if it is within the **maximum_hops** from the initial URL. The first page crawled is 0 hops, each link
crawled from the first page is 1 hop, each link crawled from those pages is 2 hops, and so on.
*/
public var maximumHops: Int?
/**
The maximum milliseconds to wait for a response from the web server.
*/
public var requestTimeout: Int?
/**
When `true`, the crawler will ignore any `robots.txt` encountered by the crawler. This should only ever be done
when crawling a web site the user owns. This must be be set to `true` when a **gateway_id** is specied in the
**credentials**.
*/
public var overrideRobotsTxt: Bool?
/**
Array of URL's to be excluded while crawling. The crawler will not follow links which contains this string. For
example, listing `https://ibm.com/watson` also excludes `https://ibm.com/watson/discovery`.
*/
public var blacklist: [String]?
// Map each property name to the key that shall be used for encoding/decoding.
private enum CodingKeys: String, CodingKey {
case url = "url"
case limitToStartingHosts = "limit_to_starting_hosts"
case crawlSpeed = "crawl_speed"
case allowUntrustedCertificate = "allow_untrusted_certificate"
case maximumHops = "maximum_hops"
case requestTimeout = "request_timeout"
case overrideRobotsTxt = "override_robots_txt"
case blacklist = "blacklist"
}
/**
Initialize a `SourceOptionsWebCrawl` with member variables.
- parameter url: The starting URL to crawl.
- parameter limitToStartingHosts: When `true`, crawls of the specified URL are limited to the host part of the
**url** field.
- parameter crawlSpeed: The number of concurrent URLs to fetch. `gentle` means one URL is fetched at a time with
a delay between each call. `normal` means as many as two URLs are fectched concurrently with a short delay
between fetch calls. `aggressive` means that up to ten URLs are fetched concurrently with a short delay between
fetch calls.
- parameter allowUntrustedCertificate: When `true`, allows the crawl to interact with HTTPS sites with SSL
certificates with untrusted signers.
- parameter maximumHops: The maximum number of hops to make from the initial URL. When a page is crawled each
link on that page will also be crawled if it is within the **maximum_hops** from the initial URL. The first page
crawled is 0 hops, each link crawled from the first page is 1 hop, each link crawled from those pages is 2 hops,
and so on.
- parameter requestTimeout: The maximum milliseconds to wait for a response from the web server.
- parameter overrideRobotsTxt: When `true`, the crawler will ignore any `robots.txt` encountered by the crawler.
This should only ever be done when crawling a web site the user owns. This must be be set to `true` when a
**gateway_id** is specied in the **credentials**.
- parameter blacklist: Array of URL's to be excluded while crawling. The crawler will not follow links which
contains this string. For example, listing `https://ibm.com/watson` also excludes
`https://ibm.com/watson/discovery`.
- returns: An initialized `SourceOptionsWebCrawl`.
*/
public init(
url: String,
limitToStartingHosts: Bool? = nil,
crawlSpeed: String? = nil,
allowUntrustedCertificate: Bool? = nil,
maximumHops: Int? = nil,
requestTimeout: Int? = nil,
overrideRobotsTxt: Bool? = nil,
blacklist: [String]? = nil
)
{
self.url = url
self.limitToStartingHosts = limitToStartingHosts
self.crawlSpeed = crawlSpeed
self.allowUntrustedCertificate = allowUntrustedCertificate
self.maximumHops = maximumHops
self.requestTimeout = requestTimeout
self.overrideRobotsTxt = overrideRobotsTxt
self.blacklist = blacklist
}
}
| apache-2.0 | 173b5ae79540344f5c886ab27b2c77af | 43.099291 | 120 | 0.689289 | 4.366573 | false | false | false | false |
watson-developer-cloud/ios-sdk | Sources/TextToSpeechV1/Models/Word.swift | 1 | 4539 | /**
* (C) Copyright IBM Corp. 2016, 2020.
*
* 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
/**
Information about a word for the custom model.
*/
public struct Word: Codable, Equatable {
/**
**Japanese only.** The part of speech for the word. The service uses the value to produce the correct intonation
for the word. You can create only a single entry, with or without a single part of speech, for any word; you cannot
create multiple entries with different parts of speech for the same word. For more information, see [Working with
Japanese entries](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-rules#jaNotes).
*/
public enum PartOfSpeech: String {
case dosi = "Dosi"
case fuku = "Fuku"
case gobi = "Gobi"
case hoka = "Hoka"
case jodo = "Jodo"
case josi = "Josi"
case kato = "Kato"
case kedo = "Kedo"
case keyo = "Keyo"
case kigo = "Kigo"
case koyu = "Koyu"
case mesi = "Mesi"
case reta = "Reta"
case stbi = "Stbi"
case stto = "Stto"
case stzo = "Stzo"
case suji = "Suji"
}
/**
The word for the custom model. The maximum length of a word is 49 characters.
*/
public var word: String
/**
The phonetic or sounds-like translation for the word. A phonetic translation is based on the SSML format for
representing the phonetic string of a word either as an IPA or IBM SPR translation. The Arabic, Chinese, Dutch,
Australian English, and Korean languages support only IPA. A sounds-like translation consists of one or more words
that, when combined, sound like the word. The maximum length of a translation is 499 characters.
*/
public var translation: String
/**
**Japanese only.** The part of speech for the word. The service uses the value to produce the correct intonation
for the word. You can create only a single entry, with or without a single part of speech, for any word; you cannot
create multiple entries with different parts of speech for the same word. For more information, see [Working with
Japanese entries](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-rules#jaNotes).
*/
public var partOfSpeech: String?
// Map each property name to the key that shall be used for encoding/decoding.
private enum CodingKeys: String, CodingKey {
case word = "word"
case translation = "translation"
case partOfSpeech = "part_of_speech"
}
/**
Initialize a `Word` with member variables.
- parameter word: The word for the custom model. The maximum length of a word is 49 characters.
- parameter translation: The phonetic or sounds-like translation for the word. A phonetic translation is based
on the SSML format for representing the phonetic string of a word either as an IPA or IBM SPR translation. The
Arabic, Chinese, Dutch, Australian English, and Korean languages support only IPA. A sounds-like translation
consists of one or more words that, when combined, sound like the word. The maximum length of a translation is
499 characters.
- parameter partOfSpeech: **Japanese only.** The part of speech for the word. The service uses the value to
produce the correct intonation for the word. You can create only a single entry, with or without a single part of
speech, for any word; you cannot create multiple entries with different parts of speech for the same word. For
more information, see [Working with Japanese
entries](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-rules#jaNotes).
- returns: An initialized `Word`.
*/
public init(
word: String,
translation: String,
partOfSpeech: String? = nil
)
{
self.word = word
self.translation = translation
self.partOfSpeech = partOfSpeech
}
}
| apache-2.0 | ef1105b24f72cf67727bc18da8a4d625 | 41.820755 | 121 | 0.680767 | 4.274011 | false | false | false | false |
sameertotey/LimoService | LimoService/StatusIndicatiorView.swift | 1 | 1094 | //
// StatusIndicatiorView.swift
// LimoService
//
// Created by Sameer Totey on 4/14/15.
// Copyright (c) 2015 Sameer Totey. All rights reserved.
//
import UIKit
class StatusIndicatiorView: UIView {
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func drawRect(rect: CGRect) {
// Drawing code
}
*/
@IBInspectable var borderColor: UIColor = UIColor.clearColor() {
didSet {
layer.borderColor = borderColor.CGColor
}
}
@IBInspectable var borderWidth: CGFloat = 0 {
didSet {
layer.borderWidth = borderWidth
}
}
@IBInspectable var cornerRadius: CGFloat = 3.0 {
didSet {
layer.cornerRadius = cornerRadius
}
}
@IBInspectable var preferredWidth: CGFloat = 6
@IBInspectable var preferredHeight: CGFloat = 100
override func intrinsicContentSize() -> CGSize {
return CGSizeMake(preferredWidth, preferredHeight)
}
}
| mit | 8e46e4e0f8fad7971787aa9ed39c2dd8 | 23.311111 | 78 | 0.629799 | 4.862222 | false | false | false | false |
emericspiroux/Open42 | correct42/Controllers/SearchUserViewController.swift | 1 | 5690 | //
// SearchUserViewController.swift
// correct42
//
// Created by larry on 02/05/2016.
// Copyright © 2016 42. All rights reserved.
//
import UIKit
/**
Display the list of all 42 School students in a tableView `usersTable`
*/
class SearchUserViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate {
// MARK: - IBOutlets
/// Table view of each `users`
@IBOutlet weak var usersTable: UITableView!
/// Search Bar to search `users` firstname, lastname or login
@IBOutlet weak var searchBar: UISearchBar!
// MARK: - Singletons
/// Singleton of `UserManager`
let userManager = UserManager.Shared()
/// Singleton of `SearchManager`
let searchManager = SearchManager.Shared()
// MARK: - Proprieties
/// Name of the custom cell call by the `usersTable`
let cellName = "searchUserCell"
/// Lazy array of all users admit to School 42, sort in alphabetical order
lazy var users:[(String,[User])] = {
return (self.searchManager.userListGroupByFirstLetter)
}()
/// Bool to keep loading two users in same time.
var requestInProgress = false
//MARK: - View methods
/**
On View did load :
1. Register Custom cells, fill delegate and dataSource `usersTable` by `SearchUserViewController` and reload `usersTable`.
2. Set Color and backgroundColor of the index section table
3. Delegate the searchBar by `SearchUserViewController`
*/
override func viewDidLoad() {
super.viewDidLoad()
let nib = UINib(nibName: cellName, bundle: nil)
usersTable.registerNib(nib, forCellReuseIdentifier: cellName)
usersTable.delegate = self
usersTable.dataSource = self
usersTable.reloadData()
usersTable.sectionIndexColor = Theme.darkText.color
usersTable.sectionIndexBackgroundColor = UIColor.clearColor()
searchBar.delegate = self
}
// MARK: - SearchBar delegation
/// If the text in `searchBar` change, this methods call `searchValueOnAPI` private function
func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
filterUsersWithLoginValue(searchText.lowercaseString)
}
/**
Display an header with the string key
in collectionArray `users`
*/
func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
let titleForHeaderInSection = users[section].0
return (titleForHeaderInSection.uppercaseString)
}
// MARK: - TableView delegation
/// Count `users` for the `usersTable` numberOfRowsInSection.
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let numberOfRowsInSection = users[section].1.count
return (numberOfRowsInSection)
}
/// Give to `usersTable` the number of section (first letter login)
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
let sectionCount = users.count
return (sectionCount)
}
/// Height of the table view
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 48
}
/// Display the first letter section in header cells
func sectionIndexTitlesForTableView(tableView: UITableView) -> [String]? {
var arrayTitle = [String]()
for section in users{
arrayTitle.append(section.0)
}
if arrayTitle.count > 5 {
return arrayTitle
}
return nil
}
/**
Fetch the selected user and perform a request (if `requestInProgress` == false)
*/
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let userObject = users[indexPath.section].1[indexPath.row]
if (!requestInProgress){
requestInProgress = true
userManager.fetchUserById(userObject.id, success: { (user) in
self.requestInProgress = false
self.userManager.searchUser = user
self.performSegueWithIdentifier("goToUserSearch", sender: self)
}) { (error) in
self.requestInProgress = false
ApiGeneral(myView: self).check(error, animate: true)
}
}
}
/**
Create a `SearchUserTableViewCell` and fill it.
- Returns: An `SearchUserTableViewCell` filled.
*/
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let userObject = users[indexPath.section].1[indexPath.row]
let userListCellPrototype:SearchUserTableViewCell? = {
let userSearchCell = self.usersTable.dequeueReusableCellWithIdentifier(self.cellName)
if userSearchCell is SearchUserTableViewCell{
return (userSearchCell as! SearchUserTableViewCell)
}
return (nil)
}()
userListCellPrototype!.loginUser.text = userObject.login
userListCellPrototype!.displayName.text = "\(userObject.lastName.capitalizedString) \(userObject.firstName.capitalizedString)"
return (userListCellPrototype!)
}
// MARK: - Segue methods
/// Set `userManager.searchUser` in `userManager.currentUser` to fill the user container view
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.destinationViewController is SearchUserContainerViewController{
if let userSearch = self.userManager.searchUser{
self.userManager.currentUser = userSearch
}
}
}
// MARK: - Private methods
/**
1. Remove all data from user and filter with `login` parameter in `searchManager.listSearchUser`.
2. Reload data in `usersTable`.
if `login` parameter is empty, display all users
- Parameter login: Login research in `searchManager.listSearchUser`
*/
private func filterUsersWithLoginValue(login:String){
if (login != ""){
self.users.removeAll()
self.users = searchManager.groupFromResearch(login)
self.usersTable.reloadData()
} else {
self.users.removeAll()
self.users = searchManager.userListGroupByFirstLetter
self.usersTable.reloadData()
}
}
}
| apache-2.0 | 030b02ee4a436a0e9f4945eefa54eabb | 31.695402 | 128 | 0.746001 | 4.104618 | false | false | false | false |
hyperoslo/Orchestra | Example/OrchestraDemo/OrchestraDemo/Sources/Models/Project.swift | 1 | 3468 | import Foundation
struct Project {
var id: Int
var name: String
var info: String
var imageURL: NSURL
var githubURL: NSURL
// MARK: - Initializers
init(id: Int, name: String, info: String, imageURL: NSURL, githubURL: NSURL) {
self.id = id
self.name = name
self.info = info
self.imageURL = imageURL
self.githubURL = githubURL
}
// MARK: - Factory
static var projects: [Project] {
return [
Project(id: 0, name: "Form",
info: "The most flexible and powerful way to build a form on iOS.",
imageURL: NSURL(
string: "https://raw.githubusercontent.com/hyperoslo/Form/master/Images/logo-v6.png")!,
githubURL: NSURL(string: "https://github.com/hyperoslo/Form")!),
Project(id: 0, name: "Sync",
info: "Modern JSON synchronization to Core Data",
imageURL: NSURL(
string: "https://raw.githubusercontent.com/hyperoslo/Sync/master/Images/logo-v2.png")!,
githubURL: NSURL(string: "https://github.com/hyperoslo/Sync")!),
Project(id: 0, name: "Pages",
info: "Pages is the easiest way of setting up a UIPageViewController.",
imageURL: NSURL(string: "https://raw.githubusercontent.com/hyperoslo/Pages/master/Images/pages_logo.png")!,
githubURL: NSURL(string: "https://github.com/hyperoslo/Pages")!),
Project(id: 0, name: "Presentation",
info: "Presentation helps you to make tutorials, release notes and animated pages.",
imageURL: NSURL(string: "https://raw.githubusercontent.com/hyperoslo/Presentation/master/Images/logo.png")!,
githubURL: NSURL(string: "https://github.com/hyperoslo/Presentation")!),
Project(id: 0, name: "Whisper",
info: "A fairy eyelash or a unicorn whisper too far.",
imageURL: NSURL(
string: "https://raw.githubusercontent.com/hyperoslo/Whisper/master/Resources/whisper-cover.png")!,
githubURL: NSURL(string: "https://github.com/hyperoslo/Whisper")!),
Project(id: 0, name: "ImagePicker",
info: "ImagePicker is an all-in-one camera solution for your iOS app. It let's your users select images from the library and take pictures at the same time.",
imageURL: NSURL(string: "https://raw.githubusercontent.com/hyperoslo/ImagePicker/master/Resources/ImagePickerIcon.png")!,
githubURL: NSURL(string: "https://github.com/hyperoslo/ImagePicker")!),
Project(id: 0, name: "Compass",
info: "Compass helps you setup a central navigation system for your application.",
imageURL: NSURL(string: "https://raw.githubusercontent.com/hyperoslo/Compass/master/Images/logo_v1.png")!,
githubURL: NSURL(string: "https://github.com/hyperoslo/Compass")!),
Project(id: 0, name: "Cache",
info: "Cache doesn't claim to be unique in this area, but it's not another monster library that gives you a god's power. It does nothing but caching, but it does it well.",
imageURL: NSURL(
string: "https://raw.githubusercontent.com/hyperoslo/Cache/master/Resources/CachePresentation.png")!,
githubURL: NSURL(string: "https://github.com/hyperoslo/Cache")!),
Project(id: 0, name: "Hue",
info: "Hue is the all-in-one coloring utility that you'll ever need.",
imageURL: NSURL(
string: "https://raw.githubusercontent.com/hyperoslo/Hue/master/Images/cover.png")!,
githubURL: NSURL(string: "https://github.com/hyperoslo/Hue")!),
]
}
}
| mit | 80c216f874cb6da2e3f49e26b4866b1d | 50.761194 | 180 | 0.669262 | 3.879195 | false | false | false | false |
ChrisAU/Papyrus | Papyrus.playground/Contents.swift | 2 | 14481 | //: Playground - noun: a place where people can play
import UIKit
func == (lhs: Square, rhs: Square) -> Bool {
return ObjectIdentifier(lhs) == ObjectIdentifier(rhs)
}
// ADVANCED:
// When player 1 is about to make a move, start calculating valid moves for player 2.
// Remove and recalculate invalidated ranges
enum Direction: CustomDebugStringConvertible {
case Prev
case Next
var inverse: Direction {
return self == .Prev ? .Next : .Prev
}
var debugDescription: String {
return self == .Prev ? "Prev" : "Next"
}
}
enum Axis: CustomDebugStringConvertible {
case Horizontal(Direction)
case Vertical(Direction)
func inverse(direction: Direction) -> Axis {
switch self {
case .Horizontal(_): return .Vertical(direction)
case .Vertical(_): return .Horizontal(direction)
}
}
var direction: Direction {
switch self {
case .Horizontal(let dir): return dir
case .Vertical(let dir): return dir
}
}
var debugDescription: String {
switch self {
case .Horizontal(let dir): return "H-\(dir)"
case .Vertical(let dir): return "V-\(dir)"
}
}
}
struct Position: Equatable, Hashable {
let axis: Axis
let iterable: Int
let fixed: Int
var hashValue: Int {
return "\(axis.debugDescription),\(iterable),\(fixed)".hashValue
}
var isInvalid: Bool {
return invalid(iterable) || invalid(fixed)
}
private func invalid(z: Int) -> Bool {
return z < 0 || z >= Dimensions
}
private func adjust(z: Int, dir: Direction) -> Int {
let n = dir == .Next ? z + 1 : z - 1
return invalid(n) ? z : n
}
func newPosition() -> Position {
return Position(axis: axis, iterable: adjust(iterable, dir: axis.direction), fixed: fixed)
}
func otherAxis(direction: Direction) -> Position {
return Position(axis: axis.inverse(direction), iterable: iterable, fixed: fixed)
}
var isHorizontal: Bool {
switch axis {
case .Horizontal(_): return true
case .Vertical(_): return false
}
}
static func newPosition(axis: Axis, iterable: Int, fixed: Int) -> Position? {
let position = Position(axis: axis, iterable: iterable, fixed: fixed)
if position.isInvalid { return nil }
return position
}
}
func == (lhs: Position, rhs: Position) -> Bool {
return lhs.hashValue == rhs.hashValue
}
class Tile: CustomDebugStringConvertible {
var letter: Character
let value: Int
init(_ letter: Character, _ value: Int) {
self.letter = letter
self.value = value
}
var debugDescription: String {
return String(letter)
}
}
class Square: CustomDebugStringConvertible, Equatable {
enum Type {
case None, Letterx2, Letterx3, Center, Wordx2, Wordx3
}
let type: Type
var tile: Tile?
init(_ type: Type) {
self.type = type
}
var debugDescription: String {
return String(tile?.letter ?? "_")
}
}
let Dimensions = 15
var squares = [[Square]]()
// column <-> is horizontal
// row v^ is vertical
for row in 1...Dimensions {
var line = [Square]()
for col in 1...Dimensions {
line.append(Square(.None))
}
squares.append(line)
}
squares[2][9].tile = Tile("R", 1)
squares[3][9].tile = Tile("E", 1)
squares[4][9].tile = Tile("S", 1)
squares[5][9].tile = Tile("U", 1)
squares[6][9].tile = Tile("M", 3)
squares[8][9].tile = Tile("S", 1)
squares[7][5].tile = Tile("A", 1)
squares[7][6].tile = Tile("R", 1)
squares[7][7].tile = Tile("C", 3)
squares[7][8].tile = Tile("H", 4)
squares[7][9].tile = Tile("E", 1)
squares[7][10].tile = Tile("R", 1)
squares[7][11].tile = Tile("S", 1)
squares[8][7].tile = Tile("A", 1)
squares[9][7].tile = Tile("R", 1)
squares[10][7].tile = Tile("D", 2)
squares[10][6].tile = Tile("A", 1)
squares[10][5].tile = Tile("E", 1)
squares[10][4].tile = Tile("D", 2)
squares[10][8].tile = Tile("E", 1)
squares[10][9].tile = Tile("R", 1)
squares[8][5].tile = Tile("R", 1)
squares[9][5].tile = Tile("I", 1)
// When a word is played, lets just store the playable boundary, rather than trying to
// calculate it after the fact, it's going to take too much computing power.
//
struct Boundary: CustomDebugStringConvertible {
let start: Position
let end: Position
var debugDescription: String {
return "\(start.iterable),\(start.fixed) - \(end.iterable), \(end.fixed)"
}
func encompasses(row: Int, column: Int) -> Bool {
if start.isHorizontal {
let sameRow = row == start.fixed && row == end.fixed
let validColumn = column >= start.iterable && column <= end.iterable
return sameRow && validColumn
} else {
let sameColumn = column == start.fixed && column == end.fixed
let validRow = row >= start.iterable && row <= end.iterable
return sameColumn && validRow
}
}
}
func letterAt(row: Int, _ col: Int) -> Character? {
return squares[row][col].tile?.letter
}
/// Get string value of letters in a given boundary.
/// Does not currently check for gaps - use another method for gap checking and validation.
func readable(boundary: Boundary) -> String? {
let start = boundary.start, end = boundary.end
if start.iterable >= end.iterable { return nil }
return String((start.iterable...end.iterable).map({ letterAt(
start.isHorizontal ? start.fixed : $0,
start.isHorizontal ? $0 : start.fixed)}))
}
//typealias Boundary = (start: Position, end: Position)
typealias Boundaries = [Boundary]
typealias PositionBoundaries = [Position: Boundary]
/// - Returns: False if outside of board boundaries.
private func outOfBounds(z: Int) -> Bool {
return z < 0 || z >= Dimensions
}
var playedBoundaries = Boundaries()
// ARCHERS
playedBoundaries.append(Boundary(
start: Position(axis: .Horizontal(.Prev), iterable: 5, fixed: 7),
end: Position(axis: .Horizontal(.Next), iterable: 11, fixed: 7)))
// DEAD
playedBoundaries.append(Boundary(
start: Position(axis: .Horizontal(.Prev), iterable: 4, fixed: 10),
end: Position(axis: .Horizontal(.Next), iterable: 9, fixed: 10)))
// CARD
playedBoundaries.append(Boundary(start:
Position(axis: .Vertical(.Prev), iterable: 7, fixed: 7), end:
Position(axis: .Vertical(.Next), iterable: 10, fixed: 7)))
// ARIE
playedBoundaries.append(Boundary(start:
Position(axis: .Vertical(.Prev), iterable: 7, fixed: 5), end:
Position(axis: .Vertical(.Next), iterable: 10, fixed: 5)))
// RESUME
playedBoundaries.append(Boundary(start:
Position(axis: .Vertical(.Prev), iterable: 2, fixed: 9), end:
Position(axis: .Vertical(.Next), iterable: 8, fixed: 9)))
/// Returns square at given boundary
func squareAt(position: Position?) -> Square? {
guard let position = position else { return nil }
if position.isHorizontal {
return squareAt(position.fixed, position.iterable)
} else {
return squareAt(position.iterable, position.fixed)
}
}
func squareAt(row: Int, _ col: Int) -> Square {
return squares[row][col]
}
func emptyAt(position: Position?) -> Bool {
return squareAt(position)?.tile == nil
}
/// Loop while we are fulfilling the validator.
/// Caveat: first position must pass validation prior to being sent to this method.
func loop(position: Position, validator: (position: Position) -> Bool, fun: ((position: Position) -> ())? = nil) -> Position? {
// Return nil if square is outside of range (should only occur first time)
if position.isInvalid { return nil }
// Check new position.
let newPosition = position.newPosition()
let continued = validator(position: newPosition)
if newPosition.isInvalid || !continued {
fun?(position: position)
return position
} else {
fun?(position: newPosition)
return loop(newPosition, validator: validator, fun: fun) ?? newPosition
}
}
/// Loop while we are fulfilling the empty value
func loop(position: Position, empty: Bool? = false, fun: ((position: Position) -> ())? = nil) -> Position? {
// Return nil if square is outside of range (should only occur first time)
// Return nil if this square is empty (should only occur first time)
if position.isInvalid || emptyAt(position) != empty! { return nil }
// Check new position.
let newPosition = position.newPosition()
if newPosition.isInvalid || emptyAt(newPosition) != empty! {
fun?(position: position)
return position
} else {
fun?(position: newPosition)
return loop(newPosition, empty: empty, fun: fun)
}
}
/*/// Method used to determine intersecting words.
func positionBoundaries(horizontal: Bool, row: Int, col: Int) -> PositionBoundaries {
// Collect valid places to play
var collected = PositionBoundaries()
func collector(position: Position) {
// Wrap collector when it needs to be moved, use another function to pass in an array
if collected[position] == nil {
let a = position.otherAxis(.Prev)
let b = position.otherAxis(.Next)
if let first = loop(a), last = loop(b) {
// Add/update boundary
collected[position] = Boundary(start: first, end: last)
}
}
}
// Find boundaries of this word
let a = Position(axis: horizontal ? .Column(.Prev) : .Row(.Prev), row: row, col: col)
let b = Position(axis: horizontal ? .Column(.Next) : .Row(.Next), row: row, col: col)
if let first = loop(a, fun: collector), last = loop(b, fun: collector) {
// Print start and end of word
print(first)
print(last)
// And any squares that are filled around this word (non-recursive)
print(collected)
}
return collected
}
*/
/// Returns all 'readable' values for a given array of position boundaries.
/// Essentially, all words.
/*func readable(positionBoundaries: PositionBoundaries) -> [String] {
var output = [String]()
for (position, range) in positionBoundaries {
if position != range.start || position != range.end {
if let word = readable(range) {
output.append(word)
}
}
}
var sorted = positionBoundaries.keys.sort { (lhs, rhs) -> Bool in
if lhs.isHorizontal {
return lhs.row < rhs.row
} else {
return lhs.col < rhs.col
}
}
if let first = sorted.first, last = sorted.last where first != last {
if let word = readable(Boundary(start: first, end: last)) {
output.append(word)
}
}
return output
}
*/
/*
// Determine boundaries of words on the board (hard coded positions)
positionBoundaries(true, row: 8, col: 6)
let arcWords = readable(positionBoundaries(true, row: 7, col: 7))
let arieWords = readable(positionBoundaries(true, row: 10, col: 4))
let deadWords = readable(positionBoundaries(false, row: 10, col: 7))
validate(deadWords)
validate(arieWords)
*/
var playableBoundaries = Boundaries()
/// - Parameter: Initial position to begin this loop, will call position's axis->direction to determine next position.
/// - Returns: Furthest possible position from initial position usign rackCount.
func getPositionLoop(initial: Position) -> Position {
var counter = rackCount
func decrementer(position: Position) -> Bool {
if emptyAt(position) { counter-- }
return counter > -1
}
let position = loop(initial, validator: decrementer) ?? initial
return position
}
/// This method will be used by AI to determine location where play is allowed.
/// - Parameter boundaries: Boundaries to use for intersection.
/// - Returns: Areas where play may be possible intersecting the given boundaries.
func findPlayableBoundaries(boundaries: Boundaries) -> Boundaries {
var allBoundaries = Boundaries()
for boundary in boundaries {
var currentBoundaries = Boundaries()
let startPosition = getPositionLoop(boundary.start)
let endPosition = getPositionLoop(boundary.end)
let start = boundary.start
let end = boundary.end
for i in startPosition.iterable...endPosition.iterable {
assert(!outOfBounds(i))
let s = i > start.iterable ? start.iterable : i
let e = i < end.iterable ? end.iterable : i
if e - s < 11 {
guard let iterationStart = Position.newPosition(boundary.start.axis, iterable: s, fixed: start.fixed),
iterationEnd = Position.newPosition(boundary.end.axis, iterable: e, fixed: end.fixed) else { continue }
let boundary = Boundary(start: iterationStart, end: iterationEnd)
if currentBoundaries.filter({$0.start == iterationStart && $0.end == iterationStart}).count == 0 {
currentBoundaries.append(boundary)
}
}
}
let inverseAxisStart = boundary.start.axis.inverse(.Prev)
let inverseAxisEnd = boundary.end.axis.inverse(.Next)
for i in boundary.start.iterable...boundary.end.iterable {
guard let startPosition = Position.newPosition(inverseAxisStart, iterable: start.fixed, fixed: i),
endPosition = Position.newPosition(inverseAxisEnd, iterable: end.fixed, fixed: i) else { continue }
let iterationStart = getPositionLoop(startPosition)
let iterationEnd = getPositionLoop(endPosition)
let boundary = Boundary(start: iterationStart, end: iterationEnd)
if currentBoundaries.filter({$0.start == iterationStart && $0.end == iterationEnd}).count == 0 {
currentBoundaries.append(boundary)
}
}
allBoundaries.extend(currentBoundaries)
}
return allBoundaries
}
// Now determine playable boundaries
let rackCount = 2
playableBoundaries = findPlayableBoundaries(playedBoundaries)
for row in 0...Dimensions-1 {
var line = [Character]()
for col in 0...Dimensions-1 {
var letter: Character = "_"
for boundary in playableBoundaries {
if boundary.encompasses(row, column: col) {
letter = letterAt(row, col) ?? "#"
break
}
}
line.append(letter)
}
print(line)
}
print(playableBoundaries.count)
| mit | c1409cd86ea2423f37cc87b1da8d4560 | 32.913349 | 127 | 0.631379 | 3.956557 | false | false | false | false |
SummerHF/SinaPractice | sina/Pods/LTMorphingLabel/LTMorphingLabel/LTMorphingLabel+Evaporate.swift | 2 | 3029 | //
// LTMorphingLabel+Evaporate.swift
// https://github.com/lexrus/LTMorphingLabel
//
// The MIT License (MIT)
// Copyright (c) 2016 Lex Tang, http://lexrus.com
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files
// (the “Software”), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software,
// and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
import UIKit
extension LTMorphingLabel {
func EvaporateLoad() {
progressClosures["Evaporate\(LTMorphingPhases.Progress)"] = {
(index: Int, progress: Float, isNewChar: Bool) in
let j: Int = Int(round(cos(Double(index)) * 1.2))
let delay = isNewChar ? self.morphingCharacterDelay * -1.0 : self.morphingCharacterDelay
return min(1.0, max(0.0, self.morphingProgress + delay * Float(j)))
}
effectClosures["Evaporate\(LTMorphingPhases.Disappear)"] = {
char, index, progress in
let newProgress = LTEasing.easeOutQuint(progress, 0.0, 1.0, 1.0)
let yOffset: CGFloat = -0.8 * CGFloat(self.font.pointSize) * CGFloat(newProgress)
let currentRect = CGRectOffset(self.previousRects[index], 0, yOffset)
let currentAlpha = CGFloat(1.0 - newProgress)
return LTCharacterLimbo(
char: char,
rect: currentRect,
alpha: currentAlpha,
size: self.font.pointSize,
drawingProgress: 0.0)
}
effectClosures["Evaporate\(LTMorphingPhases.Appear)"] = {
char, index, progress in
let newProgress = 1.0 - LTEasing.easeOutQuint(progress, 0.0, 1.0)
let yOffset = CGFloat(self.font.pointSize) * CGFloat(newProgress) * 1.2
return LTCharacterLimbo(
char: char,
rect: CGRectOffset(self.newRects[index], 0.0, yOffset),
alpha: CGFloat(self.morphingProgress),
size: self.font.pointSize,
drawingProgress: 0.0
)
}
}
}
| mit | 7ce6ea2486c8edbc37b1e35960cd0061 | 39.824324 | 100 | 0.629262 | 4.515695 | false | false | false | false |
hzy87email/actor-platform | actor-apps/app-ios/ActorApp/Controllers/Settings/SettingsPrivacyViewController.swift | 3 | 3363 | //
// Copyright (c) 2014-2015 Actor LLC. <https://actor.im>
//
import UIKit
class SettingsPrivacyViewController: AATableViewController {
private var authSessions = [ARApiAuthSession]()
private var data: UAGrouppedTableData!
init() {
super.init(style: UITableViewStyle.Grouped)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.title = NSLocalizedString("PrivacyTitle", comment: "Controller title")
tableView.backgroundColor = MainAppTheme.list.backyardColor
tableView.separatorStyle = UITableViewCellSeparatorStyle.None
data = UAGrouppedTableData(tableView: tableView)
let header = data.addSection(true)
.setFooterText("PrivacyTerminateHint")
header.addDangerCell("PrivacyTerminate") { () -> () in
self.confirmDangerSheetUser("PrivacyTerminateAlert", tapYes: { () -> () in
// Terminating all sessions and reload list
self.executeSafe(Actor.terminateAllSessionsCommand(), successBlock: { (val) -> Void in
self.loadSessions()
})
}, tapNo: nil)
}
data.addSection(true)
.addCustomCells(44, countClosure: { () -> Int in
return self.authSessions.count
}, closure: { (tableView, index, indexPath) -> UITableViewCell in
let cell = tableView.dequeueReusableCellWithIdentifier(UABaseTableData.ReuseCommonCell, forIndexPath: indexPath) as! CommonCell
let session = self.authSessions[indexPath.row]
if session.getAuthHolder().ordinal() != jint(ARApiAuthHolder.THISDEVICE.rawValue) {
cell.style = .Normal
cell.setContent(session.getDeviceTitle())
} else {
cell.style = .Hint
cell.setContent("(Current) \(session.getDeviceTitle())")
}
return cell
})
.setAction { (index) -> () in
let session = self.authSessions[index]
if session.getAuthHolder().ordinal() != jint(ARApiAuthHolder.THISDEVICE.rawValue) {
self.confirmDangerSheetUser("PrivacyTerminateAlertSingle", tapYes: { () -> () in
// Terminating session and reload list
self.executeSafe(Actor.terminateSessionCommandWithId(session.getId()), successBlock: { (val) -> Void in
self.loadSessions()
})
}, tapNo: nil)
}
}
// Starting to load sessions
loadSessions()
}
private func loadSessions() {
execute(Actor.loadSessionsCommand(), successBlock: { (val) -> Void in
let list = val as! JavaUtilList
self.authSessions = []
for i in 0..<list.size() {
self.authSessions.append(list.getWithInt(jint(i)) as! ARApiAuthSession)
}
self.tableView.reloadData()
}, failureBlock: nil)
}
}
| mit | f4bc11f7a8d2a6ca7a45a99179a1d581 | 39.035714 | 147 | 0.552483 | 5.338095 | false | false | false | false |
KoCMoHaBTa/MHAppKit | MHAppKit/Views/BadgeLabel.swift | 1 | 2708 | //
// BadgeLabel.swift
// MHAppKit
//
// Created by Milen Halachev on 3/3/16.
// Copyright (c) 2016 Milen Halachev. All rights reserved.
//
#if canImport(UIKit) && !os(watchOS)
import Foundation
import UIKit
///A UILable subclass that draws itself as a badge
open class BadgeLabel: UILabel {
///Controls whenever to hide the badge draw when the value is 0. Default to `true`.
open var hideAtBadgeValueZero = true
///Controls whenever to animate the badge value changes. Default to `true`.
open var animateBadgeValueChange = true
///The padding of the content - affects intrinsicContentSize.
open var padding: CGFloat = 6
///The badge value
open var badgeValue: String? {
didSet {
self.text = self.badgeValue
self.isHidden = self.badgeValue == nil || (self.hideAtBadgeValueZero && self.badgeValue == "0")
if self.animateBadgeValueChange {
self.performBadgeValueChangeAnimation()
}
}
}
public override init(frame: CGRect) {
super.init(frame: frame)
self.loadDefaultBadgeConfiguration()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.loadDefaultBadgeConfiguration()
}
open override func layoutSubviews() {
super.layoutSubviews()
self.layer.cornerRadius = self.bounds.height / 2
}
open override var intrinsicContentSize : CGSize {
let size = super.intrinsicContentSize
let height = size.height + self.padding
let width = max(size.width, size.height) + self.padding
return CGSize(width: width, height: height)
}
///Loads the default badge style configuration.
open func loadDefaultBadgeConfiguration() {
self.backgroundColor = .red
self.textColor = .white
self.font = .systemFont(ofSize: 12)
self.textAlignment = .center
self.layer.masksToBounds = true
}
///Performs the animation used when the badge value is changed. You can override this method in order to provide custom animation.
open func performBadgeValueChangeAnimation() {
let animation = CABasicAnimation(keyPath: "transform.scale")
animation.fromValue = 1.5
animation.toValue = 1
animation.duration = 0.2
animation.timingFunction = CAMediaTimingFunction(controlPoints: 0.4, 1.3, 1, 1)
self.layer.add(animation, forKey: "bounce")
}
}
#endif
| mit | 13dd2cb8e39a8ee1526458f816ea0e9a | 27.505263 | 134 | 0.607459 | 4.923636 | false | false | false | false |
caicai0/ios_demo | load/thirdpart/SwiftSoup/XmlTreeBuilder.swift | 3 | 5295 | //
// XmlTreeBuilder.swift
// SwiftSoup
//
// Created by Nabil Chatbi on 14/10/16.
// Copyright © 2016 Nabil Chatbi.. All rights reserved.
//
import Foundation
/**
* Use the {@code XmlTreeBuilder} when you want to parse XML without any of the HTML DOM rules being applied to the
* document.
* <p>Usage example: {@code Document xmlDoc = Jsoup.parse(html, baseUrl, Parser.xmlParser())}</p>
*
*/
public class XmlTreeBuilder: TreeBuilder {
public override init() {
super.init()
}
public override func defaultSettings() -> ParseSettings {
return ParseSettings.preserveCase
}
public func parse(_ input: String, _ baseUri: String)throws->Document {
return try parse(input, baseUri, ParseErrorList.noTracking(), ParseSettings.preserveCase)
}
override public func initialiseParse(_ input: String, _ baseUri: String, _ errors: ParseErrorList, _ settings: ParseSettings) {
super.initialiseParse(input, baseUri, errors, settings)
stack.append(doc) // place the document onto the stack. differs from HtmlTreeBuilder (not on stack)
doc.outputSettings().syntax(syntax: OutputSettings.Syntax.xml)
}
override public func process(_ token: Token)throws->Bool {
// start tag, end tag, doctype, comment, character, eof
switch (token.type) {
case .StartTag:
try insert(token.asStartTag())
break
case .EndTag:
try popStackToClose(token.asEndTag())
break
case .Comment:
try insert(token.asComment())
break
case .Char:
try insert(token.asCharacter())
break
case .Doctype:
try insert(token.asDoctype())
break
case .EOF: // could put some normalisation here if desired
break
// default:
// try Validate.fail(msg: "Unexpected token type: " + token.tokenType())
}
return true
}
private func insertNode(_ node: Node)throws {
try currentElement()?.appendChild(node)
}
@discardableResult
func insert(_ startTag: Token.StartTag)throws->Element {
let tag: Tag = try Tag.valueOf(startTag.name(), settings)
// todo: wonder if for xml parsing, should treat all tags as unknown? because it's not html.
let el: Element = try Element(tag, baseUri, settings.normalizeAttributes(startTag._attributes))
try insertNode(el)
if (startTag.isSelfClosing()) {
tokeniser.acknowledgeSelfClosingFlag()
if (!tag.isKnownTag()) // unknown tag, remember this is self closing for output. see above.
{
tag.setSelfClosing()
}
} else {
stack.append(el)
}
return el
}
func insert(_ commentToken: Token.Comment)throws {
let comment: Comment = Comment(commentToken.getData(), baseUri)
var insert: Node = comment
if (commentToken.bogus) { // xml declarations are emitted as bogus comments (which is right for html, but not xml)
// so we do a bit of a hack and parse the data as an element to pull the attributes out
let data: String = comment.getData()
if (data.characters.count > 1 && (data.startsWith("!") || data.startsWith("?"))) {
let doc: Document = try SwiftSoup.parse("<" + data.substring(1, data.characters.count - 2) + ">", baseUri, Parser.xmlParser())
let el: Element = doc.child(0)
insert = XmlDeclaration(settings.normalizeTag(el.tagName()), comment.getBaseUri(), data.startsWith("!"))
insert.getAttributes()?.addAll(incoming: el.getAttributes())
}
}
try insertNode(insert)
}
func insert(_ characterToken: Token.Char)throws {
let node: Node = TextNode(characterToken.getData()!, baseUri)
try insertNode(node)
}
func insert(_ d: Token.Doctype)throws {
let doctypeNode = DocumentType(settings.normalizeTag(d.getName()), d.getPubSysKey(), d.getPublicIdentifier(), d.getSystemIdentifier(), baseUri)
try insertNode(doctypeNode)
}
/**
* If the stack contains an element with this tag's name, pop up the stack to remove the first occurrence. If not
* found, skips.
*
* @param endTag
*/
private func popStackToClose(_ endTag: Token.EndTag)throws {
let elName: String = try endTag.name()
var firstFound: Element? = nil
for pos in (0..<stack.count).reversed() {
let next: Element = stack[pos]
if (next.nodeName().equals(elName)) {
firstFound = next
break
}
}
if (firstFound == nil) {
return // not found, skip
}
for pos in (0..<stack.count).reversed() {
let next: Element = stack[pos]
stack.remove(at: pos)
if (next == firstFound!) {
break
}
}
}
func parseFragment(_ inputFragment: String, _ baseUri: String, _ errors: ParseErrorList, _ settings: ParseSettings)throws->Array<Node> {
initialiseParse(inputFragment, baseUri, errors, settings)
try runParser()
return doc.getChildNodes()
}
}
| mit | adf69acdadd2d214af58adc2ba289054 | 35.260274 | 151 | 0.606725 | 4.433836 | false | false | false | false |
michael-lehew/swift-corelibs-foundation | Foundation/NSURLProtocol.swift | 1 | 15489 | // This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
/*!
@header NSURLProtocol.h
This header file describes the constructs used to represent URL
protocols, and describes the extensible system by which specific
classes can be made to handle the loading of particular URL types or
schemes.
<p>NSURLProtocol is an abstract class which provides the
basic structure for performing protocol-specific loading of URL
data.
<p>The NSURLProtocolClient describes the integration points a
protocol implemention can use to hook into the URL loading system.
NSURLProtocolClient describes the methods a protocol implementation
needs to drive the URL loading system from a NSURLProtocol subclass.
<p>To support customization of protocol-specific requests,
protocol implementors are encouraged to provide categories on
NSURLRequest and NSMutableURLRequest. Protocol implementors who
need to extend the capabilities of NSURLRequest and
NSMutableURLRequest in this way can store and retrieve
protocol-specific request data by using the
<tt>+propertyForKey:inRequest:</tt> and
<tt>+setProperty:forKey:inRequest:</tt> class methods on
NSURLProtocol. See the NSHTTPURLRequest on NSURLRequest and
NSMutableHTTPURLRequest on NSMutableURLRequest for examples of
such extensions.
<p>An essential responsibility for a protocol implementor is
creating a NSURLResponse for each request it processes successfully.
A protocol implementor may wish to create a custom, mutable
NSURLResponse class to aid in this work.
*/
/*!
@protocol NSURLProtocolClient
@discussion NSURLProtocolClient provides the interface to the URL
loading system that is intended for use by NSURLProtocol
implementors.
*/
public protocol URLProtocolClient : NSObjectProtocol {
/*!
@method URLProtocol:wasRedirectedToRequest:
@abstract Indicates to an NSURLProtocolClient that a redirect has
occurred.
@param URLProtocol the NSURLProtocol object sending the message.
@param request the NSURLRequest to which the protocol implementation
has redirected.
*/
func urlProtocol(_ protocol: URLProtocol, wasRedirectedTo request: URLRequest, redirectResponse: URLResponse)
/*!
@method URLProtocol:cachedResponseIsValid:
@abstract Indicates to an NSURLProtocolClient that the protocol
implementation has examined a cached response and has
determined that it is valid.
@param URLProtocol the NSURLProtocol object sending the message.
@param cachedResponse the NSCachedURLResponse object that has
examined and is valid.
*/
func urlProtocol(_ protocol: URLProtocol, cachedResponseIsValid cachedResponse: CachedURLResponse)
/*!
@method URLProtocol:didReceiveResponse:
@abstract Indicates to an NSURLProtocolClient that the protocol
implementation has created an NSURLResponse for the current load.
@param URLProtocol the NSURLProtocol object sending the message.
@param response the NSURLResponse object the protocol implementation
has created.
@param cacheStoragePolicy The NSURLCacheStoragePolicy the protocol
has determined should be used for the given response if the
response is to be stored in a cache.
*/
func urlProtocol(_ protocol: URLProtocol, didReceive response: URLResponse, cacheStoragePolicy policy: URLCache.StoragePolicy)
/*!
@method URLProtocol:didLoadData:
@abstract Indicates to an NSURLProtocolClient that the protocol
implementation has loaded URL data.
@discussion The data object must contain only new data loaded since
the previous call to this method (if any), not cumulative data for
the entire load.
@param URLProtocol the NSURLProtocol object sending the message.
@param data URL load data being made available.
*/
func urlProtocol(_ protocol: URLProtocol, didLoad data: Data)
/*!
@method URLProtocolDidFinishLoading:
@abstract Indicates to an NSURLProtocolClient that the protocol
implementation has finished loading successfully.
@param URLProtocol the NSURLProtocol object sending the message.
*/
func urlProtocolDidFinishLoading(_ protocol: URLProtocol)
/*!
@method URLProtocol:didFailWithError:
@abstract Indicates to an NSURLProtocolClient that the protocol
implementation has failed to load successfully.
@param URLProtocol the NSURLProtocol object sending the message.
@param error The error that caused the load to fail.
*/
func urlProtocol(_ protocol: URLProtocol, didFailWithError error: NSError)
/*!
@method URLProtocol:didReceiveAuthenticationChallenge:
@abstract Start authentication for the specified request
@param protocol The protocol object requesting authentication.
@param challenge The authentication challenge.
@discussion The protocol client guarantees that it will answer the
request on the same thread that called this method. It may add a
default credential to the challenge it issues to the connection delegate,
if the protocol did not provide one.
*/
func urlProtocol(_ protocol: URLProtocol, didReceive challenge: URLAuthenticationChallenge)
/*!
@method URLProtocol:didCancelAuthenticationChallenge:
@abstract Cancel authentication for the specified request
@param protocol The protocol object cancelling authentication.
@param challenge The authentication challenge.
*/
func urlProtocol(_ protocol: URLProtocol, didCancel challenge: URLAuthenticationChallenge)
}
/*!
@class NSURLProtocol
@abstract NSURLProtocol is an abstract class which provides the
basic structure for performing protocol-specific loading of URL
data. Concrete subclasses handle the specifics associated with one
or more protocols or URL schemes.
*/
open class URLProtocol : NSObject {
/*!
@method initWithRequest:cachedResponse:client:
@abstract Initializes an NSURLProtocol given request,
cached response, and client.
@param request The request to load.
@param cachedResponse A response that has been retrieved from the
cache for the given request. The protocol implementation should
apply protocol-specific validity checks if such tests are
necessary.
@param client The NSURLProtocolClient object that serves as the
interface the protocol implementation can use to report results back
to the URL loading system.
*/
public init(request: URLRequest, cachedResponse: CachedURLResponse?, client: URLProtocolClient?) { NSUnimplemented() }
/*!
@method client
@abstract Returns the NSURLProtocolClient of the receiver.
@result The NSURLProtocolClient of the receiver.
*/
open var client: URLProtocolClient? { NSUnimplemented() }
/*!
@method request
@abstract Returns the NSURLRequest of the receiver.
@result The NSURLRequest of the receiver.
*/
/*@NSCopying*/ open var request: URLRequest { NSUnimplemented() }
/*!
@method cachedResponse
@abstract Returns the NSCachedURLResponse of the receiver.
@result The NSCachedURLResponse of the receiver.
*/
/*@NSCopying*/ open var cachedResponse: CachedURLResponse? { NSUnimplemented() }
/*======================================================================
Begin responsibilities for protocol implementors
The methods between this set of begin-end markers must be
implemented in order to create a working protocol.
======================================================================*/
/*!
@method canInitWithRequest:
@abstract This method determines whether this protocol can handle
the given request.
@discussion A concrete subclass should inspect the given request and
determine whether or not the implementation can perform a load with
that request. This is an abstract method. Sublasses must provide an
implementation. The implementation in this class calls
NSRequestConcreteImplementation.
@param request A request to inspect.
@result YES if the protocol can handle the given request, NO if not.
*/
open class func canInit(with request: URLRequest) -> Bool { NSUnimplemented() }
/*!
@method canonicalRequestForRequest:
@abstract This method returns a canonical version of the given
request.
@discussion It is up to each concrete protocol implementation to
define what "canonical" means. However, a protocol should
guarantee that the same input request always yields the same
canonical form. Special consideration should be given when
implementing this method since the canonical form of a request is
used to look up objects in the URL cache, a process which performs
equality checks between NSURLRequest objects.
<p>
This is an abstract method; sublasses must provide an
implementation. The implementation in this class calls
NSRequestConcreteImplementation.
@param request A request to make canonical.
@result The canonical form of the given request.
*/
open class func canonicalRequest(for request: URLRequest) -> URLRequest { NSUnimplemented() }
/*!
@method requestIsCacheEquivalent:toRequest:
@abstract Compares two requests for equivalence with regard to caching.
@discussion Requests are considered euqivalent for cache purposes
if and only if they would be handled by the same protocol AND that
protocol declares them equivalent after performing
implementation-specific checks.
@result YES if the two requests are cache-equivalent, NO otherwise.
*/
open class func requestIsCacheEquivalent(_ a: URLRequest, to b: URLRequest) -> Bool { NSUnimplemented() }
/*!
@method startLoading
@abstract Starts protocol-specific loading of a request.
@discussion When this method is called, the protocol implementation
should start loading a request.
*/
open func startLoading() { NSUnimplemented() }
/*!
@method stopLoading
@abstract Stops protocol-specific loading of a request.
@discussion When this method is called, the protocol implementation
should end the work of loading a request. This could be in response
to a cancel operation, so protocol implementations must be able to
handle this call while a load is in progress.
*/
open func stopLoading() { NSUnimplemented() }
/*======================================================================
End responsibilities for protocol implementors
======================================================================*/
/*!
@method propertyForKey:inRequest:
@abstract Returns the property in the given request previously
stored with the given key.
@discussion The purpose of this method is to provide an interface
for protocol implementors to access protocol-specific information
associated with NSURLRequest objects.
@param key The string to use for the property lookup.
@param request The request to use for the property lookup.
@result The property stored with the given key, or nil if no property
had previously been stored with the given key in the given request.
*/
open class func property(forKey key: String, in request: URLRequest) -> AnyObject? { NSUnimplemented() }
/*!
@method setProperty:forKey:inRequest:
@abstract Stores the given property in the given request using the
given key.
@discussion The purpose of this method is to provide an interface
for protocol implementors to customize protocol-specific
information associated with NSMutableURLRequest objects.
@param value The property to store.
@param key The string to use for the property storage.
@param request The request in which to store the property.
*/
open class func setProperty(_ value: AnyObject, forKey key: String, in request: NSMutableURLRequest) { NSUnimplemented() }
/*!
@method removePropertyForKey:inRequest:
@abstract Remove any property stored under the given key
@discussion Like setProperty:forKey:inRequest: above, the purpose of this
method is to give protocol implementors the ability to store
protocol-specific information in an NSURLRequest
@param key The key whose value should be removed
@param request The request to be modified
*/
open class func removeProperty(forKey key: String, in request: NSMutableURLRequest) { NSUnimplemented() }
/*!
@method registerClass:
@abstract This method registers a protocol class, making it visible
to several other NSURLProtocol class methods.
@discussion When the URL loading system begins to load a request,
each protocol class that has been registered is consulted in turn to
see if it can be initialized with a given request. The first
protocol handler class to provide a YES answer to
<tt>+canInitWithRequest:</tt> "wins" and that protocol
implementation is used to perform the URL load. There is no
guarantee that all registered protocol classes will be consulted.
Hence, it should be noted that registering a class places it first
on the list of classes that will be consulted in calls to
<tt>+canInitWithRequest:</tt>, moving it in front of all classes
that had been registered previously.
<p>A similar design governs the process to create the canonical form
of a request with the <tt>+canonicalRequestForRequest:</tt> class
method.
@param protocolClass the class to register.
@result YES if the protocol was registered successfully, NO if not.
The only way that failure can occur is if the given class is not a
subclass of NSURLProtocol.
*/
open class func registerClass(_ protocolClass: AnyClass) -> Bool { NSUnimplemented() }
/*!
@method unregisterClass:
@abstract This method unregisters a protocol.
@discussion After unregistration, a protocol class is no longer
consulted in calls to NSURLProtocol class methods.
@param protocolClass The class to unregister.
*/
open class func unregisterClass(_ protocolClass: AnyClass) { NSUnimplemented() }
open class func canInit(with task: URLSessionTask) -> Bool { NSUnimplemented() }
public convenience init(task: URLSessionTask, cachedResponse: CachedURLResponse?, client: URLProtocolClient?) { NSUnimplemented() }
/*@NSCopying*/ open var task: URLSessionTask? { NSUnimplemented() }
}
| apache-2.0 | 13b9b4eeb46dc7c12bed9ebe60a0fa3f | 44.422287 | 135 | 0.700884 | 5.751578 | false | false | false | false |
icanb/react-arkit | ios/Views/ARNodeView.swift | 1 | 2631 | //
// ARSceneView.swift
// ReactArkit
//
// Created by Ilter Canberk on 8/6/17.
// Copyright © 2017. All rights reserved.
//
import Foundation
import UIKit
import ARKit
func warnForProp(_ prop: String) {
print("\(prop) must be provided to the node")
}
@objc public class ARNodeView: SCNNode {
var modelNode: SCNNode?
var modelScale: SCNVector3?
override public init() {
super.init()
initGeometry()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initGeometry()
}
func initGeometry() {
self.geometry = SCNBox.init()
}
func setSize(_ size: NSDictionary) {
if self.geometry == nil {
self.geometry = SCNGeometry.init()
}
if size["scale"] != nil {
let s: Float = Float(size["scale"] as! CGFloat)
self.modelScale = SCNVector3Make(s, s, s)
if self.modelNode != nil {
self.modelNode?.scale = self.modelScale!
}
}
}
func setModelAssetPath(_ source: NSString) {
let urlParts = source.components(separatedBy: ":")
let geoScene = SCNScene(named: urlParts[0])
guard let newModelNode: SCNNode = urlParts.count > 1 ? geoScene?.rootNode.childNode(withName: urlParts[1], recursively: true) : geoScene?.rootNode else {
print("Asset url could not be resolved")
return
}
self.modelNode = newModelNode
self.addChildNode(newModelNode)
// Reset the position so that the child node is
// positioned at the center of the parent node.
// We don't want this to be affected by the positioning
// within the scene.
self.modelNode?.position = SCNVector3Make(0, 0, 0)
self.modelNode?.scale = self.modelScale ?? SCNVector3Make(1, 1, 1)
self.geometry?.firstMaterial?.transparency = 0.0
}
func setGeoposition(_ position: NSDictionary) {
guard let xPos = position.value(forKey: "x") as! Float?
else { return warnForProp("X position") }
guard let yPos = position.value(forKey: "y") as! Float?
else { return warnForProp("Y position") }
guard let zPos = position.value(forKey: "z") as! Float?
else { return warnForProp("Z position") }
let boxPosition = SCNVector3Make(xPos, yPos, zPos)
self.position = boxPosition
}
func removeFromSuperview() {
self.removeFromParentNode()
}
func setColor(_ color: UIColor) {
self.geometry?.firstMaterial?.diffuse.contents = color
}
}
| mit | 0d12f583f3adbed2a3db8fd7b5efd79f | 26.978723 | 161 | 0.604943 | 4.154818 | false | false | false | false |
cuappdev/tcat-ios | TCAT/Model/Section.swift | 1 | 2035 | //
// Section.swift
// TCAT
//
// Created by Omar Rasheed on 5/29/19.
// Copyright © 2019 cuappdev. All rights reserved.
//
import UIKit
import CoreLocation
enum Section {
case currentLocation(location: Place)
case recentSearches(items: [Place])
case searchResults(items: [Place])
case seeAllStops
private func getVal() -> Any? {
switch self {
case .seeAllStops: return nil
case .currentLocation(let location):
return location
case .recentSearches(let items),
.searchResults(let items):
return items
}
}
var isEmpty: Bool {
switch self {
case .currentLocation, .seeAllStops: return false
case .recentSearches(let items),
.searchResults(let items): return items.isEmpty
}
}
func getItems() -> [Place] {
switch self {
case .seeAllStops: return []
case .currentLocation(let currLocation): return [currLocation]
case .recentSearches(let items),
.searchResults(let items): return items
}
}
func getItem(at index: Int) -> Place? {
switch self {
case .currentLocation, .seeAllStops: return nil
case .recentSearches(let items),
.searchResults(let items): return items[optional: index]
}
}
func getCurrentLocation() -> Place? {
if let loc = self.getVal() as? Place {
return loc
}
return nil
}
}
extension Section: Equatable {
public static func == (lhs: Section, rhs: Section) -> Bool {
switch (lhs, rhs) {
case (.seeAllStops, .seeAllStops):
return true
case (.currentLocation(let locA), .currentLocation(let locB)):
return locA == locB
case (.searchResults(let itemsA), .searchResults(let itemsB)),
(.recentSearches(let itemsA), .recentSearches(let itemsB)):
return itemsA == itemsB
default: return false
}
}
}
| mit | 9938f476c2d87f57aa4df1370bec63bd | 25.415584 | 72 | 0.584071 | 4.393089 | false | false | false | false |
justindarc/firefox-ios | XCUITests/DownloadFilesTests.swift | 1 | 6769 | import XCTest
let testFileName = "Small.zip"
let testFileSize = "178 bytes"
let testURL = "http://demo.borland.com/testsite/download_testpage.php"
class DownloadFilesTests: BaseTestCase {
override func tearDown() {
// The downloaded file has to be removed between tests
waitForExistence(app.tables["DownloadsTable"])
let list = app.tables["DownloadsTable"].cells.count
if list != 0 {
for _ in 0...list-1 {
waitForExistence(app.tables["DownloadsTable"].cells.element(boundBy: 0))
app.tables["DownloadsTable"].cells.element(boundBy: 0).swipeLeft()
waitForExistence(app.tables.cells.buttons["Delete"])
app.tables.cells.buttons["Delete"].tap()
}
}
}
private func deleteItem(itemName: String) {
app.tables.cells.staticTexts[itemName].swipeLeft()
app.tables.cells.buttons["Delete"].tap()
}
func testDownloadFilesAppMenuFirstTime() {
navigator.goto(LibraryPanel_Downloads)
XCTAssertTrue(app.tables["DownloadsTable"].exists)
// Check that there is not any items and the default text shown is correct
checkTheNumberOfDownloadedItems(items: 0)
XCTAssertTrue(app.staticTexts["Downloaded files will show up here."].exists)
}
func testDownloadFileContextMenu() {
navigator.openURL(testURL)
waitUntilPageLoad()
// Verify that the context menu prior to download a file is correct
app.webViews.staticTexts[testFileName].tap()
waitForExistence(app.webViews.buttons["Download"])
app.webViews.buttons["Download"].tap()
waitForExistence(app.tables["Context Menu"])
XCTAssertTrue(app.tables["Context Menu"].staticTexts[testFileName].exists)
XCTAssertTrue(app.tables["Context Menu"].cells["download"].exists)
app.buttons["Cancel"].tap()
navigator.goto(BrowserTabMenu)
navigator.goto(LibraryPanel_Downloads)
checkTheNumberOfDownloadedItems(items: 0)
}
func testDownloadFile() {
downloadFile(fileName: testFileName, numberOfDownlowds: 1)
navigator.goto(BrowserTabMenu)
navigator.goto(LibraryPanel_Downloads)
waitForExistence(app.tables["DownloadsTable"])
// There should be one item downloaded. It's name and size should be shown
checkTheNumberOfDownloadedItems(items: 1)
XCTAssertTrue(app.tables.cells.staticTexts[testFileName].exists)
XCTAssertTrue(app.tables.cells.staticTexts[testFileSize].exists)
}
func testDeleteDownloadedFile() {
downloadFile(fileName: testFileName, numberOfDownlowds: 1)
navigator.goto(BrowserTabMenu)
navigator.goto(LibraryPanel_Downloads)
waitForExistence(app.tables["DownloadsTable"])
deleteItem(itemName: testFileName)
waitForNoExistence(app.tables.cells.staticTexts[testFileName])
// After removing the number of items should be 0
checkTheNumberOfDownloadedItems(items: 0)
}
func testShareDownloadedFile() {
downloadFile(fileName: testFileName, numberOfDownlowds: 1)
navigator.goto(BrowserTabMenu)
navigator.goto(LibraryPanel_Downloads)
app.tables.cells.staticTexts[testFileName].swipeLeft()
XCTAssertTrue(app.tables.cells.buttons["Share"].exists)
XCTAssertTrue(app.tables.cells.buttons["Delete"].exists)
app.tables.cells.buttons["Share"].tap()
waitForExistence(app.otherElements["ActivityListView"])
if iPad() {
app.otherElements["PopoverDismissRegion"].tap()
} else {
app.buttons["Cancel"].tap()
}
}
func testLongPressOnDownloadedFile() {
downloadFile(fileName: testFileName, numberOfDownlowds: 1)
navigator.goto(BrowserTabMenu)
navigator.goto(LibraryPanel_Downloads)
waitForExistence(app.tables["DownloadsTable"])
app.tables.cells.staticTexts[testFileName].press(forDuration: 2)
waitForExistence(app.otherElements["ActivityListView"])
if iPad() {
app.otherElements["PopoverDismissRegion"].tap()
} else {
app.buttons["Cancel"].tap()
}
}
private func downloadFile(fileName: String, numberOfDownlowds: Int) {
navigator.openURL(testURL)
waitUntilPageLoad()
for _ in 0..<numberOfDownlowds {
app.webViews.staticTexts[fileName].tap()
waitForExistence(app.webViews.buttons["Download"])
app.webViews.buttons["Download"].tap()
waitForExistence(app.tables["Context Menu"])
app.tables["Context Menu"].cells["download"].tap()
}
}
func testDownloadMoreThanOneFile() {
downloadFile(fileName: testFileName, numberOfDownlowds: 2)
navigator.goto(BrowserTabMenu)
navigator.goto(LibraryPanel_Downloads)
waitForExistence(app.tables["DownloadsTable"])
checkTheNumberOfDownloadedItems(items: 2)
}
func testRemoveUserDataRemovesDownloadedFiles() {
// The option to remove downloaded files from clear private data is off by default
navigator.goto(ClearPrivateDataSettings)
XCTAssertTrue(app.cells.switches["Downloaded Files"].isEnabled, "The switch is not set correclty by default")
// Change the value of the setting to on (make an action for this)
downloadFile(fileName: testFileName, numberOfDownlowds: 1)
// Check there is one item
navigator.goto(BrowserTabMenu)
navigator.goto(LibraryPanel_Downloads)
waitForExistence(app.tables["DownloadsTable"])
checkTheNumberOfDownloadedItems(items: 1)
// Remove private data once the switch to remove downloaded files is enabled
navigator.goto(ClearPrivateDataSettings)
app.cells.switches["Downloaded Files"].tap()
navigator.performAction(Action.AcceptClearPrivateData)
navigator.goto(BrowserTabMenu)
navigator.goto(LibraryPanel_Downloads)
// Check there is still one item
checkTheNumberOfDownloadedItems(items: 0)
}
private func checkTheNumberOfDownloadedItems(items: Int) {
waitForExistence(app.tables["DownloadsTable"])
let list = app.tables["DownloadsTable"].cells.count
XCTAssertEqual(list, items, "The number of items in the downloads table is not correct")
}
func testToastButtonToGoToDownloads() {
downloadFile(fileName: testFileName, numberOfDownlowds: 1)
waitForExistence(app.buttons["Downloads"])
app.buttons["Downloads"].tap()
waitForExistence(app.tables["DownloadsTable"], timeout: 3)
checkTheNumberOfDownloadedItems(items: 1)
}
}
| mpl-2.0 | c226f4904163191e9007f40b74ab80be | 38.584795 | 117 | 0.677796 | 4.838456 | false | true | false | false |
optimizely/swift-sdk | Sources/Implementation/Datastore/DataStoreMemory.swift | 1 | 2819 | //
// Copyright 2019-2021, Optimizely, Inc. and contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
/// Implementation of OPTDataStore as a generic for per type storeage in memory. On background and foreground
/// the file is saved.
/// This class should be used as a singleton per storeName and type (T)
public class DataStoreMemory<T>: BackgroundingCallbacks, OPTDataStore where T: Codable {
let dataStoreName: String
let lock: DispatchQueue
var data: T?
var backupDataStore: OPTDataStore
public enum BackingStore { case userDefaults, file }
init(storeName: String, backupStore: BackingStore = .file) {
dataStoreName = storeName
lock = DispatchQueue(label: storeName)
switch backupStore {
case .file:
self.backupDataStore = DataStoreFile<T>(storeName: storeName, async: false)
case .userDefaults:
self.backupDataStore = DataStoreUserDefaults()
}
load(forKey: dataStoreName)
subscribe()
}
deinit {
unsubscribe()
}
public func getItem(forKey: String) -> Any? {
var retVal: T?
lock.sync {
retVal = self.data
}
return retVal
}
public func load(forKey: String) {
lock.sync {
if let contents = backupDataStore.getItem(forKey: dataStoreName) as? T {
self.data = contents
}
}
}
public func saveItem(forKey: String, value: Any) {
lock.async {
if let value = value as? T {
self.data = value
}
}
}
public func removeItem(forKey: String) {
lock.async {
self.data = nil
self.backupDataStore.removeItem(forKey: forKey)
}
// this is a no op here. data could be niled out.
}
func save(forKey: String, value: Any) {
lock.async {
self.backupDataStore.saveItem(forKey: forKey, value: value)
}
}
@objc func applicationDidEnterBackground() {
if let data = self.data {
self.save(forKey: dataStoreName, value: data as Any)
}
}
@objc func applicationDidBecomeActive() {
self.load(forKey: dataStoreName)
}
}
| apache-2.0 | c2d6be25c8136f55d95c80aa51355e63 | 29.311828 | 109 | 0.620433 | 4.532154 | false | false | false | false |
knomi/Allsorts | AllsortsTests/TestHelpers.swift | 1 | 2823 | //
// TestHelpers.swift
// Allsorts
//
// Copyright (c) 2015 Pyry Jahkola. All rights reserved.
//
import XCTest
import Allsorts
// -----------------------------------------------------------------------------
// MARK: - Assertions
func AssertContains<T : Comparable>(_ interval: @autoclosure () -> Range<T>,
_ expression: @autoclosure () -> T,
_ message: String = "",
file: StaticString = #file,
line: UInt = #line)
{
let ivl = interval()
let expr = expression()
let msg = message.isEmpty ? "\(ivl) does not contain \(expr)"
: "\(ivl) does not contain \(expr) -- \(message)"
XCTAssert(ivl.contains(expr), msg, file: file, line: line)
}
func AssertContains<T : Comparable>(_ interval: @autoclosure () -> ClosedRange<T>,
_ expression: @autoclosure () -> T,
_ message: String = "",
file: StaticString = #file,
line: UInt = #line)
{
let ivl = interval()
let expr = expression()
let msg = message.isEmpty ? "\(ivl) does not contain \(expr)"
: "\(ivl) does not contain \(expr) -- \(message)"
XCTAssert(ivl.contains(expr), msg, file: file, line: line)
}
// -----------------------------------------------------------------------------
// MARK: - Conformance checkers
func isComparableType<T : Comparable>(_: T.Type) -> Bool { return true }
func isComparableType<T : Any>(_: T.Type) -> Bool { return false }
func isOrderableType<T : Orderable>(_: T.Type) -> Bool { return true }
func isOrderableType<T : Any>(_: T.Type) -> Bool { return false }
// MARK: - Random numbers
func bitwiseCeil<T : UnsignedInteger>(_ x: T) -> T {
var i = ~T(0)
while ~i < x {
i = T.multiplyWithOverflow(i, 2).0
}
return ~i
}
func randomMax<T : UnsignedInteger>(_ max: T) -> T {
let m = bitwiseCeil(max)
var buf = T(0)
repeat {
arc4random_buf(&buf, MemoryLayout<UInt>.size)
buf = buf & m
} while buf > max
return buf
}
func random<T : UnsignedInteger>(_ interval: ClosedRange<T>) -> T {
let a = interval.lowerBound
let b = interval.upperBound
return a + randomMax(b - a)
}
func random(_ interval: ClosedRange<Int>) -> Int {
let a = UInt(bitPattern: interval.lowerBound)
let b = UInt(bitPattern: interval.upperBound)
let n = b - a
return Int(bitPattern: UInt.addWithOverflow(a, randomMax(n)).0)
}
func randomArray(count: Int, value: ClosedRange<Int>) -> [Int] {
var ints = [Int]()
for _ in 0 ..< count {
ints.append(random(value))
}
return ints
}
| mit | 9f7dbebc34ff21652f90e53e16772741 | 31.079545 | 82 | 0.510804 | 4.097242 | false | false | false | false |
kylef/Curassow | Sources/Curassow/SynchronousWorker.swift | 1 | 3996 | #if os(Linux)
import Glibc
#else
import Darwin.C
#endif
import fd
import Nest
import Inquiline
public final class SynchronousWorker : WorkerType {
let configuration: Configuration
let logger: Logger
let listeners: [Socket]
var timeout: Int {
return configuration.timeout / 2
}
let notify: (Void) -> Void
let application: (RequestType) -> ResponseType
var isAlive: Bool = false
let parentPid: pid_t
public init(configuration: Configuration, logger: Logger, listeners: [Listener], notify: @escaping (Void) -> Void, application: @escaping Application) {
self.parentPid = getpid()
self.logger = logger
self.listeners = listeners.map { Socket(descriptor: $0.fileNumber) }
self.configuration = configuration
self.notify = notify
self.application = application
}
func registerSignals() throws {
let signals = try SignalHandler()
signals.register(.interrupt, handleQuit)
signals.register(.quit, handleQuit)
signals.register(.terminate, handleTerminate)
sharedHandler = signals
SignalHandler.registerSignals()
}
public func run() {
logger.info("Booting worker process with pid: \(getpid())")
do {
try registerSignals()
} catch {
logger.info("Failed to boot \(error)")
return
}
isAlive = true
listeners.forEach { $0.blocking = false }
if listeners.count == 1 {
runOne(listeners.first!)
} else {
runMultiple(listeners)
}
}
func isParentAlive() -> Bool {
if getppid() != parentPid {
logger.info("Parent changed, shutting down")
return false
}
return true
}
func runOne(_ listener: Socket) {
while isAlive {
_ = sharedHandler?.process()
notify()
accept(listener)
if !isParentAlive() {
return
}
_ = wait()
}
}
func runMultiple(_ listeners: [Socket]) {
while isAlive {
_ = sharedHandler?.process()
notify()
let sockets = wait().filter {
$0.fileNumber != sharedHandler!.pipe.reader.fileNumber
}
sockets.forEach(accept)
if !isParentAlive() {
return
}
}
}
// MARK: Signal Handling
func handleQuit() {
isAlive = false
}
func handleTerminate() {
isAlive = false
}
func wait() -> [Socket] {
let timeout: timeval
if self.timeout > 0 {
timeout = timeval(tv_sec: self.timeout, tv_usec: 0)
} else {
timeout = timeval(tv_sec: 120, tv_usec: 0)
}
let socks = listeners + [Socket(descriptor: sharedHandler!.pipe.reader.fileNumber)]
let result = try? fd.select(reads: socks, writes: [Socket](), errors: [Socket](), timeout: timeout)
return result?.reads ?? []
}
func accept(_ listener: Socket) {
if let connection = try? listener.accept() {
let client = Socket(descriptor: connection.fileNumber)
client.blocking = true
handle(client)
}
}
func handle(_ client: Socket) {
let parser = HTTPParser(reader: client)
let response: ResponseType
do {
let request = try parser.parse()
response = application(request)
print("[worker] \(request.method) \(request.path) - \(response.statusLine)")
} catch let error as HTTPParserError {
response = error.response()
} catch {
print("[worker] Unknown error: \(error)")
response = Response(.internalServerError, contentType: "text/plain", content: "Internal Server Error")
}
sendResponse(client, response: response)
client.shutdown()
_ = try? client.close()
}
}
func sendResponse(_ client: Socket, response: ResponseType) {
client.send("HTTP/1.1 \(response.statusLine)\r\n")
client.send("Connection: close\r\n")
for (key, value) in response.headers {
if key != "Connection" {
client.send("\(key): \(value)\r\n")
}
}
client.send("\r\n")
if let body = response.body {
var body = body
while let bytes = body.next() {
client.send(bytes)
}
}
}
| bsd-2-clause | fa19af9224f95762347c6577a9b34ab3 | 21.324022 | 154 | 0.626877 | 3.984048 | false | false | false | false |
DimitreBogdanov/SQLite | SQLift/Classes/PreparedStatement.swift | 1 | 6875 | //
// PreparedStatement.swift
// SQLite
//
// Created by Dimitre Bogdanov on 2016-02-16.
// Copyright © 2016 Dimitre Bogdanov. All rights reserved.
//
import Foundation
import SQLite3
//Class used to prepare SQL statements, usually while binding values
class PreparedStatement{
//Pointer to the sql statement object used by the database to prepare the SQL
fileprivate var statement: OpaquePointer? = nil
//Reference to the database pointer used for the connection
fileprivate var database:OpaquePointer? = nil
//Should there be an error from a failure of operation, it would be stored in this variable
var error:String = ""
//Used for text binding
internal let SQLITE_STATIC = unsafeBitCast(0, to: sqlite3_destructor_type.self)
internal let SQLITE_TRANSIENT = unsafeBitCast(-1, to: sqlite3_destructor_type.self)
//Class initializer
//Prepares the sql statement with the SQL provided and the database poitner using the v2 C api
//Should there be an error while preparation, it would be stored in the _.error variable
init(sql:String, db: inout OpaquePointer){
database = db
if sqlite3_prepare_v2(db, sql, -1, &statement, nil) != SQLITE_OK{
error = (NSString(utf8String: sqlite3_errmsg(statement))! as String)
}
}
//Class initializer
//Prepares the sql statement with the SQL provided and the database poitner using the v2 C api
//All values passed are automatically bound if the statement preparation does not fail
//Should there be an error while preparation, it would be stored in the _.error variable
init(sql:String, db: inout OpaquePointer, values:[Any]){
database = db
if sqlite3_prepare_v2(db, sql, -1, &statement, nil) != SQLITE_OK{
error = (NSString(utf8String: sqlite3_errmsg(statement))! as String)
}
bindParameters(values)
}
//Loops through the provided parameters and binds them to the prepared statement
func bindParameters(_ values:[Any]){
for i in 0 ..< values.count{
bindParameter(Int32(i.advanced(by: 1)), value: values[i])
if error.trimmingCharacters(in: CharacterSet.whitespaces).isEmpty{
return
}
}
}
//Binds a value at the given index
//TODO blob, date implementation
func bindParameter(_ index:Int32, value:Any?){
if value == nil{
if sqlite3_bind_null(statement, index) != SQLITE_OK{
error = String(cString: sqlite3_errmsg(database))
print(error)
return
}
}else if value is Int{
if sqlite3_bind_int(statement, index, Int32(value as! Int)) != SQLITE_OK{
error = String(cString: sqlite3_errmsg(database))
print(error)
return
}
}else if value is String{
if sqlite3_bind_text(statement, index, value as! String, -1, SQLITE_TRANSIENT) != SQLITE_OK{
error = String(cString: sqlite3_errmsg(database))
print(error)
return
}
}else if value is Double{
if sqlite3_bind_double(statement, index, value as! Double) != SQLITE_OK{
error = String(cString: sqlite3_errmsg(database))
print(error)
return
}
}else if value is Bool{
if sqlite3_bind_int(statement, index, (value as! Bool) ? 1 : 0) != SQLITE_OK{
error = String(cString: sqlite3_errmsg(database))
print(error)
return
}
}else if value is NSDate{
let date:Date = value as! Date
let calendar = Calendar.current
let components = (calendar as NSCalendar).components([.day , .month , .year, .hour, .minute, .second], from: date)
let year = components.year
let month = components.month
let day = components.day
let hour = components.hour
let minute = components.minute
let seconds = components.second
let datetime:String = "\(year!)-\(timeString(unit: month!))-\(timeString(unit: day!)) \(timeString(unit: hour!)):\(timeString(unit: minute!)):\(timeString(unit: seconds!))"
if sqlite3_bind_text(statement, index, datetime, -1, SQLITE_TRANSIENT) != SQLITE_OK{
error = String(cString: sqlite3_errmsg(database))
print(error)
return
}
}else {
//Doesnt work yet
//sqlite3_bind_blob(statement, index, value, <#T##n: Int32##Int32#>, <#T##((UnsafeMutablePointer<Void>) -> Void)!##((UnsafeMutablePointer<Void>) -> Void)!##(UnsafeMutablePointer<Void>) -> Void#>)
}
}
//Reset the prepared statement
//Allows the statement to be reused afterwards
//Returns false if the reset failed
//_.error would contain any error if it does fail
func reset()->Bool{
if sqlite3_reset(statement) != SQLITE_OK{
error = (NSString(utf8String: sqlite3_errmsg(statement))! as String)
return false
}
return true
}
//Destroys the prepared statement and frees up the memory
//Returns false if the destroy operation failed
//_.error would contain any error if it does fail
func destroy()->Bool{
if sqlite3_finalize(statement) != SQLITE_OK{
error = (NSString(utf8String: sqlite3_errmsg(statement))! as String)
return false
}
statement = nil
return true
}
//Execute a select statement
//Used when expecting results to be returned from the query
//Returns a ResultSet initialized with the pointer of the PreparedStatement
func executeSelect()->ResultSet{
let result = ResultSet(pointer:statement!)
result.isSuccessful = true
return result
}
//Execute a statement that would update/write to the database
//Used in a situation where you would execute an UPDATE or INSERT INTO statement
//Can throw a DatabaseException.ExecutionError
//The error can either be retrieved through the _.error class member
//Or it can be retrieved through the exception by using the following syntax
//do{
// try _.executeUpdate()
//}catch DatabaseException.ExecutionError(let error){
// *error variable now contains the content of the error message*
//}
func executeUpdate()throws{
if sqlite3_step(statement) != SQLITE_DONE{
error = (NSString(utf8String: sqlite3_errmsg(statement))! as String)
throw DatabaseException.updateError(error: error)
}
_ = reset()
_ = destroy()
}
}
| apache-2.0 | dbb38c2b29a63a5fd99fd0b5e9ad0235 | 39.916667 | 207 | 0.612162 | 4.576565 | false | false | false | false |
hivinau/bioserenity | bios.cars/Car.swift | 1 | 1359 | //
// Car.swift
// bios.cars
//
// Created by iOS Developer on 22/07/2017.
// Copyright © 2017 fdapps. All rights reserved.
//
import Foundation
@objc(Car)
public class Car: NSObject {
private var _brand: String?
private var _name: String?
private var _speedMax: Int?
private var _cv: Int?
private var _currentSpeed: Int?
public var brand: String? {
get {
return _brand
}
}
public var name: String? {
get {
return _name
}
}
public var speedMax: Int? {
get {
return _speedMax
}
}
public var cv: Int? {
get {
return _cv
}
}
public var currentSpeed: Int? {
get {
return _currentSpeed
}
}
public init(brand: String?, name: String?, speedMax: Int?, cv: Int?, currentSpeed: Int?) {
super.init()
self._brand = brand
self._name = name
self._speedMax = speedMax
self._cv = cv
self._currentSpeed = currentSpeed
}
}
public func ==(lhs: Car, rhs: Car) -> Bool {
return (lhs.name == rhs.name) && (lhs.brand == rhs.brand) && (lhs.cv == rhs.cv)
}
| apache-2.0 | 9ed8014e222b55d6dcbfc5b0736b5e3d | 17.351351 | 94 | 0.462445 | 4.27044 | false | false | false | false |
mozilla-mobile/firefox-ios | Client/Telemetry/SponsoredTileTelemetry.swift | 2 | 2446 | // This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/
import Foundation
import Glean
// Telemetry for the Sponsored tiles located in the Top sites on the Firefox home page
// Using Pings to send the telemetry events
class SponsoredTileTelemetry {
// Source is only new tab at the moment, more source could be added later
static let source = "newtab"
enum UserDefaultsKey: String {
case keyContextId = "com.moz.contextId.key"
}
static var contextId: String? {
get { UserDefaults.standard.object(forKey: UserDefaultsKey.keyContextId.rawValue) as? String }
set { UserDefaults.standard.set(newValue, forKey: UserDefaultsKey.keyContextId.rawValue) }
}
static func clearUserDefaults() {
SponsoredTileTelemetry.contextId = nil
}
static func setupContextId() {
// Use existing client UUID, if doesn't exists create a new one
if let stringContextId = contextId, let clientUUID = UUID(uuidString: stringContextId) {
GleanMetrics.TopSites.contextId.set(clientUUID)
} else {
let newUUID = UUID()
GleanMetrics.TopSites.contextId.set(newUUID)
contextId = newUUID.uuidString
}
}
static func sendImpressionTelemetry(tile: SponsoredTile, position: Int) {
let extra = GleanMetrics.TopSites.ContileImpressionExtra(position: Int32(position), source: SponsoredTileTelemetry.source)
GleanMetrics.TopSites.contileImpression.record(extra)
GleanMetrics.TopSites.contileTileId.set(Int64(tile.tileId))
GleanMetrics.TopSites.contileAdvertiser.set(tile.title)
GleanMetrics.TopSites.contileReportingUrl.set(tile.impressionURL)
GleanMetrics.Pings.shared.topsitesImpression.submit()
}
static func sendClickTelemetry(tile: SponsoredTile, position: Int) {
let extra = GleanMetrics.TopSites.ContileClickExtra(position: Int32(position), source: SponsoredTileTelemetry.source)
GleanMetrics.TopSites.contileClick.record(extra)
GleanMetrics.TopSites.contileTileId.set(Int64(tile.tileId))
GleanMetrics.TopSites.contileAdvertiser.set(tile.title)
GleanMetrics.TopSites.contileReportingUrl.set(tile.clickURL)
GleanMetrics.Pings.shared.topsitesImpression.submit()
}
}
| mpl-2.0 | c1f2f0c25dd775669e66249ccfe87f99 | 41.172414 | 130 | 0.721177 | 4.239168 | false | false | false | false |
Azero123/JW-Broadcasting | JW Broadcasting/RootController.swift | 1 | 21371 | //
// rootController.swift
// JW Broadcasting
//
// Created by Austin Zelenka on 9/22/15.
// Copyright © 2015 Austin Zelenka. All rights reserved.
//
import UIKit
import TVMLKit
var disableNavBar=false
extension UITabBarController : TVApplicationControllerDelegate {
/*method to check whether the tab bar is lined up or not*/
func tabBarIsVisible() ->Bool {
return self.view.frame.origin.y == 0
}
func setTabBarVisible(visible:Bool, animated:Bool) {
if (disableNavBar == false){
/*figure out what the height of the tab bar is*/
let frame = self.tabBar.frame
let height = frame.size.height
let offsetY = (visible==false ? -height : 0)
/*animate the removal of the tab bar so it looks nice if "animated" is true*/
UIView.animateWithDuration(animated ? 0.3 : 0.0) {
/*adjust the view to move upward hiding the tab bar and then stretch it to make up for moving it*/
self.tabBar.frame=CGRect(x: 0, y: offsetY, width: self.tabBar.frame.size.width, height: self.tabBar.frame.size.height)
self.tabBarController?.viewControllers![(self.tabBarController?.selectedIndex)!].view.layoutIfNeeded()
}
}
self.tabBarController?.viewControllers![(self.tabBarController?.selectedIndex)!].updateFocusIfNeeded()
}
}
/*
language dictionary break down
code = language code used by tv.jw.org... all the files are inside various language code named folders
locale = matches typical locale abbreviation and can be used with NSLocale
isRTL = Bool for right to left languages
name = Displayable string name for the language you are in?
vernacular = Displayable string name in that language?
isLangPair = 0; unkown bool
isSignLanguage = Bool for sign languages
*/
func languageFromLocale(var locale:String) -> NSDictionary?{
locale=locale.componentsSeparatedByString("-")[0]
if (languageList?.count>0){
for language in languageList! {
/* This just simply looks for corresponding language for the system language Locale */
if (language.objectForKey("locale") as! String==locale){
return language
}
}
}
return nil
}
func languageFromCode(code:String) -> NSDictionary?{
if (languageList?.count>0){
for language in languageList! {
/* This just simply looks for corresponding language for the system language code */
if (language.objectForKey("code") as! String==code){
return language
}
}
}
return nil
}
var translatedKeyPhrases:NSDictionary?
let logoImageView=UIImageView(image: UIImage(named: "JWOrgLogo.png"))
let logoLabelView=UILabel()
class rootController: UITabBarController, UITabBarControllerDelegate{
var _disableNavBarTimeOut=false
var disableNavBarTimeOut:Bool {
set (newValue){
_disableNavBarTimeOut=newValue
if (newValue == true){
timer?.invalidate()
}
else {
timer=NSTimer.scheduledTimerWithTimeInterval(12, target: self, selector: "hide", userInfo: nil, repeats: false)
}
}
get {
return _disableNavBarTimeOut
}
}
override func viewDidLoad() {
super.viewDidLoad()
/*
Create a JW.org logo on the left side of the tab bar.
*/
if (JWLogo){
/*logoLabelView.font=UIFont(name: "jwtv", size: self.tabBar.frame.size.height+60) // Use the font from jw.org to display the jw logo
logoLabelView.frame=CGRect(x: 110, y: 10+10, width: self.tabBar.frame.size.height+60, height: self.tabBar.frame.size.height+60)//initial logo position and size
logoLabelView.text=""//The unique key code for the JW.org logo
logoLabelView.textAlignment = .Left
logoLabelView.lineBreakMode = .ByClipping
logoLabelView.frame=CGRect(x: 110, y: 10+10, width: logoLabelView.intrinsicContentSize().width, height: self.tabBar.frame.size.height+60)//corrected position
logoLabelView.textColor=UIColor(colorLiteralRed: 0.3, green: 0.44, blue: 0.64, alpha: 1.0) // JW blue color
self.tabBar.addSubview(logoLabelView)*/
//logoImageView.backgroundColor=UIColor.blueColor()
logoImageView.frame=CGRect(x: 110, y: 10+10, width: 110, height: 110)
self.tabBar.addSubview(logoImageView)
}
/*
This loop cycles through all the view controllers and their corresponding tab bar items.
All the tab bar items are set to grey text.
If the view controller is disabled in the control file then it is removed.
The Language view controllers text is made to be the language icon found in the jwtv.tff font file.
*/
for viewController in self.viewControllers! {
let fontattributes=[NSForegroundColorAttributeName:UIColor.grayColor()] as Dictionary<String,AnyObject>
let tabBarItem=self.tabBar.items?[(self.viewControllers?.indexOf(viewController))!]
if (tabBarItem != nil){
tabBarItem!.setTitleTextAttributes(fontattributes, forState: .Normal)
}
if (viewController.isKindOfClass(HomeController.self)){//Remove home page if disabled
if (Home==false){
self.viewControllers?.removeAtIndex((self.viewControllers?.indexOf(viewController))!)
}
}
else if (viewController.isKindOfClass(VideoOnDemandController.self)){//Remove VOD page if disabled
if (VOD==false){
self.viewControllers?.removeAtIndex((self.viewControllers?.indexOf(viewController))!)
}
}
else if (viewController.isKindOfClass(AudioController.self)){//Remove Audio page if disabled
if (Audio==false){
self.viewControllers?.removeAtIndex((self.viewControllers?.indexOf(viewController))!)
}
}
else if (viewController.isKindOfClass(LanguageSelector.self)){//Remove Language page if disabled
if (Language==false){
self.viewControllers?.removeAtIndex((self.viewControllers?.indexOf(viewController))!)
}
else {//Set language page to language icon
self.tabBar.items?[(self.viewControllers?.indexOf(viewController))!].title=" "
let fontattributes=[NSFontAttributeName:UIFont(name: "jwtv", size: 36)!,NSForegroundColorAttributeName:UIColor.grayColor()] as Dictionary<String,AnyObject>
self.tabBar.items?[(self.viewControllers?.indexOf(viewController))!].setTitleTextAttributes(fontattributes, forState: .Normal)
}
}
else if (viewController.isKindOfClass(SearchController.self)){//Remove Search page if disabled
if (Search==false){
self.viewControllers?.removeAtIndex((self.viewControllers?.indexOf(viewController))!)
}
else {
self.tabBar.items?[(self.viewControllers?.indexOf(viewController))!].title="Search"
}
}
else if (viewController.isKindOfClass(MediaOnDemandController.self)){//Remove MOD page if disabled
if (BETAMedia==false){
self.viewControllers?.removeAtIndex((self.viewControllers?.indexOf(viewController))!)
}
else {
self.tabBar.items?[(self.viewControllers?.indexOf(viewController))!].title="Video on Demand"
}
}
else if (viewController.isKindOfClass(NewAudioController.self)){//Remove MOD page if disabled
if (NewAudio==false){
self.viewControllers?.removeAtIndex((self.viewControllers?.indexOf(viewController))!)
}
else {
self.tabBar.items?[(self.viewControllers?.indexOf(viewController))!].title="Audio"
}
}
}
if (textDirection == .RightToLeft){ // select the far right page if language is right to left
self.selectedIndex=(self.viewControllers?.count)!-1
}
else {
self.selectedIndex=0
}
/*self delegating :D*/
self.delegate=self
/* make the tab bar on top match the rest of the app*/
UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.blackColor()], forState:.Normal)
UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.whiteColor()], forState:.Selected)
fetchDataUsingCache(base+"/"+version+"/languages/"+languageCode+"/web", downloaded: {
dispatch_async(dispatch_get_main_queue()) {
let download=dictionaryOfPath(base+"/"+version+"/languages/"+languageCode+"/web")
languageList=download?.objectForKey("languages") as? Array<NSDictionary>
//dispatch_async(dispatch_get_main_queue()) {
if (languageList?.count==0){
self.performSelector("displayUnableToConnect", withObject: self, afterDelay: 1.0)
}
else {
let settings=NSUserDefaults.standardUserDefaults()
var language:NSDictionary?
if ((settings.objectForKey("language")) != nil){
language=languageFromCode(settings.objectForKey("language") as! String) //Attempt using language from settings file
}
if (language == nil){
language=languageFromLocale(NSLocale.preferredLanguages()[0]) ; print("system language")} //Attempt using system language
if (language == nil){
print("unable to find a language")
//Language detection has failed default to english
self.performSelector("displayFailedToFindLanguage", withObject: nil, afterDelay: 1.0); print("default english")
language=languageFromLocale("en")
}
if (language == nil){ language=languageList?.first; print("default random") } //English failed use any language
if ((language) != nil){
self.setLanguage(language!.objectForKey("code") as! String, newTextDirection: ( language!.objectForKey("isRTL")?.boolValue == true ? UIUserInterfaceLayoutDirection.RightToLeft : UIUserInterfaceLayoutDirection.LeftToRight ))
//textDirection=UIUserInterfaceLayoutDirection.RightToLeft
}
}
}
})
if (disableNavBarTimeOut == false){
timer=NSTimer.scheduledTimerWithTimeInterval(12, target: self, selector: "hide", userInfo: nil, repeats: false)
}
let swipeRecognizer = UISwipeGestureRecognizer(target: self, action: "swiped:")
swipeRecognizer.direction = .Right //|| .Up || .Left || .Right
self.view.addGestureRecognizer(swipeRecognizer)
let tapRecognizer = UITapGestureRecognizer(target: self, action: "tapped:")
tapRecognizer.allowedPressTypes = [NSNumber(integer: UIPressType.PlayPause.rawValue)];
self.view.addGestureRecognizer(tapRecognizer)
}
func displayFailedToFindLanguage(){
//Alert the user that we do not know what language they are using
let alert=UIAlertController(title: "Language Unknown", message: "Unable to find a language for you.", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "Okay", style: .Default , handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
}
func displayUnableToConnect(){
//Let the user know that we were not able to connect to JW.org
if (translatedKeyPhrases != nil){
//alert the user translated text that connection failed
let alert=UIAlertController(title: translatedKeyPhrases?.objectForKey("msgAPIFailureErrorTitle") as? String, message: translatedKeyPhrases?.objectForKey("msgAPIFailureErrorBody")as? String, preferredStyle: UIAlertControllerStyle.Alert)
self.presentViewController(alert, animated: true, completion: nil)
}
else {
//alert the user without translated text that the connection failed.
let alert=UIAlertController(title: "Cannot connect to JW Broadcasting", message: "Make sure you're connected to the internet then try again.", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "Okay", style: .Default , handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
}
}
func tapped(tap:UIGestureRecognizer){
//upon tap of the remote we bring the tab bar down
keepDown()
}
func swipe(recognizer:UIGestureRecognizer){
//upon swipe of the remote we bring the tab bar down
keepDown()
}
func swiped(sender:UISwipeGestureRecognizer){
//upon swipe of the remote we bring the tab bar down
keepDown()
}
override func pressesBegan(presses: Set<UIPress>, withEvent event: UIPressesEvent?){
//upon press of the remote we bring the tab bar down
super.pressesBegan(presses, withEvent: event)
}
override func tabBar(tabBar: UITabBar, didSelectItem item: UITabBarItem) {
keepDown()
self.setTabBarVisible(true, animated: true)
}
var timer:NSTimer?=nil
func keepDown(){
/*
This method restarts thte timer for how long the tab bar can be seen.
*/
timer?.invalidate()
if (disableNavBarTimeOut == false){
timer=NSTimer.scheduledTimerWithTimeInterval(12, target: self, selector: "hide", userInfo: nil, repeats: false)
}
self.setTabBarVisible(true, animated: true)
}
func hide(){
//Hides tab bar
self.setTabBarVisible(false, animated: true)
}
// }
/*
Whenever the language is set or changed this method will change the tab bar buttons to match the appropriate languages and order.
First it checks whether the text direction (Left to right, or right to left) has changed.
If the current direction and the new direction are different then the order is reversed by setting the view controller array in reversed order. Animated for fun and beauty (:
Sets the buttons using their corresponding keys for title. If the language is in right to left the for loop is reversed.
NOTE
As of September I do not see any right-to-left languages in tv.jw.org however that could change or I could be mistaken. The point is this is untested.
*/
func setLanguage(newLanguageCode:String, newTextDirection:UIUserInterfaceLayoutDirection){
if (newLanguageCode != languageCode){
print("[Translation] Setting new language \(newLanguageCode)")
fileDownloadedClosures.removeAll()
languageCode=newLanguageCode
/*
Save settings language settings to settings.plist file in library folder.
*/
let settings=NSUserDefaults.standardUserDefaults()
//.setObject("", forKey: "")
settings.setObject(newLanguageCode, forKey: "language")
/* check for possible direction change*/
if (newTextDirection != textDirection){
textDirection=newTextDirection
self.setViewControllers(self.viewControllers?.reverse(), animated: true)
if (JWLogo){
if (textDirection == .RightToLeft){
logoImageView.frame=CGRect(x: self.tabBar.frame.size.width-logoImageView.frame.size.width-110, y: 10+10, width: 110, height: 110)
}
else {
logoLabelView.textAlignment = .Left
logoImageView.frame=CGRect(x: 110, y: 10+10, width: 110, height: 110)
print(logoImageView.frame)
}
}
}
/* download new translation */
translatedKeyPhrases=dictionaryOfPath(base+"/"+version+"/translations/"+languageCode)?.objectForKey("translations")?.objectForKey(languageCode) as? NSDictionary
if (translatedKeyPhrases != nil){ // if the language file was obtained
/*These keys are what I found correspond to the navigation buttons on tv.jw.org*/
let startIndex=0
let endIndex=self.viewControllers!.count
/* replace titles */
for var i=startIndex ; i<endIndex ; i++ {
var keyForButton=""
let viewController = self.viewControllers![i]
if (viewController.isKindOfClass(HomeController.self)){
keyForButton="lnkHomeView"
}
else if (viewController.isKindOfClass(MediaOnDemandController.self)){
keyForButton="homepageVODBlockTitle"//
}
else if (viewController.isKindOfClass(VideoOnDemandController.self)){
keyForButton="homepageVODBlockTitle"//
}
else if (viewController.isKindOfClass(AudioController.self)){
keyForButton="homepageAudioBlockTitle"//
}
else if (viewController.isKindOfClass(LanguageSelector.self)){
//"lnkLanguage"//
keyForButton=" "
/*self.tabBar.items?[(self.viewControllers?.indexOf(viewController))!].title=" "
let fontattributes=[NSFontAttributeName:UIFont(name: "jwtv", size: 36)!,NSForegroundColorAttributeName:UIColor.grayColor()] as Dictionary<String,AnyObject>
self.tabBar.items?[(self.viewControllers?.indexOf(viewController))!].setTitleTextAttributes(fontattributes, forState: .Normal)*/
}
else if (viewController.isKindOfClass(SearchController.self)){
keyForButton="Search"
}
else if (viewController.isKindOfClass(NewAudioController.self)){
keyForButton="homepageAudioBlockTitle"
}
let newText=translatedKeyPhrases?.objectForKey(keyForButton) as? String
if (newText != nil){
self.tabBar.items?[i].title=newText
}
else {
self.tabBar.items?[i].title=keyForButton
}
if (viewController.isKindOfClass(LanguageSelector.self)){
let fontattributes=[NSFontAttributeName:UIFont(name: "jwtv", size: 36)!,NSForegroundColorAttributeName:UIColor.grayColor()] as Dictionary<String,AnyObject>
self.tabBar.items?[(self.viewControllers?.indexOf(viewController))!].setTitleTextAttributes(fontattributes, forState: .Normal)
}
else {
let fontattributes=[NSForegroundColorAttributeName:UIColor.grayColor()] as Dictionary<String,AnyObject>
self.tabBar.items?[i].setTitleTextAttributes(fontattributes, forState: .Normal)
}
}
}
else {
self.performSelector("displayUnableToConnect", withObject: self, afterDelay: 1.0)
}
print("completed")
checkBranchesFor("language")
}
if (false){
var subviews:Array<UIView>=self.tabBar.subviews
//logoLabelView.hidden=false
logoImageView.hidden=false
while subviews.first != nil {
let subview = subviews.first
subviews.removeFirst()
subviews.appendContentsOf(subview!.subviews)
if (subview!.isKindOfClass(NSClassFromString("UITabBarButton")!)){
if (CGRectIntersectsRect((subview?.frame)!, logoImageView.frame)){
//logoLabelView.hidden=true
logoImageView.hidden=true
}
}
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit | 3c016fe4526a6a3704396a9e9845dd67 | 42.402439 | 247 | 0.599138 | 5.451621 | false | false | false | false |
Za1006/TIY-Assignments | VenueMenu/VenueMenu/APIController.swift | 1 | 2067 | //
// APIController.swift
// VenueMenu
//
// Created by Elizabeth Yeh on 11/29/15.
// Copyright © 2015 The Iron Yard. All rights reserved.
//
import Foundation
class APIController
{
var delegate: FoursquareAPIResultsProtocol?
init(delegate: FoursquareAPIResultsProtocol)
{
self.delegate = delegate
}
func searchFoursquareFor(searchTerm: String)
{
let location = "Orlando, FL"
let escapedLocation = location.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())
let escapedSearchTerm = searchTerm.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())
let urlPath = "https://api.foursquare.com/v2/venues/search?client_id=KQVWNK0N2IZG0JO5YEIHEM2LBSET02GOM3CSJQ4YFSP5PWAZ&client_secret=SUTWYTLTZPR1EJV3422DUFJQVICHSJCKG5WBW02ITASNOKIS&v=20130815&near=\(escapedLocation!)&query=\(escapedSearchTerm!)"
let url = NSURL(string: urlPath)
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithURL(url!, completionHandler: {data, response, error -> Void in
print("Task completed")
if error != nil
{
print(error!.localizedDescription)
}
else
{
if let dictionary = self.parseJSON(data!)
{
if let responseDictionary: NSDictionary = dictionary["response"] as? NSDictionary
{
self.delegate!.didReceiveFoursquareAPIResults(responseDictionary)
}
}
}
})
task.resume()
}
func parseJSON(data: NSData) -> NSDictionary?
{
do
{
let dictionary: NSDictionary! = try NSJSONSerialization.JSONObjectWithData(data, options: []) as! NSDictionary
return dictionary
}
catch let error as NSError
{
print(error)
return nil
}
}
}
| cc0-1.0 | e9ee7093b529c3108d139c7f64128c17 | 29.835821 | 253 | 0.621491 | 4.861176 | false | false | false | false |
MarcoSantarossa/SwiftyToggler | Source/Common/PresentingMode.swift | 1 | 1619 | //
// PresentingMode.swift
//
// Copyright (c) 2017 Marco Santarossa (https://marcosantadev.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.
//
enum PresentingMode: Equatable {
case modal(UIWindowProtocol)
case inParent(UIViewControllerProtocol, UIViewProtocol?)
}
func == (lhs: PresentingMode, rhs: PresentingMode) -> Bool {
switch (lhs, rhs) {
case (.modal(let windowL), .modal(let windowR)):
return windowL === windowR
case (.inParent(let vcL, let viewL), .inParent(let vcR, let viewR)):
return vcL === vcR && viewL === viewR
default:
return false
}
}
| mit | d92cd6726633b950e1511eeefd670482 | 40.512821 | 81 | 0.736875 | 3.901205 | false | false | false | false |
TheHolyGrail/Zoot | ELHybridWebTests/WebViewControllerDelegateTests.swift | 2 | 2272 | //
// WebViewControllerDelegateTests.swift
// ELHybridWeb
//
// Created by Angelo Di Paolo on 5/20/15.
// Copyright (c) 2015 WalmartLabs. All rights reserved.
//
import UIKit
import XCTest
import ELHybridWeb
class WebViewControllerDelegateTests: XCTestCase, WebViewControllerDelegate {
var didStartLoadExpectation: XCTestExpectation?
var didFinishLoadExpectation: XCTestExpectation?
var shouldStartLoadExpectation: XCTestExpectation?
var didFailLoadExpectation: XCTestExpectation?
func testDelegateDidStartLoad() {
let vc = WebViewController()
vc.delegate = self
didStartLoadExpectation = expectation(description: "did start load")
vc.webViewDidStartLoad(UIWebView())
waitForExpectations(timeout: 4.0, handler: nil)
}
func testDelegateDidFinishLoad() {
let vc = WebViewController()
vc.delegate = self
didFinishLoadExpectation = expectation(description: "did finish load")
vc.webViewDidFinishLoad(UIWebView())
waitForExpectations(timeout: 4.0, handler: nil)
}
func testDelegateShouldStartLoad() {
let request = URLRequest(url: NSURL(string: "")! as URL)
let vc = WebViewController()
vc.delegate = self
shouldStartLoadExpectation = expectation(description: "should start load")
let _ = vc.webView(UIWebView(), shouldStartLoadWith: request, navigationType: .reload)
waitForExpectations(timeout: 4.0, handler: nil)
}
// MARK: WebViewControllerDelegate
func webViewControllerDidStartLoad(_ webViewController: WebViewController) {
didStartLoadExpectation?.fulfill()
}
func webViewControllerDidFinishLoad(_ webViewController: WebViewController) {
didFinishLoadExpectation?.fulfill()
}
func webViewController(_ webViewController: WebViewController, shouldStartLoadWithRequest request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
shouldStartLoadExpectation?.fulfill()
return true
}
func webViewController(_ webViewController: WebViewController, didFailLoadWithError error: Error) {
didFailLoadExpectation?.fulfill()
}
}
| mit | b7f000b0d4ec19caf27c93bb53192bd7 | 31.457143 | 165 | 0.694982 | 5.795918 | false | true | false | false |
abunur/quran-ios | Quran/AudioDownloadsDataSource.swift | 1 | 9818 | //
// AudioDownloadsDataSource.swift
// Quran
//
// Created by Mohamed Afifi on 4/17/17.
//
// Quran for iOS is a Quran reading application for iOS.
// Copyright (C) 2017 Quran.com
//
// 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.
//
import BatchDownloader
import GenericDataSources
protocol AudioDownloadsDataSourceDelegate: class {
func audioDownloadsDataSource(_ dataSource: AbstractDataSource, errorOccurred error: Error)
}
class AudioDownloadsDataSource: BasicDataSource<DownloadableQariAudio, AudioDownloadTableViewCell> {
private let deletionInteractor: AnyInteractor<Qari, Void>
private let downloader: DownloadManager
private let ayahsDownloader: AnyInteractor<AyahsAudioDownloadRequest, DownloadBatchResponse>
fileprivate let qariAudioDownloadRetriever: AnyInteractor<[Qari], [QariAudioDownload]>
fileprivate var downloadingObservers: [Qari: DownloadingObserver<DownloadableQariAudio>] = [:]
weak var delegate: AudioDownloadsDataSourceDelegate?
var onEditingChanged: (() -> Void)?
init(downloader: DownloadManager,
ayahsDownloader: AnyInteractor<AyahsAudioDownloadRequest, DownloadBatchResponse>,
qariAudioDownloadRetriever: AnyInteractor<[Qari], [QariAudioDownload]>,
deletionInteractor: AnyInteractor<Qari, Void>) {
self.downloader = downloader
self.ayahsDownloader = ayahsDownloader
self.qariAudioDownloadRetriever = qariAudioDownloadRetriever
self.deletionInteractor = deletionInteractor
super.init()
}
override func ds_collectionView(_ collectionView: GeneralCollectionView, willBeginEditingItemAt indexPath: IndexPath) {
// call it in the next cycle to give isEditing a chance to change
DispatchQueue.main.async {
self.onEditingChanged?()
}
}
override func ds_collectionView(_ collectionView: GeneralCollectionView, didEndEditingItemAt indexPath: IndexPath) {
onEditingChanged?()
}
override func ds_collectionView(_ collectionView: GeneralCollectionView, canEditItemAt indexPath: IndexPath) -> Bool {
let item = self.item(at: indexPath)
return item.response == nil && item.audio.downloadedSizeInBytes != 0
}
override func ds_collectionView(_ collectionView: GeneralCollectionView,
commit editingStyle: UITableViewCellEditingStyle,
forItemAt indexPath: IndexPath) {
guard editingStyle == .delete else {
return
}
let item = self.item(at: indexPath)
Analytics.shared.deletingQuran(qari: item.audio.qari)
deletionInteractor
.execute(item.audio.qari)
.then(on: .main) { () -> Void in
let newDownload = QariAudioDownload(qari: item.audio.qari, downloadedSizeInBytes: 0, downloadedSuraCount: 0)
let newItem = DownloadableQariAudio(audio: newDownload, response: nil)
self.items[indexPath.item] = newItem
self.ds_reusableViewDelegate?.ds_reloadItems(at: [indexPath], with: .automatic)
}.catch(on: .main) { error in
self.delegate?.audioDownloadsDataSource(self, errorOccurred: error)
}
}
override func ds_collectionView(_ collectionView: GeneralCollectionView,
configure cell: AudioDownloadTableViewCell,
with item: DownloadableQariAudio,
at indexPath: IndexPath) {
cell.configure(with: item.audio)
cell.downloadButton.state = item.state
cell.onShouldStartDownload = { [weak self] in
self?.onShouldStartDownload(item: item)
}
cell.onShouldCancelDownload = { [weak self] in
self?.onShouldCancelDownload(item: item)
}
}
override func ds_collectionView(_ collectionView: GeneralCollectionView, willDisplay cell: ReusableCell, forItemAt indexPath: IndexPath) {
(cell as? AudioDownloadTableViewCell)?.downloadButton.state = item(at: indexPath).state
}
override var items: [DownloadableQariAudio] {
didSet {
downloadingObservers.forEach { $1.stop() }
downloadingObservers.removeAll()
for item in items where item.response != nil {
downloadingObservers[item.audio.qari] = DownloadingObserver(item: item, delegate: self)
}
}
}
private var cancelled: Protected<Bool> = Protected(false)
func onShouldStartDownload(item: DownloadableQariAudio) {
cancelled.value = false
Analytics.shared.downloadingQuran(qari: item.audio.qari)
// download the audio
ayahsDownloader
.execute(AyahsAudioDownloadRequest(start: Quran.startAyah, end: Quran.lastAyah, qari: item.audio.qari))
.then { response -> Void in
guard !self.cancelled.value else {
response.cancel()
return
}
guard let itemIndex = self.items.index(of: item) else {
return
}
// update the item to be downloading
let newItem = DownloadableQariAudio(audio: item.audio, response: response)
self.items[itemIndex] = newItem
// observe download progress
self.downloadingObservers[newItem.audio.qari] = DownloadingObserver(item: newItem, delegate: self)
}.suppress()
}
func onShouldCancelDownload(item: DownloadableQariAudio) {
if let observer = downloadingObservers[item.audio.qari] {
observer.cancel()
} else {
cancelled.value = true // if cancelled early
}
guard let itemIndex = self.items.index(of: item) else {
return
}
// update the item to be not downloading
self.items[itemIndex] = DownloadableQariAudio(audio: item.audio, response: nil)
}
}
extension AudioDownloadsDataSource: DownloadingObserverDelegate {
func onDownloadProgressUpdated(progress: Float, for item: DownloadableQariAudio) {
guard let localIndexPath = self.indexPath(for: item) else {
CLog("Cannot updated progress for audio \(item.audio.qari.name)")
return
}
let cell = self.ds_reusableViewDelegate?.ds_cellForItem(at: localIndexPath) as? AudioDownloadTableViewCell
let scale: Float = 2_000
let oldValue = floor((cell?.downloadButton.state.progress ?? 0) * scale)
let newValue = floor(item.state.progress * scale)
cell?.downloadButton.state = item.state
if newValue - oldValue > 0.9 {
reload(item: item, response: item.response)
}
}
func onDownloadCompleted(withError error: Error, for item: DownloadableQariAudio) {
guard let localIndexPath = indexPath(for: item) else {
CLog("Cannot error download for audio \(item.audio.qari.name)")
return
}
// update the item to be not downloading
let newItem = DownloadableQariAudio(audio: item.audio, response: nil)
self.items[localIndexPath.item] = newItem
// update the UI
delegate?.audioDownloadsDataSource(self, errorOccurred: error)
let cell = ds_reusableViewDelegate?.ds_cellForItem(at: localIndexPath) as? AudioDownloadTableViewCell
cell?.downloadButton.state = newItem.state
}
func onDownloadCompleted(for item: DownloadableQariAudio) {
guard let localIndexPath = indexPath(for: item) else {
CLog("Cannot complete download for audio \(item.audio.qari.name)")
return
}
// remove old observer
let observer = downloadingObservers.removeValue(forKey: item.audio.qari)
observer?.stop()
// update the cell
let cell = self.ds_reusableViewDelegate?.ds_cellForItem(at: localIndexPath) as? AudioDownloadTableViewCell
cell?.downloadButton.state = .downloaded
reload(item: item, response: nil)
}
private func reload(item: DownloadableQariAudio, response: DownloadBatchResponse?) {
qariAudioDownloadRetriever.execute([item.audio.qari])
.then(on: .main) { audios -> Void in
guard let audio = audios.first else {
return
}
guard let localIndexPath = self.indexPath(for: item) else {
CLog("Cannot get audio indexPath for \(item.audio.qari.name)")
return
}
let oldItem = self.items[localIndexPath.item]
let finalResponse: DownloadBatchResponse?
if response == nil || oldItem.response == nil {
finalResponse = nil
} else {
finalResponse = response
}
// update the item response
let newItem = DownloadableQariAudio(audio: audio, response: finalResponse)
self.items[localIndexPath.item] = newItem
let cell = self.ds_reusableViewDelegate?.ds_cellForItem(at: localIndexPath) as? AudioDownloadTableViewCell
cell?.configure(with: audio)
}.suppress()
}
}
| gpl-3.0 | f8046d41d636e08151b8dcee7b83c030 | 38.910569 | 142 | 0.643614 | 5.089684 | false | false | false | false |
rdhiggins/PythonMacros | PythonMacros/UIAlertController+Window.swift | 1 | 1478 | //
// UIAlertController+Window.swift
// PythonTest.Swift
//
// Created by Rodger Higgins on 6/16/16.
// Copyright © 2016 Rodger Higgins. All rights reserved.
//
import UIKit
// Need this
private var alertWindowKey: UInt8 = 0
/// This extension provides a mechanism for displaying UIAlertController
/// from places that are not connected to a UIViewController. It essentially
/// creates a UIWindow with a transparent root view controller.
///
/// Uses the Objective-C associated object.
extension UIAlertController {
var alertWindow: UIWindow {
get {
return associatedObject(self, key: &alertWindowKey) {
return UIWindow(frame: UIScreen.main.bounds)
}
}
set {
associateObject(self, key: &alertWindowKey, value: newValue)
}
}
func show() {
self.show(true)
}
func show(_ animated: Bool) {
let window = alertWindow
window.rootViewController = UIViewController()
window.tintColor = UIApplication.shared.delegate?.window!!.tintColor
let topWindow = UIApplication.shared.windows.last
window.windowLevel = (topWindow?.windowLevel)! + 1
window.makeKeyAndVisible()
window.rootViewController?.present(self, animated: animated, completion: nil)
}
open override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
self.alertWindow.isHidden = true
}
}
| mit | 5f909fa6e37a0a52f03878b24c025a56 | 24.912281 | 85 | 0.660799 | 4.703822 | false | false | false | false |
nangege/SkinManager | SkinManager/PickerProtocol.swift | 1 | 1354 | //
// Skin.swift
// Pods
//
// Created by nantang on 2016/11/8.
//
//
import Foundation
public protocol ValueProtocol{
var skinValue:Any? { get }
}
public protocol Applicable{
func apply(to: AnyObject,sel: Selector)
}
public protocol PickerProtocol: class,ValueProtocol,Applicable {
associatedtype ValueType
var value:ValueType? { get }
}
private struct Closue<T> {
typealias ClosueType = () -> T?
var closue: ClosueType?
init(closue: ClosueType?) {
self.closue = closue
}
}
struct AssociatedKey {
static var ValueGenerator = "ValueGenerator"
}
extension PickerProtocol{
typealias ValueGenerator = () -> ValueType?
var valueGenerator: ValueGenerator? {
get{ return (objc_getAssociatedObject(self, &AssociatedKey.ValueGenerator) as? Closue<ValueType>)?.closue }
set{ objc_setAssociatedObject(self, &AssociatedKey.ValueGenerator, Closue<ValueType>( closue: newValue ), .OBJC_ASSOCIATION_COPY_NONATOMIC) }
}
public var value: ValueType? {
return valueGenerator?()
}
}
extension PickerProtocol {
public var skinValue: Any? {
return self.value as Any?
}
}
extension PickerProtocol{
public func apply(to obj: AnyObject, sel: Selector) {
guard obj.responds(to: sel) == true else { return }
_ = obj.perform(sel, with: skinValue)
}
}
| mit | 73619f703d4aa0c9ef44d2a7d16987fb | 18.342857 | 145 | 0.680207 | 3.620321 | false | false | false | false |
PANDA-Guide/PandaGuideApp | Carthage/Checkouts/SwiftTweaks/SwiftTweaks/TweakWindow.swift | 1 | 6564 | //
// TweakWindow.swift
// KATweak
//
// Created by Bryan Clark on 11/4/15.
// Copyright © 2015 Khan Academy. All rights reserved.
//
import UIKit
/// A UIWindow that handles the presentation and dismissal of a TweaksViewController automatically.
/// By default, the SwiftTweaks UI appears when you shake your device - but you can supply an alternate gesture, too!
/// If you'd prefer to not use this, you can also init and present a TweaksViewController yourself.
@objc public final class TweakWindow: UIWindow {
public enum GestureType {
case shake
case gesture(UIGestureRecognizer)
}
/// The amount of time you need to shake your device to bring up the Tweaks UI
private static let shakeWindowTimeInterval: Double = 0.4
/// The GestureType used to determine when to present the UI.
private let gestureType: GestureType
/// By holding on to the TweaksViewController, we get easy state restoration!
private var tweaksViewController: TweaksViewController! // requires self for init
/// Represents the "floating tweaks UI"
fileprivate var floatingTweakGroupUIWindow: HitTransparentWindow?
fileprivate let tweakStore: TweakStore
/// We need to know if we're running in the simulator (because shake gestures don't have a time duration in the simulator)
private let runningInSimulator: Bool
/// Whether or not the device is shaking. Used in determining when to present the Tweaks UI when the device is shaken.
private var shaking: Bool = false
private var shouldPresentTweaks: Bool {
if tweakStore.enabled {
switch gestureType {
case .shake: return shaking || runningInSimulator
case .gesture: return true
}
} else {
return false
}
}
// MARK: Init
public init(frame: CGRect, gestureType: GestureType = .shake, tweakStore: TweakStore) {
self.gestureType = gestureType
self.tweakStore = tweakStore
// Are we running on a Mac? If so, then we're in a simulator!
#if (arch(i386) || arch(x86_64))
self.runningInSimulator = true
#else
self.runningInSimulator = false
#endif
super.init(frame: frame)
tintColor = AppTheme.Colors.controlTinted
switch gestureType {
case .gesture(let gestureRecognizer):
gestureRecognizer.addTarget(self, action: #selector(self.presentTweaks))
case .shake:
break
}
tweaksViewController = TweaksViewController(tweakStore: tweakStore, delegate: self)
tweaksViewController.floatingTweaksWindowPresenter = self
}
public required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: Shaking & Gestures
public override func motionBegan(_ motion: UIEventSubtype, with event: UIEvent?) {
if motion == .motionShake {
shaking = true
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(TweakWindow.shakeWindowTimeInterval * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)) {
if self.shouldPresentTweaks {
self.presentTweaks()
}
}
}
super.motionBegan(motion, with: event)
}
public override func motionEnded(_ motion: UIEventSubtype, with event: UIEvent?) {
if motion == .motionShake {
shaking = false
}
super.motionEnded(motion, with: event)
}
// MARK: Presenting & Dismissing
@objc private func presentTweaks() {
guard let rootViewController = rootViewController else {
return
}
var visibleViewController = rootViewController
while (visibleViewController.presentedViewController != nil) {
visibleViewController = visibleViewController.presentedViewController!
}
if !(visibleViewController is TweaksViewController) {
visibleViewController.present(tweaksViewController, animated: true, completion: nil)
}
}
fileprivate func dismissTweaks(_ completion: (() -> ())? = nil) {
tweaksViewController.dismiss(animated: true, completion: completion)
}
}
extension TweakWindow: TweaksViewControllerDelegate {
public func tweaksViewControllerRequestsDismiss(_ tweaksViewController: TweaksViewController, completion: (() -> ())? = nil) {
dismissTweaks(completion)
}
}
extension TweakWindow: FloatingTweaksWindowPresenter {
private static let presentationDuration: Double = 0.2
private static let presentationDamping: CGFloat = 0.8
private static let presentationVelocity: CGFloat = 5
private static let dismissalDuration: Double = 0.2
/// Presents a floating TweakGroup over your app's UI, so you don't have to hop in and out of the full-modal Tweak UI.
internal func presentFloatingTweaksUI(forTweakGroup tweakGroup: TweakGroup) {
if (floatingTweakGroupUIWindow == nil) {
let window = HitTransparentWindow()
window.frame = UIScreen.main.bounds
window.backgroundColor = UIColor.clear
let floatingTweakGroupFrame = CGRect(
origin: CGPoint(
x: FloatingTweakGroupViewController.margins,
y: window.frame.size.height - FloatingTweakGroupViewController.height - FloatingTweakGroupViewController.margins
),
size: CGSize(
width: window.frame.size.width - FloatingTweakGroupViewController.margins*2,
height: FloatingTweakGroupViewController.height
)
)
let floatingTweaksVC = FloatingTweakGroupViewController(frame: floatingTweakGroupFrame, tweakStore: tweakStore, presenter: self)
floatingTweaksVC.tweakGroup = tweakGroup
window.rootViewController = floatingTweaksVC
window.addSubview(floatingTweaksVC.view)
window.alpha = 0
let initialWindowFrame = window.frame.offsetBy(dx: 0, dy: floatingTweaksVC.view.bounds.height)
let destinationWindowFrame = window.frame
window.makeKeyAndVisible()
floatingTweakGroupUIWindow = window
window.frame = initialWindowFrame
UIView.animate(
withDuration: TweakWindow.presentationDuration,
delay: 0,
usingSpringWithDamping: TweakWindow.presentationDamping,
initialSpringVelocity: TweakWindow.presentationVelocity,
options: .beginFromCurrentState,
animations: {
window.frame = destinationWindowFrame
window.alpha = 1
},
completion: nil
)
}
}
/// Dismisses the floating TweakGroup
func dismissFloatingTweaksUI() {
guard let floatingTweakGroupUIWindow = floatingTweakGroupUIWindow else { return }
UIView.animate(
withDuration: TweakWindow.dismissalDuration,
delay: 0,
options: .curveEaseIn,
animations: {
floatingTweakGroupUIWindow.alpha = 0
floatingTweakGroupUIWindow.frame = floatingTweakGroupUIWindow.frame.offsetBy(dx: 0, dy: floatingTweakGroupUIWindow.frame.height)
},
completion: { _ in
floatingTweakGroupUIWindow.isHidden = true
self.floatingTweakGroupUIWindow = nil
}
)
}
}
| gpl-3.0 | 244d21b65ecd6fb429ed03dc90a66f0e | 30.401914 | 163 | 0.752552 | 4.066295 | false | false | false | false |
LimonTop/StoreKit | StoreKitExample/AppDelegate.swift | 1 | 3491 | //
// AppDelegate.swift
// StoreKitExample
//
// Created by catch on 15/9/27.
// Copyright © 2015年 Limon. All rights reserved.
//
import UIKit
import StoreKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
let splitViewController = self.window!.rootViewController as! UISplitViewController
let navigationController = splitViewController.viewControllers[splitViewController.viewControllers.count-1] as! UINavigationController
navigationController.topViewController!.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem()
splitViewController.delegate = self
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
saveContext(coreDataStack.context)
}
// MARK: - Split view
func splitViewController(splitViewController: UISplitViewController, collapseSecondaryViewController secondaryViewController:UIViewController, ontoPrimaryViewController primaryViewController:UIViewController) -> Bool {
guard let secondaryAsNavController = secondaryViewController as? UINavigationController else { return false }
guard let topAsDetailController = secondaryAsNavController.topViewController as? DetailViewController else { return false }
if topAsDetailController.detailItem == nil {
// Return true to indicate that we have handled the collapse by doing nothing; the secondary controller will be discarded.
return true
}
return false
}
}
| mit | 365928699dac9086d50cffb65325ca0d | 52.661538 | 285 | 0.764622 | 6.195382 | false | false | false | false |
WangYang-iOS/YiDeXuePin_Swift | DiYa/DiYa/Class/Class/Controller/WYShopCartController.swift | 1 | 10052 | //
// WYShopCartController.swift
// DiYa
//
// Created by wangyang on 2017/9/28.
// Copyright © 2017年 wangyang. All rights reserved.
//
import UIKit
import MJRefresh
class WYShopCartController: WYBaseViewController {
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var bottomHeight: NSLayoutConstraint!
@IBOutlet weak var bottomView: YYShopcartBottomView!
var goodsList = [ShopcartModel]()
var price : CGFloat = 0
var isEditingShopCart: Bool = false {
didSet {
bottomView.isEditing = isEditingShopCart
if isEditingShopCart {
rightBarButton(title: "完成")
}else {
rightBarButton(title: "编辑")
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
setUI()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
isEditingShopCart = false
tableView.reloadData()
}
}
extension WYShopCartController : UITableViewDelegate,UITableViewDataSource {
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if isEditingShopCart {
let cell = tableView.dequeueReusableCell(withIdentifier: "YYEditShopCartCell", for: indexPath) as! YYEditShopCartCell
cell.delegate = self
let list = goodsList[indexPath.section]
cell.goodsModel = list.cartGoodsFormList[indexPath.row]
return cell
}else {
let cell = tableView.dequeueReusableCell(withIdentifier: "YYShopcartCell", for: indexPath) as! YYShopcartCell
cell.delegate = self
let list = goodsList[indexPath.section]
cell.goodsModel = list.cartGoodsFormList[indexPath.row]
return cell
}
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
//
let model = goodsList[indexPath.section].cartGoodsFormList[indexPath.row]
let vc = YYGoodsDetailController()
vc.goodsId = model.id
navigationController?.pushViewController(vc, animated: true)
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerView = YYShopcartHeaderView.loadXib1() as! YYShopcartHeaderView
headerView.frame = RECT(x: 0, y: 0, width: SCREEN_WIDTH, height: 44)
headerView.delegate = self
headerView.shopCarModel = goodsList[section]
return headerView
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let list = goodsList[section]
return list.cartGoodsFormList.count
}
func numberOfSections(in tableView: UITableView) -> Int {
return goodsList.count
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 44
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 0.01
}
}
///设置UI 下拉刷新
extension WYShopCartController {
fileprivate func setUI() {
navigationItem.title = "购物车"
isEditingShopCart = false
bottomHeight.constant = tabBarController?.tabBar.frame.size.height ?? 49
bottomView.delegate = self
bottomView.price = "0.00"
tableView.register(UINib.init(nibName: "YYShopcartCell", bundle: nil), forCellReuseIdentifier: "YYShopcartCell")
tableView.register(UINib.init(nibName: "YYEditShopCartCell", bundle: nil), forCellReuseIdentifier: "YYEditShopCartCell")
requestShopcartData()
tableView.mj_header = MJRefreshStateHeader.init(refreshingBlock: {
self.requestShopcartData()
})
}
///计算选中的商品总价
fileprivate func refreshSelectedprice() {
price = 0
for (_,shopcartModel) in goodsList.enumerated() {
if shopcartModel.isSelected {
for (_,goodsModel) in shopcartModel.cartGoodsFormList.enumerated() {
price = price + CGFloat((goodsModel.discountPrice as NSString).floatValue * (goodsModel.number as NSString).floatValue)
}
}else {
for (_,goodsModel) in shopcartModel.cartGoodsFormList.enumerated() {
if goodsModel.isSelected {
price = price + CGFloat((goodsModel.discountPrice as NSString).floatValue * (goodsModel.number as NSString).floatValue)
}
}
}
}
bottomView.price = String(format: "%.2f", price)
refreshBottomSelectedButton()
}
fileprivate func refreshBottomSelectedButton() {
var allSelected = true
for (_,shopcartModel) in goodsList.enumerated() {
if !shopcartModel.isSelected {
allSelected = false
}
}
bottomView.allSelected = allSelected
}
}
///请求数据
extension WYShopCartController {
func requestShopcartData() {
SHOW_PROGRESS(view: view)
WYNetWorkTool.share.request(url: "/cart/list.htm", dic: [:]) { (success, result) in
HIDDEN_PROGRESS(view: self.view)
if success {
guard
let result = result,
let json = result["data"],
let array = NSArray.yy_modelArray(with: ShopcartModel.self, json: json) as? [ShopcartModel] else {
return
}
self.goodsList = array
}
self.tableView.mj_header.endRefreshing()
self.tableView.reloadData()
}
}
}
extension WYShopCartController : YYShopcartHeaderViewDelegate {
func didClickCategory(shopcartModel: ShopcartModel) {
shopcartModel.isSelected = !shopcartModel.isSelected
//更改该分区全部商品的选中状态
for (_,goodsModel) in shopcartModel.cartGoodsFormList.enumerated() {
goodsModel.isSelected = shopcartModel.isSelected
}
tableView.reloadData()
refreshSelectedprice()
}
func didSelectedCategory(categoryId: String) {
let vc = YYClassListViewController()
vc.categoryId = categoryId
navigationController?.pushViewController(vc, animated: true)
}
}
extension WYShopCartController : YYShopcartCellDelegate {
func didSelectCell(goodsModel: GoodsModel) {
goodsModel.isSelected = !goodsModel.isSelected
///遍历购物车数组,判断每个分区商品是否全部选中
for (_,shopcartModel) in goodsList.enumerated() {
//设置一个遍历,标记该分区是否全选
var allSelected = true
for (_,model) in shopcartModel.cartGoodsFormList.enumerated() {
//如果点击的商品是这个分区下
if model == goodsModel {
//则先判断是否选中,如果没有选中,则该分区不是全选状态
if goodsModel.isSelected == false {
shopcartModel.isSelected = false
allSelected = false
}
}else {
//如果点击的商品和遍历的商品不是同一个 ,则先判断是否选中,如果不是,则该分区并不是全部选中状态
if model.isSelected == false {
allSelected = false
}
}
}
//将上述过程产生的标记赋值给该分区
shopcartModel.isSelected = allSelected
}
//刷新表格
tableView.reloadData()
refreshSelectedprice()
}
}
extension WYShopCartController : YYEditShopCartCellDelegate {
func didSelectedGoods(goodsModel: GoodsModel) {
goodsModel.isSelected = !goodsModel.isSelected
///遍历购物车数组,判断每个分区商品是否全部选中
for (_,shopcartModel) in goodsList.enumerated() {
//设置一个标记,标记该分区是否全选
var allSelected = true
for (_,model) in shopcartModel.cartGoodsFormList.enumerated() {
//如果点击的商品是这个分区下
if model == goodsModel {
//则先判断是否选中,如果没有选中,则该分区不是全选状态
if goodsModel.isSelected == false {
shopcartModel.isSelected = false
allSelected = false
}
}else {
//如果点击的商品和遍历的商品不是同一个 ,则先判断是否选中,如果不是,则该分区并不是全部选中状态
if model.isSelected == false {
allSelected = false
}
}
}
//将上述过程产生的标记赋值给该分区
shopcartModel.isSelected = allSelected
}
//刷新表格
tableView.reloadData()
refreshSelectedprice()
}
func didSelectedCategory(goodsModel: GoodsModel) {
//选择分类
}
}
extension WYShopCartController : YYShopcartBottomViewDelegate {
func didAllSelectedGoods(isSelected: Bool) {
for (_,shopcartModel) in goodsList.enumerated() {
shopcartModel.isSelected = isSelected
for (_,goodsModel) in shopcartModel.cartGoodsFormList.enumerated() {
goodsModel.isSelected = shopcartModel.isSelected
}
}
tableView.reloadData()
refreshSelectedprice()
}
func didCommitOrder() {
//
}
func didClickDeleteGoods() {
//
}
func didClickFavorateGoods() {
//
}
}
extension WYShopCartController {
override func clickRightButton() {
isEditingShopCart = !isEditingShopCart
tableView.reloadData()
}
}
| mit | e9fc0fc6d5b8e289277231f9f711127d | 34.835878 | 143 | 0.602727 | 4.744315 | false | false | false | false |
gorhack/Borrowed | Borrowed/AppDelegate.swift | 1 | 6118 | //
// AppDelegate.swift
// Borrowed
//
// Created by Kyle Gorak on 12/28/14.
// Copyright (c) 2014 Kyle Gorak. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "com.prndl.Borrowed" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1] as NSURL
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("Borrowed", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
// The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("Borrowed.sqlite")
var error: NSError? = nil
var failureReason = "There was an error creating or loading the application's saved data."
if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil, error: &error) == nil {
coordinator = nil
// Report any error we got.
let dict = NSMutableDictionary()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error
error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext? = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
if coordinator == nil {
return nil
}
var managedObjectContext = NSManagedObjectContext()
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if let moc = self.managedObjectContext {
var error: NSError? = nil
if moc.hasChanges && !moc.save(&error) {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
}
}
}
| gpl-2.0 | a71d9bce65898844927482a716414bec | 54.117117 | 290 | 0.71592 | 5.744601 | false | false | false | false |
esttorhe/Moya | Source/Endpoint.swift | 2 | 4716 | import Foundation
/// Used for stubbing responses.
public enum EndpointSampleResponse {
/// The network returned a response, including status code and data.
case NetworkResponse(Int, NSData)
/// The network failed to send the request, or failed to retrieve a response (eg a timeout).
case NetworkError(NSError)
}
/// Class for reifying a target of the Target enum unto a concrete Endpoint.
public class Endpoint<Target> {
public typealias SampleResponseClosure = () -> EndpointSampleResponse
public let URL: String
public let method: Moya.Method
public let sampleResponseClosure: SampleResponseClosure
public let parameters: [String: AnyObject]?
public let parameterEncoding: Moya.ParameterEncoding
public let httpHeaderFields: [String: String]?
/// Main initializer for Endpoint.
public init(URL: String,
sampleResponseClosure: SampleResponseClosure,
method: Moya.Method = Moya.Method.GET,
parameters: [String: AnyObject]? = nil,
parameterEncoding: Moya.ParameterEncoding = .URL,
httpHeaderFields: [String: String]? = nil) {
self.URL = URL
self.sampleResponseClosure = sampleResponseClosure
self.method = method
self.parameters = parameters
self.parameterEncoding = parameterEncoding
self.httpHeaderFields = httpHeaderFields
}
/// Convenience method for creating a new Endpoint with the same properties as the receiver, but with added parameters.
public func endpointByAddingParameters(parameters: [String: AnyObject]) -> Endpoint<Target> {
return endpointByAdding(parameters: parameters)
}
/// Convenience method for creating a new Endpoint with the same properties as the receiver, but with added HTTP header fields.
public func endpointByAddingHTTPHeaderFields(httpHeaderFields: [String: String]) -> Endpoint<Target> {
return endpointByAdding(httpHeaderFields: httpHeaderFields)
}
/// Convenience method for creating a new Endpoint with the same properties as the receiver, but with another parameter encoding.
public func endpointByAddingParameterEncoding(newParameterEncoding: Moya.ParameterEncoding) -> Endpoint<Target> {
return endpointByAdding(parameterEncoding: newParameterEncoding)
}
/// Convenience method for creating a new Endpoint, with changes only to the properties we specify as parameters
public func endpointByAdding(parameters parameters: [String: AnyObject]? = nil, httpHeaderFields: [String: String]? = nil, parameterEncoding: Moya.ParameterEncoding? = nil) -> Endpoint<Target> {
let newParameters = addParameters(parameters)
let newHTTPHeaderFields = addHTTPHeaderFields(httpHeaderFields)
let newParameterEncoding = parameterEncoding ?? self.parameterEncoding
return Endpoint(URL: URL, sampleResponseClosure: sampleResponseClosure, method: method, parameters: newParameters, parameterEncoding: newParameterEncoding, httpHeaderFields: newHTTPHeaderFields)
}
private func addParameters(parameters: [String: AnyObject]?) -> [String: AnyObject]? {
guard let unwrappedParameters = parameters where unwrappedParameters.count > 0 else {
return self.parameters
}
var newParameters = self.parameters ?? [String: AnyObject]()
unwrappedParameters.forEach { (key, value) in
newParameters[key] = value
}
return newParameters
}
private func addHTTPHeaderFields(headers: [String: String]?) -> [String: String]? {
guard let unwrappedHeaders = headers where unwrappedHeaders.count > 0 else {
return self.httpHeaderFields
}
var newHTTPHeaderFields = self.httpHeaderFields ?? [String: String]()
unwrappedHeaders.forEach { (key, value) in
newHTTPHeaderFields[key] = value
}
return newHTTPHeaderFields
}
}
/// Extension for converting an Endpoint into an NSURLRequest.
extension Endpoint {
public var urlRequest: NSURLRequest {
let request: NSMutableURLRequest = NSMutableURLRequest(URL: NSURL(string: URL)!)
request.HTTPMethod = method.rawValue
request.allHTTPHeaderFields = httpHeaderFields
return parameterEncoding.encode(request, parameters: parameters).0
}
}
/// Required for making Endpoint conform to Equatable.
public func ==<T>(lhs: Endpoint<T>, rhs: Endpoint<T>) -> Bool {
return lhs.urlRequest.isEqual(rhs.urlRequest)
}
/// Required for using Endpoint as a key type in a Dictionary.
extension Endpoint: Equatable, Hashable {
public var hashValue: Int {
return urlRequest.hash
}
}
| mit | 2cba0fff93a11999c567d220cf4a61cd | 41.872727 | 202 | 0.713953 | 5.439446 | false | false | false | false |
freesuraj/PGParallaxView | FrameMe/CustomCollectionViewCell.swift | 1 | 1244 | //
// CustomCollectionViewCell.swift
// FrameMe
//
// Created by Suraj Pathak on 29/12/15.
// Copyright © 2015 Suraj Pathak. All rights reserved.
//
import UIKit
class CustomCollectionViewCell: UICollectionViewCell, PGParallaxEffectProtocol {
@IBOutlet weak var parallaxImageView: UIImageView!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var webView: UIWebView!
var parallaxEffectView: UIView {
return parallaxImageView!
}
static var reuseIdentifier: String {
return "CustomCollectionViewCell"
}
override func awakeFromNib() {
parallaxImageView.clipsToBounds = true
}
override func layoutSubviews() {
parallaxImageView.clipsToBounds = true
}
func asyncLoadImageViewFromUrlString(urlString: String) {
guard let url = NSURL(string: urlString) else {
return
}
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
if let data = NSData(contentsOfURL: url) {
dispatch_async(dispatch_get_main_queue(), {
self.parallaxImageView.image = UIImage(data: data)
})
}
})
}
}
| mit | e46f5b67b005ea1cb636cab69ac00628 | 26.021739 | 87 | 0.629928 | 4.893701 | false | false | false | false |
yaslab/Harekaze-iOS | Harekaze/ViewControllers/Root/NavigationDrawerTableViewController.swift | 1 | 6631 | /**
*
* NavigationDrawerTableViewController.swift
* Harekaze
* Created by Yuki MIZUNO on 2016/07/07.
*
* Copyright (c) 2016-2017, Yuki MIZUNO
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
import UIKit
import Material
private struct Item {
var text: String
var image: UIImage?
}
class NavigationDrawerTableViewController: UITableViewController {
// MARK: - Private instance fileds
private var dataSourceItems: [Item] = []
private var secondDataSourceItems: [Item] = []
// MARK: - View initialization
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(NavigationDrawerMaterialTableViewCell.self, forCellReuseIdentifier: "MaterialTableViewCell")
tableView.separatorStyle = UITableViewCellSeparatorStyle.none
/// Prepares the items that are displayed within the tableView.
dataSourceItems.append(Item(text: "On Air", image: UIImage(named: "ic_tv")?.withRenderingMode(.alwaysTemplate)))
dataSourceItems.append(Item(text: "Guide", image: UIImage(named: "ic_view_list")?.withRenderingMode(.alwaysTemplate)))
dataSourceItems.append(Item(text: "Recordings", image: UIImage(named: "ic_video_library")?.withRenderingMode(.alwaysTemplate)))
dataSourceItems.append(Item(text: "Timers", image: UIImage(named: "ic_av_timer")?.withRenderingMode(.alwaysTemplate)))
dataSourceItems.append(Item(text: "Downloads", image: UIImage(named: "ic_file_download")?.withRenderingMode(.alwaysTemplate)))
secondDataSourceItems.append(Item(text: "Settings", image: UIImage(named: "ic_settings")?.withRenderingMode(.alwaysTemplate)))
}
// MARK: - Memory/resource management
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 3
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch section {
case 0:
return 1
case 1:
return dataSourceItems.count
case 2:
return secondDataSourceItems.count
default:
return 0
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "MaterialTableViewCell", for: indexPath)
switch (indexPath as NSIndexPath).section {
case 0:
cell.imageView?.image = UIImage(named: "Harekaze")
cell.imageView?.layer.cornerRadius = 12
cell.imageView?.clipsToBounds = true
cell.textLabel?.text = "Harekaze"
cell.textLabel?.textColor = Material.Color.grey.darken3
case 1:
let item: Item = dataSourceItems[(indexPath as NSIndexPath).row]
cell.textLabel!.text = item.text
cell.imageView!.image = item.image
case 2:
let item: Item = secondDataSourceItems[(indexPath as NSIndexPath).row]
cell.textLabel!.text = item.text
cell.imageView!.image = item.image
default:
break
}
return cell
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
switch (indexPath as NSIndexPath).section {
case 0:
return 64
default:
return 48
}
}
override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 8
}
override func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
let layerView = UIView()
layerView.clipsToBounds = true
if section != tableView.numberOfSections - 1 {
let line = CALayer()
line.borderColor = Material.Color.grey.lighten1.cgColor
line.borderWidth = 1
line.frame = CGRect(x: 0, y: -0.5, width: tableView.frame.width, height: 1)
layerView.layer.addSublayer(line)
}
return layerView
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
// Change current selected tab
guard let navigationController = navigationDrawerController?.rootViewController as? NavigationController else {
return
}
switch (indexPath as NSIndexPath).section {
case 1:
let item: Item = dataSourceItems[(indexPath as NSIndexPath).row]
if let v = navigationController.viewControllers.first as? BottomNavigationController {
for viewController: UIViewController in v.viewControllers! {
if item.text == viewController.title! {
v.selectedViewController = viewController
// Highlight current selected tab
for i in 0..<tableView.numberOfRows(inSection: indexPath.section) {
let cell = tableView.cellForRow(at: IndexPath(row: i, section: indexPath.section))
cell?.textLabel?.textColor = Material.Color.grey.darken3
}
let cell = tableView.cellForRow(at: indexPath)
cell?.textLabel?.textColor = Material.Color.blue.darken3
break
}
}
}
case 2:
let item: Item = secondDataSourceItems[(indexPath as NSIndexPath).row]
let navigationController = navigationController.storyboard!.instantiateViewController(withIdentifier: "\(item.text)NavigationController")
present(navigationController, animated: true, completion: {
self.navigationDrawerController?.closeLeftView()
})
default:
break
}
}
}
| bsd-3-clause | 5e52e9d59a0fd3362ae86cbc06f2a312 | 34.271277 | 140 | 0.744986 | 4.280826 | false | false | false | false |
natecook1000/swift | test/type/types.swift | 4 | 7583 | // RUN: %target-typecheck-verify-swift
var a : Int
func test() {
var y : a // expected-error {{use of undeclared type 'a'}}
var z : y // expected-error {{use of undeclared type 'y'}}
var w : Swift.print // expected-error {{no type named 'print' in module 'Swift'}}
}
var b : (Int) -> Int = { $0 }
var c2 : (field : Int) // expected-error {{cannot create a single-element tuple with an element label}}{{11-19=}}
var d2 : () -> Int = { 4 }
var d3 : () -> Float = { 4 }
var d4 : () -> Int = { d2 } // expected-error{{function produces expected type 'Int'; did you mean to call it with '()'?}} {{26-26=()}}
var e0 : [Int]
e0[] // expected-error {{cannot subscript a value of type '[Int]' with an index of type '()'}}
// expected-note @-1 {{overloads for 'subscript' exist with these partially matching parameter lists: (Int), (Range<Int>),}}
var f0 : [Float]
var f1 : [(Int,Int)]
var g : Swift // expected-error {{use of undeclared type 'Swift'}} expected-note {{cannot use module 'Swift' as a type}}
var h0 : Int?
_ = h0 == nil // no-warning
var h1 : Int??
_ = h1! == nil // no-warning
var h2 : [Int?]
var h3 : [Int]?
var h3a : [[Int?]]
var h3b : [Int?]?
var h4 : ([Int])?
var h5 : ([([[Int??]])?])?
var h7 : (Int,Int)?
var h8 : ((Int) -> Int)?
var h9 : (Int?) -> Int?
var h10 : Int?.Type?.Type
var i = Int?(42)
func testInvalidUseOfParameterAttr() {
var bad_io : (Int) -> (inout Int, Int) // expected-error {{'inout' may only be used on parameters}}
func bad_io2(_ a: (inout Int, Int)) {} // expected-error {{'inout' may only be used on parameters}}
var bad_is : (Int) -> (__shared Int, Int) // expected-error {{'__shared' may only be used on parameters}}
func bad_is2(_ a: (__shared Int, Int)) {} // expected-error {{'__shared' may only be used on parameters}}
var bad_iow : (Int) -> (__owned Int, Int) // expected-error {{'__owned' may only be used on parameters}}
func bad_iow2(_ a: (__owned Int, Int)) {} // expected-error {{'__owned' may only be used on parameters}}
}
// <rdar://problem/15588967> Array type sugar default construction syntax doesn't work
func test_array_construct<T>(_: T) {
_ = [T]() // 'T' is a local name
_ = [Int]() // 'Int is a global name'
_ = [UnsafeMutablePointer<Int>]() // UnsafeMutablePointer<Int> is a specialized name.
_ = [UnsafeMutablePointer<Int?>]() // Nesting.
_ = [([UnsafeMutablePointer<Int>])]()
_ = [(String, Float)]()
}
extension Optional {
init() {
self = .none
}
}
// <rdar://problem/15295763> default constructing an optional fails to typecheck
func test_optional_construct<T>(_: T) {
_ = T?() // Local name.
_ = Int?() // Global name
_ = (Int?)() // Parenthesized name.
}
// Test disambiguation of generic parameter lists in expression context.
struct Gen<T> {}
var y0 : Gen<Int?>
var y1 : Gen<Int??>
var y2 : Gen<[Int?]>
var y3 : Gen<[Int]?>
var y3a : Gen<[[Int?]]>
var y3b : Gen<[Int?]?>
var y4 : Gen<([Int])?>
var y5 : Gen<([([[Int??]])?])?>
var y7 : Gen<(Int,Int)?>
var y8 : Gen<((Int) -> Int)?>
var y8a : Gen<[([Int]?) -> Int]>
var y9 : Gen<(Int?) -> Int?>
var y10 : Gen<Int?.Type?.Type>
var y11 : Gen<Gen<Int>?>
var y12 : Gen<Gen<Int>?>?
var y13 : Gen<Gen<Int?>?>?
var y14 : Gen<Gen<Int?>>?
var y15 : Gen<Gen<Gen<Int?>>?>
var y16 : Gen<Gen<Gen<Int?>?>>
var y17 : Gen<Gen<Gen<Int?>?>>?
var z0 = Gen<Int?>()
var z1 = Gen<Int??>()
var z2 = Gen<[Int?]>()
var z3 = Gen<[Int]?>()
var z3a = Gen<[[Int?]]>()
var z3b = Gen<[Int?]?>()
var z4 = Gen<([Int])?>()
var z5 = Gen<([([[Int??]])?])?>()
var z7 = Gen<(Int,Int)?>()
var z8 = Gen<((Int) -> Int)?>()
var z8a = Gen<[([Int]?) -> Int]>()
var z9 = Gen<(Int?) -> Int?>()
var z10 = Gen<Int?.Type?.Type>()
var z11 = Gen<Gen<Int>?>()
var z12 = Gen<Gen<Int>?>?()
var z13 = Gen<Gen<Int?>?>?()
var z14 = Gen<Gen<Int?>>?()
var z15 = Gen<Gen<Gen<Int?>>?>()
var z16 = Gen<Gen<Gen<Int?>?>>()
var z17 = Gen<Gen<Gen<Int?>?>>?()
y0 = z0
y1 = z1
y2 = z2
y3 = z3
y3a = z3a
y3b = z3b
y4 = z4
y5 = z5
y7 = z7
y8 = z8
y8a = z8a
y9 = z9
y10 = z10
y11 = z11
y12 = z12
y13 = z13
y14 = z14
y15 = z15
y16 = z16
y17 = z17
// Type repr formation.
// <rdar://problem/20075582> Swift does not support short form of dictionaries with tuples (not forming TypeExpr)
let tupleTypeWithNames = (age:Int, count:Int)(4, 5)
let dictWithTuple = [String: (age:Int, count:Int)]()
// <rdar://problem/21684837> typeexpr not being formed for postfix !
let bb2 = [Int!](repeating: nil, count: 2) // expected-warning {{using '!' is not allowed here; treating this as '?' instead}}{{15-16=?}}
// <rdar://problem/21560309> inout allowed on function return type
func r21560309<U>(_ body: (_: inout Int) -> inout U) {} // expected-error {{'inout' may only be used on parameters}}
r21560309 { x in x }
// <rdar://problem/21949448> Accepts-invalid: 'inout' shouldn't be allowed on stored properties
class r21949448 {
var myArray: inout [Int] = [] // expected-error {{'inout' may only be used on parameters}}
}
// SE-0066 - Standardize function type argument syntax to require parentheses
let _ : Int -> Float // expected-error {{single argument function types require parentheses}} {{9-9=(}} {{12-12=)}}
let _ : inout Int -> Float // expected-error {{'inout' may only be used on parameters}}
// expected-error@-1 {{single argument function types require parentheses}} {{15-15=(}} {{18-18=)}}
func testNoParenFunction(x: Int -> Float) {} // expected-error {{single argument function types require parentheses}} {{29-29=(}} {{32-32=)}}
func testNoParenFunction(x: inout Int -> Float) {} // expected-error {{single argument function types require parentheses}} {{35-35=(}} {{38-38=)}}
func foo1(a : UnsafePointer<Void>) {} // expected-warning {{UnsafePointer<Void> has been replaced by UnsafeRawPointer}}{{15-34=UnsafeRawPointer}}
func foo2(a : UnsafeMutablePointer<()>) {} // expected-warning {{UnsafeMutablePointer<Void> has been replaced by UnsafeMutableRawPointer}}{{15-39=UnsafeMutableRawPointer}}
class C {
func foo1(a : UnsafePointer<Void>) {} // expected-warning {{UnsafePointer<Void> has been replaced by UnsafeRawPointer}}{{17-36=UnsafeRawPointer}}
func foo2(a : UnsafeMutablePointer<()>) {} // expected-warning {{UnsafeMutablePointer<Void> has been replaced by UnsafeMutableRawPointer}}{{17-41=UnsafeMutableRawPointer}}
func foo3() {
let _ : UnsafePointer<Void> // expected-warning {{UnsafePointer<Void> has been replaced by UnsafeRawPointer}}{{13-32=UnsafeRawPointer}}
let _ : UnsafeMutablePointer<Void> // expected-warning {{UnsafeMutablePointer<Void> has been replaced by UnsafeMutableRawPointer}}{{13-39=UnsafeMutableRawPointer}}
}
}
let _ : inout @convention(c) (Int) -> Int // expected-error {{'inout' may only be used on parameters}}
func foo3(inout a: Int -> Void) {} // expected-error {{'inout' before a parameter name is not allowed, place it before the parameter type instead}} {{11-16=}} {{20-20=inout }}
// expected-error @-1 {{single argument function types require parentheses}} {{20-20=(}} {{23-23=)}}
func sr5505(arg: Int) -> String {
return "hello"
}
var _: sr5505 = sr5505 // expected-error {{use of undeclared type 'sr5505'}}
typealias A = (inout Int ..., Int ... = [42, 12]) -> Void // expected-error {{'inout' must not be used on variadic parameters}}
// expected-error@-1 {{only a single element can be variadic}} {{35-39=}}
// expected-error@-2 {{default argument not permitted in a tuple type}} {{39-49=}}
| apache-2.0 | ae5a23eb540bce7546bd63d7512f6025 | 37.887179 | 175 | 0.620467 | 3.241984 | false | false | false | false |
moltin/ios-swift-example | MoltinSwiftExample/MoltinSwiftExample/ProductsListTableViewCell.swift | 1 | 1403 | //
// ProductsListTableViewCell.swift
// MoltinSwiftExample
//
// Created by Dylan McKee on 16/08/2015.
// Copyright (c) 2015 Moltin. All rights reserved.
//
import UIKit
class ProductsListTableViewCell: UITableViewCell {
@IBOutlet weak var productNameLabel:UILabel?
@IBOutlet weak var productPriceLabel:UILabel?
@IBOutlet weak var productImageView:UIImageView?
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
func configureWithProduct(_ productDict: NSDictionary) {
// Setup the cell with information provided in productDict.
productNameLabel?.text = productDict.value(forKey: "title") as? String
productPriceLabel?.text = productDict.value(forKeyPath: "price.data.formatted.with_tax") as? String
var imageUrl = ""
if let images = productDict.object(forKey: "images") as? NSArray {
if (images.firstObject != nil) {
imageUrl = (images.firstObject as! NSDictionary).value(forKeyPath: "url.https") as! String
}
}
productImageView?.sd_setImage(with: URL(string: imageUrl))
}
}
| mit | 614250ca8ec60978d2a10b0196de4c84 | 28.229167 | 107 | 0.64077 | 4.772109 | false | false | false | false |
ish2028/MSeriesBle | MSeriesBle/Classes/MSBLEMachineBroadcast.swift | 1 | 2660 | //
// MSBLEMachineBroadcast.swift
// MSeries
//
// Created by Ismael Huerta on 9/9/16.
// Copyright © 2016 Ismael Huerta. All rights reserved.
//
import Foundation
public class MSBLEMachineBroadcast: NSObject {
public var name = "";
public var address = "";
public var isRealTime = false
public var receivedTime = Date()
public var machineID: Int = 0
public var buildMajor: Int?
public var buildMinor: Int?
public var dataType: Int?
public var interval: Int?
public var rpm: Int?
public var heartRate: Int?
public var power: Int?
public var kCal: Int?
public var time: TimeInterval?
public var trip: Double?
public var gear: Int?
public init(manufactureData: Data) {
var data = manufactureData
if (data.count > 17){
data = data.subdata(in: Range(uncheckedBounds: (lower: 2, upper: data.count)))
}
var tempTrip: Int32?
for (index, byte) in data.enumerated(){
switch index {
case 0: buildMajor = Int(byte)
case 1: buildMinor = Int(byte)
case 2: dataType = Int(byte);
case 3: machineID = Int(byte)
case 4: rpm = Int(byte)
case 5: rpm = Int(UInt16(byte) << 8 | UInt16(rpm!))
case 6: heartRate = Int(byte)
case 7: heartRate = Int(UInt16(byte) << 8 | UInt16(heartRate!))
case 8: power = Int(byte)
case 9: power = Int(UInt16(byte) << 8 | UInt16(power!))
case 10: kCal = Int(byte)
case 11: kCal = Int(UInt16(byte) << 8 | UInt16(kCal!))
case 12: time = Double(byte) * 60
case 13: time = time! + Double(byte)
case 14: tempTrip = Int32(byte)
case 15: tempTrip = Int32(UInt16(byte) << 8 | UInt16(tempTrip!))
case 16: gear = Int(byte)
default: break
}
}
rpm = rpm!/10
heartRate = heartRate!/10
super.init()
if (dataType == 0 || dataType == 255) {
interval = 0
}
else if (dataType! > 128 && dataType! < 255) {
interval = dataType! - 128
}
isRealTime = dataType! < 255
if tempTrip! & 32768 != 0 {
trip = (Double(tempTrip! & 32767) * 0.62137119) / 10.0
}
else {
trip = Double(tempTrip!) / 10.0
}
}
public var scanResult: String {
get {
return "scanResult"
}
}
public var isValid: Bool {
get {
return name.characters.count > 0 && machineID > 0
}
}
}
| mit | e06a5fcec63adb7a18a9aab463e7cf19 | 29.563218 | 90 | 0.527266 | 3.870451 | false | false | false | false |
mownier/photostream | Photostream/Modules/Login/Interactor/LoginInteractor.swift | 1 | 1046 | //
// LoginInteractor.swift
// Photostream
//
// Created by Mounir Ybanez on 04/08/2016.
// Copyright © 2016 Mounir Ybanez. All rights reserved.
//
import Foundation
class LoginInteractor: LoginInteractorInterface {
var service: AuthenticationService!
weak var output: LoginInteractorOutput?
required init(service: AuthenticationService) {
self.service = service
}
fileprivate func saveUser(_ user: User!) {
// TODO: Save user into the keychain or any encrpted storage
}
}
extension LoginInteractor: LoginInteractorInput {
func login(email: String, password: String) {
var data = AuthentationServiceLoginData()
data.email = email
data.password = password
service.login(data: data) { (result) in
if let error = result.error {
self.output?.loginDidFail(error: error)
} else {
self.saveUser(result.user)
self.output?.loginDidSucceed(user: result.user!)
}
}
}
}
| mit | 0ac2ca4fa6d42752e5195df018f80695 | 25.125 | 68 | 0.629665 | 4.484979 | false | false | false | false |
aeidelson/light-playground | swift_app/light-playground/LightGrid/CPULightGrid.swift | 1 | 19429 | import CoreGraphics
import Foundation
/// An implementation of LightGrid which draws using the CPU exclusively.
final class CPULightGrid: LightGrid {
public init(
context: LightSimulatorContext,
size: CGSize,
initialRenderProperties: RenderImageProperties
) {
self.context = context
self.width = Int(size.width.rounded())
self.height = Int(size.height.rounded())
self.totalPixels = width * height
self.renderProperties = initialRenderProperties
self.data = ContiguousArray<LightGridPixel>(
repeating: LightGridPixel(r: 0, g: 0, b: 0),
count: totalPixels)
}
public var renderProperties: RenderImageProperties {
didSet {
if !oldValue.exposure.isEqual(to: renderProperties.exposure) {
updateImage(renderProperties: renderProperties)
}
}
}
public func reset(updateImage: Bool) {
for i in 0..<totalPixels {
data[i].r = 0
data[i].g = 0
data[i].b = 0
}
totalSegmentCount = 0
if updateImage {
self.updateImage(renderProperties: renderProperties)
}
}
public func drawSegments(layout: SimulationLayout, segments: [LightSegment], lowQuality: Bool) {
if layout.version < latestLayoutVersion {
return
}
latestLayoutVersion = layout.version
if lowQuality {
for segment in segments {
BresenhamLightGridSegmentDraw.drawSegment(
gridWidth: width,
gridHeight: height,
data: &data,
segment: segment)
}
} else {
for segment in segments {
WuFasterLightGridSegmentDraw.drawSegment(
gridWidth: width,
gridHeight: height,
data: &data,
segment: segment)
}
}
totalSegmentCount += UInt64(segments.count)
updateImage(renderProperties: renderProperties)
}
private func updateImage(renderProperties: RenderImageProperties) {
let brightness: Float
if totalSegmentCount == 0 {
brightness = 0
} else {
brightness = Float(renderProperties.exposure) / Float(totalSegmentCount)
}
let bufferSize = totalPixels * componentsPerPixel
let imagePixelBuffer = UnsafeMutablePointer<UInt8>.allocate(capacity: bufferSize)
for i in 0..<totalPixels {
imagePixelBuffer[i * componentsPerPixel + 0] = UInt8(min(Float(data[i].r) * brightness, 255))
imagePixelBuffer[i * componentsPerPixel + 1] = UInt8(min(Float(data[i].g) * brightness, 255))
imagePixelBuffer[i * componentsPerPixel + 2] = UInt8(min(Float(data[i].b) * brightness, 255))
}
let imageDataProvider = CGDataProvider(
data: NSData(
bytesNoCopy: UnsafeMutableRawPointer(imagePixelBuffer),
length: bufferSize,
freeWhenDone: true))
let bitsPerPixel = componentsPerPixel * bitsPerComponent
let image = CGImage(
width: width,
height: height,
bitsPerComponent: bitsPerComponent,
bitsPerPixel: bitsPerPixel,
bytesPerRow: width * bitsPerPixel / 8,
space: CGColorSpaceCreateDeviceRGB(),
// Alpha is ignored.
bitmapInfo: CGBitmapInfo(rawValue: CGImageAlphaInfo.noneSkipLast.rawValue),
provider: imageDataProvider!,
decode: nil,
shouldInterpolate: true,
intent: .defaultIntent)
if let imageUnwrapped = image {
snapshotHandler(SimulationSnapshot(image: imageUnwrapped, totalLightSegmentsTraced: totalSegmentCount))
}
}
public let width: Int
public let height: Int
public var snapshotHandler: (SimulationSnapshot) -> Void = { _ in }
// MARK: Private
private let context: LightSimulatorContext
fileprivate let totalPixels: Int
fileprivate var data: ContiguousArray<LightGridPixel>
fileprivate var totalSegmentCount = UInt64(0)
private var latestLayoutVersion = UInt64(0)
// MARK: Variables for generating images.
private let componentsPerPixel = 4
private let bitsPerComponent = 8
}
private func calculateBrightness(
lightCount: Int,
segmentCount: Int,
exposure: Float
) -> Float {
return Float(exp(1 + 10 * exposure)) / Float(segmentCount / lightCount)
}
/// Represents a single pixel in the light grid.
fileprivate struct LightGridPixel {
public var r: UInt32
public var g: UInt32
public var b: UInt32
}
/// Returns the index of the pixel, and is a 0-based index.
@inline(__always) private func indexFromLocation(_ gridWidth: Int, _ gridHeight: Int, _ x: Int, _ y: Int) -> Int {
#if DEBUG
precondition(x >= 0)
precondition(x < gridWidth)
precondition(y >= 0)
precondition(y < gridHeight)
#endif
return y * gridWidth + x
}
/// A private class to contain all the nasty line drawing code.
/// Taken almost directly from:
/// https://github.com/ssloy/tinyrenderer/wiki/Lesson-1:-Bresenham%E2%80%99s-Line-Drawing-Algorithm
private final class BresenhamLightGridSegmentDraw {
static func drawSegment(
gridWidth: Int,
gridHeight: Int,
data: inout ContiguousArray<LightGridPixel>,
segment: LightSegment
) {
// Figure out the color for the segment.
var dxFloat = abs(Float(segment.pos2.x) - Float(segment.pos1.x))
var dyFloat = abs(Float(segment.pos2.y) - Float(segment.pos1.y))
if dyFloat > dxFloat {
swap(&dxFloat, &dyFloat)
}
// Save ourselves a lot of trouble by avoiding zero-values.
if abs(dxFloat) < 0.01 {
dxFloat = 0.01
}
let br = max(abs(sqrtf(dxFloat*dxFloat + dyFloat*dyFloat) / dxFloat), 2)
let colorR = UInt32(Float(segment.color.r) * br)
let colorG = UInt32(Float(segment.color.g) * br)
let colorB = UInt32(Float(segment.color.b) * br)
var steep = false
var x0 = Int(segment.pos1.x.rounded())
var y0 = Int(segment.pos1.y.rounded())
var x1 = Int(segment.pos2.x.rounded())
var y1 = Int(segment.pos2.y.rounded())
if abs(x0 - x1) < abs(y0 - y1) {
swap(&x0, &y0)
swap(&x1, &y1)
steep = true
}
if x0 > x1 {
swap(&x0, &x1)
swap(&y0, &y1)
}
let dx = x1 - x0
let dy = y1 - y0
let derror2 = abs(dy) * 2
var error2 = 0
var y = y0
for x in x0...x1 {
let index = steep ?
indexFromLocation(gridWidth, gridHeight, y, x) :
indexFromLocation(gridWidth, gridHeight, x, y)
data[index].r += colorR
data[index].g += colorG
data[index].b += colorB
error2 += derror2
if error2 > dx {
y += (y1 > y0 ? 1 : -1)
error2 -= dx * 2
}
}
}
}
/// A private class to contain all the nasty line drawing code.
/// Taken almost directly from: http://rosettacode.org/wiki/Xiaolin_Wu%27s_line_algorithm#C
private final class WuLightGridSegmentDraw {
@inline(__always) private static func plot(
gridWidth: Int,
gridHeight: Int,
data: inout ContiguousArray<LightGridPixel>,
x: Int,
y: Int,
color: (Float, Float, Float),
br: Float
) {
let index = indexFromLocation(gridWidth, gridHeight, x, y)
let initialPixel = data[index]
data[index].r = initialPixel.r + UInt32(color.0 * br)
data[index].g = initialPixel.g + UInt32(color.1 * br)
data[index].b = initialPixel.b + UInt32(color.2 * br)
}
@inline(__always) private static func ipart(_ x: Float) -> Int {
return Int(x)
}
@inline(__always) private static func round(_ x: Float) -> Int {
return ipart(x + 0.5)
}
@inline(__always) private static func fpart(_ x: Float) -> Float {
if x < 0 {
return 1 - (x - floor(x))
}
return x - floor(x)
}
@inline(__always) private static func rfpart(_ x: Float) -> Float {
return 1 - fpart(x)
}
// An optimization for cases where we want both the rfpart and the fpart.
@inline(__always) private static func rffpart(_ x: Float) -> (rfpart: Float, fpart: Float) {
let fp = fpart(x)
return (
rfpart: 1 - fp,
fpart: fp
)
}
static func drawSegment(
gridWidth: Int,
gridHeight: Int,
data: inout ContiguousArray<LightGridPixel>,
segment: LightSegment
) {
var x0 = Float(segment.pos1.x)
var y0 = Float(segment.pos1.y)
var x1 = Float(segment.pos2.x)
var y1 = Float(segment.pos2.y)
// As an optimization, we convert the color to float once.
let lightColorFloat = (Float(segment.color.r), Float(segment.color.g), Float(segment.color.b))
let steep = abs(y1 - y0) > abs(x1 - x0)
if steep {
swap(&x0, &y0)
swap(&x1, &y1)
}
if x0 > x1 {
swap(&x0, &x1)
swap(&y0, &y1)
}
// First endpoint
var dx = x1 - x0
let dy = y1 - y0
// Save ourselves a lot of trouble by avoiding zero-values.
if abs(dx) < 0.01 {
dx = 0.01
}
let gradient = dy / dx
let brCoeff: Float = min(abs(sqrtf(dx*dx + dy*dy) / dx), 2.0)
var xend = round(x0)
var yend = y0 + gradient * (Float(xend) - x0)
var xgap = rfpart(x0 + 0.5)
let xpxl1 = xend
let ypxl1 = ipart(yend)
if steep {
plot(
gridWidth: gridWidth,
gridHeight: gridHeight,
data: &data,
x: ypxl1,
y: xpxl1,
color: lightColorFloat,
br: rfpart(yend) * xgap * brCoeff)
plot(
gridWidth: gridWidth,
gridHeight: gridHeight,
data: &data,
x: ypxl1+1,
y: xpxl1,
color: lightColorFloat,
br: fpart(yend) * xgap * brCoeff)
} else {
plot(
gridWidth: gridWidth,
gridHeight: gridHeight,
data: &data,
x: xpxl1,
y: ypxl1,
color: lightColorFloat,
br: rfpart(yend) * xgap * brCoeff)
plot(
gridWidth: gridWidth,
gridHeight: gridHeight,
data: &data,
x: xpxl1,
y: ypxl1+1,
color: lightColorFloat,
br: fpart(yend) * xgap * brCoeff)
}
var intery = yend + gradient
// Second endpoint
xend = round(x1)
yend = y1 + gradient * (Float(xend) - x1)
xgap = fpart(x1 + 0.5)
let xpxl2 = xend
let ypxl2 = ipart(yend)
if steep {
plot(
gridWidth: gridWidth,
gridHeight: gridHeight,
data: &data,
x: ypxl2,
y: xpxl2,
color: lightColorFloat,
br: rfpart(yend) * xgap * brCoeff)
plot(
gridWidth: gridWidth,
gridHeight: gridHeight,
data: &data,
x: ypxl2+1,
y: xpxl2,
color: lightColorFloat,
br: fpart(yend) * xgap * brCoeff)
} else {
plot(
gridWidth: gridWidth,
gridHeight: gridHeight,
data: &data,
x: xpxl2,
y: ypxl2,
color: lightColorFloat,
br: rfpart(yend) * xgap * brCoeff)
plot(
gridWidth: gridWidth,
gridHeight: gridHeight,
data: &data,
x: xpxl2,
y: ypxl2+1,
color: lightColorFloat,
br: fpart(yend) * xgap * brCoeff)
}
// Main loop. This is called a lot, so should be made as efficient as possible.
if steep {
// For efficiency, we use the a while loop rather than the normal swift range.
var x = (xpxl1 + 1)
while x <= (xpxl2 - 1) {
let precalcIpart = ipart(intery)
let parts = rffpart(intery)
plot(
gridWidth: gridWidth,
gridHeight: gridHeight,
data: &data,
x: precalcIpart,
y: x,
color: lightColorFloat,
br: parts.rfpart * brCoeff)
plot(
gridWidth: gridWidth,
gridHeight: gridHeight,
data: &data,
x: precalcIpart+1,
y: x,
color: lightColorFloat,
br: parts.fpart * brCoeff)
intery = intery + gradient
x += 1
}
} else {
// For efficiency, we use the a while loop rather than the normal swift range.
var x = (xpxl1 + 1)
while x <= (xpxl2 - 1) {
let precalcIpart = ipart(intery)
let parts = rffpart(intery)
plot(
gridWidth: gridWidth,
gridHeight: gridHeight,
data: &data,
x: x,
y: precalcIpart,
color: lightColorFloat,
br: parts.rfpart * brCoeff)
plot(
gridWidth: gridWidth,
gridHeight: gridHeight,
data: &data,
x: x,
y: precalcIpart+1,
color: lightColorFloat,
br: parts.fpart * brCoeff)
intery = intery + gradient
x += 1
}
}
}
}
/// A modified version of the Wu line algorithm (above) that sacrifices quality (AA) for speed.
private final class WuFasterLightGridSegmentDraw {
@inline(__always) private static func plot(
gridWidth: Int,
gridHeight: Int,
data: inout ContiguousArray<LightGridPixel>,
x: Int,
y: Int,
color: (UInt32, UInt32,UInt32)
) {
let index = indexFromLocation(gridWidth, gridHeight, x, y)
let initialPixel = data[index]
data[index].r = initialPixel.r + color.0
data[index].g = initialPixel.g + color.1
data[index].b = initialPixel.b + color.2
}
@inline(__always) private static func ipart(_ x: Float) -> Int {
return Int(x)
}
@inline(__always) private static func round(_ x: Float) -> Int {
return ipart(x + 0.5)
}
@inline(__always) private static func fpart(_ x: Float) -> Float {
if x < 0 {
return 1 - (x - floor(x))
}
return x - floor(x)
}
// An optimization for cases where we want both the rfpart and the fpart.
@inline(__always) private static func rffpart(_ x: Float) -> (rfpart: Float, fpart: Float) {
let fp = fpart(x)
return (
rfpart: 1 - fp,
fpart: fp
)
}
static func drawSegment(
gridWidth: Int,
gridHeight: Int,
data: inout ContiguousArray<LightGridPixel>,
segment: LightSegment
) {
var x0 = Float(segment.pos1.x)
var y0 = Float(segment.pos1.y)
var x1 = Float(segment.pos2.x)
var y1 = Float(segment.pos2.y)
let steep = abs(y1 - y0) > abs(x1 - x0)
if steep {
swap(&x0, &y0)
swap(&x1, &y1)
}
if x0 > x1 {
swap(&x0, &x1)
swap(&y0, &y1)
}
var dx = x1 - x0
let dy = y1 - y0
// Save ourselves a lot of trouble by avoiding zero-values.
if abs(dx) < 0.01 {
dx = 0.01
}
let gradient = dy / dx
let brCoeff: Float = min(abs(sqrtf(dx*dx + dy*dy) / dx), 2.0)
// As an optimization, we convert the color to float once.
let lightColorUInt32 = (
UInt32((Float(segment.color.r) * brCoeff).rounded()),
UInt32((Float(segment.color.g) * brCoeff).rounded()),
UInt32((Float(segment.color.b) * brCoeff).rounded()))
// First endpoint
var xend = round(x0)
var yend = y0 + gradient * (Float(xend) - x0)
let xpxl1 = xend
let ypxl1 = ipart(yend)
if steep {
plot(
gridWidth: gridWidth,
gridHeight: gridHeight,
data: &data,
x: ypxl1,
y: xpxl1,
color: lightColorUInt32)
} else {
plot(
gridWidth: gridWidth,
gridHeight: gridHeight,
data: &data,
x: xpxl1,
y: ypxl1,
color: lightColorUInt32)
}
var intery = yend + gradient
// Second endpoint
xend = round(x1)
yend = y1 + gradient * (Float(xend) - x1)
let xpxl2 = xend
let ypxl2 = ipart(yend)
if steep {
plot(
gridWidth: gridWidth,
gridHeight: gridHeight,
data: &data,
x: ypxl2,
y: xpxl2,
color: lightColorUInt32)
} else {
plot(
gridWidth: gridWidth,
gridHeight: gridHeight,
data: &data,
x: xpxl2,
y: ypxl2,
color: lightColorUInt32)
}
// Main loop. This is called a lot, so should be made as efficient as possible.
if steep {
// For efficiency, we use the a while loop rather than the normal swift range.
var x = (xpxl1 + 1)
while x <= (xpxl2 - 1) {
let precalcIpart = Int(intery.rounded())
plot(
gridWidth: gridWidth,
gridHeight: gridHeight,
data: &data,
x: precalcIpart,
y: x,
color: lightColorUInt32)
intery = intery + gradient
x += 1
}
} else {
// For efficiency, we use the a while loop rather than the normal swift range.
var x = (xpxl1 + 1)
while x <= (xpxl2 - 1) {
let precalcIpart = Int(intery.rounded())
plot(
gridWidth: gridWidth,
gridHeight: gridHeight,
data: &data,
x: x,
y: precalcIpart,
color: lightColorUInt32)
intery = intery + gradient
x += 1
}
}
}
}
| apache-2.0 | 7b5ad10850a7493db69c24f0080a4cb3 | 29.987241 | 115 | 0.506768 | 4.181877 | false | false | false | false |
HJianBo/Mqtt | Sources/Mqtt/Packet/PubRecPacket.swift | 1 | 1287 | //
// PubrecPacket.swift
// Mqtt
//
// Created by Heee on 16/2/2.
// Copyright © 2016年 hjianbo.me. All rights reserved.
//
import Foundation
/**
PUBREC Packet is the response to a PUBLISH Packet with QoS 2. It is the second packet of the QoS
2 protocol exchange.
**Fixed Header:**
1. *Remaining Length field:* This is the length of the variable header.
For the PUBREC Packet this has the value 2.
**Variable Header:**
The variable header contains the Packet Identifier from the PUBLISH Packet that is being acknowledged.
**Payload:**
The PUBREC Packet has no payload.
*/
struct PubRecPacket: Packet {
var fixedHeader: FixedHeader
var packetId: UInt16
var varHeader: Array<UInt8> {
return packetId.bytes
}
var payload = [UInt8]()
init(packetId: UInt16) {
fixedHeader = FixedHeader(type: .pubrec)
self.packetId = packetId
}
}
extension PubRecPacket: InitializeWithResponse {
init(header: FixedHeader, bytes: [UInt8]) {
self.fixedHeader = header
packetId = UInt16(bytes[0])*256+UInt16(bytes[1])
}
}
extension PubRecPacket {
public var description: String {
return "PubRec(packetId: \(packetId))"
}
}
| mit | bd3410a6ca15348fa52bed4ec2e0e2f2 | 21.526316 | 103 | 0.639408 | 3.86747 | false | false | false | false |
jigneshsheth/Datastructures | DataStructure/DataStructureTests/Shopify/SpacecraftTest.swift | 1 | 2444 | //
// SpacecraftTest.swift
// DataStructureTests
//
// Created by Jigs Sheth on 10/31/21.
// Copyright © 2021 jigneshsheth.com. All rights reserved.
//
import XCTest
@testable import DataStructure
class SpacecraftTest: XCTestCase {
override func setUpWithError() throws {
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDownWithError() throws {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testSpacecarft() throws {
let spaceCraft = Spacecraft(position: Point(x: 0, y: 0))
var go = true
while go {
print("\n ---- Choose 1 below option --- \n")
print(" ---- Choose W to Move UP --- ")
print(" ---- Choose A to Move Left --- ")
print(" ---- Choose D to Move Right --- ")
print(" ---- Choose S to descrease the speed --- \n")
print(" ---- Reset R -- End \"E\"-")
guard let selection = readLine()?.uppercased(), selection.contains("W") || selection.contains("A") || selection.contains("S") || selection.contains("D") || selection.contains("R") || selection.contains("E") else {
print("\n##### Wrong key selection ###########\n")
continue
}
switch selection {
case "W","S":
print(" ---- Enter valid speed: between 1 to 5 --- \n")
guard let value = readLine(),let speed = Int(value) else {
print("\n ## Enter valid speed ##\n")
continue
}
spaceCraft.setSpeed(speed: speed)
print("Move up")
case "A":
// print(" ---- Move Left --- \n")
// guard let value = readLine(),let leftPoint = Int(value) else {
// print("\n ## Invalid entry ##\n")
// continue
// }
// spaceCraft.moveLeft(position:leftPoint)
spaceCraft.moveLeft(position:1)
case "D":
// print(" ---- Move Right --- \n")
// guard let value = readLine(),let rightPoint = Int(value) else {
// print("\n ## Invalid entry ##\n")
// continue
// }
// spaceCraft.moveRight(position:rightPoint)
spaceCraft.moveRight(position:1)
case "R":
spaceCraft.reset()
case "E":
go = false
break
default:
print("\n##### Wrong key selection ########### \n")
}
print(spaceCraft.description)
}
}
func testPerformanceExample() throws {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| mit | a710cf58eeb9dc5c4b2d307a4e279433 | 27.741176 | 216 | 0.608269 | 3.436006 | false | true | false | false |
sarvex/SwiftRecepies | Basics/Accepting User Text Input with UITextField/Accepting User Text Input with UITextField/ViewController.swift | 1 | 5080 | //
// ViewController.swift
// Accepting User Text Input with UITextField
//
// Created by Vandad Nahavandipoor on 6/29/14.
// Copyright (c) 2014 Pixolity Ltd. All rights reserved.
//
// These example codes are written for O'Reilly's iOS 8 Swift Programming Cookbook
// If you use these solutions in your apps, you can give attribution to
// Vandad Nahavandipoor for his work. Feel free to visit my blog
// at http://vandadnp.wordpress.com for daily tips and tricks in Swift
// and Objective-C and various other programming languages.
//
// You can purchase "iOS 8 Swift Programming Cookbook" from
// the following URL:
// http://shop.oreilly.com/product/0636920034254.do
//
// If you have any questions, you can contact me directly
// at [email protected]
// Similarly, if you find an error in these sample codes, simply
// report them to O'Reilly at the following URL:
// http://www.oreilly.com/catalog/errata.csp?isbn=0636920034254
/* 1 */
//import UIKit
//
//class ViewController: UIViewController {
//
// var textField: UITextField!
//
//}
/* 2 */
//import UIKit
//
//class ViewController: UIViewController {
//
// var textField: UITextField!
//
// override func viewDidLoad() {
// super.viewDidLoad()
//
// textField = UITextField(frame: CGRect(x: 0, y: 0, width: 200, height: 31))
//
// textField.borderStyle = .RoundedRect
//
// textField.contentVerticalAlignment = .Center
//
// textField.textAlignment = .Center
//
// textField.text = "Sir Richard Branson"
// textField.center = view.center
// view.addSubview(textField)
//
// }
//
//}
/* 3 */
//import UIKit
//
//class ViewController: UIViewController, UITextFieldDelegate {
//
// <# the rest of your code goes here #>
//
//}
/* 4 */
//import UIKit
//
//class ViewController: UIViewController, UITextFieldDelegate {
//
// var textField: UITextField!
// var label: UILabel!
//
//}
/* 5 */
//import UIKit
//
//class ViewController: UIViewController, UITextFieldDelegate {
//
// var textField: UITextField!
// var label: UILabel!
//
// func calculateAndDisplayTextFieldLengthWithText(text: String){
//
// var characterOrCharacters = "Character"
// if count(text) != 1{
// characterOrCharacters += "s"
// }
//
// let stringLength = count(text)
//
// label.text = "\(stringLength) \(characterOrCharacters)"
//
// }
//
//
// func textField(paramTextField: UITextField,
// shouldChangeCharactersInRange range: NSRange,
// replacementString string: String) -> Bool{
//
// let text = paramTextField.text as NSString
//
// let wholeText =
// text.stringByReplacingCharactersInRange(
// range, withString: string)
//
// calculateAndDisplayTextFieldLengthWithText(wholeText)
//
// return true
//
// }
//
// func textFieldShouldReturn(paramTextField: UITextField) -> Bool{
// paramTextField.resignFirstResponder()
// return true
// }
//
// override func viewDidLoad() {
// super.viewDidLoad()
//
// textField = UITextField(frame:
// CGRect(x: 38, y: 30, width: 220, height: 31))
//
// textField.delegate = self
// textField.borderStyle = .RoundedRect
// textField.contentVerticalAlignment = .Center
// textField.textAlignment = .Center
// textField.text = "Sir Richard Branson"
// view.addSubview(textField)
//
// label = UILabel(frame: CGRect(x: 38, y: 61, width: 220, height: 31))
// view.addSubview(label)
// calculateAndDisplayTextFieldLengthWithText(textField.text)
//
// }
//
//}
/* 6 */
//import UIKit
//
//class ViewController: UIViewController {
//
// var textField: UITextField!
//
// override func viewDidLoad() {
// super.viewDidLoad()
//
// textField = UITextField(frame:
// CGRect(x: 38, y: 30, width: 220, height: 31))
//
// textField.borderStyle = .RoundedRect
// textField.contentVerticalAlignment = .Center
// textField.textAlignment = .Center
// textField.placeholder = "Enter your text here..."
// view.addSubview(textField)
//
// }
//
//}
/* 7 */
import UIKit
class ViewController: UIViewController {
var textField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
textField = UITextField(frame:
CGRect(x: 38, y: 30, width: 220, height: 31))
textField.borderStyle = .RoundedRect
textField.contentVerticalAlignment = .Center
textField.textAlignment = .Left
textField.placeholder = "Enter your text here..."
let currencyLabel = UILabel(frame: CGRectZero)
currencyLabel.text = NSNumberFormatter().currencySymbol
currencyLabel.font = textField.font
currencyLabel.textAlignment = .Right
currencyLabel.sizeToFit()
/* Give more width to the label so that it aligns properly on the
text field's left view, when the label's text itself is right aligned
*/
currencyLabel.frame.size.width += 10
textField.leftView = currencyLabel
textField.leftViewMode = .Always
view.addSubview(textField)
}
} | isc | f31127800ea7e9f134247e5acccddeff | 24.661616 | 83 | 0.66063 | 3.866058 | false | false | false | false |
funfunStudy/algorithm | swift/DigitalRoot/DigitalRoot/main.swift | 1 | 900 | //
// main.swift
// DigitalRoot
//
// Created by Moonbeom KWON on 2017. 8. 28..
// Copyright © 2017년 mbkyle. All rights reserved.
//
import Foundation
print("Hello, World!")
var inputList: NSMutableArray = NSMutableArray()
repeat {
if let input: String = readLine() {
if Int(input) == 0 {
break
} else if input.trimmingCharacters(in: .whitespaces).characters.count > 0 {
inputList.add(input)
}
}
} while true
func getDigitalRoot(input: String) -> Int {
let rootNumber: Int = Array(input.characters).map{ Int(String($0))! }.reduce(0, +)
if rootNumber > 10 {
return getDigitalRoot(input: String(rootNumber))
} else {
return rootNumber
}
}
print("\n\n")
for inputString in inputList {
if let input = inputString as? String {
print(getDigitalRoot(input: input))
}
}
| mit | 21195c5d007d35d6ea93ac0d33d9558f | 19.386364 | 86 | 0.603122 | 3.67623 | false | false | false | false |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.