repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
jacobwhite/firefox-ios | Client/Frontend/Browser/FindInPageBar.swift | 1 | 7136 | /* 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
protocol FindInPageBarDelegate: class {
func findInPage(_ findInPage: FindInPageBar, didTextChange text: String)
func findInPage(_ findInPage: FindInPageBar, didFindPreviousWithText text: String)
func findInPage(_ findInPage: FindInPageBar, didFindNextWithText text: String)
func findInPageDidPressClose(_ findInPage: FindInPageBar)
}
private struct FindInPageUX {
static let ButtonColor = UIColor.black
static let MatchCountColor = UIColor.lightGray
static let MatchCountFont = UIConstants.DefaultChromeFont
static let SearchTextColor = UIColor(rgb: 0xe66000)
static let SearchTextFont = UIConstants.DefaultChromeFont
static let TopBorderColor = UIColor(rgb: 0xEEEEEE)
}
class FindInPageBar: UIView {
weak var delegate: FindInPageBarDelegate?
fileprivate let searchText = UITextField()
fileprivate let matchCountView = UILabel()
fileprivate let previousButton = UIButton()
fileprivate let nextButton = UIButton()
var currentResult = 0 {
didSet {
if totalResults > 500 {
matchCountView.text = "\(currentResult)/500+"
} else {
matchCountView.text = "\(currentResult)/\(totalResults)"
}
}
}
var totalResults = 0 {
didSet {
if totalResults > 500 {
matchCountView.text = "\(currentResult)/500+"
} else {
matchCountView.text = "\(currentResult)/\(totalResults)"
}
previousButton.isEnabled = totalResults > 1
nextButton.isEnabled = previousButton.isEnabled
}
}
var text: String? {
get {
return searchText.text
}
set {
searchText.text = newValue
didTextChange(searchText)
}
}
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = .white
searchText.addTarget(self, action: #selector(didTextChange), for: .editingChanged)
searchText.textColor = FindInPageUX.SearchTextColor
searchText.font = FindInPageUX.SearchTextFont
searchText.autocapitalizationType = .none
searchText.autocorrectionType = .no
searchText.inputAssistantItem.leadingBarButtonGroups = []
searchText.inputAssistantItem.trailingBarButtonGroups = []
searchText.enablesReturnKeyAutomatically = true
searchText.returnKeyType = .search
searchText.accessibilityIdentifier = "FindInPage.searchField"
addSubview(searchText)
matchCountView.textColor = FindInPageUX.MatchCountColor
matchCountView.font = FindInPageUX.MatchCountFont
matchCountView.isHidden = true
matchCountView.accessibilityIdentifier = "FindInPage.matchCount"
addSubview(matchCountView)
previousButton.setImage(UIImage(named: "find_previous"), for: [])
previousButton.setTitleColor(FindInPageUX.ButtonColor, for: [])
previousButton.accessibilityLabel = NSLocalizedString("Previous in-page result", tableName: "FindInPage", comment: "Accessibility label for previous result button in Find in Page Toolbar.")
previousButton.addTarget(self, action: #selector(didFindPrevious), for: .touchUpInside)
previousButton.accessibilityIdentifier = "FindInPage.find_previous"
addSubview(previousButton)
nextButton.setImage(UIImage(named: "find_next"), for: [])
nextButton.setTitleColor(FindInPageUX.ButtonColor, for: [])
nextButton.accessibilityLabel = NSLocalizedString("Next in-page result", tableName: "FindInPage", comment: "Accessibility label for next result button in Find in Page Toolbar.")
nextButton.addTarget(self, action: #selector(didFindNext), for: .touchUpInside)
nextButton.accessibilityIdentifier = "FindInPage.find_next"
addSubview(nextButton)
let closeButton = UIButton()
closeButton.setImage(UIImage(named: "find_close"), for: [])
closeButton.setTitleColor(FindInPageUX.ButtonColor, for: [])
closeButton.accessibilityLabel = NSLocalizedString("Done", tableName: "FindInPage", comment: "Done button in Find in Page Toolbar.")
closeButton.addTarget(self, action: #selector(didPressClose), for: .touchUpInside)
closeButton.accessibilityIdentifier = "FindInPage.close"
addSubview(closeButton)
let topBorder = UIView()
topBorder.backgroundColor = FindInPageUX.TopBorderColor
addSubview(topBorder)
searchText.snp.makeConstraints { make in
make.leading.top.bottom.equalTo(self).inset(UIEdgeInsets(top: 0, left: 8, bottom: 0, right: 0))
}
searchText.setContentHuggingPriority(.defaultLow, for: .horizontal)
searchText.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
matchCountView.snp.makeConstraints { make in
make.leading.equalTo(searchText.snp.trailing)
make.centerY.equalTo(self)
}
matchCountView.setContentHuggingPriority(.defaultHigh, for: .horizontal)
matchCountView.setContentCompressionResistancePriority(.defaultHigh, for: .horizontal)
previousButton.snp.makeConstraints { make in
make.leading.equalTo(matchCountView.snp.trailing)
make.size.equalTo(self.snp.height)
make.centerY.equalTo(self)
}
nextButton.snp.makeConstraints { make in
make.leading.equalTo(previousButton.snp.trailing)
make.size.equalTo(self.snp.height)
make.centerY.equalTo(self)
}
closeButton.snp.makeConstraints { make in
make.leading.equalTo(nextButton.snp.trailing)
make.size.equalTo(self.snp.height)
make.trailing.centerY.equalTo(self)
}
topBorder.snp.makeConstraints { make in
make.height.equalTo(1)
make.left.right.top.equalTo(self)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
@discardableResult override func becomeFirstResponder() -> Bool {
searchText.becomeFirstResponder()
return super.becomeFirstResponder()
}
@objc fileprivate func didFindPrevious(_ sender: UIButton) {
delegate?.findInPage(self, didFindPreviousWithText: searchText.text ?? "")
}
@objc fileprivate func didFindNext(_ sender: UIButton) {
delegate?.findInPage(self, didFindNextWithText: searchText.text ?? "")
}
@objc fileprivate func didTextChange(_ sender: UITextField) {
matchCountView.isHidden = searchText.text?.trimmingCharacters(in: .whitespaces).isEmpty ?? true
delegate?.findInPage(self, didTextChange: searchText.text ?? "")
}
@objc fileprivate func didPressClose(_ sender: UIButton) {
delegate?.findInPageDidPressClose(self)
}
}
| mpl-2.0 | 9a1d10e693b5e7616bc35d0157c64887 | 40.011494 | 197 | 0.681334 | 5.278107 | false | false | false | false |
AshuMishra/BMSLocationFinder | BMSLocationFinder/BMSLocationFinder/Helper/ENSideMenu.swift | 1 | 10315 | //
// SideMenu.swift
// SwiftSideMenu
//
// Created by Evgeny on 24.07.14.
// Copyright (c) 2014 Evgeny Nazarov. All rights reserved.
//
import UIKit
@objc public protocol ENSideMenuDelegate {
optional func sideMenuWillOpen()
optional func sideMenuWillClose()
optional func sideMenuShouldOpenSideMenu () -> Bool
}
@objc public protocol ENSideMenuProtocol {
var sideMenu : ENSideMenu? { get }
func setContentViewController(contentViewController: UIViewController)
}
public enum ENSideMenuAnimation : Int {
case None
case Default
}
public enum ENSideMenuPosition : Int {
case Left
case Right
}
public extension UIViewController {
public func toggleSideMenuView () {
sideMenuController()?.sideMenu?.toggleMenu()
}
public func hideSideMenuView () {
sideMenuController()?.sideMenu?.hideSideMenu()
}
public func showSideMenuView () {
sideMenuController()?.sideMenu?.showSideMenu()
}
public func sideMenuController () -> ENSideMenuProtocol? {
var iteration : UIViewController? = self.parentViewController
if (iteration == nil) {
return topMostController()
}
do {
if (iteration is ENSideMenuProtocol) {
return iteration as? ENSideMenuProtocol
} else if (iteration?.parentViewController != nil && iteration?.parentViewController != iteration) {
iteration = iteration!.parentViewController;
} else {
iteration = nil;
}
} while (iteration != nil)
return iteration as? ENSideMenuProtocol
}
internal func topMostController () -> ENSideMenuProtocol? {
var topController : UIViewController? = UIApplication.sharedApplication().keyWindow?.rootViewController
while (topController?.presentedViewController is ENSideMenuProtocol) {
topController = topController?.presentedViewController;
}
return topController as? ENSideMenuProtocol
}
}
public class ENSideMenu : NSObject {
public var menuWidth : CGFloat = 160.0 {
didSet {
needUpdateApperance = true
updateFrame()
}
}
private let menuPosition:ENSideMenuPosition = .Left
public var bouncingEnabled :Bool = true
private let sideMenuContainerView = UIView()
private var menuTableViewController : UITableViewController!
private var animator : UIDynamicAnimator!
private let sourceView : UIView!
private var needUpdateApperance : Bool = false
public weak var delegate : ENSideMenuDelegate?
private var isMenuOpen : Bool = false
public init(sourceView: UIView, menuPosition: ENSideMenuPosition) {
super.init()
self.sourceView = sourceView
self.menuPosition = menuPosition
self.setupMenuView()
animator = UIDynamicAnimator(referenceView:sourceView)
// Add right swipe gesture recognizer
let rightSwipeGestureRecognizer = UISwipeGestureRecognizer(target: self, action: "handleGesture:")
rightSwipeGestureRecognizer.direction = UISwipeGestureRecognizerDirection.Right
sourceView.addGestureRecognizer(rightSwipeGestureRecognizer)
// Add left swipe gesture recognizer
let leftSwipeGestureRecognizer = UISwipeGestureRecognizer(target: self, action: "handleGesture:")
leftSwipeGestureRecognizer.direction = UISwipeGestureRecognizerDirection.Left
if (menuPosition == .Left) {
sourceView.addGestureRecognizer(rightSwipeGestureRecognizer)
sideMenuContainerView.addGestureRecognizer(leftSwipeGestureRecognizer)
}
else {
sideMenuContainerView.addGestureRecognizer(rightSwipeGestureRecognizer)
sourceView.addGestureRecognizer(leftSwipeGestureRecognizer)
}
}
public convenience init(sourceView: UIView, menuTableViewController: UITableViewController, menuPosition: ENSideMenuPosition) {
self.init(sourceView: sourceView, menuPosition: menuPosition)
self.menuTableViewController = menuTableViewController
self.menuTableViewController.tableView.frame = sideMenuContainerView.bounds
self.menuTableViewController.tableView.autoresizingMask = .FlexibleHeight | .FlexibleWidth
sideMenuContainerView.addSubview(self.menuTableViewController.tableView)
}
private func updateFrame() {
let menuFrame = CGRectMake(
(menuPosition == .Left) ?
isMenuOpen ? 0 : -menuWidth-1.0 :
isMenuOpen ? sourceView.frame.size.width - menuWidth : sourceView.frame.size.width+1.0,
sourceView.frame.origin.y,
menuWidth,
sourceView.frame.size.height
)
sideMenuContainerView.frame = menuFrame
}
private func setupMenuView() {
// Configure side menu container
updateFrame()
sideMenuContainerView.backgroundColor = UIColor.clearColor()
sideMenuContainerView.clipsToBounds = false
sideMenuContainerView.layer.masksToBounds = false;
sideMenuContainerView.layer.shadowOffset = (menuPosition == .Left) ? CGSizeMake(1.0, 1.0) : CGSizeMake(-1.0, -1.0);
sideMenuContainerView.layer.shadowRadius = 1.0;
sideMenuContainerView.layer.shadowOpacity = 0.125;
sideMenuContainerView.layer.shadowPath = UIBezierPath(rect: sideMenuContainerView.bounds).CGPath
sourceView.addSubview(sideMenuContainerView)
if (NSClassFromString("UIVisualEffectView") != nil) {
// Add blur view
var visualEffectView = UIVisualEffectView(effect: UIBlurEffect(style: .Light)) as UIVisualEffectView
visualEffectView.frame = sideMenuContainerView.bounds
visualEffectView.autoresizingMask = .FlexibleHeight | .FlexibleWidth
sideMenuContainerView.addSubview(visualEffectView)
}
else {
// TODO: add blur for ios 7
}
}
private func toggleMenu (shouldOpen: Bool) {
if (shouldOpen && delegate?.sideMenuShouldOpenSideMenu?() == false) {
return;
}
updateSideMenuApperanceIfNeeded()
isMenuOpen = shouldOpen
if (bouncingEnabled) {
animator.removeAllBehaviors()
var gravityDirectionX: CGFloat
var pushMagnitude: CGFloat
var boundaryPointX: CGFloat
var boundaryPointY: CGFloat
if (menuPosition == .Left) {
// Left side menu
gravityDirectionX = (shouldOpen) ? 4 : -4
pushMagnitude = (shouldOpen) ? 20 : -20
boundaryPointX = (shouldOpen) ? menuWidth : -menuWidth-2
boundaryPointY = 20
}
else {
// Right side menu
gravityDirectionX = (shouldOpen) ? -1 : 1
pushMagnitude = (shouldOpen) ? -20 : 20
boundaryPointX = (shouldOpen) ? sourceView.frame.size.width-menuWidth : sourceView.frame.size.width+menuWidth+2
boundaryPointY = -20
}
let gravityBehavior = UIGravityBehavior(items: [sideMenuContainerView])
gravityBehavior.gravityDirection = CGVectorMake(gravityDirectionX, 0)
animator.addBehavior(gravityBehavior)
let collisionBehavior = UICollisionBehavior(items: [sideMenuContainerView])
collisionBehavior.addBoundaryWithIdentifier("menuBoundary", fromPoint: CGPointMake(boundaryPointX, boundaryPointY),
toPoint: CGPointMake(boundaryPointX, sourceView.frame.size.height))
animator.addBehavior(collisionBehavior)
let pushBehavior = UIPushBehavior(items: [sideMenuContainerView], mode: UIPushBehaviorMode.Instantaneous)
pushBehavior.magnitude = pushMagnitude
animator.addBehavior(pushBehavior)
let menuViewBehavior = UIDynamicItemBehavior(items: [sideMenuContainerView])
menuViewBehavior.elasticity = 0.25
animator.addBehavior(menuViewBehavior)
}
else {
var destFrame :CGRect
if (menuPosition == .Left) {
destFrame = CGRectMake((shouldOpen) ? -2.0 : -menuWidth, 0, menuWidth, sideMenuContainerView.frame.size.height)
}
else {
destFrame = CGRectMake((shouldOpen) ? sourceView.frame.size.width-menuWidth : sourceView.frame.size.width+2.0,
0,
menuWidth,
sideMenuContainerView.frame.size.height)
}
UIView.animateWithDuration(0.4, animations: { () -> Void in
self.sideMenuContainerView.frame = destFrame
})
}
if (shouldOpen) {
delegate?.sideMenuWillOpen?()
} else {
delegate?.sideMenuWillClose?()
}
}
internal func handleGesture(gesture: UISwipeGestureRecognizer) {
toggleMenu((self.menuPosition == .Right && gesture.direction == .Left)
|| (self.menuPosition == .Left && gesture.direction == .Right))
}
private func updateSideMenuApperanceIfNeeded () {
if (needUpdateApperance) {
var frame = sideMenuContainerView.frame
frame.size.width = menuWidth
sideMenuContainerView.frame = frame
sideMenuContainerView.layer.shadowPath = UIBezierPath(rect: sideMenuContainerView.bounds).CGPath
needUpdateApperance = false
}
}
public func toggleMenu () {
if (isMenuOpen) {
toggleMenu(false)
}
else {
updateSideMenuApperanceIfNeeded()
toggleMenu(true)
}
}
public func showSideMenu () {
if (!isMenuOpen) {
toggleMenu(true)
}
}
public func hideSideMenu () {
if (isMenuOpen) {
toggleMenu(false)
}
}
}
| mit | 0692390156b669f43803171c176b33ab | 35.971326 | 131 | 0.626079 | 6.074794 | false | false | false | false |
victorpimentel/SwiftLint | Source/SwiftLintFramework/Rules/ImplicitReturnRule.swift | 2 | 3187 | //
// ImplicitReturnRule.swift
// SwiftLint
//
// Created by Marcelo Fabri on 04/30/17.
// Copyright © 2017 Realm. All rights reserved.
//
import Foundation
import SourceKittenFramework
public struct ImplicitReturnRule: ConfigurationProviderRule, CorrectableRule, OptInRule {
public var configuration = SeverityConfiguration(.warning)
public init() {}
public static let description = RuleDescription(
identifier: "implicit_return",
name: "Implicit Return",
description: "Prefer implicit returns in closures.",
nonTriggeringExamples: [
"foo.map { $0 + 1 }",
"foo.map({ $0 + 1 })",
"foo.map { value in value + 1 }",
"func foo() -> Int {\n return 0\n}",
"if foo {\n return 0\n}",
"var foo: Bool { return true }"
],
triggeringExamples: [
"foo.map { value in\n ↓return value + 1\n}",
"foo.map {\n ↓return $0 + 1\n}"
],
corrections: [
"foo.map { value in\n ↓return value + 1\n}": "foo.map { value in\n value + 1\n}",
"foo.map {\n ↓return $0 + 1\n}": "foo.map {\n $0 + 1\n}"
]
)
public func validate(file: File) -> [StyleViolation] {
return violationRanges(in: file).flatMap {
StyleViolation(ruleDescription: type(of: self).description,
severity: configuration.severity,
location: Location(file: file, characterOffset: $0.location))
}
}
public func correct(file: File) -> [Correction] {
let violatingRanges = file.ruleEnabled(violatingRanges: self.violationRanges(in: file), for: self)
var correctedContents = file.contents
var adjustedLocations = [Int]()
for violatingRange in violatingRanges.reversed() {
if let indexRange = correctedContents.nsrangeToIndexRange(violatingRange) {
correctedContents = correctedContents.replacingCharacters(in: indexRange, with: "")
adjustedLocations.insert(violatingRange.location, at: 0)
}
}
file.write(correctedContents)
return adjustedLocations.map {
Correction(ruleDescription: type(of: self).description,
location: Location(file: file, characterOffset: $0))
}
}
private func violationRanges(in file: File) -> [NSRange] {
let pattern = "(?:\\bin|\\{)\\s+(return\\s+)"
let contents = file.contents.bridge()
return file.matchesAndSyntaxKinds(matching: pattern).flatMap { result, kinds in
let range = result.range
guard kinds == [.keyword, .keyword] || kinds == [.keyword],
let byteRange = contents.NSRangeToByteRange(start: range.location,
length: range.length),
let outerKind = file.structure.kinds(forByteOffset: byteRange.location).last,
SwiftExpressionKind(rawValue: outerKind.kind) == .call else {
return nil
}
return result.rangeAt(1)
}
}
}
| mit | a1d980ce2879c48334f01e0a81fdb976 | 36.833333 | 106 | 0.572373 | 4.507801 | false | false | false | false |
haranicle/RealmRelationsSample | RealmRelationsSample/Person.swift | 1 | 435 | //
// Person.swift
// RealmRelationsSample
//
// Created by haranicle on 2015/02/27.
// Copyright (c) 2015年 haranicle. All rights reserved.
//
import Realm
class Person: RLMObject {
dynamic var name = ""
dynamic var age = 0
dynamic var face = Face()
dynamic var sushi = RLMArray(objectClassName: "Sushi")
dynamic var company = Company()
dynamic var friends = RLMArray(objectClassName: "OtherPerson")
}
| mit | 262691c8bc1d83966766de8c92c3aad8 | 21.789474 | 66 | 0.681293 | 3.700855 | false | false | false | false |
whiteshadow-gr/HatForIOS | HATTests/Services Tests/HATFileServiceTests.swift | 1 | 16128 | //
/**
* Copyright (C) 2018 HAT Data Exchange Ltd
*
* SPDX-License-Identifier: MPL2
*
* This file is part of the Hub of All Things project (HAT).
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/
*/
import Alamofire
import Mockingjay
import SwiftyJSON
import XCTest
internal class HATFileServiceTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testSearchFiles() {
let body: [Dictionary<String, Any>] = [[
"fileId": "iphonerumpelphoto",
"name": "rumpelPhoto",
"source": "iPhone",
"dateCreated": "2017-11-05T10:40:44.527Z",
"lastUpdated": "2017-11-05T10:40:44.527Z",
"tags": [
"iphone",
"viewer",
"photo"
],
"status": [
"size": 4752033,
"status": "Completed"
],
"contentUrl": "https://hubat-net-hatservice-v3ztbxc9civz-storages3bucket-m0gs7co0oyi2.s3-eu-west-1.amazonaws.com/testing.hubat.net/iphonerumpelphoto?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Date=20180118T180720Z&X-Amz-SignedHeaders=host&X-Amz-Expires=299&X-Amz-Credential=AKIAJBUBR3WGX4MX6H6A%2F20180118%2Feu-west-1%2Fs3%2Faws4_request&X-Amz-Signature=ac0eac4e41889443c9bec3cf9dfc119b65b1955479a9193f50f0812dd8bdd868",
"contentPublic": false,
"permissions": [
[
"userId": "de35e18d-147f-4664-8de7-409abf881754",
"contentReadable": true
]
]
]]
let userDomain: String = "testing.hubat.net"
let urlToConnect: String = "https://testing.hubat.net/api/v2.6/files/search"
let expectationTest: XCTestExpectation = expectation(description: "Searching files for photos...")
MockingjayProtocol.addStub(matcher: http(.post, uri: urlToConnect), builder: json(body))
func completion(profileImages: [HATFileUpload], newToken: String?) {
XCTAssertTrue(!profileImages.isEmpty)
expectationTest.fulfill()
}
func failed(error: HATError) {
XCTFail()
expectationTest.fulfill()
}
HATFileService.searchFiles(userDomain: userDomain, token: "", successCallback: completion, errorCallBack: failed)
waitForExpectations(timeout: 10) { error in
if let error: Error = error {
print("Error: \(error.localizedDescription)")
}
}
}
func testDeleteFile() {
let body: [Dictionary<String, Any>] = []
let userDomain: String = "testing.hubat.net"
let urlToConnect: String = "https://\(userDomain)/api/v2.6/files/file/1)"
let expectationTest: XCTestExpectation = expectation(description: "Deleting files from photos...")
MockingjayProtocol.addStub(matcher: everything, builder: json(body))
func completion(result: Bool, newToken: String?) {
XCTAssertTrue(result)
expectationTest.fulfill()
}
func failed(error: HATError) {
XCTFail()
expectationTest.fulfill()
}
HATFileService.deleteFile(fileID: "1", token: "", userDomain: userDomain, successCallback: completion, errorCallBack: failed)
waitForExpectations(timeout: 10) { error in
if let error: Error = error {
print("Error: \(error.localizedDescription)")
}
}
}
func testMakeFilePublic() {
let body: [Dictionary<String, Any>] = []
let userDomain: String = "testing.hubat.net"
let urlToConnect: String = "https://\(userDomain)/api/v2.6/files/allowAccessPublic/1"
let expectationTest: XCTestExpectation = expectation(description: "Making file Public...")
MockingjayProtocol.addStub(matcher: http(.get, uri: urlToConnect), builder: json(body))
func completion(result: Bool) {
XCTAssertTrue(result)
expectationTest.fulfill()
}
func failed(error: HATError) {
XCTFail()
expectationTest.fulfill()
}
HATFileService.makeFilePublic(fileID: "1", token: "", userDomain: userDomain, successCallback: completion, errorCallBack: failed)
waitForExpectations(timeout: 10) { error in
if let error: Error = error {
print("Error: \(error.localizedDescription)")
}
}
}
func testMakeFilePrivate() {
let body: [Dictionary<String, Any>] = []
let userDomain: String = "testing.hubat.net"
let urlToConnect: String = "https://\(userDomain)/api/v2.6/files/restrictAccessPublic/1"
let expectationTest: XCTestExpectation = expectation(description: "Making file Private...")
MockingjayProtocol.addStub(matcher: http(.get, uri: urlToConnect), builder: json(body))
func completion(result: Bool) {
XCTAssertTrue(result)
expectationTest.fulfill()
}
func failed(error: HATError) {
XCTFail()
expectationTest.fulfill()
}
HATFileService.makeFilePrivate(fileID: "1", token: "", userDomain: userDomain, successCallback: completion, errorCallBack: failed)
waitForExpectations(timeout: 10) { error in
if let error: Error = error {
print("Error: \(error.localizedDescription)")
}
}
}
func testMarkUploadedFileAsComplete() {
let body: Dictionary<String, Any> = [
"fileId": "iphonerumpelphoto",
"name": "rumpelPhoto",
"source": "iPhone",
"dateCreated": "2017-11-05T10:40:44.527Z",
"lastUpdated": "2017-11-05T10:40:44.527Z",
"tags": [
"iphone",
"viewer",
"photo"
],
"status": [
"size": 4752033,
"status": "Completed"
],
"contentUrl": "https://hubat-net-hatservice-v3ztbxc9civz-storages3bucket-m0gs7co0oyi2.s3-eu-west-1.amazonaws.com/testing.hubat.net/iphonerumpelphoto?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Date=20180118T180720Z&X-Amz-SignedHeaders=host&X-Amz-Expires=299&X-Amz-Credential=AKIAJBUBR3WGX4MX6H6A%2F20180118%2Feu-west-1%2Fs3%2Faws4_request&X-Amz-Signature=ac0eac4e41889443c9bec3cf9dfc119b65b1955479a9193f50f0812dd8bdd868",
"contentPublic": false,
"permissions": [
[
"userId": "de35e18d-147f-4664-8de7-409abf881754",
"contentReadable": true
]
]
]
let userDomain: String = "testing.hubat.net"
let urlToConnect: String = "https://\(userDomain)/api/v2.6/files/file/1/complete"
let expectationTest: XCTestExpectation = expectation(description: "Marking up file as completed for photos...")
MockingjayProtocol.addStub(matcher: http(.put, uri: urlToConnect), builder: json(body))
func completion(file: HATFileUpload, newToken: String?) {
XCTAssertTrue(file.status.status == "Completed")
expectationTest.fulfill()
}
func failed(error: HATTableError) {
XCTFail()
expectationTest.fulfill()
}
HATFileService.completeUploadFileToHAT(fileID: "1", token: "", tags: [], userDomain: userDomain, completion: completion, errorCallback: failed)
waitForExpectations(timeout: 10) { error in
if let error: Error = error {
print("Error: \(error.localizedDescription)")
}
}
}
func testUploadFile() {
let body: Dictionary<String, Any> = [
"fileId": "iphonerumpelphoto",
"name": "rumpelPhoto",
"source": "iPhone",
"dateCreated": "2017-11-05T10:40:44.527Z",
"lastUpdated": "2017-11-05T10:40:44.527Z",
"tags": [
"iphone",
"viewer",
"photo"
],
"status": [
"size": 4752033,
"status": "Completed"
],
"contentUrl": "https://hubat-net-hatservice-v3ztbxc9civz-storages3bucket-m0gs7co0oyi2.s3-eu-west-1.amazonaws.com/testing.hubat.net/iphonerumpelphoto?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Date=20180118T180720Z&X-Amz-SignedHeaders=host&X-Amz-Expires=299&X-Amz-Credential=AKIAJBUBR3WGX4MX6H6A%2F20180118%2Feu-west-1%2Fs3%2Faws4_request&X-Amz-Signature=ac0eac4e41889443c9bec3cf9dfc119b65b1955479a9193f50f0812dd8bdd868",
"contentPublic": false,
"permissions": [
[
"userId": "de35e18d-147f-4664-8de7-409abf881754",
"contentReadable": true
]
]
]
let userDomain: String = "testing.hubat.net"
let urlToConnect: String = "https://\(userDomain)/api/v2.6/files/upload"
let expectationTest: XCTestExpectation = expectation(description: "Upload file to HAT...")
MockingjayProtocol.addStub(matcher: http(.post, uri: urlToConnect), builder: json(body))
func completion(file: HATFileUpload, newToken: String?) {
XCTAssertTrue(file.status.status == "Completed")
expectationTest.fulfill()
}
func failed(error: HATTableError) {
XCTFail()
expectationTest.fulfill()
}
HATFileService.uploadFileToHAT(fileName: "test", token: "", userDomain: userDomain, tags: [], completion: completion, errorCallback: failed)
waitForExpectations(timeout: 10) { error in
if let error: Error = error {
print("Error: \(error.localizedDescription)")
}
}
}
func testUpdateParameters() {
let body: Dictionary<String, Any> = [
"fileId": "iphonerumpelphoto",
"name": "rumpelPhoto",
"source": "iPhone",
"dateCreated": "2017-11-05T10:40:44.527Z",
"lastUpdated": "2017-11-05T10:40:44.527Z",
"tags": [
"iphone",
"viewer",
"photo"
],
"status": [
"size": 4752033,
"status": "Completed"
],
"contentUrl": "https://hubat-net-hatservice-v3ztbxc9civz-storages3bucket-m0gs7co0oyi2.s3-eu-west-1.amazonaws.com/testing.hubat.net/iphonerumpelphoto?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Date=20180118T180720Z&X-Amz-SignedHeaders=host&X-Amz-Expires=299&X-Amz-Credential=AKIAJBUBR3WGX4MX6H6A%2F20180118%2Feu-west-1%2Fs3%2Faws4_request&X-Amz-Signature=ac0eac4e41889443c9bec3cf9dfc119b65b1955479a9193f50f0812dd8bdd868",
"contentPublic": false,
"permissions": [
[
"userId": "de35e18d-147f-4664-8de7-409abf881754",
"contentReadable": true
]
]
]
let userDomain: String = "testing.hubat.net"
let urlToConnect: String = "https://\(userDomain)/api/v2.6/files/file/1"
let expectationTest: XCTestExpectation = expectation(description: "Updating parameters of a file from HAT...")
MockingjayProtocol.addStub(matcher: http(.put, uri: urlToConnect), builder: json(body))
func completion(file: HATFileUpload, newToken: String?) {
XCTAssertTrue(file.status.status == "Completed")
expectationTest.fulfill()
}
func failed(error: HATTableError) {
XCTFail()
expectationTest.fulfill()
}
HATFileService.updateParametersOfFile(fileID: "1", fileName: "test", token: "", userDomain: userDomain, tags: [], completion: completion, errorCallback: failed)
waitForExpectations(timeout: 10) { error in
if let error: Error = error {
print("Error: \(error.localizedDescription)")
}
}
}
@available(iOS 10.0, *)
func testUploadToHATWrapper() {
let body: Dictionary<String, Any> = [
"fileId": "iphonerumpelphoto",
"name": "rumpelPhoto",
"source": "iPhone",
"dateCreated": "2017-11-05T10:40:44.527Z",
"lastUpdated": "2017-11-05T10:40:44.527Z",
"tags": [
"iphone",
"viewer",
"photo"
],
"status": [
"size": 4752033,
"status": "Completed"
],
"contentUrl": "https://hubat-net-hatservice-v3ztbxc9civz-storages3bucket-m0gs7co0oyi2.s3-eu-west-1.amazonaws.com/testing.hubat.net/iphonerumpelphoto?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Date=20180118T180720Z&X-Amz-SignedHeaders=host&X-Amz-Expires=299&X-Amz-Credential=AKIAJBUBR3WGX4MX6H6A%2F20180118%2Feu-west-1%2Fs3%2Faws4_request&X-Amz-Signature=ac0eac4e41889443c9bec3cf9dfc119b65b1955479a9193f50f0812dd8bdd868",
"contentPublic": false,
"permissions": [
[
"userId": "de35e18d-147f-4664-8de7-409abf881754",
"contentReadable": true
]
]
]
let userDomain: String = "testing.hubat.net"
let expectationTest: XCTestExpectation = expectation(description: "Updating parameters of a file from HAT...")
MockingjayProtocol.addStub(matcher: everything, builder: json(body))
func completion(file: HATFileUpload, newToken: String?) {
XCTAssertTrue(file.status.status == "Completed")
expectationTest.fulfill()
}
func failed(error: HATTableError) {
XCTFail()
expectationTest.fulfill()
}
let renderer: UIGraphicsImageRenderer = UIGraphicsImageRenderer(size: CGSize(width: 25, height: 25))
let image: UIImage = renderer.image { ctx in
ctx.cgContext.setFillColor(UIColor.red.cgColor)
ctx.cgContext.setStrokeColor(UIColor.green.cgColor)
ctx.cgContext.setLineWidth(10)
let rectangle: CGRect = CGRect(x: 0, y: 0, width: 25, height: 25)
ctx.cgContext.addEllipse(in: rectangle)
ctx.cgContext.drawPath(using: .fillStroke)
}
HATFileService.uploadFileToHATWrapper(token: "", userDomain: userDomain, fileToUpload: image, tags: [], progressUpdater: nil, completion: completion, errorCallBack: failed)
waitForExpectations(timeout: 10) { error in
if let error: Error = error {
print("Error: \(error.localizedDescription)")
}
}
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| mpl-2.0 | d1e2ed59dc304abb4895576818e50f92 | 37.4 | 428 | 0.563988 | 4.124808 | false | true | false | false |
XWJACK/Music | Music/Modules/Center/MusicCenterTableViewCell.swift | 1 | 1472 | //
// MusicCenterTableViewCell.swift
// Music
//
// Created by Jack on 5/7/17.
// Copyright © 2017 Jack. All rights reserved.
//
import UIKit
class MusicCenterClearCacheTableViewCell: MusicTableViewCell {
var rightView = UIView()
let indicator = UIActivityIndicatorView(activityIndicatorStyle: .white)
let cacheLabel = UILabel()
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
rightView.backgroundColor = .clear
cacheLabel.textColor = .white
cacheLabel.text = ""
rightView.addSubview(cacheLabel)
rightView.addSubview(indicator)
contentView.addSubview(rightView)
rightView.snp.makeConstraints { (make) in
make.right.equalToSuperview().offset(-20)
make.centerY.equalToSuperview()
make.top.equalToSuperview().offset(5)
make.bottom.equalToSuperview().offset(-5)
}
indicator.snp.makeConstraints { (make) in
make.centerY.equalToSuperview()
make.right.equalToSuperview()
}
cacheLabel.snp.makeConstraints { (make) in
make.left.right.equalToSuperview()
make.centerY.equalToSuperview()
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mit | 6678c81730fdc80067499e8fd6928fd7 | 28.42 | 75 | 0.624745 | 5.054983 | false | false | false | false |
fabioalmeida/FAAutoLayout | FAAutoLayout/Classes/NSLayoutConstraint+FAAutoLayout.swift | 1 | 11112 | //
// NSLayoutConstraint+FAAutoLayout.swift
// FAAutoLayout
//
// Created by Fábio Almeida on 14/06/2017.
// Copyright (c) 2017 Fábio Almeida. All rights reserved.
//
import UIKit
// MARK: - Internal
internal extension NSLayoutConstraint {
/// Helper method to facilitate the creation of leading space constraints
class func leadingSpaceConstraint(fromView: UIView, toView: UIView, relation: NSLayoutConstraint.Relation,
multiplier m: CGFloat, constant c: CGFloat) -> NSLayoutConstraint {
return NSLayoutConstraint.createConstraint(fromItem: fromView,
toItem: toView,
fromAttribute: .leading,
toAttribute: .leading,
relatedBy: relation,
multiplier: m,
constant: c)
}
/// Helper method to facilitate the creation of trailing space constraints
class func trailingSpaceConstraint(fromView: UIView, toView: UIView, relation: NSLayoutConstraint.Relation,
multiplier m: CGFloat, constant c: CGFloat) -> NSLayoutConstraint {
// in trailing contraints we need to invert the views order so that we don't need to use negative constants
return NSLayoutConstraint.createConstraint(fromItem: toView,
toItem: fromView,
fromAttribute: .trailing,
toAttribute: .trailing,
relatedBy: relation,
multiplier: m,
constant: c,
itemUsingAutoLayout: fromView)
}
/// Helper method to facilitate the creation of top space constraints
class func topSpaceConstraint(fromView: UIView, toView: UIView, relation: NSLayoutConstraint.Relation,
multiplier m: CGFloat, constant c: CGFloat) -> NSLayoutConstraint {
return NSLayoutConstraint.createConstraint(fromItem: fromView,
toItem: toView,
fromAttribute: .top,
toAttribute: .top,
relatedBy: relation,
multiplier: m,
constant: c)
}
/// Helper method to facilitate the creation of bottom space constraints
class func bottomSpaceConstraint(fromView: UIView, toView: UIView, relation: NSLayoutConstraint.Relation,
multiplier m: CGFloat, constant c: CGFloat) -> NSLayoutConstraint {
// in bottom contraints we need to invert the views order so that we don't need to use negative constants
return NSLayoutConstraint.createConstraint(fromItem: toView,
toItem: fromView,
fromAttribute: .bottom,
toAttribute: .bottom,
relatedBy: relation,
multiplier: m,
constant: c,
itemUsingAutoLayout: fromView)
}
/// Helper method to facilitate the creation of width constraints
class func widthConstraint(fromView: UIView, toView: UIView?, relation: NSLayoutConstraint.Relation,
multiplier m: CGFloat, constant c: CGFloat) -> NSLayoutConstraint {
let toAttribute = toView != nil ? NSLayoutConstraint.Attribute.width : NSLayoutConstraint.Attribute.notAnAttribute
return NSLayoutConstraint.createConstraint(fromItem: fromView,
toItem: toView,
fromAttribute: .width,
toAttribute: toAttribute,
relatedBy: relation,
multiplier: m,
constant: c)
}
/// Helper method to facilitate the creation of height constraints
class func heightConstraint(fromView: UIView, toView: UIView?, relation: NSLayoutConstraint.Relation,
multiplier m: CGFloat, constant c: CGFloat) -> NSLayoutConstraint {
let toAttribute = toView != nil ? NSLayoutConstraint.Attribute.height : NSLayoutConstraint.Attribute.notAnAttribute
return NSLayoutConstraint.createConstraint(fromItem: fromView,
toItem: toView,
fromAttribute: .height,
toAttribute: toAttribute,
relatedBy: relation,
multiplier: m,
constant: c)
}
/// Helper method to facilitate the creation of horizontal centering constraints
class func centerHorizontallyConstraint(fromView: UIView, toView: UIView, relation: NSLayoutConstraint.Relation,
multiplier m: CGFloat, constant c: CGFloat) -> NSLayoutConstraint {
return NSLayoutConstraint.createConstraint(fromItem: fromView,
toItem: toView,
fromAttribute: .centerX,
toAttribute: .centerX,
relatedBy: relation,
multiplier: m,
constant: c)
}
/// Helper method to facilitate the creation of vertical centering constraints
class func centerVerticallyConstraint(fromView: UIView, toView: UIView, relation: NSLayoutConstraint.Relation,
multiplier m: CGFloat, constant c: CGFloat) -> NSLayoutConstraint {
return NSLayoutConstraint.createConstraint(fromItem: fromView,
toItem: toView,
fromAttribute: .centerY,
toAttribute: .centerY,
relatedBy: relation,
multiplier: m,
constant: c)
}
/// Helper method to facilitate the creation of horizontal spacing constraints
class func horizontalSpaceConstraint(fromView: UIView, toView: UIView, relation: NSLayoutConstraint.Relation,
multiplier m: CGFloat, constant c: CGFloat) -> NSLayoutConstraint {
return NSLayoutConstraint.createConstraint(fromItem: fromView,
toItem: toView,
fromAttribute: .leading,
toAttribute: .trailing,
relatedBy: relation,
multiplier: m,
constant: c)
}
/// Helper method to facilitate the creation of vertical spacing constraints
class func verticalSpaceConstraint(fromView: UIView, toView: UIView, relation: NSLayoutConstraint.Relation,
multiplier m: CGFloat, constant c: CGFloat) -> NSLayoutConstraint {
return NSLayoutConstraint.createConstraint(fromItem: fromView,
toItem: toView,
fromAttribute: .top,
toAttribute: .bottom,
relatedBy: relation,
multiplier: m,
constant: c)
}
}
// MARK: - Private
fileprivate extension NSLayoutConstraint {
/// Creates the constraint and set the `translatesAutoresizingMaskIntoConstraints` attribute to false on the `fromItem`
class func createConstraint(fromItem fromView: UIView, toItem toView: UIView?, fromAttribute: NSLayoutConstraint.Attribute, toAttribute: NSLayoutConstraint.Attribute,
relatedBy relation: NSLayoutConstraint.Relation, multiplier m: CGFloat, constant c: CGFloat) -> NSLayoutConstraint {
return NSLayoutConstraint.createConstraint(fromItem: fromView,
toItem: toView,
fromAttribute: fromAttribute,
toAttribute: toAttribute,
relatedBy: relation,
multiplier: m,
constant: c,
itemUsingAutoLayout: fromView)
}
/// Creates the constraint and set the `translatesAutoresizingMaskIntoConstraints` attribute to false on the `itemUsingAutoLayout`
class func createConstraint(fromItem fromView: UIView, toItem toView: UIView?, fromAttribute: NSLayoutConstraint.Attribute, toAttribute: NSLayoutConstraint.Attribute,
relatedBy relation: NSLayoutConstraint.Relation, multiplier m: CGFloat, constant c: CGFloat, itemUsingAutoLayout: UIView?) -> NSLayoutConstraint {
if let itemUsingAutoLayout = itemUsingAutoLayout {
itemUsingAutoLayout.translatesAutoresizingMaskIntoConstraints = false
}
return NSLayoutConstraint(item: fromView,
attribute: fromAttribute,
relatedBy: relation,
toItem: toView,
attribute: toAttribute,
multiplier: m,
constant: c)
}
}
| mit | 6105882b55ccd465fe1deaeb04cc111f | 58.411765 | 178 | 0.469937 | 8.187178 | false | false | false | false |
hrscy/TodayNews | News/News/Classes/Mine/View/PostVideoOrArticleView.swift | 1 | 2025 | //
// PostVideoOrArticleView.swift
// News
//
// Created by 杨蒙 on 2017/12/10.
// Copyright © 2017年 hrscy. All rights reserved.
//
import UIKit
import Kingfisher
class PostVideoOrArticleView: UIView, NibLoadable {
/// 原内容是否已经删除
var delete = false {
didSet {
originContentHasDeleted()
}
}
/// 原内容已经删除
func originContentHasDeleted() {
titleLabel.text = "原内容已经删除"
titleLabel.textAlignment = .center
iconButtonWidth.constant = 0
layoutIfNeeded()
}
var group = DongtaiOriginGroup() {
didSet {
titleLabel.text = " " + group.title
if group.thumb_url != "" {
iconButton.kf.setBackgroundImage(with: URL(string: group.thumb_url)!, for: .normal)
} else if group.user.avatar_url != "" {
iconButton.kf.setBackgroundImage(with: URL(string: group.user.avatar_url)!, for: .normal)
} else if group.delete {
originContentHasDeleted()
}
switch group.media_type {
case .postArticle:
iconButton.setImage(nil, for: .normal)
case .postVideo:
iconButton.theme_setImage("images.smallvideo_all_32x32_", forState: .normal)
}
}
}
/// 图标
@IBOutlet weak var iconButton: UIButton!
/// 标题
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var iconButtonWidth: NSLayoutConstraint!
/// 覆盖按钮点击
@IBAction func coverButtonClicked(_ sender: UIButton) {
}
override func awakeFromNib() {
super.awakeFromNib()
theme_backgroundColor = "colors.cellBackgroundColor"
titleLabel.theme_textColor = "colors.black"
titleLabel.theme_backgroundColor = "colors.grayColor247"
}
override func layoutSubviews() {
super.layoutSubviews()
width = screenWidth - 30
}
}
| mit | f900a1efb80d8a89a213625541e70b19 | 26.885714 | 105 | 0.584529 | 4.560748 | false | false | false | false |
TrustWallet/trust-wallet-ios | Trust/Export/Coordinators/ExportPrivateKeyCoordinator.swift | 1 | 847 | // Copyright DApps Platform Inc. All rights reserved.
import Foundation
import UIKit
import TrustKeystore
final class ExportPrivateKeyCoordinator: RootCoordinator {
let privateKey: Data
var coordinators: [Coordinator] = []
var rootViewController: UIViewController {
return exportViewController
}
lazy var exportViewController: ExportPrivateKeyViewConroller = {
let controller = ExportPrivateKeyViewConroller(viewModel: viewModel)
controller.navigationItem.title = NSLocalizedString("export.privateKey.navigation.title", value: "Export Private Key", comment: "")
return controller
}()
private lazy var viewModel: ExportPrivateKeyViewModel = {
return .init(privateKey: privateKey)
}()
init(
privateKey: Data
) {
self.privateKey = privateKey
}
}
| gpl-3.0 | 8f640ba31593aff3766c584bab753e9c | 29.25 | 139 | 0.711924 | 5.228395 | false | false | false | false |
ashfurrow/eidolon | KioskTests/App/ArtsyProviderTests.swift | 2 | 1522 | import Quick
import Nimble
import RxSwift
@testable
import Kiosk
import Moya
class ArtsyProviderTests: QuickSpec {
override func spec() {
let fakeEndpointsClosure = { (target: ArtsyAPI) -> Endpoint in
return Endpoint(url: url(target), sampleResponseClosure: {.networkResponse(200, target.sampleData)}, method: target.method, task: target.task, httpHeaderFields: nil)
}
var fakeOnline: PublishSubject<Bool>!
var subject: Networking!
var defaults: UserDefaults!
beforeEach {
fakeOnline = PublishSubject<Bool>()
subject = Networking(provider: OnlineProvider<ArtsyAPI>(endpointClosure: fakeEndpointsClosure, stubClosure: MoyaProvider<ArtsyAPI>.immediatelyStub, online: fakeOnline.asObservable()))
// We fake our defaults to avoid actually hitting the network
defaults = UserDefaults()
defaults.set(NSDate.distantFuture, forKey: "TokenExpiry")
defaults.set("Some key", forKey: "TokenKey")
}
it ("waits for the internet to happen before continuing with network operations") {
var called = false
let disposeBag = DisposeBag()
subject.request(ArtsyAPI.ping, defaults: defaults).subscribe(onNext: { _ in
called = true
}).disposed(by: disposeBag)
expect(called) == false
// Fake getting online
fakeOnline.onNext(true)
expect(called) == true
}
}
}
| mit | eb1484b010131f202b7a09c67edcb937 | 33.590909 | 195 | 0.637319 | 5.212329 | false | false | false | false |
arsonik/SharpTv | Source/SharpTvSwitch.swift | 1 | 958 | //
// YamahaAVSwitch.swift
// Pods
//
// Created by Florian Morello on 21/11/15.
//
//
import UIKit
public class SharpTvSwitch : UISwitch {
public weak var sharp:SharpTv? {
didSet {
let _ = sharp?.sendString(SharpTv.Power.Get.rawValue)
}
}
public override func awakeFromNib() {
super.awakeFromNib()
addTarget(self, action: #selector(SharpTvSwitch.valueChanged), for: UIControlEvents.valueChanged)
}
internal func updated(_ notification: Notification) {
/*
if let v = (notification.object as? SharpTv)?.mainZonePower where !highlighted && notification.name == YamahaAV.updatedNotificationName {
setOn(v, animated: true)
}
*/
}
@IBAction func valueChanged() {
let _ = sharp?.sendString(isOn ? SharpTv.Power.On.rawValue : SharpTv.Power.Off.rawValue)
}
deinit {
NotificationCenter.default.removeObserver(self)
}
}
| mit | 6c9d2b3993a759b6058659a1a4ee9f07 | 22.365854 | 145 | 0.634656 | 4.008368 | false | false | false | false |
AndreyPanov/ApplicationCoordinator | ApplicationCoordinator/Flows/MainTabbarFlow/TabbarCoordinator.swift | 1 | 1242 | class TabbarCoordinator: BaseCoordinator {
private let tabbarView: TabbarView
private let coordinatorFactory: CoordinatorFactory
init(tabbarView: TabbarView, coordinatorFactory: CoordinatorFactory) {
self.tabbarView = tabbarView
self.coordinatorFactory = coordinatorFactory
}
override func start() {
tabbarView.onViewDidLoad = runItemFlow()
tabbarView.onItemFlowSelect = runItemFlow()
tabbarView.onSettingsFlowSelect = runSettingsFlow()
}
private func runItemFlow() -> ((UINavigationController) -> ()) {
return { [unowned self] navController in
if navController.viewControllers.isEmpty == true {
let itemCoordinator = self.coordinatorFactory.makeItemCoordinator(navController: navController)
self.addDependency(itemCoordinator)
itemCoordinator.start()
}
}
}
private func runSettingsFlow() -> ((UINavigationController) -> ()) {
return { [unowned self] navController in
if navController.viewControllers.isEmpty == true {
let settingsCoordinator = self.coordinatorFactory.makeSettingsCoordinator(navController: navController)
self.addDependency(settingsCoordinator)
settingsCoordinator.start()
}
}
}
}
| mit | 3c00b424e296a203f675776499c87d61 | 33.5 | 111 | 0.723027 | 5.04878 | false | false | false | false |
googlearchive/science-journal-ios | ScienceJournal/UI/TriggerListCell.swift | 1 | 3576 | /*
* Copyright 2019 Google LLC. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import UIKit
import third_party_objective_c_material_components_ios_components_CollectionCells_CollectionCells
import third_party_objective_c_material_components_ios_components_Typography_Typography
protocol TriggerListCellDelegate: class {
/// Called when the switch value changes.
func triggerListCellSwitchValueChanged(_ triggerListCell: TriggerListCell)
/// Called when the menu button is pressed.
func triggerListCellMenuButtonPressed(_ triggerListCell: TriggerListCell)
}
/// A cell used to display a trigger in the trigger list.
class TriggerListCell: MDCCollectionViewCell {
// MARK: - Constants
/// The cell height.
static let height: CGFloat = 54
private let horizontalPadding: CGFloat = 16
// MARK: - Properties
/// The delegate.
weak var delegate: TriggerListCellDelegate?
/// The text label.
let textLabel = UILabel()
/// The switch.
let aSwitch = UISwitch()
/// The menu button.
let menuButton = MenuButton()
// MARK: - Public
override init(frame: CGRect) {
super.init(frame: frame)
configureView()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
configureView()
}
// MARK: - Private
private func configureView() {
// Stack view.
let stackView = UIStackView()
stackView.alignment = .center
stackView.spacing = horizontalPadding
stackView.layoutMargins =
UIEdgeInsets(top: 0, left: horizontalPadding, bottom: 0, right: horizontalPadding)
stackView.isLayoutMarginsRelativeArrangement = true
stackView.translatesAutoresizingMaskIntoConstraints = false
contentView.addSubview(stackView)
stackView.pinToEdgesOfView(contentView)
// Text label.
textLabel.alpha = MDCTypography.body1FontOpacity()
textLabel.font = MDCTypography.body1Font()
textLabel.lineBreakMode = .byTruncatingTail
textLabel.numberOfLines = 2
textLabel.translatesAutoresizingMaskIntoConstraints = false
textLabel.setContentCompressionResistancePriority(.defaultHigh, for: .horizontal)
stackView.addArrangedSubview(textLabel)
// Switch.
aSwitch.addTarget(self, action: #selector(switchValueChanged(_:)), for: .valueChanged)
aSwitch.translatesAutoresizingMaskIntoConstraints = false
aSwitch.setContentHuggingPriority(.required, for: .horizontal)
stackView.addArrangedSubview(aSwitch)
// Menu button.
menuButton.addTarget(self, action: #selector(menuButtonPressed), for: .touchUpInside)
menuButton.tintColor = .darkGray
menuButton.translatesAutoresizingMaskIntoConstraints = false
menuButton.hitAreaInsets = UIEdgeInsets(top: -20, left: -10, bottom: -20, right: -10)
stackView.addArrangedSubview(menuButton)
}
// MARK: - User actions
@objc func switchValueChanged(_ aSwitch: UISwitch) {
delegate?.triggerListCellSwitchValueChanged(self)
}
@objc func menuButtonPressed() {
delegate?.triggerListCellMenuButtonPressed(self)
}
}
| apache-2.0 | 5913cc59b1822b35c45fe4b1acfcf0cd | 30.646018 | 97 | 0.74245 | 4.730159 | false | false | false | false |
kysonyangs/ysbilibili | ysbilibili/Classes/Home/Live/ViewModel/YSLiveReloadURLhelper.swift | 1 | 3330 | //
// HomeLiveReloadURLhelper.swift
// zhnbilibili
//
// Created by zhn on 16/11/30.
// Copyright © 2016年 zhn. All rights reserved.
//
import UIKit
class YSLiveReloadURLhelper: NSObject {
// 加密过的,sign 和 area 有关系只能用这种方法拿
class func createReloadSectionURL(area: String) -> String {
// 1. 推荐主播
if area == "hot" {
return "http://live.bilibili.com/AppIndex/recommendRefresh?actionKey=appkey&appkey=27eb53fc9058f8c3&build=3970&device=phone&mobi_app=iphone&platform=ios&sign=ee5759f6df79cf2abbaf7927ab35e983&ts=1479286545"
}
// 2. 绘画
if area == "draw" {
return "http://live.bilibili.com/AppIndex/dynamic?actionKey=appkey&appkey=27eb53fc9058f8c3&area=draw&build=3970&device=phone&mobi_app=iphone&platform=ios&sign=dd48aa4f416222aadaa591af573c4faa&ts=1479286692"
}
// 3. 手机直播
if area == "mobile" {
return "http://live.bilibili.com/AppIndex/dynamic?actionKey=appkey&appkey=27eb53fc9058f8c3&area=mobile&build=3970&device=phone&mobi_app=iphone&platform=ios&sign=b70507f063d8325b85426e6b4feddbc6&ts=1479286747"
}
// 4. 唱见舞见
if area == "sing-dance" {
return "http://live.bilibili.com/AppIndex/dynamic?actionKey=appkey&appkey=27eb53fc9058f8c3&area=sing-dance&build=3970&device=phone&mobi_app=iphone&platform=ios&sign=4cd40a5e0073765d156e26ac6115e23a&ts=1479287001"
}
// 5. 手机游戏
if area == "mobile-game" {
return "http://live.bilibili.com/AppIndex/dynamic?actionKey=appkey&appkey=27eb53fc9058f8c3&area=mobile-game&build=3970&device=phone&mobi_app=iphone&platform=ios&sign=6254a0cac7ff9da85a24c037971303f4&ts=1479287130"
}
// 6.单机
if area == "single"{
return "http://live.bilibili.com/AppIndex/dynamic?actionKey=appkey&appkey=27eb53fc9058f8c3&area=single&build=3970&device=phone&mobi_app=iphone&platform=ios&sign=b16eb80648d3eccd337d83bc97c8a5c2&ts=1479287170"
}
// 7. 网络游戏
if area == "online" {
return "http://live.bilibili.com/AppIndex/dynamic?actionKey=appkey&appkey=27eb53fc9058f8c3&area=online&build=3970&device=phone&mobi_app=iphone&platform=ios&sign=0a987b8f320d44ff992ef14c82f8b840&ts=1479287203"
}
// 8.电子竞技
if area == "e-sports" {
return "http://live.bilibili.com/AppIndex/dynamic?actionKey=appkey&appkey=27eb53fc9058f8c3&area=e-sports&build=3970&device=phone&mobi_app=iphone&platform=ios&sign=7b11eb5ad6446055e551ac3cffdfcfb9&ts=1479287244"
}
// 9. 御宅文化
if area == "otaku" {
return "http://live.bilibili.com/AppIndex/dynamic?actionKey=appkey&appkey=27eb53fc9058f8c3&area=otaku&build=3970&device=phone&mobi_app=iphone&platform=ios&sign=59ccc610ead8551347fbbf414caf3191&ts=1479287296"
}
// 10.放映厅
if area == "movie" {
return "http://live.bilibili.com/AppIndex/dynamic?actionKey=appkey&appkey=27eb53fc9058f8c3&area=movie&build=3970&device=phone&mobi_app=iphone&platform=ios&sign=07a772a0824d9289da692be8ed3044cb&ts=1479287345"
}
return ""
}
}
| mit | b2d71b91aa8d5cd24d9ca572f52a43c9 | 45.73913 | 225 | 0.674419 | 2.887198 | false | false | false | false |
IvanVorobei/ParallaxTableView | ParallaxTableView - project/ParallaxTableView/Sparrow/UI/Views/Views/SPUIViewExtenshion.swift | 1 | 1697 | // The MIT License (MIT)
// Copyright © 2016 Ivan Vorobei ([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 UIKit
// MARK: - convertToImage
extension UIView {
func convertToImage() -> UIImage {
return UIImage.drawFromView(view: self)
}
}
// MARK: - gradeView
extension UIView {
func addGrade(alpha: CGFloat, color: UIColor = UIColor.black) {
let gradeView = UIView.init()
gradeView.alpha = 0
self.addSubview(gradeView)
SPConstraintsAssistent.setEqualSizeConstraint(gradeView, superVuew: self)
gradeView.alpha = alpha
gradeView.backgroundColor = color
}
}
| mit | fa625ac1779ac3e9f97d17e0a5e30a61 | 37.545455 | 81 | 0.728774 | 4.428198 | false | false | false | false |
swiftmi/swiftmi-app | swiftmi/swiftmi/SplotLightHelper.swift | 2 | 1941 | //
// SplotLightHelper.swift
// swiftmi
//
// Created by yangyin on 15/11/2.
// Copyright © 2015年 swiftmi. All rights reserved.
//
import CoreSpotlight
import MobileCoreServices
open class SplotlightHelper:NSObject
{
static var domainIdentifier:String = Bundle.main.bundleIdentifier!;
class func AddItemToCoreSpotlight(_ id:String,title:String,contentDescription:String)
{
if #available(iOS 9.0, *) {
let attributeSet = CSSearchableItemAttributeSet(itemContentType: kUTTypeText as String)
attributeSet.title = title;
attributeSet.contentDescription = contentDescription;
let item = CSSearchableItem(uniqueIdentifier: id, domainIdentifier: domainIdentifier, attributeSet: attributeSet)
// expire after a month
item.expirationDate = Date(timeInterval: 30*24*60*60, since:Date())
CSSearchableIndex.default().indexSearchableItems([item], completionHandler: { error -> Void in
if let err = error
{
print("index error:\(err.localizedDescription)")
}else{
print("index success")
}
})
} else {
// Fallback on earlier versions
}
}
class func RemoveItemFromCoreSplotlight(_ id:String)
{
if #available(iOS 9.0, *) {
CSSearchableIndex.default().deleteSearchableItems(withIdentifiers: [id]) { error -> Void in
if let err = error {
print("remove index error: \(err.localizedDescription)")
} else {
print("Search item successfully removed!")
}
}
} else {
// Fallback on earlier versions
}
}
}
| mit | e4e3b2b405e94fb61646f0e77232b327 | 29.28125 | 125 | 0.54644 | 5.428571 | false | false | false | false |
SECH-Tag-EEXCESS-Browser/iOSX-App | Team UI/Browser/Browser/JSONData.swift | 1 | 2834 | //
// JSONParser.swift
// Browser
//
// Created by Burak Erol on 10.12.15.
// Copyright © 2015 SECH-Tag-EEXCESS-Browser. All rights reserved.
//
import Foundation
enum JSONData {
case JSONObject([String:JSONData])
case JSONArray([JSONData])
case JSONString(String)
case JSONNumber(NSNumber)
case JSONBool(Bool)
var object : [String : JSONData]? {
switch self {
case .JSONObject(let aData):
return aData
default:
return nil
}
}
var array : [JSONData]? {
switch self {
case .JSONArray(let aData):
return aData
default:
return nil
}
}
var string : String? {
switch self {
case .JSONString(let aData):
return aData
default:
return nil
}
}
var integer : Int? {
switch self {
case .JSONNumber(let aData):
return aData.integerValue
default:
return nil
}
}
var bool: Bool? {
switch self {
case .JSONBool(let value):
return value
default:
return nil
}
}
subscript(i: Int) -> JSONData? {
get {
switch self {
case .JSONArray(let value):
return value[i]
default:
return nil
}
}
}
subscript(key: String) -> JSONData? {
get {
switch self {
case .JSONObject(let value):
return value[key]
default:
return nil
}
}
}
static func fromObject(object: AnyObject) -> JSONData? {
switch object {
case let value as String:
return JSONData.JSONString(value as String)
case let value as NSNumber:
return JSONData.JSONNumber(value)
case let value as NSDictionary:
var jsonObject: [String:JSONData] = [:]
for (key, value) : (AnyObject, AnyObject) in value {
if let key = key as? String {
if let value = JSONData.fromObject(value) {
jsonObject[key] = value
} else {
return nil
}
}
}
return JSONData.JSONObject(jsonObject)
case let value as NSArray:
var jsonArray: [JSONData] = []
for v in value {
if let v = JSONData.fromObject(v) {
jsonArray.append(v)
} else {
return nil
}
}
return JSONData.JSONArray(jsonArray)
default:
return nil
}
}
} | mit | c023ae603529f0ee45d5292b9a634262 | 22.815126 | 67 | 0.463466 | 5.077061 | false | false | false | false |
teaxus/TSAppEninge | Source/Basic/Controller/TSImagePicker/TSImagePicker.swift | 1 | 4316 | //
// TSImagePicker.swift
// StandardProject
//
// Created by teaxus on 16/1/7.
// Copyright © 2016年 teaxus. All rights reserved.
//
import UIKit
//import TSAppEngine
import AssetsLibrary
class TSImageCamera:UIImagePickerController,UIImagePickerControllerDelegate,UINavigationControllerDelegate {
var action:ReturnArrayLib_URL_Image?
var VC_push:UIViewController?
var useSourceType = UIImagePickerControllerSourceType.camera
func show(after_select:@escaping ReturnArrayLib_URL_Image){
self.action = after_select
self.delegate = self
self.modalTransitionStyle = .coverVertical//设置换场动画
self.allowsEditing = true
self.navigationBar.tintColor = UIColor.red
let author = ALAssetsLibrary.authorizationStatus()
if author == .restricted || author == .denied{
}
else{
self.sourceType = useSourceType
}
VC_push?.present(self, animated: false) { () -> Void in
self.setNeedsStatusBarAppearanceUpdate()//改变后需要及时刷新的调用
}
}
//MARK:imagepicker代理方法
private func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
let image_upload = info[UIImagePickerControllerEditedImage] as! UIImage
self.VC_push?.dismiss(animated: true, completion: { () -> Void in
self.action?([],[],[image_upload])
})
}
}
public class TSImagePicker: NSObject ,UIActionSheetDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate{
let imagePicker_now = TSImageCamera()
var action:ReturnArrayLib_URL_Image?
var max:Int = 9999
let VC_now_appear:TSAppEngineViewController? = TSAppEngineViewController.VC_now_appear
var arry_other_action = [UIAlertAction]()
public convenience init(action_return:@escaping ReturnArrayLib_URL_Image,max_select:Int) {
self.init()
action = action_return
max = max_select
}
public func show(){
let alertController = UIAlertController(title: nil, message: nil, preferredStyle: UIAlertControllerStyle.actionSheet)
let cancelAction = UIAlertAction(title: "取消", style: UIAlertActionStyle.cancel, handler: nil)
let deleteAction = UIAlertAction(title: "拍照", style: UIAlertActionStyle.default, handler: { (_) -> Void in
self.imagePicker_now.useSourceType = .camera
self.imagePicker_now.VC_push = self.VC_now_appear
self.imagePicker_now.show(after_select: { (_, _, arr_image) -> Void in
self.action?([],[],arr_image)
})
})
let archiveAction = UIAlertAction(title: "从相册选择", style: UIAlertActionStyle.default, handler: {(_) -> Void in
if self.max == 1{//选择只是一张的时候
self.imagePicker_now.useSourceType = .photoLibrary
self.imagePicker_now.VC_push = self.VC_now_appear
self.imagePicker_now.show(after_select: { (_, _, arr_image) -> Void in
self.action?([],[],arr_image)
})
}
else{//当多选的时候
//MARK:从相片册选择
let VC = TSImagePickViewController(nibName: "TSImagePickViewController", bundle: nil)
VC.max_select = self.max
VC.action = {(arr_asset,arr_url,arr_image) -> Void in
self.action?(arr_asset,arr_url,arr_image)
}
self.VC_now_appear?.navigationController?.pushViewController(VC, animated: true)
}
})
alertController.addAction(cancelAction)
alertController.addAction(deleteAction)
alertController.addAction(archiveAction)
for action in arry_other_action{
alertController.addAction(action)
}
self.VC_now_appear?.present(alertController, animated: true, completion: { () -> Void in
})
}
//MARK:Action sheet代理方法
public func actionSheet(_ actionSheet: UIActionSheet, clickedButtonAt buttonIndex: Int) {
if buttonIndex == 1{//拍照
}
else if buttonIndex == 2{
}
}
}
| mit | 2c637160692f4c835f41dfc2f4c54f03 | 37.861111 | 131 | 0.629974 | 4.705157 | false | false | false | false |
Tanglo/VergeOfStrife | Vos Map Maker/VoSMap.swift | 1 | 2000 | //
// VoSMap.swift
// VergeOfStrife
//
// Created by Lee Walsh on 30/03/2015.
// Copyright (c) 2015 Lee David Walsh. All rights reserved.
//
import Cocoa
struct VoSSize {
var width = 0.0
var height = 0.0
}
struct VoSPoint {
var x = 0.0
var y = 0.0
}
struct VoSRect {
var origin = VoSPoint(x: 0.0, y: 0.0)
var size = VoSSize(width: 0.0, height: 0.0)
}
class VoSMap: NSObject, NSCoding {
var grid: VoSGrid
var tileSetName: String
var tileSize: VoSSize
override init() {
grid = VoSGrid()
tileSetName = "Default"
tileSize = VoSSize(width: 50, height: 50.0)
}
required init(coder aDecoder: NSCoder) {
self.grid = aDecoder.decodeObjectForKey("grid") as! VoSGrid
self.tileSetName = aDecoder.decodeObjectForKey("tileSetName") as! String
self.tileSize = VoSSize()
self.tileSize.width = aDecoder.decodeDoubleForKey("tileSize.width")
self.tileSize.height = aDecoder.decodeDoubleForKey("tileSize.height")
}
func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(grid, forKey: "grid")
aCoder.encodeObject(tileSetName, forKey: "tileSetName")
aCoder.encodeDouble(tileSize.width, forKey: "tileSize.width")
aCoder.encodeDouble(tileSize.height, forKey: "tileSize.height")
}
func importMapFromString(mapString: String) {
let crSet = NSCharacterSet(charactersInString: "\n\r")
let newMapRows = reverse(mapString.componentsSeparatedByCharactersInSet(crSet))
let rowCount = newMapRows.count
var colCount = 0
var tileCodes = [String]()
for mapRow in newMapRows {
let newTilesCodes = mapRow.componentsSeparatedByString(",")
tileCodes += newTilesCodes
if newTilesCodes.count > colCount {
colCount = newTilesCodes.count
}
}
grid = VoSGrid(rows: rowCount, columns: colCount, tileValues: tileCodes)
}
} | mit | 111b5c3d1d42a62ab54c1edb0a5dd7a5 | 28.865672 | 87 | 0.6375 | 3.831418 | false | false | false | false |
tuarua/Swift-IOS-ANE | framework_src/native_library/FreSwiftExampleANE/FreSwift/FreSwiftHelper.swift | 1 | 19988 | /* Copyright 2017 Tua Rua Ltd.
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
public class FreSwiftHelper {
private static var logger: FreSwiftLogger {
return FreSwiftLogger.shared
}
@discardableResult
static func callMethod(_ rawValue: FREObject?, name: String, args: [Any?]) -> FREObject? {
guard let rv = rawValue else {
return nil
}
let argsArray: NSPointerArray = NSPointerArray(options: .opaqueMemory)
for i in 0..<args.count {
argsArray.addPointer(newObject(any: args[i]))
}
var ret: FREObject?
var thrownException: FREObject?
var numArgs: UInt32 = 0
numArgs = UInt32((argsArray.count))
#if os(iOS) || os(tvOS)
let status = FreSwiftBridge.bridge.FRECallObjectMethod(object: rv, methodName: name,
argc: numArgs, argv: argsArray,
result: &ret, thrownException: &thrownException)
#else
let status = FRECallObjectMethod(rv, name, numArgs, arrayToFREArray(argsArray), &ret, &thrownException)
#endif
if FRE_OK == status { return ret }
logger.error(message: "cannot call method \(name) on \(rv.toString())",
stackTrace: getActionscriptException(thrownException),
type: getErrorCode(status))
return nil
}
static func getAsString(_ rawValue: FREObject) -> String? {
var len: UInt32 = 0
var valuePtr: UnsafePointer<UInt8>?
#if os(iOS) || os(tvOS)
let status = FreSwiftBridge.bridge.FREGetObjectAsUTF8(object: rawValue,
length: &len, value: &valuePtr)
#else
let status = FREGetObjectAsUTF8(rawValue, &len, &valuePtr)
#endif
if FRE_OK == status {
return NSString(bytes: valuePtr!, length: Int(len), encoding: String.Encoding.utf8.rawValue) as String?
}
logger.error(message: "cannot get FREObject \(rawValue.toString(true)) as String",
type: getErrorCode(status))
return nil
}
static func getAsBool(_ rawValue: FREObject) -> Bool? {
var val: UInt32 = 0
#if os(iOS) || os(tvOS)
let status = FreSwiftBridge.bridge.FREGetObjectAsBool(object: rawValue, value: &val)
#else
let status = FREGetObjectAsBool(rawValue, &val)
#endif
if FRE_OK == status { return val == 1 }
logger.error(message: "cannot get FREObject \(rawValue.toString()) as Bool",
type: getErrorCode(status))
return nil
}
static func getAsDouble(_ rawValue: FREObject) -> Double? {
var ret: Double = 0.0
#if os(iOS) || os(tvOS)
let status = FreSwiftBridge.bridge.FREGetObjectAsDouble(object: rawValue, value: &ret)
#else
let status = FREGetObjectAsDouble(rawValue, &ret)
#endif
if FRE_OK == status { return ret }
logger.error(message: "cannot get FREObject \(rawValue.toString()) as Double",
type: getErrorCode(status))
return nil
}
static func getAsDate(_ rawValue: FREObject) -> Date? {
if let timeFre = rawValue["time"],
let time = getAsDouble(timeFre) {
return Date(timeIntervalSince1970: time / 1000.0)
}
return nil
}
static func getAsInt(_ rawValue: FREObject) -> Int? {
var ret: Int32 = 0
#if os(iOS) || os(tvOS)
let status = FreSwiftBridge.bridge.FREGetObjectAsInt32(object: rawValue, value: &ret)
#else
let status = FREGetObjectAsInt32(rawValue, &ret)
#endif
if FRE_OK == status { return Int(ret) }
logger.error(message: "cannot get FREObject \(rawValue.toString()) as Int",
type: getErrorCode(status))
return nil
}
static func getAsUInt(_ rawValue: FREObject) -> UInt? {
var ret: UInt32 = 0
#if os(iOS) || os(tvOS)
let status = FreSwiftBridge.bridge.FREGetObjectAsUint32(object: rawValue, value: &ret)
#else
let status = FREGetObjectAsUint32(rawValue, &ret)
#endif
if FRE_OK == status { return UInt(ret) }
logger.error(message: "cannot get FREObject \(rawValue.toString()) as UInt",
type: getErrorCode(status))
return nil
}
static func getAsId(_ rawValue: FREObject?) -> Any? {
guard let rv = rawValue else { return nil }
let objectType: FreObjectTypeSwift = getType(rv)
switch objectType {
case .int:
return getAsInt(rv)
case .vector, .array:
return FREArray(rv).value
case .string:
return getAsString(rv)
case .boolean:
return getAsBool(rv)
case .object, .class:
return getAsDictionary(rv) as [String: AnyObject]?
case .number:
return getAsDouble(rv)
case .bitmapdata:
return FreBitmapDataSwift(freObject: rv).asCGImage()
case .bytearray:
let asByteArray = FreByteArraySwift(freByteArray: rv)
let byteData = asByteArray.value
asByteArray.releaseBytes()
return byteData
case .point:
return CGPoint(rv)
case .rectangle:
return CGRect(rv)
case .date:
return getAsDate(rv)
case .null:
return nil
}
}
public static func newObject(any: Any?) -> FREObject? {
if any == nil {
return nil
} else if any is FREObject, let v = any as? FREObject {
return (v)
} else if any is FreObjectSwift, let v = any as? FreObjectSwift {
return v.rawValue
} else if any is String, let v = any as? String {
return newObject(v)
} else if any is Int, let v = any as? Int {
return newObject(v)
} else if any is Int32, let v = any as? Int32 {
return newObject(Int(v))
} else if any is UInt, let v = any as? UInt {
return newObject(v)
} else if any is UInt32, let v = any as? UInt32 {
return newObject(UInt(v))
} else if any is Double, let v = any as? Double {
return newObject(v)
} else if any is CGFloat, let v = any as? CGFloat {
return newObject(v)
} else if any is Float, let v = any as? Float {
return newObject(Double(v))
} else if any is Bool, let v = any as? Bool {
return newObject(v)
} else if any is Date, let v = any as? Date {
return newObject(v)
} else if any is CGRect, let v = any as? CGRect {
return v.toFREObject()
} else if any is CGPoint, let v = any as? CGPoint {
return v.toFREObject()
} else if any is NSNumber, let v = any as? NSNumber {
return v.toFREObject()
}
return nil
}
public static func arrayToFREArray(_ array: NSPointerArray?) -> UnsafeMutablePointer<FREObject?>? {
if let array = array {
let ret = UnsafeMutablePointer<FREObject?>.allocate(capacity: array.count)
for i in 0..<array.count {
ret[i] = array.pointer(at: i)
}
return ret
}
return nil
}
public static func getType(_ rawValue: FREObject?) -> FreObjectTypeSwift {
guard let rawValue = rawValue else { return FreObjectTypeSwift.null }
var objectType = FRE_TYPE_NULL
#if os(iOS) || os(tvOS)
let status = FreSwiftBridge.bridge.FREGetObjectType(object: rawValue, objectType: &objectType)
#else
let status = FREGetObjectType(rawValue, &objectType)
#endif
if FRE_OK == status {
let type = FreObjectTypeSwift(rawValue: objectType.rawValue) ?? FreObjectTypeSwift.null
return FreObjectTypeSwift.number == type || FreObjectTypeSwift.object == type
? getActionscriptType(rawValue)
: type
}
logger.error(message: "cannot get type", type: getErrorCode(status))
return FreObjectTypeSwift.null
}
fileprivate static func getActionscriptType(_ rawValue: FREObject) -> FreObjectTypeSwift {
if let type = rawValue.className?.lowercased() {
if type == "int" {
return FreObjectTypeSwift.int
} else if type == "date" {
return FreObjectTypeSwift.date
} else if type == "string" {
return FreObjectTypeSwift.string
} else if type == "number" {
return FreObjectTypeSwift.number
} else if type == "boolean" {
return FreObjectTypeSwift.boolean
} else if type == "flash.geom::rectangle" {
return FreObjectTypeSwift.rectangle
} else if type == "flash.geom::point" {
return FreObjectTypeSwift.point
} else {
return FreObjectTypeSwift.class
}
}
return FreObjectTypeSwift.null
}
static func getAsDictionary(_ rawValue: FREObject) -> [String: AnyObject]? {
var ret = [String: AnyObject]()
guard let aneUtils = FREObject(className: "com.tuarua.fre.ANEUtils"),
let classProps = aneUtils.call(method: "getClassProps", args: rawValue) else {
return nil
}
let array = FREArray(classProps)
for fre in array {
if let propNameAs = fre["name"],
let propName = String(propNameAs),
let propValAs = rawValue[propName],
let propVal = FreObjectSwift(propValAs).value {
ret.updateValue(propVal as AnyObject, forKey: propName)
}
}
return ret
}
static func getAsDictionary(_ rawValue: FREObject) -> [String: Any]? {
var ret = [String: Any]()
guard let aneUtils = FREObject(className: "com.tuarua.fre.ANEUtils"),
let classProps = aneUtils.call(method: "getClassProps", args: rawValue) else {
return nil
}
let array = FREArray(classProps)
for fre in array {
if let propNameAs = fre["name"],
let propName = String(propNameAs),
let propValAs = rawValue[propName],
let propVal = FreObjectSwift(propValAs).value {
ret.updateValue(propVal as Any, forKey: propName)
}
}
return ret
}
static func getAsDictionary(_ rawValue: FREObject) -> [String: NSObject]? {
var ret = [String: NSObject]()
guard let aneUtils = FREObject(className: "com.tuarua.fre.ANEUtils"),
let classProps = aneUtils.call(method: "getClassProps", args: rawValue) else {
return nil
}
let array = FREArray(classProps)
for fre in array {
if let propNameAs = fre["name"],
let propName = String(propNameAs),
let propValAs = rawValue[propName],
let propVal = FreObjectSwift(propValAs).value,
let pv = propVal as? NSObject {
ret.updateValue(pv, forKey: propName)
}
}
return ret
}
static func getAsArray(_ rawValue: FREObject) -> [Any]? {
var ret: [Any] = [Any]()
let array = FREArray(rawValue)
for fre in array {
if let v = FreObjectSwift(fre).value {
ret.append(v)
}
}
return ret
}
public static func getProperty(rawValue: FREObject, name: String) -> FREObject? {
var ret: FREObject?
var thrownException: FREObject?
#if os(iOS) || os(tvOS)
let status = FreSwiftBridge.bridge.FREGetObjectProperty(object: rawValue,
propertyName: name,
propertyValue: &ret,
thrownException: &thrownException)
#else
let status = FREGetObjectProperty(rawValue, name, &ret, &thrownException)
#endif
if FRE_OK == status { return ret }
logger.error(message: "cannot get property \(name) of \(rawValue.toString())",
stackTrace: getActionscriptException(thrownException),
type: getErrorCode(status))
return nil
}
public static func setProperty(rawValue: FREObject, name: String, prop: FREObject?) {
var thrownException: FREObject?
#if os(iOS) || os(tvOS)
let status = FreSwiftBridge.bridge.FRESetObjectProperty(object: rawValue,
propertyName: name,
propertyValue: prop,
thrownException: &thrownException)
#else
let status = FRESetObjectProperty(rawValue, name, prop, &thrownException)
#endif
if FRE_OK == status { return }
logger.error(message: "cannot set property \(name) of \(rawValue.toString()) to \(FreObjectSwift(prop).value ?? "unknown")",
stackTrace: getActionscriptException(thrownException),
type: getErrorCode(status))
}
static func getActionscriptException(_ thrownException: FREObject?) -> String {
guard let thrownException = thrownException else {
return ""
}
guard FreObjectTypeSwift.class == thrownException.type else {
return ""
}
guard thrownException.hasOwnProperty(name: "getStackTrace"),
let asStackTrace = thrownException.call(method: "getStackTrace"),
FreObjectTypeSwift.string == asStackTrace.type,
let ret = String(asStackTrace)
else {
return ""
}
return ret
}
public static func newObject(_ string: String) -> FREObject? {
var ret: FREObject?
#if os(iOS) || os(tvOS)
let status = FreSwiftBridge.bridge.FRENewObjectFromUTF8(length: UInt32(string.utf8.count),
value: string, object: &ret)
#else
let status = FRENewObjectFromUTF8(UInt32(string.utf8.count), string, &ret)
#endif
if FRE_OK == status { return ret }
logger.error(message: "cannot create FREObject from \(string)",
type: getErrorCode(status))
return nil
}
public static func newObject(_ double: Double) -> FREObject? {
var ret: FREObject?
#if os(iOS) || os(tvOS)
let status = FreSwiftBridge.bridge.FRENewObjectFromDouble(value: double, object: &ret)
#else
let status = FRENewObjectFromDouble(double, &ret)
#endif
if FRE_OK == status { return ret }
logger.error(message: "cannot create FREObject from \(double)",
type: getErrorCode(status))
return nil
}
public static func newObject(_ cgFloat: CGFloat) -> FREObject? {
var ret: FREObject?
#if os(iOS) || os(tvOS)
let status = FreSwiftBridge.bridge.FRENewObjectFromDouble(value: Double(cgFloat), object: &ret)
#else
let status = FRENewObjectFromDouble(Double(cgFloat), &ret)
#endif
if FRE_OK == status { return ret }
logger.error(message: "cannot create FREObject from \(cgFloat)",
type: getErrorCode(status))
return nil
}
public static func newObject(_ date: Date) -> FREObject? {
var ret: FREObject?
let secs: Double = Double(date.timeIntervalSince1970) * 1000.0
let argsArray: NSPointerArray = NSPointerArray(options: .opaqueMemory)
argsArray.addPointer(secs.toFREObject())
ret = newObject(className: "Date", argsArray)
return ret
}
public static func newObject(_ int: Int) -> FREObject? {
var ret: FREObject?
#if os(iOS) || os(tvOS)
let status = FreSwiftBridge.bridge.FRENewObjectFromInt32(value: Int32(int), object: &ret)
#else
let status = FRENewObjectFromInt32(Int32(int), &ret)
#endif
if FRE_OK == status { return ret }
logger.error(message: "cannot create FREObject from \(int)",
type: getErrorCode(status))
return nil
}
public static func newObject(_ uint: UInt) -> FREObject? {
var ret: FREObject?
#if os(iOS) || os(tvOS)
let status = FreSwiftBridge.bridge.FRENewObjectFromUint32(value: UInt32(uint), object: &ret)
#else
let status = FRENewObjectFromUint32(UInt32(uint), &ret)
#endif
if FRE_OK == status { return ret }
logger.error(message: "cannot create FREObject from \(uint)",
type: getErrorCode(status))
return nil
}
public static func newObject(_ bool: Bool) -> FREObject? {
var ret: FREObject?
#if os(iOS) || os(tvOS)
let status = FreSwiftBridge.bridge.FRENewObjectFromBool(value: bool, object: &ret)
#else
let b: UInt32 = (bool == true) ? 1 : 0
let status = FRENewObjectFromBool(b, &ret)
#endif
if FRE_OK == status { return ret }
logger.error(message: "cannot create FREObject from \(bool)",
type: getErrorCode(status))
return nil
}
public static func newObject(className: String, _ args: NSPointerArray?) -> FREObject? {
var ret: FREObject?
var thrownException: FREObject?
var numArgs: UInt32 = 0
if args != nil {
numArgs = UInt32((args?.count)!)
}
#if os(iOS) || os(tvOS)
let status = FreSwiftBridge.bridge.FRENewObject(className: className, argc: numArgs, argv: args,
object: &ret, thrownException: &thrownException)
#else
let status = FRENewObject(className, numArgs, arrayToFREArray(args), &ret, &thrownException)
#endif
if FRE_OK == status { return ret }
logger.error(message: "cannot create new class \(className)",
stackTrace: getActionscriptException(thrownException),
type: getErrorCode(status))
return nil
}
public static func newObject(className: String) -> FREObject? {
var ret: FREObject?
var thrownException: FREObject?
#if os(iOS) || os(tvOS)
let status = FreSwiftBridge.bridge.FRENewObject(className: className, argc: 0, argv: nil,
object: &ret, thrownException: &thrownException)
#else
let status = FRENewObject(className, 0, nil, &ret, &thrownException)
#endif
if FRE_OK == status { return ret }
logger.error(message: "cannot create new class \(className)",
stackTrace: getActionscriptException(thrownException),
type: getErrorCode(status))
return nil
}
static func getErrorCode(_ result: FREResult) -> FreError.Code {
switch result {
case FRE_NO_SUCH_NAME:
return .noSuchName
case FRE_INVALID_OBJECT:
return .invalidObject
case FRE_TYPE_MISMATCH:
return .typeMismatch
case FRE_ACTIONSCRIPT_ERROR:
return .actionscriptError
case FRE_INVALID_ARGUMENT:
return .invalidArgument
case FRE_READ_ONLY:
return .readOnly
case FRE_WRONG_THREAD:
return .wrongThread
case FRE_ILLEGAL_STATE:
return .illegalState
case FRE_INSUFFICIENT_MEMORY:
return .insufficientMemory
default:
return .ok
}
}
}
| apache-2.0 | b4f5bd088ecbb6a20db03ae8d278f747 | 36.927894 | 132 | 0.588103 | 4.428983 | false | false | false | false |
akane/Gaikan | GaikanTests/UIKit/Extension/UILabelSpec.swift | 1 | 1005 | //
// This file is part of Gaikan
//
// Created by JC on 11/09/15.
// For the full copyright and license information, please view the LICENSE
// file that was distributed with this source code
//
import Foundation
import Quick
import Nimble
import Gaikan
class UILabelSpec: QuickSpec {
override func spec() {
var label: UILabel!
beforeEach {
label = UILabel()
}
describe("styleInline") {
var style: StyleRule!
context("when giving style") {
it("should inherit view styles") {
style = [ .tintColor: UIColor.blue ]
label.styleInline = style
expect(label.tintColor) == UIColor.blue
}
it("should apply color") {
style = [ .color: UIColor.red ]
label.styleInline = style
expect(label.textColor) == UIColor.red
}
}
}
}
}
| mit | 738f98dcdb8dd03b8ab8e743479afc2b | 21.840909 | 74 | 0.516418 | 4.975248 | false | false | false | false |
brentdax/swift | stdlib/public/core/Optional.swift | 1 | 26579 | //===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
/// A type that represents either a wrapped value or `nil`, the absence of a
/// value.
///
/// You use the `Optional` type whenever you use optional values, even if you
/// never type the word `Optional`. Swift's type system usually shows the
/// wrapped type's name with a trailing question mark (`?`) instead of showing
/// the full type name. For example, if a variable has the type `Int?`, that's
/// just another way of writing `Optional<Int>`. The shortened form is
/// preferred for ease of reading and writing code.
///
/// The types of `shortForm` and `longForm` in the following code sample are
/// the same:
///
/// let shortForm: Int? = Int("42")
/// let longForm: Optional<Int> = Int("42")
///
/// The `Optional` type is an enumeration with two cases. `Optional.none` is
/// equivalent to the `nil` literal. `Optional.some(Wrapped)` stores a wrapped
/// value. For example:
///
/// let number: Int? = Optional.some(42)
/// let noNumber: Int? = Optional.none
/// print(noNumber == nil)
/// // Prints "true"
///
/// You must unwrap the value of an `Optional` instance before you can use it
/// in many contexts. Because Swift provides several ways to safely unwrap
/// optional values, you can choose the one that helps you write clear,
/// concise code.
///
/// The following examples use this dictionary of image names and file paths:
///
/// let imagePaths = ["star": "/glyphs/star.png",
/// "portrait": "/images/content/portrait.jpg",
/// "spacer": "/images/shared/spacer.gif"]
///
/// Getting a dictionary's value using a key returns an optional value, so
/// `imagePaths["star"]` has type `Optional<String>` or, written in the
/// preferred manner, `String?`.
///
/// Optional Binding
/// ----------------
///
/// To conditionally bind the wrapped value of an `Optional` instance to a new
/// variable, use one of the optional binding control structures, including
/// `if let`, `guard let`, and `switch`.
///
/// if let starPath = imagePaths["star"] {
/// print("The star image is at '\(starPath)'")
/// } else {
/// print("Couldn't find the star image")
/// }
/// // Prints "The star image is at '/glyphs/star.png'"
///
/// Optional Chaining
/// -----------------
///
/// To safely access the properties and methods of a wrapped instance, use the
/// postfix optional chaining operator (postfix `?`). The following example uses
/// optional chaining to access the `hasSuffix(_:)` method on a `String?`
/// instance.
///
/// if imagePaths["star"]?.hasSuffix(".png") == true {
/// print("The star image is in PNG format")
/// }
/// // Prints "The star image is in PNG format"
///
/// Using the Nil-Coalescing Operator
/// ---------------------------------
///
/// Use the nil-coalescing operator (`??`) to supply a default value in case
/// the `Optional` instance is `nil`. Here a default path is supplied for an
/// image that is missing from `imagePaths`.
///
/// let defaultImagePath = "/images/default.png"
/// let heartPath = imagePaths["heart"] ?? defaultImagePath
/// print(heartPath)
/// // Prints "/images/default.png"
///
/// The `??` operator also works with another `Optional` instance on the
/// right-hand side. As a result, you can chain multiple `??` operators
/// together.
///
/// let shapePath = imagePaths["cir"] ?? imagePaths["squ"] ?? defaultImagePath
/// print(shapePath)
/// // Prints "/images/default.png"
///
/// Unconditional Unwrapping
/// ------------------------
///
/// When you're certain that an instance of `Optional` contains a value, you
/// can unconditionally unwrap the value by using the forced
/// unwrap operator (postfix `!`). For example, the result of the failable `Int`
/// initializer is unconditionally unwrapped in the example below.
///
/// let number = Int("42")!
/// print(number)
/// // Prints "42"
///
/// You can also perform unconditional optional chaining by using the postfix
/// `!` operator.
///
/// let isPNG = imagePaths["star"]!.hasSuffix(".png")
/// print(isPNG)
/// // Prints "true"
///
/// Unconditionally unwrapping a `nil` instance with `!` triggers a runtime
/// error.
@_frozen
public enum Optional<Wrapped> : ExpressibleByNilLiteral {
// The compiler has special knowledge of Optional<Wrapped>, including the fact
// that it is an `enum` with cases named `none` and `some`.
/// The absence of a value.
///
/// In code, the absence of a value is typically written using the `nil`
/// literal rather than the explicit `.none` enumeration case.
case none
/// The presence of a value, stored as `Wrapped`.
case some(Wrapped)
/// Creates an instance that stores the given value.
@_transparent
public init(_ some: Wrapped) { self = .some(some) }
/// Evaluates the given closure when this `Optional` instance is not `nil`,
/// passing the unwrapped value as a parameter.
///
/// Use the `map` method with a closure that returns a nonoptional value.
/// This example performs an arithmetic operation on an
/// optional integer.
///
/// let possibleNumber: Int? = Int("42")
/// let possibleSquare = possibleNumber.map { $0 * $0 }
/// print(possibleSquare)
/// // Prints "Optional(1764)"
///
/// let noNumber: Int? = nil
/// let noSquare = noNumber.map { $0 * $0 }
/// print(noSquare)
/// // Prints "nil"
///
/// - Parameter transform: A closure that takes the unwrapped value
/// of the instance.
/// - Returns: The result of the given closure. If this instance is `nil`,
/// returns `nil`.
@inlinable
public func map<U>(
_ transform: (Wrapped) throws -> U
) rethrows -> U? {
switch self {
case .some(let y):
return .some(try transform(y))
case .none:
return .none
}
}
/// Evaluates the given closure when this `Optional` instance is not `nil`,
/// passing the unwrapped value as a parameter.
///
/// Use the `flatMap` method with a closure that returns an optional value.
/// This example performs an arithmetic operation with an optional result on
/// an optional integer.
///
/// let possibleNumber: Int? = Int("42")
/// let nonOverflowingSquare = possibleNumber.flatMap { x -> Int? in
/// let (result, overflowed) = x.multipliedReportingOverflow(by: x)
/// return overflowed ? nil : result
/// }
/// print(nonOverflowingSquare)
/// // Prints "Optional(1764)"
///
/// - Parameter transform: A closure that takes the unwrapped value
/// of the instance.
/// - Returns: The result of the given closure. If this instance is `nil`,
/// returns `nil`.
@inlinable
public func flatMap<U>(
_ transform: (Wrapped) throws -> U?
) rethrows -> U? {
switch self {
case .some(let y):
return try transform(y)
case .none:
return .none
}
}
/// Creates an instance initialized with `nil`.
///
/// Do not call this initializer directly. It is used by the compiler when you
/// initialize an `Optional` instance with a `nil` literal. For example:
///
/// var i: Index? = nil
///
/// In this example, the assignment to the `i` variable calls this
/// initializer behind the scenes.
@_transparent
public init(nilLiteral: ()) {
self = .none
}
/// The wrapped value of this instance, unwrapped without checking whether
/// the instance is `nil`.
///
/// The `unsafelyUnwrapped` property provides the same value as the forced
/// unwrap operator (postfix `!`). However, in optimized builds (`-O`), no
/// check is performed to ensure that the current instance actually has a
/// value. Accessing this property in the case of a `nil` value is a serious
/// programming error and could lead to undefined behavior or a runtime
/// error.
///
/// In debug builds (`-Onone`), the `unsafelyUnwrapped` property has the same
/// behavior as using the postfix `!` operator and triggers a runtime error
/// if the instance is `nil`.
///
/// The `unsafelyUnwrapped` property is recommended over calling the
/// `unsafeBitCast(_:)` function because the property is more restrictive
/// and because accessing the property still performs checking in debug
/// builds.
///
/// - Warning: This property trades safety for performance. Use
/// `unsafelyUnwrapped` only when you are confident that this instance
/// will never be equal to `nil` and only after you've tried using the
/// postfix `!` operator.
@inlinable
public var unsafelyUnwrapped: Wrapped {
@inline(__always)
get {
if let x = self {
return x
}
_debugPreconditionFailure("unsafelyUnwrapped of nil optional")
}
}
/// - Returns: `unsafelyUnwrapped`.
///
/// This version is for internal stdlib use; it avoids any checking
/// overhead for users, even in Debug builds.
@inlinable
internal var _unsafelyUnwrappedUnchecked: Wrapped {
@inline(__always)
get {
if let x = self {
return x
}
_sanityCheckFailure("_unsafelyUnwrappedUnchecked of nil optional")
}
}
}
extension Optional : CustomDebugStringConvertible {
/// A textual representation of this instance, suitable for debugging.
public var debugDescription: String {
switch self {
case .some(let value):
var result = "Optional("
debugPrint(value, terminator: "", to: &result)
result += ")"
return result
case .none:
return "nil"
}
}
}
extension Optional : CustomReflectable {
public var customMirror: Mirror {
switch self {
case .some(let value):
return Mirror(
self,
children: [ "some": value ],
displayStyle: .optional)
case .none:
return Mirror(self, children: [:], displayStyle: .optional)
}
}
}
@_transparent
public // COMPILER_INTRINSIC
func _diagnoseUnexpectedNilOptional(_filenameStart: Builtin.RawPointer,
_filenameLength: Builtin.Word,
_filenameIsASCII: Builtin.Int1,
_line: Builtin.Word,
_isImplicitUnwrap: Builtin.Int1) {
_preconditionFailure(
Bool(_isImplicitUnwrap)
? "Unexpectedly found nil while implicitly unwrapping an Optional value"
: "Unexpectedly found nil while unwrapping an Optional value",
file: StaticString(_start: _filenameStart,
utf8CodeUnitCount: _filenameLength,
isASCII: _filenameIsASCII),
line: UInt(_line))
}
extension Optional : Equatable where Wrapped : Equatable {
/// Returns a Boolean value indicating whether two optional instances are
/// equal.
///
/// Use this equal-to operator (`==`) to compare any two optional instances of
/// a type that conforms to the `Equatable` protocol. The comparison returns
/// `true` if both arguments are `nil` or if the two arguments wrap values
/// that are equal. Conversely, the comparison returns `false` if only one of
/// the arguments is `nil` or if the two arguments wrap values that are not
/// equal.
///
/// let group1 = [1, 2, 3, 4, 5]
/// let group2 = [1, 3, 5, 7, 9]
/// if group1.first == group2.first {
/// print("The two groups start the same.")
/// }
/// // Prints "The two groups start the same."
///
/// You can also use this operator to compare a nonoptional value to an
/// optional that wraps the same type. The nonoptional value is wrapped as an
/// optional before the comparison is made. In the following example, the
/// `numberToMatch` constant is wrapped as an optional before comparing to the
/// optional `numberFromString`:
///
/// let numberToFind: Int = 23
/// let numberFromString: Int? = Int("23") // Optional(23)
/// if numberToFind == numberFromString {
/// print("It's a match!")
/// }
/// // Prints "It's a match!"
///
/// An instance that is expressed as a literal can also be used with this
/// operator. In the next example, an integer literal is compared with the
/// optional integer `numberFromString`. The literal `23` is inferred as an
/// `Int` instance and then wrapped as an optional before the comparison is
/// performed.
///
/// if 23 == numberFromString {
/// print("It's a match!")
/// }
/// // Prints "It's a match!"
///
/// - Parameters:
/// - lhs: An optional value to compare.
/// - rhs: Another optional value to compare.
@inlinable
public static func ==(lhs: Wrapped?, rhs: Wrapped?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l == r
case (nil, nil):
return true
default:
return false
}
}
}
extension Optional: Hashable where Wrapped: Hashable {
/// Hashes the essential components of this value by feeding them into the
/// given hasher.
///
/// - Parameter hasher: The hasher to use when combining the components
/// of this instance.
@inlinable
public func hash(into hasher: inout Hasher) {
switch self {
case .none:
hasher.combine(0 as UInt8)
case .some(let wrapped):
hasher.combine(1 as UInt8)
hasher.combine(wrapped)
}
}
}
// Enable pattern matching against the nil literal, even if the element type
// isn't equatable.
@_fixed_layout
public struct _OptionalNilComparisonType : ExpressibleByNilLiteral {
/// Create an instance initialized with `nil`.
@_transparent
public init(nilLiteral: ()) {
}
}
extension Optional {
/// Returns a Boolean value indicating whether an argument matches `nil`.
///
/// You can use the pattern-matching operator (`~=`) to test whether an
/// optional instance is `nil` even when the wrapped value's type does not
/// conform to the `Equatable` protocol. The pattern-matching operator is used
/// internally in `case` statements for pattern matching.
///
/// The following example declares the `stream` variable as an optional
/// instance of a hypothetical `DataStream` type, and then uses a `switch`
/// statement to determine whether the stream is `nil` or has a configured
/// value. When evaluating the `nil` case of the `switch` statement, this
/// operator is called behind the scenes.
///
/// var stream: DataStream? = nil
/// switch stream {
/// case nil:
/// print("No data stream is configured.")
/// case let x?:
/// print("The data stream has \(x.availableBytes) bytes available.")
/// }
/// // Prints "No data stream is configured."
///
/// - Note: To test whether an instance is `nil` in an `if` statement, use the
/// equal-to operator (`==`) instead of the pattern-matching operator. The
/// pattern-matching operator is primarily intended to enable `case`
/// statement pattern matching.
///
/// - Parameters:
/// - lhs: A `nil` literal.
/// - rhs: A value to match against `nil`.
@_transparent
public static func ~=(lhs: _OptionalNilComparisonType, rhs: Wrapped?) -> Bool {
switch rhs {
case .some:
return false
case .none:
return true
}
}
// Enable equality comparisons against the nil literal, even if the
// element type isn't equatable
/// Returns a Boolean value indicating whether the left-hand-side argument is
/// `nil`.
///
/// You can use this equal-to operator (`==`) to test whether an optional
/// instance is `nil` even when the wrapped value's type does not conform to
/// the `Equatable` protocol.
///
/// The following example declares the `stream` variable as an optional
/// instance of a hypothetical `DataStream` type. Although `DataStream` is not
/// an `Equatable` type, this operator allows checking whether `stream` is
/// `nil`.
///
/// var stream: DataStream? = nil
/// if stream == nil {
/// print("No data stream is configured.")
/// }
/// // Prints "No data stream is configured."
///
/// - Parameters:
/// - lhs: A value to compare to `nil`.
/// - rhs: A `nil` literal.
@_transparent
public static func ==(lhs: Wrapped?, rhs: _OptionalNilComparisonType) -> Bool {
switch lhs {
case .some:
return false
case .none:
return true
}
}
/// Returns a Boolean value indicating whether the left-hand-side argument is
/// not `nil`.
///
/// You can use this not-equal-to operator (`!=`) to test whether an optional
/// instance is not `nil` even when the wrapped value's type does not conform
/// to the `Equatable` protocol.
///
/// The following example declares the `stream` variable as an optional
/// instance of a hypothetical `DataStream` type. Although `DataStream` is not
/// an `Equatable` type, this operator allows checking whether `stream` wraps
/// a value and is therefore not `nil`.
///
/// var stream: DataStream? = fetchDataStream()
/// if stream != nil {
/// print("The data stream has been configured.")
/// }
/// // Prints "The data stream has been configured."
///
/// - Parameters:
/// - lhs: A value to compare to `nil`.
/// - rhs: A `nil` literal.
@_transparent
public static func !=(lhs: Wrapped?, rhs: _OptionalNilComparisonType) -> Bool {
switch lhs {
case .some:
return true
case .none:
return false
}
}
/// Returns a Boolean value indicating whether the right-hand-side argument is
/// `nil`.
///
/// You can use this equal-to operator (`==`) to test whether an optional
/// instance is `nil` even when the wrapped value's type does not conform to
/// the `Equatable` protocol.
///
/// The following example declares the `stream` variable as an optional
/// instance of a hypothetical `DataStream` type. Although `DataStream` is not
/// an `Equatable` type, this operator allows checking whether `stream` is
/// `nil`.
///
/// var stream: DataStream? = nil
/// if nil == stream {
/// print("No data stream is configured.")
/// }
/// // Prints "No data stream is configured."
///
/// - Parameters:
/// - lhs: A `nil` literal.
/// - rhs: A value to compare to `nil`.
@_transparent
public static func ==(lhs: _OptionalNilComparisonType, rhs: Wrapped?) -> Bool {
switch rhs {
case .some:
return false
case .none:
return true
}
}
/// Returns a Boolean value indicating whether the right-hand-side argument is
/// not `nil`.
///
/// You can use this not-equal-to operator (`!=`) to test whether an optional
/// instance is not `nil` even when the wrapped value's type does not conform
/// to the `Equatable` protocol.
///
/// The following example declares the `stream` variable as an optional
/// instance of a hypothetical `DataStream` type. Although `DataStream` is not
/// an `Equatable` type, this operator allows checking whether `stream` wraps
/// a value and is therefore not `nil`.
///
/// var stream: DataStream? = fetchDataStream()
/// if nil != stream {
/// print("The data stream has been configured.")
/// }
/// // Prints "The data stream has been configured."
///
/// - Parameters:
/// - lhs: A `nil` literal.
/// - rhs: A value to compare to `nil`.
@_transparent
public static func !=(lhs: _OptionalNilComparisonType, rhs: Wrapped?) -> Bool {
switch rhs {
case .some:
return true
case .none:
return false
}
}
}
/// Performs a nil-coalescing operation, returning the wrapped value of an
/// `Optional` instance or a default value.
///
/// A nil-coalescing operation unwraps the left-hand side if it has a value, or
/// it returns the right-hand side as a default. The result of this operation
/// will have the nonoptional type of the left-hand side's `Wrapped` type.
///
/// This operator uses short-circuit evaluation: `optional` is checked first,
/// and `defaultValue` is evaluated only if `optional` is `nil`. For example:
///
/// func getDefault() -> Int {
/// print("Calculating default...")
/// return 42
/// }
///
/// let goodNumber = Int("100") ?? getDefault()
/// // goodNumber == 100
///
/// let notSoGoodNumber = Int("invalid-input") ?? getDefault()
/// // Prints "Calculating default..."
/// // notSoGoodNumber == 42
///
/// In this example, `goodNumber` is assigned a value of `100` because
/// `Int("100")` succeeded in returning a non-`nil` result. When
/// `notSoGoodNumber` is initialized, `Int("invalid-input")` fails and returns
/// `nil`, and so the `getDefault()` method is called to supply a default
/// value.
///
/// - Parameters:
/// - optional: An optional value.
/// - defaultValue: A value to use as a default. `defaultValue` is the same
/// type as the `Wrapped` type of `optional`.
@_transparent
public func ?? <T>(optional: T?, defaultValue: @autoclosure () throws -> T)
rethrows -> T {
switch optional {
case .some(let value):
return value
case .none:
return try defaultValue()
}
}
/// Performs a nil-coalescing operation, returning the wrapped value of an
/// `Optional` instance or a default `Optional` value.
///
/// A nil-coalescing operation unwraps the left-hand side if it has a value, or
/// returns the right-hand side as a default. The result of this operation
/// will be the same type as its arguments.
///
/// This operator uses short-circuit evaluation: `optional` is checked first,
/// and `defaultValue` is evaluated only if `optional` is `nil`. For example:
///
/// let goodNumber = Int("100") ?? Int("42")
/// print(goodNumber)
/// // Prints "Optional(100)"
///
/// let notSoGoodNumber = Int("invalid-input") ?? Int("42")
/// print(notSoGoodNumber)
/// // Prints "Optional(42)"
///
/// In this example, `goodNumber` is assigned a value of `100` because
/// `Int("100")` succeeds in returning a non-`nil` result. When
/// `notSoGoodNumber` is initialized, `Int("invalid-input")` fails and returns
/// `nil`, and so `Int("42")` is called to supply a default value.
///
/// Because the result of this nil-coalescing operation is itself an optional
/// value, you can chain default values by using `??` multiple times. The
/// first optional value that isn't `nil` stops the chain and becomes the
/// result of the whole expression. The next example tries to find the correct
/// text for a greeting in two separate dictionaries before falling back to a
/// static default.
///
/// let greeting = userPrefs[greetingKey] ??
/// defaults[greetingKey] ?? "Greetings!"
///
/// If `userPrefs[greetingKey]` has a value, that value is assigned to
/// `greeting`. If not, any value in `defaults[greetingKey]` will succeed, and
/// if not that, `greeting` will be set to the nonoptional default value,
/// `"Greetings!"`.
///
/// - Parameters:
/// - optional: An optional value.
/// - defaultValue: A value to use as a default. `defaultValue` and
/// `optional` have the same type.
@_transparent
public func ?? <T>(optional: T?, defaultValue: @autoclosure () throws -> T?)
rethrows -> T? {
switch optional {
case .some(let value):
return value
case .none:
return try defaultValue()
}
}
//===----------------------------------------------------------------------===//
// Bridging
//===----------------------------------------------------------------------===//
#if _runtime(_ObjC)
extension Optional : _ObjectiveCBridgeable {
// The object that represents `none` for an Optional of this type.
@inlinable // FIXME(sil-serialize-all)
internal static var _nilSentinel : AnyObject {
@_silgen_name("_swift_Foundation_getOptionalNilSentinelObject")
get
}
@inlinable // FIXME(sil-serialize-all)
public func _bridgeToObjectiveC() -> AnyObject {
// Bridge a wrapped value by unwrapping.
if let value = self {
return _bridgeAnythingToObjectiveC(value)
}
// Bridge nil using a sentinel.
return type(of: self)._nilSentinel
}
@inlinable // FIXME(sil-serialize-all)
public static func _forceBridgeFromObjectiveC(
_ source: AnyObject,
result: inout Optional<Wrapped>?
) {
// Map the nil sentinel back to .none.
// NB that the signature of _forceBridgeFromObjectiveC adds another level
// of optionality, so we need to wrap the immediate result of the conversion
// in `.some`.
if source === _nilSentinel {
result = .some(.none)
return
}
// Otherwise, force-bridge the underlying value.
let unwrappedResult = source as! Wrapped
result = .some(.some(unwrappedResult))
}
@inlinable // FIXME(sil-serialize-all)
public static func _conditionallyBridgeFromObjectiveC(
_ source: AnyObject,
result: inout Optional<Wrapped>?
) -> Bool {
// Map the nil sentinel back to .none.
// NB that the signature of _forceBridgeFromObjectiveC adds another level
// of optionality, so we need to wrap the immediate result of the conversion
// in `.some` to indicate success of the bridging operation, with a nil
// result.
if source === _nilSentinel {
result = .some(.none)
return true
}
// Otherwise, try to bridge the underlying value.
if let unwrappedResult = source as? Wrapped {
result = .some(.some(unwrappedResult))
return true
} else {
result = .none
return false
}
}
@inlinable // FIXME(sil-serialize-all)
@_effects(readonly)
public static func _unconditionallyBridgeFromObjectiveC(_ source: AnyObject?)
-> Optional<Wrapped> {
if let nonnullSource = source {
// Map the nil sentinel back to none.
if nonnullSource === _nilSentinel {
return .none
} else {
return .some(nonnullSource as! Wrapped)
}
} else {
// If we unexpectedly got nil, just map it to `none` too.
return .none
}
}
}
#endif
| apache-2.0 | 03bb11b883c08ebea746445dc12aa983 | 34.628686 | 82 | 0.62967 | 4.295943 | false | false | false | false |
Hypercubesoft/HCFramework | HCFramework/Managers/HCImagePicker.swift | 1 | 6357 | //
// HCImagePicker.swift
// iOSTemplate
//
// Created by Hypercube 2 on 10/3/17.
// Copyright © 2017 Hypercube. All rights reserved.
//
import UIKit
public typealias CompletionHandler = (_ success:Bool, _ res:AnyObject?) -> Void
// NOTE: Add NSCameraUsageDescription to plist file
open class HCImagePicker: NSObject, UIImagePickerControllerDelegate, UINavigationControllerDelegate
{
open var imageSelectionInProgress = false
open var imageSelectCompletitionHandler:CompletionHandler?
public static let sharedManager: HCImagePicker =
{
let instance = HCImagePicker()
return instance
}()
/// Open UIImagePickerController with Camera like source type with the possibility of setting Completition Handler Function.
///
/// - Parameters:
/// - completitionHandler: Completion Handler Function. By default it is not set.
open func takePictureFromCamera(allowEditing: Bool = true, completitionHandler:CompletionHandler? = nil)
{
self.imageSelectCompletitionHandler = completitionHandler
self.openCamera(allowEditing: allowEditing)
}
/// Open UIImagePickerController with PhotosAlbum like source type with the possibility of setting Completition Handler Function.
///
/// - Parameters:
/// - completitionHandler: Completion Handler Function. By default it is not set.
open func getPictureFromGallery(allowEditing: Bool = true, completitionHandler:CompletionHandler? = nil)
{
self.imageSelectCompletitionHandler = completitionHandler
self.openGallery(allowEditing: allowEditing)
}
/// Open dialog to choose the image source from where the image will be obtained.
///
/// - Parameters:
/// - title: Dialog title. Default value is "Select picture".
/// - fromCameraButtonTitle: From camera button title. Default value is "From Camera".
/// - fromGalleryButtonTitle: From gallery button title. Default value is "From Gallery".
/// - cancelButtonTitle: Cancel button title. Default value is "Cancel".
/// - completitionHandler: Completion Handler Function. By default it is not set.
open func selectPicture(title:String = "Select picture", fromCameraButtonTitle:String = "From Camera", fromGalleryButtonTitle:String = "From Gallery", cancelButtonTitle:String = "Cancel", allowEditing: Bool = true, completitionHandler:CompletionHandler? = nil)
{
self.imageSelectCompletitionHandler = completitionHandler
HCDialog.showDialogWithMultipleActions(message: "", title: title, alertButtonTitles:
[
fromCameraButtonTitle,
fromGalleryButtonTitle,
cancelButtonTitle]
, alertButtonActions:
[
{ (alert) in
self.openCamera(allowEditing: allowEditing)
},
{ (alert) in
self.openGallery(allowEditing: allowEditing)
},
nil
], alertButtonStyles:
[
.default,
.default,
.cancel
])
}
/// Open UIImagePickerController with Camera like source type
private func openCamera(allowEditing: Bool)
{
if UIImagePickerController.isSourceTypeAvailable(.camera)
{
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = .camera
imagePicker.allowsEditing = allowEditing
imageSelectionInProgress = true
UIApplication.shared.keyWindow?.rootViewController?.present(imagePicker, animated: true, completion: nil)
}
}
/// Open UIImagePickerController with PhotosAlbum like source type
private func openGallery(allowEditing: Bool)
{
if UIImagePickerController.isSourceTypeAvailable(.savedPhotosAlbum){
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = .savedPhotosAlbum;
imagePicker.allowsEditing = allowEditing
imageSelectionInProgress = true
UIApplication.shared.keyWindow?.rootViewController?.present(imagePicker, animated: true, completion: nil)
}
}
/// Fix orientation for image. This is useful in some cases, for example, when image taken from camera has wrong orientation after upload to server.
///
/// - Parameter img: Image for which we need to fix orientation
/// - Returns: Image with valid orientation
private func fixOrientation(img: UIImage) -> UIImage {
if (img.imageOrientation == .up) {
return img
}
UIGraphicsBeginImageContextWithOptions(img.size, false, img.scale)
let rect = CGRect(x: 0, y: 0, width: img.size.width, height: img.size.height)
img.draw(in: rect)
let normalizedImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return normalizedImage
}
public func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
picker.dismiss(animated: true) {
if picker.allowsEditing
{
if let image = info[UIImagePickerController.InfoKey.editedImage.rawValue] as? UIImage {
if let completion = self.imageSelectCompletitionHandler
{
completion(true, self.fixOrientation(img: image))
}
}
} else {
if let image = info[UIImagePickerController.InfoKey.originalImage.rawValue] as? UIImage {
if let completion = self.imageSelectCompletitionHandler
{
completion(true, self.fixOrientation(img: image))
}
}
}
}
}
public func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
picker.dismiss(animated: true, completion: {
if let completion = self.imageSelectCompletitionHandler
{
completion(false, nil)
}
})
}
}
| mit | 5aff82249c26055fecfae2500e7030af | 39.484076 | 264 | 0.633732 | 5.762466 | false | false | false | false |
jakeheis/Shout | Sources/Shout/SSH.swift | 1 | 8648 | //
// SSH.swift
// Shout
//
// Created by Jake Heiser on 3/4/18.
//
import Foundation
import Socket
/// Manages an SSH session
public class SSH {
public enum PtyType: String {
case vanilla
case vt100
case vt102
case vt220
case ansi
case xterm
}
/// Connects to a remote server and opens an SSH session
///
/// - Parameters:
/// - host: the host to connect to
/// - port: the port to connect to; default 22
/// - username: the username to login with
/// - authMethod: the authentication method to use while logging in
/// - execution: the block executed with the open, authenticated SSH session
/// - Throws: SSHError if the session fails at any point
public static func connect(host: String, port: Int32 = 22, username: String, authMethod: SSHAuthMethod, execution: (_ ssh: SSH) throws -> ()) throws {
let ssh = try SSH(host: host, port: port)
try ssh.authenticate(username: username, authMethod: authMethod)
try execution(ssh)
}
let session: Session
private let sock: Socket
public var ptyType: PtyType? = nil
/// Creates a new SSH session
///
/// - Parameters:
/// - host: the host to connect to
/// - port: the port to connect to; default 22
/// - timeout: timeout to use (in msec); default 0
/// - Throws: SSHError if the SSH session couldn't be created
public init(host: String, port: Int32 = 22, timeout: UInt = 0) throws {
self.sock = try Socket.create()
self.session = try Session()
session.blocking = 1
try sock.connect(to: host, port: port, timeout: timeout)
try session.handshake(over: sock)
}
/// Authenticate the session using a public/private key pair
///
/// - Parameters:
/// - username: the username to login with
/// - privateKey: the path to the private key
/// - publicKey: the path to the public key; defaults to private key path + ".pub"
/// - passphrase: the passphrase encrypting the key; defaults to nil
/// - Throws: SSHError if authentication fails
public func authenticate(username: String, privateKey: String, publicKey: String? = nil, passphrase: String? = nil) throws {
let key = SSHKey(privateKey: privateKey, publicKey: publicKey, passphrase: passphrase)
try authenticate(username: username, authMethod: key)
}
/// Authenticate the session using a password
///
/// - Parameters:
/// - username: the username to login with
/// - password: the user's password
/// - Throws: SSHError if authentication fails
public func authenticate(username: String, password: String) throws {
try authenticate(username: username, authMethod: SSHPassword(password))
}
/// Authenticate the session using the SSH agent
///
/// - Parameter username: the username to login with
/// - Throws: SSHError if authentication fails
public func authenticateByAgent(username: String) throws {
try authenticate(username: username, authMethod: SSHAgent())
}
/// Authenticate the session using the given authentication method
///
/// - Parameters:
/// - username: the username to login with
/// - authMethod: the authentication method to use
/// - Throws: SSHError if authentication fails
public func authenticate(username: String, authMethod: SSHAuthMethod) throws {
try authMethod.authenticate(ssh: self, username: username)
}
/// Execute a command on the remote server
///
/// - Parameters:
/// - command: the command to execute
/// - silent: whether or not to execute the command silently; defaults to false
/// - Returns: exit code of the command
/// - Throws: SSHError if the command couldn't be executed
@discardableResult
public func execute(_ command: String, silent: Bool = false) throws -> Int32 {
return try execute(command, output: { (output) in
if silent == false {
print(output, terminator: "")
fflush(stdout)
}
})
}
/// Execute a command on the remote server and capture the output
///
/// - Parameter command: the command to execute
/// - Returns: a tuple with the exit code of the command and the output of the command
/// - Throws: SSHError if the command couldn't be executed
public func capture(_ command: String) throws -> (status: Int32, output: String) {
var ongoing = ""
let status = try execute(command) { (output) in
ongoing += output
}
return (status, ongoing)
}
/// Execute a command on the remote server
///
/// - Parameters:
/// - command: the command to execute
/// - output: block handler called every time a chunk of command output is received
/// - Returns: exit code of the command
/// - Throws: SSHError if the command couldn't be executed
public func execute(_ command: String, output: ((_ output: String) -> ())) throws -> Int32 {
let channel = try session.openCommandChannel()
if let ptyType = ptyType {
try channel.requestPty(type: ptyType.rawValue)
}
try channel.exec(command: command)
var dataLeft = true
while dataLeft {
switch channel.readData() {
case .data(let data):
guard let str = String(data: data, encoding: .utf8) else {
throw SSHError.genericError("SSH failed to create string using UTF8 encoding")
}
output(str)
case .done:
dataLeft = false
case .eagain:
break
case .error(let error):
throw error
}
}
try channel.close()
return channel.exitStatus()
}
/// Upload a file from the local device to the remote server
///
/// - Parameters:
/// - localURL: the path to the existing file on the local device
/// - remotePath: the location on the remote server whether the file should be uploaded to
/// - permissions: the file permissions to create the new file with; defaults to FilePermissions.default
/// - Throws: SSHError if local file can't be read or upload fails
@discardableResult
public func sendFile(localURL: URL, remotePath: String, permissions: FilePermissions = .default) throws -> Int32 {
guard let resources = try? localURL.resourceValues(forKeys: [.fileSizeKey]),
let fileSize = resources.fileSize,
let inputStream = InputStream(url: localURL) else {
throw SSHError.genericError("couldn't open file at \(localURL)")
}
let channel = try session.openSCPChannel(fileSize: Int64(fileSize), remotePath: remotePath, permissions: permissions)
inputStream.open()
defer { inputStream.close() }
let bufferSize = Int(Channel.packetDefaultSize)
var buffer = Data(capacity: bufferSize)
while inputStream.hasBytesAvailable {
let bytesRead: Int = try buffer.withUnsafeMutableBytes {
guard let pointer = $0.bindMemory(to: UInt8.self).baseAddress else {
throw SSHError.genericError("SSH write failed to bind buffer memory")
}
return inputStream.read(pointer, maxLength: bufferSize)
}
if bytesRead == 0 { break }
var bytesSent = 0
while bytesSent < bytesRead {
let chunk = bytesSent == 0 ? buffer : buffer.advanced(by: bytesSent)
switch channel.write(data: chunk, length: bytesRead - bytesSent) {
case .written(let count):
bytesSent += count
case .eagain:
break
case .error(let error):
throw error
}
}
}
try channel.sendEOF()
try channel.waitEOF()
try channel.close()
try channel.waitClosed()
return channel.exitStatus()
}
/// Open an SFTP session with the remote server
///
/// - Returns: the opened SFTP session
/// - Throws: SSHError if an SFTP session could not be opened
public func openSftp() throws -> SFTP {
return try session.openSftp()
}
}
| mit | 6f3cad9245c64df392c18cdfbcdbd702 | 36.275862 | 154 | 0.594704 | 4.877609 | false | false | false | false |
honghaoz/2048-Solver-AI | 2048 AI/AI/AI-Expectimax.swift | 1 | 12636 | // Copyright © 2019 ChouTi. All rights reserved.
import Foundation
class AIExpectimax {
var dimension: Int = 0
weak var gameModel: Game2048!
init(gameModel: Game2048) {
self.gameModel = gameModel
self.dimension = gameModel.dimension
}
func nextCommand() -> MoveCommand? {
if GameModelHelper.isGameEnded(&gameModel.gameBoard) {
return nil
} else {
let (command, _) = _nextCommand(&gameModel.gameBoard, level: 0)
return command
}
}
func _nextCommand(_ gameBoard: inout SquareGameBoard<UnsafeMutablePointer<Tile>>, level: Int = 0, maxDepth: Int = 3) -> (MoveCommand?, Double) {
var choosenCommand: MoveCommand?
var maxScore: Double = 0.0
let commands = GameModelHelper.validMoveCommandsInGameBoard(&gameBoard, shuffle: false)
for command in commands {
// Copy a new board, Alloc
var copyGameBoard = GameModelHelper.copyGameBoard(&gameBoard)
// Perform command
_ = GameModelHelper.performMoveCommand(command, onGameBoard: ©GameBoard)
// var (score, (x, y)) = evaluateUsingMonoHeuristic(GameModelHelper.intGameBoardFromGameBoard(©GameBoard))
// GameModelHelper.insertTile(©GameBoard, pos: (y, x), value: 2)
var score = heuristicSMonotonic(©GameBoard)
GameModelHelper.insertTileAtRandomLocation(©GameBoard)
if level < maxDepth {
let (nextCommand, nextLevelScore) = _nextCommand(©GameBoard, level: level + 1, maxDepth: maxDepth)
if nextCommand != nil {
score += nextLevelScore * pow(0.9, Double(level) + 1.0)
}
}
if score > maxScore {
maxScore = score
choosenCommand = command
}
// Dealloc
GameModelHelper.deallocGameBoard(©GameBoard)
// Expectimax
// score += heuristicScore(&gameBoardCopy)
// // availableSpot
// let availableSpots = GameModelHelper.gameBoardEmptySpots(&gameBoardCopy)
// if availableSpots.count == 0 {
// // Dealloc
// GameModelHelper.deallocGameBoard(&gameBoardCopy)
// continue
// }
//
// for eachAvailableSpot in availableSpots {
// // Try to insert 2
// GameModelHelper.insertTile(&gameBoardCopy, pos: eachAvailableSpot, value: 2)
// score += heuristicScore(&gameBoardCopy) * 0.85 * powf(0.25, Float(level))
// var (_, nextLevelScore) = _nextCommand(&gameBoardCopy, level: level + 1, maxDepth: maxDepth)
// score += nextLevelScore
//
// // Restore
// gameBoardCopy[eachAvailableSpot.0, eachAvailableSpot.1].pointee = .Empty
//
// // Try to insert 4
// GameModelHelper.insertTile(&gameBoardCopy, pos: eachAvailableSpot, value: 4)
// score += heuristicScore(&gameBoardCopy) * 0.15 * powf(0.25, Float(level))
// (_, nextLevelScore) = _nextCommand(&gameBoardCopy, level: level + 1, maxDepth: maxDepth)
// score += nextLevelScore
//
// // Restore
// gameBoardCopy[eachAvailableSpot.0, eachAvailableSpot.1].pointee = .Empty
// }
}
return (choosenCommand, maxScore)
}
// MARK: Heuristic
func heuristicScore(_ gameBoard: inout SquareGameBoard<UnsafeMutablePointer<Tile>>) -> Double {
let myScore = heuristicSMonotonic(&gameBoard)
return myScore
}
func heuristicSMonotonic(_ gameBoard: inout SquareGameBoard<UnsafeMutablePointer<Tile>>) -> Double {
let ratio: Double = 0.25
var maxScore: Double = -1.0
// Construct 8 different patterns into one linear array
// Direction for the first row
for startDirection in 0..<2 {
// Whether flip the board
for flip in 0..<2 {
// Whether it's row or column
for rOrC in 0..<2 {
var oneDimension = [UnsafeMutablePointer<Tile>]()
for row in stride(from: 0, to: dimension, by: 2) {
let firstRow = (flip != 0) ? (dimension - 1 - row) : row
if rOrC != 0 {
oneDimension.append(contentsOf: gameBoard.getRow(firstRow, reversed: startDirection != 0))
} else {
oneDimension.append(contentsOf: gameBoard.getColumn(firstRow, reversed: startDirection != 0))
}
let secondRow = (flip != 0) ? (dimension - 1 - row - 1) : row + 1
if secondRow >= 0, secondRow < dimension {
if rOrC != 0 {
oneDimension.append(contentsOf: gameBoard.getRow(firstRow, reversed: startDirection == 0))
} else {
oneDimension.append(contentsOf: gameBoard.getColumn(firstRow, reversed: startDirection == 0))
}
}
}
var weight: Double = 1.0
var result: Double = 0.0
for (_, tile) in oneDimension.enumerated() {
switch tile.pointee {
case .Empty:
break
case let .Number(num):
result += Double(num) * weight
}
weight *= ratio
}
if result > maxScore {
maxScore = result
}
}
}
}
return maxScore
}
func heuristicFreeTiles(_ gameBoard: inout SquareGameBoard<UnsafeMutablePointer<Tile>>) -> Float {
let maxLimit: Float = Float(dimension * dimension)
return Float(GameModelHelper.gameBoardEmptySpotsCount(&gameBoard)) / maxLimit * 12
}
func heuristicMonotonicity(_ gameBoard: inout SquareGameBoard<UnsafeMutablePointer<Tile>>) -> Float {
let r: Float = 0.25
let dimension = gameBoard.dimension
var maxResult: Float = 0.0
var result: Float = 0.0
// Top Left
for i in 0..<dimension {
for j in 0..<dimension {
switch gameBoard[i, j].pointee {
case .Empty:
continue
case let .Number(num):
result += Float(num) * pow(r, Float(i + j))
}
}
}
if result > maxResult {
maxResult = result
}
// Top Right
result = 0
for i in 0..<dimension {
for j in stride(from: dimension - 1, to: -1, by: -1) {
switch gameBoard[i, j].pointee {
case .Empty:
continue
case .Number:
result += pow(r, Float(i + j))
}
}
}
if result > maxResult {
maxResult = result
}
// Bottom Left
result = 0
for i in stride(from: dimension - 1, to: -1, by: -1) {
for j in 0..<dimension {
switch gameBoard[i, j].pointee {
case .Empty:
continue
case .Number:
result += pow(r, Float(i + j))
}
}
}
if result > maxResult {
maxResult = result
}
// Bottom Right
result = 0
for i in stride(from: dimension - 1, to: -1, by: -1) {
for j in stride(from: dimension - 1, to: -1, by: -1) {
switch gameBoard[i, j].pointee {
case .Empty:
continue
case .Number:
result += pow(r, Float(i + j))
}
}
}
if result > maxResult {
maxResult = result
}
return maxResult
}
private func evaluateUsingMonoHeuristic(gameboard: [[Int]], ratio: Double = 0.25) -> (Double, (Int, Int)) {
let d = gameboard.count
var hasZero = false
for i in 0..<d {
for j in 0..<d {
if gameboard[i][j] == 0 {
hasZero = true
}
}
}
assert(hasZero == true, "")
let yRange = (0...gameboard.count - 1).map { $0 }
let yRangeReverse = Array((0...gameboard.count - 1).map { $0 }.reversed())
let xRange = yRange
let xRangeReverse = yRangeReverse
let size = gameboard.count
// Array that contains evaluation results and initial tiles
var results: [Double] = [Double]()
var initialTiles: [(Int, Int)] = [(Int, Int)]()
// Row first, col first
var tempResult = 0.0
var initialTile: (Int, Int) = (-1, -1)
var reverse = false
var weight = 1.0
for j in yRange {
let jCopy = j
for i in xRange {
let iCopy = !reverse ? i : size - i - 1
let curVal = gameboard[jCopy][iCopy]
if curVal == 0, initialTile == (-1, -1) {
initialTile = (iCopy, jCopy)
}
tempResult += Double(curVal) * weight
weight *= ratio
}
reverse = !reverse
}
results.append(tempResult)
let (x, y) = (initialTile.0, initialTile.1)
initialTiles.append((x, y))
tempResult = 0.0
initialTile = (-1, -1)
reverse = false
weight = 1.0
for j in yRange {
let jCopy = j
for i in xRangeReverse {
let iCopy = !reverse ? i : size - i - 1
let curVal = gameboard[jCopy][iCopy]
if curVal == 0, initialTile == (-1, -1) {
initialTile = (iCopy, jCopy)
}
tempResult += Double(curVal) * weight
weight *= ratio
}
reverse = !reverse
}
results.append(tempResult)
let (x2, y2) = (initialTile.0, initialTile.1)
initialTiles.append((x2, y2))
tempResult = 0.0
initialTile = (-1, -1)
reverse = false
weight = 1.0
for i in xRange {
let iCopy = i
for j in yRange {
let jCopy = !reverse ? j : size - j - 1
let curVal = gameboard[jCopy][iCopy]
if curVal == 0, initialTile == (-1, -1) {
initialTile = (iCopy, jCopy)
}
tempResult += Double(curVal) * weight
weight *= ratio
}
reverse = !reverse
}
results.append(tempResult)
let (x3, y3) = (initialTile.0, initialTile.1)
initialTiles.append((x3, y3))
tempResult = 0.0
initialTile = (-1, -1)
reverse = false
weight = 1.0
for i in xRange {
let iCopy = i
for j in yRangeReverse {
let jCopy = !reverse ? j : size - j - 1
let curVal = gameboard[jCopy][iCopy]
if curVal == 0, initialTile == (-1, -1) {
initialTile = (iCopy, jCopy)
}
tempResult += Double(curVal) * weight
weight *= ratio
}
reverse = !reverse
}
results.append(tempResult)
let (x4, y4) = (initialTile.0, initialTile.1)
initialTiles.append((x4, y4))
tempResult = 0.0
initialTile = (-1, -1)
reverse = false
weight = 1.0
for j in yRangeReverse {
let jCopy = j
for i in xRangeReverse {
let iCopy = !reverse ? i : size - i - 1
let curVal = gameboard[jCopy][iCopy]
if curVal == 0, initialTile == (-1, -1) {
initialTile = (iCopy, jCopy)
}
tempResult += Double(curVal) * weight
weight *= ratio
}
reverse = !reverse
}
results.append(tempResult)
let (x5, y5) = (initialTile.0, initialTile.1)
initialTiles.append((x5, y5))
tempResult = 0.0
initialTile = (-1, -1)
reverse = false
weight = 1.0
for j in yRangeReverse {
let jCopy = j
for i in xRange {
let iCopy = !reverse ? i : size - i - 1
let curVal = gameboard[jCopy][iCopy]
if curVal == 0, initialTile == (-1, -1) {
initialTile = (iCopy, jCopy)
}
tempResult += Double(curVal) * weight
weight *= ratio
}
reverse = !reverse
}
results.append(tempResult)
let (x6, y6) = (initialTile.0, initialTile.1)
initialTiles.append((x6, y6))
tempResult = 0.0
initialTile = (-1, -1)
reverse = false
weight = 1.0
for i in xRangeReverse {
let iCopy = i
for j in yRange {
let jCopy = !reverse ? j : size - j - 1
let curVal = gameboard[jCopy][iCopy]
if curVal == 0, initialTile == (-1, -1) {
initialTile = (iCopy, jCopy)
}
tempResult += Double(curVal) * weight
weight *= ratio
}
reverse = !reverse
}
results.append(tempResult)
let (x7, y7) = (initialTile.0, initialTile.1)
initialTiles.append((x7, y7))
tempResult = 0.0
initialTile = (-1, -1)
reverse = false
weight = 1.0
for i in xRangeReverse {
let iCopy = i
for j in yRangeReverse {
let jCopy = !reverse ? j : size - j - 1
let curVal = gameboard[jCopy][iCopy]
if curVal == 0, initialTile == (-1, -1) {
initialTile = (iCopy, jCopy)
}
tempResult += Double(curVal) * weight
weight *= ratio
}
reverse = !reverse
}
results.append(tempResult)
let (x8, y8) = (initialTile.0, initialTile.1)
initialTiles.append((x8, y8))
let maxIndex = results.findMaxIndex()
return (results[maxIndex], initialTiles[maxIndex])
}
}
| gpl-2.0 | 7fba5418806a155d0cdc778e74f87364 | 29.519324 | 146 | 0.562723 | 3.80687 | false | false | false | false |
okerivy/AlgorithmLeetCode | AlgorithmLeetCode/AlgorithmLeetCode/M_82_RemoveDuplicatesFromSortedListII.swift | 1 | 2647 | //
// M_82_RemoveDuplicatesFromSortedListII.swift
// AlgorithmLeetCode
//
// Created by okerivy on 2017/3/23.
// Copyright © 2017年 okerivy. All rights reserved.
//
import Foundation
// MARK: - 题目名称: 82. Remove Duplicates from Sorted List II
/* MARK: - 所属类别:
标签: Linked List
相关题目:
*/
/* MARK: - 题目英文:
Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
For example,
Given 1->2->3->3->4->4->5, return 1->2->5.
Given 1->1->1->2->3, return 2->3.
*/
/* MARK: - 题目翻译:
给定一个已排序的链表,删除所有具有重复编号的节点,只留下与原始列表不同的数字。
例如,
Given 1->2->3->3->4->4->5, return 1->2->5.
Given 1->1->1->2->3, return 2->3.
*/
/* MARK: - 解题思路:
需要在一个有序的链表里面删除所有的重复元素的节点。因为不同于上题可以保留一个,这次需要全部删除,所以我们遍历的时候需要记录一个prev节点,用来处理删除节点之后节点重新连接的问题。
*/
/* MARK: - 复杂度分析:
*/
// MARK: - 代码:
private class Solution {
func deleteDuplicates(_ head: SinglyListNode?) -> SinglyListNode? {
if head == nil || head?.next == nil {
return head
}
var p = head
// 记录初始位置
let dummy = CreatSinglyList().convertArrayToSinglyList([-1])
dummy?.next = head
var prev = dummy
while p != nil && p?.next != nil {
if p?.next?.val == p?.val {
//如果有重复,则继续遍历,直到不重复的节点
var n = p?.next?.next
while n != nil {
if p?.val != n?.val {
break
}
n = n?.next
}
prev?.next = n
p = n
} else {
//如果没有重复,则prev为p,next为p->next
prev = p
p = p?.next
}
}
return dummy?.next
}
}
// MARK: - 测试代码:
func RemoveDuplicatesFromSortedListII() {
// 单链表
var head1 = CreatSinglyList().convertArrayToSinglyList([1, 2, 3, 3, 5, 6, 6, 6, 7, 8])
var head2 = CreatSinglyList().convertArrayToSinglyList([1, 1, 1, 1, 5, 6, 6, 6, 7, 8])
head1 = Solution().deleteDuplicates(head1)
head2 = Solution().deleteDuplicates(head2)
print(head1 ?? "没有找到")
print(head2 ?? "没有找到")
}
| mit | 3427401cfac84312b7b62ec1af09bd94 | 18.821429 | 128 | 0.522072 | 3.153409 | false | false | false | false |
xuech/OMS-WH | OMS-WH/Utilities/Libs/DatePickerDialog.swift | 1 | 12832 | import Foundation
import UIKit
private extension Selector {
static let buttonTapped = #selector(DatePickerDialog.buttonTapped)
static let deviceOrientationDidChange = #selector(DatePickerDialog.deviceOrientationDidChange)
}
open class DatePickerDialog: UIView {
public typealias DatePickerCallback = ( Date? ) -> Void
// MARK: - Constants
private let kDatePickerDialogDefaultButtonHeight: CGFloat = 50
private let kDatePickerDialogDefaultButtonSpacerHeight: CGFloat = 1
private let kDatePickerDialogCornerRadius: CGFloat = 7
private let kDatePickerDialogDoneButtonTag: Int = 1
// MARK: - Views
private var dialogView: UIView!
private var titleLabel: UILabel!
open var datePicker: UIDatePicker!
private var cancelButton: UIButton!
private var doneButton: UIButton!
// MARK: - Variables
private var defaultDate: Date?
private var datePickerMode: UIDatePickerMode?
private var callback: DatePickerCallback?
var showCancelButton:Bool = false
var locale: Locale?
private var textColor: UIColor!
private var buttonColor: UIColor!
private var font: UIFont!
// MARK: - Dialog initialization
public init(textColor: UIColor = UIColor.black, buttonColor: UIColor = UIColor.blue, font: UIFont = .boldSystemFont(ofSize: 15), locale: Locale? = nil, showCancelButton:Bool = true) {
super.init(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: UIScreen.main.bounds.size.height))
self.textColor = textColor
self.buttonColor = buttonColor
self.font = font
self.showCancelButton = showCancelButton
self.locale = locale
setupView()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
func setupView() {
self.dialogView = createContainerView()
self.dialogView!.layer.shouldRasterize = true
self.dialogView!.layer.rasterizationScale = UIScreen.main.scale
self.layer.shouldRasterize = true
self.layer.rasterizationScale = UIScreen.main.scale
self.dialogView!.layer.opacity = 0.5
self.dialogView!.layer.transform = CATransform3DMakeScale(1.3, 1.3, 1)
self.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0)
self.addSubview(self.dialogView!)
}
/// Handle device orientation changes
@objc func deviceOrientationDidChange(_ notification: Notification) {
self.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: UIScreen.main.bounds.size.height)
let screenSize = countScreenSize()
let dialogSize = CGSize(width: 300, height: 230 + kDatePickerDialogDefaultButtonHeight + kDatePickerDialogDefaultButtonSpacerHeight)
dialogView.frame = CGRect(x: (screenSize.width - dialogSize.width) / 2, y: (screenSize.height - dialogSize.height) / 2, width: dialogSize.width, height: dialogSize.height)
}
/// Create the dialog view, and animate opening the dialog
open func show(_ title: String, doneButtonTitle: String = "Done", cancelButtonTitle: String = "Cancel", defaultDate: Date = Date(), minimumDate: Date? = nil, maximumDate: Date? = nil, datePickerMode: UIDatePickerMode = .dateAndTime, callback: @escaping DatePickerCallback) {
self.titleLabel.text = title
self.doneButton.setTitle(doneButtonTitle, for: .normal)
if showCancelButton {
self.cancelButton.setTitle(cancelButtonTitle, for: .normal)
}
self.datePickerMode = datePickerMode
self.callback = callback
self.defaultDate = defaultDate
self.datePicker.datePickerMode = self.datePickerMode ?? UIDatePickerMode.date
self.datePicker.date = self.defaultDate ?? Date()
self.datePicker.maximumDate = maximumDate
self.datePicker.minimumDate = minimumDate
if let locale = self.locale {
self.datePicker.locale = locale
}
/* Add dialog to main window */
guard let appDelegate = UIApplication.shared.delegate else { fatalError() }
guard let window = appDelegate.window else { fatalError() }
window?.addSubview(self)
window?.bringSubview(toFront: self)
window?.endEditing(true)
NotificationCenter.default.addObserver(self, selector: .deviceOrientationDidChange, name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil)
/* Anim */
UIView.animate(
withDuration: 0.2,
delay: 0,
options: .curveEaseInOut,
animations: {
self.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.4)
self.dialogView!.layer.opacity = 1
self.dialogView!.layer.transform = CATransform3DMakeScale(1, 1, 1)
}
)
}
/// Dialog close animation then cleaning and removing the view from the parent
private func close() {
NotificationCenter.default.removeObserver(self)
let currentTransform = self.dialogView.layer.transform
let startRotation = (self.value(forKeyPath: "layer.transform.rotation.z") as? NSNumber) as? Double ?? 0.0
let rotation = CATransform3DMakeRotation((CGFloat)(-startRotation + .pi * 270 / 180), 0, 0, 0)
self.dialogView.layer.transform = CATransform3DConcat(rotation, CATransform3DMakeScale(1, 1, 1))
self.dialogView.layer.opacity = 1
UIView.animate(
withDuration: 0.2,
delay: 0,
options: [],
animations: {
self.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0)
self.dialogView.layer.transform = CATransform3DConcat(currentTransform, CATransform3DMakeScale(0.6, 0.6, 1))
self.dialogView.layer.opacity = 0
}) { (finished) in
for v in self.subviews {
v.removeFromSuperview()
}
self.removeFromSuperview()
self.setupView()
}
}
/// Creates the container view here: create the dialog, then add the custom content and buttons
private func createContainerView() -> UIView {
let screenSize = countScreenSize()
let dialogSize = CGSize(
width: 300,
height: 230
+ kDatePickerDialogDefaultButtonHeight
+ kDatePickerDialogDefaultButtonSpacerHeight)
// For the black background
self.frame = CGRect(x: 0, y: 0, width: screenSize.width, height: screenSize.height)
// This is the dialog's container; we attach the custom content and the buttons to this one
let dialogContainer = UIView(frame: CGRect(x: (screenSize.width - dialogSize.width) / 2, y: (screenSize.height - dialogSize.height) / 2, width: dialogSize.width, height: dialogSize.height))
// First, we style the dialog to match the iOS8 UIAlertView >>>
let gradient: CAGradientLayer = CAGradientLayer(layer: self.layer)
gradient.frame = dialogContainer.bounds
gradient.colors = [UIColor(red: 218/255, green: 218/255, blue: 218/255, alpha: 1).cgColor,
UIColor(red: 233/255, green: 233/255, blue: 233/255, alpha: 1).cgColor,
UIColor(red: 218/255, green: 218/255, blue: 218/255, alpha: 1).cgColor]
let cornerRadius = kDatePickerDialogCornerRadius
gradient.cornerRadius = cornerRadius
dialogContainer.layer.insertSublayer(gradient, at: 0)
dialogContainer.layer.cornerRadius = cornerRadius
dialogContainer.layer.borderColor = UIColor(red: 198/255, green: 198/255, blue: 198/255, alpha: 1).cgColor
dialogContainer.layer.borderWidth = 1
dialogContainer.layer.shadowRadius = cornerRadius + 5
dialogContainer.layer.shadowOpacity = 0.1
dialogContainer.layer.shadowOffset = CGSize(width: 0 - (cornerRadius + 5) / 2, height: 0 - (cornerRadius + 5) / 2)
dialogContainer.layer.shadowColor = UIColor.black.cgColor
dialogContainer.layer.shadowPath = UIBezierPath(roundedRect: dialogContainer.bounds, cornerRadius: dialogContainer.layer.cornerRadius).cgPath
// There is a line above the button
let lineView = UIView(frame: CGRect(x: 0, y: dialogContainer.bounds.size.height - kDatePickerDialogDefaultButtonHeight - kDatePickerDialogDefaultButtonSpacerHeight, width: dialogContainer.bounds.size.width, height: kDatePickerDialogDefaultButtonSpacerHeight))
lineView.backgroundColor = UIColor(red: 198/255, green: 198/255, blue: 198/255, alpha: 1)
dialogContainer.addSubview(lineView)
//Title
self.titleLabel = UILabel(frame: CGRect(x: 10, y: 10, width: 280, height: 30))
self.titleLabel.textAlignment = .center
self.titleLabel.textColor = self.textColor
self.titleLabel.font = self.font.withSize(17)
dialogContainer.addSubview(self.titleLabel)
self.datePicker = UIDatePicker(frame: CGRect(x: 0, y: 30, width: 0, height: 0))
self.datePicker.setValue(self.textColor, forKeyPath: "textColor")
self.datePicker.autoresizingMask = .flexibleRightMargin
self.datePicker.frame.size.width = 300
self.datePicker.frame.size.height = 216
dialogContainer.addSubview(self.datePicker)
// Add the buttons
addButtonsToView(container: dialogContainer)
return dialogContainer
}
/// Add buttons to container
private func addButtonsToView(container: UIView) {
var buttonWidth = container.bounds.size.width / 2
var leftButtonFrame = CGRect(
x: 0,
y: container.bounds.size.height - kDatePickerDialogDefaultButtonHeight,
width: buttonWidth,
height: kDatePickerDialogDefaultButtonHeight
)
var rightButtonFrame = CGRect(
x: buttonWidth,
y: container.bounds.size.height - kDatePickerDialogDefaultButtonHeight,
width: buttonWidth,
height: kDatePickerDialogDefaultButtonHeight
)
if showCancelButton == false {
buttonWidth = container.bounds.size.width
leftButtonFrame = CGRect()
rightButtonFrame = CGRect(
x: 0,
y: container.bounds.size.height - kDatePickerDialogDefaultButtonHeight,
width: buttonWidth,
height: kDatePickerDialogDefaultButtonHeight
)
}
let interfaceLayoutDirection = UIApplication.shared.userInterfaceLayoutDirection
let isLeftToRightDirection = interfaceLayoutDirection == .leftToRight
if showCancelButton {
self.cancelButton = UIButton(type: .custom) as UIButton
self.cancelButton.frame = isLeftToRightDirection ? leftButtonFrame : rightButtonFrame
self.cancelButton.setTitleColor(UIColor.lightGray, for: .normal)
self.cancelButton.setTitleColor(UIColor.lightGray, for: .highlighted)
self.cancelButton.titleLabel!.font = self.font.withSize(14)
self.cancelButton.layer.cornerRadius = kDatePickerDialogCornerRadius
self.cancelButton.addTarget(self, action: .buttonTapped, for: .touchUpInside)
container.addSubview(self.cancelButton)
}
self.doneButton = UIButton(type: .custom) as UIButton
self.doneButton.frame = isLeftToRightDirection ? rightButtonFrame : leftButtonFrame
self.doneButton.tag = kDatePickerDialogDoneButtonTag
self.doneButton.setTitleColor(self.buttonColor, for: .normal)
self.doneButton.setTitleColor(self.buttonColor, for: .highlighted)
self.doneButton.titleLabel!.font = self.font.withSize(14)
self.doneButton.layer.cornerRadius = kDatePickerDialogCornerRadius
self.doneButton.addTarget(self, action: .buttonTapped, for: .touchUpInside)
container.addSubview(self.doneButton)
}
@objc func buttonTapped(sender: UIButton!) {
if sender.tag == kDatePickerDialogDoneButtonTag {
self.callback?(self.datePicker.date)
} else {
self.callback?(nil)
}
close()
}
// MARK: - Helpers
/// Count and return the screen's size
func countScreenSize() -> CGSize {
let screenWidth = UIScreen.main.bounds.size.width
let screenHeight = UIScreen.main.bounds.size.height
return CGSize(width: screenWidth, height: screenHeight)
}
}
| mit | f8a0a4bcbbadb5384e0541d3901d751f | 45.661818 | 278 | 0.654224 | 5.143086 | false | false | false | false |
danger/danger-swift | Sources/Danger/DangerResults.swift | 1 | 1019 | import Foundation
// MARK: - Violation
/// The result of a warn, message, or fail.
public struct Violation: Encodable {
let message: String
let file: String?
let line: Int?
init(message: String, file: String? = nil, line: Int? = nil) {
self.message = message
self.file = file
self.line = line
}
}
/// Meta information for showing in the text info
public struct Meta: Encodable {
let runtimeName = "Danger Swift"
let runtimeHref = "https://danger.systems/swift"
}
// MARK: - Results
/// The representation of what running a Dangerfile generates.
struct DangerResults: Encodable {
/// Failed messages.
var fails = [Violation]()
/// Messages for info.
var warnings = [Violation]()
/// A set of messages to show inline.
var messages = [Violation]()
/// Markdown messages to attach at the bottom of the comment.
var markdowns = [Violation]()
/// Information to pass back to Danger JS about the runtime
let meta = Meta()
}
| mit | 0cd1ce294b93a6d8649dcf9df03aed9b | 23.261905 | 66 | 0.647694 | 4.159184 | false | false | false | false |
Constructor-io/constructorio-client-swift | AutocompleteClient/FW/Logic/Result/CIOResult.swift | 1 | 2354 | //
// CIOResult.swift
// AutocompleteClient
//
// Copyright © Constructor.io. All rights reserved.
// http://constructor.io/
//
import Foundation
/**
Struct encapsulating a result with associated metadata and variations
*/
@objc
public class CIOResult: NSObject {
/**
The value (or name) of the result
*/
public let value: String
/**
Additional data about the result
*/
public let data: CIOResultData
/**
Terms associated with the result that was matched on
*/
public let matchedTerms: [String]
/**
Variations for the result
*/
public let variations: [CIOResult]
/**
Variations map for the result
*/
public let variationsMap: Any
/**
Additional metadata
*/
public let json: JSONObject
/**
The underlying recommendations strategy for the result (only applies to recommendations)
*/
public let strategy: CIORecommendationsStrategy
/**
Labels associated with the result item
*/
public let labels: [String: Bool]
/**
Create a result object
- Parameters:
- json: JSON data from the server response
*/
public init?(json: JSONObject) {
guard let dataObj = json["data"] as? JSONObject else { return nil }
guard let value = json["value"] as? String else { return nil }
guard let data = CIOResultData(json: dataObj) else { return nil }
let matchedTerms = (json["matched_terms"] as? [String]) ?? [String]()
let variationsObj = json["variations"] as? [JSONObject]
let variations: [CIOResult] = variationsObj?.compactMap { obj in return CIOResult(json: obj) } ?? []
let variationsMap = json["variations_map"] as Any
let strategyData = json["strategy"] as? JSONObject ?? [String: Any]()
let labels = json["labels"] as? [String: Bool] ?? [:]
let strategy = CIORecommendationsStrategy(json: strategyData)!
self.value = value
self.data = data
self.matchedTerms = matchedTerms
self.variations = variations
self.json = json
self.strategy = strategy
self.variationsMap = variationsMap
self.labels = labels
}
}
extension CIOResult: Identifiable {
public var id: String {
return data.id ?? "variation"
}
}
| mit | 5833514b7f2b1c72cf4c3039a4360f52 | 23.768421 | 108 | 0.622184 | 4.533719 | false | false | false | false |
OlegKetrar/NumberPad | Sources/NumberPad.swift | 1 | 6226 | //
// NumberPad.swift
// NumberPad
//
// Created by Oleg Ketrar on 27.11.16.
// Copyright © 2016 Oleg Ketrar. All rights reserved.
//
import UIKit
/// Number keyboard with Return button.
/// Can be configured with custom styles.
/// Can have plus (+) or dot (.) as optional button.
public final class NumberPad: UIInputView, Reusable {
/// Uses default style.
private struct DefaultStyle: KeyboardStyle {}
// MARK:
private let visualEffectView: UIVisualEffectView = {
return UIVisualEffectView(frame: CGRect.zero)
}()
private var onTextInputClosure: (String) -> Void = { _ in }
private var onBackspaceClosure: () -> Void = {}
private var onActionClosure: () -> Void = {}
private let optionalKey: Key.Optional?
// MARK: Outlets
@IBOutlet private weak var contentView: UIView!
@IBOutlet private weak var zeroButton: UIButton!
@IBOutlet private weak var optionalButton: UIButton!
@IBOutlet private weak var actionButton: UIButton!
@IBOutlet private var digitButtons: [UIButton]!
@IBOutlet private weak var backspaceButton: LongPressButton!
// MARK: Init
override public init(frame: CGRect, inputViewStyle: UIInputViewStyle) {
optionalKey = nil
super.init(frame: frame, inputViewStyle: inputViewStyle)
replaceWithNib()
defaultConfiguring()
}
required public init?(coder aDecoder: NSCoder) {
optionalKey = nil
super.init(coder: aDecoder)
replaceWithNib()
defaultConfiguring()
}
/// Creates keyboard without optional key.
public convenience init() {
self.init(optionalKey: nil)
}
/// Main initializer.
/// - parameter optionalKey: pass `nil` if you do not need optional button.
public init(optionalKey: Key.Optional?) {
self.optionalKey = optionalKey
super.init(frame: .zero, inputViewStyle: .keyboard)
replaceWithNib()
defaultConfiguring()
autoresizingMask = [.flexibleWidth, .flexibleHeight]
}
private func defaultConfiguring() {
// adjust actionButton title font size
actionButton.titleLabel?.numberOfLines = 1
actionButton.titleLabel?.adjustsFontSizeToFitWidth = true
actionButton.titleLabel?.minimumScaleFactor = 0.5
actionButton.titleLabel?.lineBreakMode = .byClipping
// configure additional buttons
if optionalKey == nil {
optionalButton.removeFromSuperview()
backspaceButton.pinToSuperview(attribute: .right)
}
// observe continius holds
backspaceButton.addAction(forContiniusHoldWith: 0.1) { [weak self] in
self?.didPress(key: .backspace)
}
// apply default style
with(style: DefaultStyle())
}
// MARK: Actions
@IBAction private func digitButtonDidPressed(_ button: UIButton) {
// validate button tag (indexes is same as elements)
guard let buttonDigit = (0..<10).index(of: button.tag - 1) else { return }
didPress(key: .digit(buttonDigit))
}
@IBAction private func optionalButtonDidPressed() {
guard let key = optionalKey else { return }
didPress(key: .optional(key))
}
@IBAction private func actionButtonDidPressed() {
didPress(key: .action)
}
private func didPress(key: Key) {
// inform delegate
switch key {
case .digit(let digit): onTextInputClosure("\(digit)")
case .optional(.plus): onTextInputClosure("+")
case .optional(.dot): onTextInputClosure(".")
case .action: onActionClosure()
case .backspace: onBackspaceClosure()
}
// play click
switch key {
case .digit(_),
.backspace,
.optional: UIDevice.current.playInputClick()
default:
break
}
}
// MARK: Configure
/// Apply custom visual style to keyboard.
/// - parameter style: custom style.
@discardableResult
public func with(style: KeyboardStyle) -> Self {
var buttonsTuple: [(UIButton, Key)] = digitButtons.enumerated().map { ($1, .digit($0)) }
buttonsTuple.append((actionButton, .action))
buttonsTuple.append((backspaceButton, .backspace))
if let optionalKey = optionalKey {
buttonsTuple.append((optionalButton, .optional(optionalKey)))
}
buttonsTuple.forEach { (button, key) in
button.setAttributedTitle(style.attributedTitleFor(key: key, state: .normal), for: .normal)
button.setAttributedTitle(style.attributedTitleFor(key: key, state: .selected), for: .selected)
button.setAttributedTitle(style.attributedTitleFor(key: key, state: .highlighted), for: .highlighted)
button.setImage(style.imageFor(key: key, state: .normal), for: .normal)
button.setImage(style.imageFor(key: key, state: .selected), for: .selected)
button.setImage(style.imageFor(key: key, state: .highlighted), for: .highlighted)
button.setBackgroundImage(style.backgroundImageFor(key: key, state: .normal), for: .normal)
button.setBackgroundImage(style.backgroundImageFor(key: key, state: .selected), for: .selected)
button.setBackgroundImage(style.backgroundImageFor(key: key, state: .highlighted), for: .highlighted)
button.layer.borderWidth = 0.5 * style.separatorThickness
button.layer.borderColor = style.separatorColor.cgColor
}
return self
}
@discardableResult
public func onTextInput(_ closure: @escaping (String) -> Void) -> Self {
onTextInputClosure = closure
return self
}
@discardableResult
public func onBackspace(_ closure: @escaping () -> Void) -> Self {
onBackspaceClosure = closure
return self
}
@discardableResult
public func onReturn(_ closure: @escaping () -> Void) -> Self {
onActionClosure = closure
return self
}
}
extension NumberPad: UIInputViewAudioFeedback {
public var enableInputClicksWhenVisible: Bool { return true }
}
| mit | b10a7ab6ad7e7c13fa243bced7b1a68d | 31.591623 | 113 | 0.639036 | 4.741051 | false | false | false | false |
Cezar2005/SuperChat | SuperChat/UtilityClasses.swift | 1 | 974 | import Foundation
//The service provides utility methods.
class UtilityClasses {
//The function convers a string value in format '{key: value}' to json object. The json object is a Dictionary type.
func convertStringToDictionary(text: String) -> [String:AnyObject]? {
if let data = text.dataUsingEncoding(NSUTF8StringEncoding) {
var error: NSError?
let json = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.allZeros, error: &error) as? [String:AnyObject]
if error != nil {
println(error)
}
return json
}
return nil
}
//The function checks the string for invalid characters.
func containsOnlyLetters(input: String) -> Bool {
for chr in input {
if (!(chr >= "a" && chr <= "z") && !(chr >= "A" && chr <= "Z") ) {
return false
}
}
return true
}
} | lgpl-3.0 | c0a6ee01fbeadfda06bed892e6254c17 | 32.62069 | 145 | 0.575975 | 4.682692 | false | false | false | false |
gregomni/swift | SwiftCompilerSources/Sources/SIL/Utils.swift | 3 | 7617 | //===--- Utils.swift - some SIL utilities ---------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import SILBridging
//===----------------------------------------------------------------------===//
// Lists
//===----------------------------------------------------------------------===//
public protocol ListNode : AnyObject {
associatedtype Element
var next: Element? { get }
var previous: Element? { get }
/// The first node in the list. Used to implement `reversed()`.
var _firstInList: Element { get }
/// The last node in the list. Used to implement `reversed()`.
var _lastInList: Element { get }
}
public struct List<NodeType: ListNode> :
CollectionLikeSequence, IteratorProtocol where NodeType.Element == NodeType {
private var currentNode: NodeType?
public init(first: NodeType?) { currentNode = first }
public mutating func next() -> NodeType? {
if let node = currentNode {
currentNode = node.next
return node
}
return nil
}
public var first: NodeType? { currentNode }
public func reversed() -> ReverseList<NodeType> {
if let node = first {
return ReverseList(first: node._lastInList)
}
return ReverseList(first: nil)
}
}
public struct ReverseList<NodeType: ListNode> :
CollectionLikeSequence, IteratorProtocol where NodeType.Element == NodeType {
private var currentNode: NodeType?
public init(first: NodeType?) { currentNode = first }
public mutating func next() -> NodeType? {
if let node = currentNode {
currentNode = node.previous
return node
}
return nil
}
public var first: NodeType? { currentNode }
public func reversed() -> ReverseList<NodeType> {
if let node = first {
return ReverseList(first: node._firstInList)
}
return ReverseList(first: nil)
}
}
//===----------------------------------------------------------------------===//
// Sequence Utilities
//===----------------------------------------------------------------------===//
/// Types conforming to `HasName` will be displayed by their name (instead of the
/// full object) in collection descriptions.
///
/// This is useful to make collections, e.g. of BasicBlocks or Functions, readable.
public protocol HasName {
var name: String { get }
}
private struct CustomMirrorChild : CustomStringConvertible, CustomReflectable {
public var description: String
public var customMirror: Mirror { Mirror(self, children: []) }
public init(description: String) { self.description = description }
}
/// Makes a Sequence's `description` and `customMirror` formatted like Array, e.g. [a, b, c].
public protocol FormattedLikeArray : Sequence, CustomStringConvertible, CustomReflectable {
}
extension FormattedLikeArray {
/// Display a Sequence in an array like format, e.g. [a, b, c]
public var description: String {
"[" + map {
if let named = $0 as? HasName {
return named.name
}
return String(describing: $0)
}.joined(separator: ", ") + "]"
}
/// The mirror which adds the children of a Sequence, similar to `Array`.
public var customMirror: Mirror {
// If the one-line description is not too large, print that instead of the
// children in separate lines.
if description.count <= 80 {
return Mirror(self, children: [])
}
let c: [Mirror.Child] = map {
let val: Any
if let named = $0 as? HasName {
val = CustomMirrorChild(description: named.name)
} else {
val = $0
}
return (label: nil, value: val)
}
return Mirror(self, children: c, displayStyle: .collection)
}
}
/// A Sequence which is not consuming and therefore behaves like a Collection.
///
/// Many sequences in SIL and the optimizer should be collections but cannot
/// because their Index cannot conform to Comparable. Those sequences conform
/// to CollectionLikeSequence.
///
/// For convenience it also inherits from FormattedLikeArray.
public protocol CollectionLikeSequence : FormattedLikeArray {
}
public extension CollectionLikeSequence {
var isEmpty: Bool { !contains(where: { _ in true }) }
}
// Also make the lazy sequences a CollectionLikeSequence if the underlying sequence is one.
extension LazySequence : CollectionLikeSequence,
FormattedLikeArray, CustomStringConvertible, CustomReflectable
where Base: CollectionLikeSequence {}
extension FlattenSequence : CollectionLikeSequence,
FormattedLikeArray, CustomStringConvertible, CustomReflectable
where Base: CollectionLikeSequence {}
extension LazyMapSequence : CollectionLikeSequence,
FormattedLikeArray, CustomStringConvertible, CustomReflectable
where Base: CollectionLikeSequence {}
extension LazyFilterSequence : CollectionLikeSequence,
FormattedLikeArray, CustomStringConvertible, CustomReflectable
where Base: CollectionLikeSequence {}
//===----------------------------------------------------------------------===//
// String parsing
//===----------------------------------------------------------------------===//
public struct StringParser {
private var s: Substring
private let originalLength: Int
private mutating func consumeWhitespace() {
s = s.drop { $0.isWhitespace }
}
public init(_ string: String) {
s = Substring(string)
originalLength = string.count
}
mutating func isEmpty() -> Bool {
consumeWhitespace()
return s.isEmpty
}
public mutating func consume(_ str: String) -> Bool {
consumeWhitespace()
if !s.starts(with: str) { return false }
s = s.dropFirst(str.count)
return true
}
public mutating func consumeInt(withWhiteSpace: Bool = true) -> Int? {
if withWhiteSpace {
consumeWhitespace()
}
var intStr = ""
s = s.drop {
if $0.isNumber {
intStr.append($0)
return true
}
return false
}
return Int(intStr)
}
public mutating func consumeIdentifier() -> String? {
consumeWhitespace()
var name = ""
s = s.drop {
if $0.isLetter {
name.append($0)
return true
}
return false
}
return name.isEmpty ? nil : name
}
public func throwError(_ message: StaticString) throws -> Never {
throw ParsingError(message: message, position: originalLength - s.count)
}
}
public struct ParsingError : Error {
public let message: StaticString
public let position: Int
}
//===----------------------------------------------------------------------===//
// Bridging Utilities
//===----------------------------------------------------------------------===//
extension Array where Element == Value {
public func withBridgedValues<T>(_ c: (BridgedValueArray) -> T) -> T {
return self.withUnsafeBytes { valPtr in
assert(valPtr.count == self.count * 16)
return c(BridgedValueArray(data: valPtr.baseAddress, count: self.count))
}
}
}
| apache-2.0 | 0f19e64f0d20c21f908b824fba9e2fa0 | 30.089796 | 93 | 0.591309 | 5.047714 | false | false | false | false |
sami4064/UpdatedIOSRTCPlugin | src/PluginRTCPeerConnection.swift | 2 | 16163 | import Foundation
class PluginRTCPeerConnection : NSObject, RTCPeerConnectionDelegate, RTCSessionDescriptionDelegate {
var rtcPeerConnectionFactory: RTCPeerConnectionFactory
var rtcPeerConnection: RTCPeerConnection!
var pluginRTCPeerConnectionConfig: PluginRTCPeerConnectionConfig
var pluginRTCPeerConnectionConstraints: PluginRTCPeerConnectionConstraints
// PluginRTCDataChannel dictionary.
var pluginRTCDataChannels: [Int : PluginRTCDataChannel] = [:]
var eventListener: (data: NSDictionary) -> Void
var eventListenerForAddStream: (pluginMediaStream: PluginMediaStream) -> Void
var eventListenerForRemoveStream: (id: String) -> Void
var onCreateDescriptionSuccessCallback: ((rtcSessionDescription: RTCSessionDescription) -> Void)!
var onCreateDescriptionFailureCallback: ((error: NSError) -> Void)!
var onSetDescriptionSuccessCallback: (() -> Void)!
var onSetDescriptionFailureCallback: ((error: NSError) -> Void)!
init(
rtcPeerConnectionFactory: RTCPeerConnectionFactory,
pcConfig: NSDictionary?,
pcConstraints: NSDictionary?,
eventListener: (data: NSDictionary) -> Void,
eventListenerForAddStream: (pluginMediaStream: PluginMediaStream) -> Void,
eventListenerForRemoveStream: (id: String) -> Void
) {
NSLog("PluginRTCPeerConnection#init()")
self.rtcPeerConnectionFactory = rtcPeerConnectionFactory
self.pluginRTCPeerConnectionConfig = PluginRTCPeerConnectionConfig(pcConfig: pcConfig)
self.pluginRTCPeerConnectionConstraints = PluginRTCPeerConnectionConstraints(pcConstraints: pcConstraints)
self.eventListener = eventListener
self.eventListenerForAddStream = eventListenerForAddStream
self.eventListenerForRemoveStream = eventListenerForRemoveStream
}
func run() {
NSLog("PluginRTCPeerConnection#run()")
self.rtcPeerConnection = self.rtcPeerConnectionFactory.peerConnectionWithICEServers(
self.pluginRTCPeerConnectionConfig.getIceServers(),
constraints: self.pluginRTCPeerConnectionConstraints.getConstraints(),
delegate: self
)
}
func createOffer(
options: NSDictionary?,
callback: (data: NSDictionary) -> Void,
errback: (error: NSError) -> Void
) {
NSLog("PluginRTCPeerConnection#createOffer()")
if self.rtcPeerConnection.signalingState.rawValue == RTCSignalingClosed.rawValue {
return
}
let pluginRTCPeerConnectionConstraints = PluginRTCPeerConnectionConstraints(pcConstraints: options)
self.onCreateDescriptionSuccessCallback = { (rtcSessionDescription: RTCSessionDescription) -> Void in
NSLog("PluginRTCPeerConnection#createOffer() | success callback [type:\(rtcSessionDescription.type)]")
let data = [
"type": rtcSessionDescription.type,
"sdp": rtcSessionDescription.description
]
callback(data: data)
}
self.onCreateDescriptionFailureCallback = { (error: NSError) -> Void in
NSLog("PluginRTCPeerConnection#createOffer() | failure callback: \(error)")
errback(error: error)
}
self.rtcPeerConnection.createOfferWithDelegate(self,
constraints: pluginRTCPeerConnectionConstraints.getConstraints())
}
func createAnswer(
options: NSDictionary?,
callback: (data: NSDictionary) -> Void,
errback: (error: NSError) -> Void
) {
NSLog("PluginRTCPeerConnection#createAnswer()")
if self.rtcPeerConnection.signalingState.rawValue == RTCSignalingClosed.rawValue {
return
}
let pluginRTCPeerConnectionConstraints = PluginRTCPeerConnectionConstraints(pcConstraints: options)
self.onCreateDescriptionSuccessCallback = { (rtcSessionDescription: RTCSessionDescription) -> Void in
NSLog("PluginRTCPeerConnection#createAnswer() | success callback [type:\(rtcSessionDescription.type)]")
let data = [
"type": rtcSessionDescription.type,
"sdp": rtcSessionDescription.description
]
callback(data: data)
}
self.onCreateDescriptionFailureCallback = { (error: NSError) -> Void in
NSLog("PluginRTCPeerConnection#createAnswer() | failure callback: \(error)")
errback(error: error)
}
self.rtcPeerConnection.createAnswerWithDelegate(self,
constraints: pluginRTCPeerConnectionConstraints.getConstraints())
}
func setLocalDescription(
desc: NSDictionary,
callback: (data: NSDictionary) -> Void,
errback: (error: NSError) -> Void
) {
NSLog("PluginRTCPeerConnection#setLocalDescription()")
if self.rtcPeerConnection.signalingState.rawValue == RTCSignalingClosed.rawValue {
return
}
let type = desc.objectForKey("type") as? String ?? ""
let sdp = desc.objectForKey("sdp") as? String ?? ""
let rtcSessionDescription = RTCSessionDescription(type: type, sdp: sdp)
self.onSetDescriptionSuccessCallback = { () -> Void in
NSLog("PluginRTCPeerConnection#setLocalDescription() | success callback")
let data = [
"type": self.rtcPeerConnection.localDescription.type,
"sdp": self.rtcPeerConnection.localDescription.description
]
callback(data: data)
}
self.onSetDescriptionFailureCallback = { (error: NSError) -> Void in
NSLog("PluginRTCPeerConnection#setLocalDescription() | failure callback: \(error)")
errback(error: error)
}
self.rtcPeerConnection.setLocalDescriptionWithDelegate(self,
sessionDescription: rtcSessionDescription
)
}
func setRemoteDescription(
desc: NSDictionary,
callback: (data: NSDictionary) -> Void,
errback: (error: NSError) -> Void
) {
NSLog("PluginRTCPeerConnection#setRemoteDescription()")
if self.rtcPeerConnection.signalingState.rawValue == RTCSignalingClosed.rawValue {
return
}
let type = desc.objectForKey("type") as? String ?? ""
let sdp = desc.objectForKey("sdp") as? String ?? ""
let rtcSessionDescription = RTCSessionDescription(type: type, sdp: sdp)
self.onSetDescriptionSuccessCallback = { () -> Void in
NSLog("PluginRTCPeerConnection#setRemoteDescription() | success callback")
let data = [
"type": self.rtcPeerConnection.remoteDescription.type,
"sdp": self.rtcPeerConnection.remoteDescription.description
]
callback(data: data)
}
self.onSetDescriptionFailureCallback = { (error: NSError) -> Void in
NSLog("PluginRTCPeerConnection#setRemoteDescription() | failure callback: \(error)")
errback(error: error)
}
self.rtcPeerConnection.setRemoteDescriptionWithDelegate(self,
sessionDescription: rtcSessionDescription
)
}
func addIceCandidate(
candidate: NSDictionary,
callback: (data: NSDictionary) -> Void,
errback: () -> Void
) {
NSLog("PluginRTCPeerConnection#addIceCandidate()")
if self.rtcPeerConnection.signalingState.rawValue == RTCSignalingClosed.rawValue {
return
}
let sdpMid = candidate.objectForKey("sdpMid") as? String ?? ""
let sdpMLineIndex = candidate.objectForKey("sdpMLineIndex") as? Int ?? 0
let candidate = candidate.objectForKey("candidate") as? String ?? ""
let result: Bool = self.rtcPeerConnection.addICECandidate(RTCICECandidate(
mid: sdpMid,
index: sdpMLineIndex,
sdp: candidate
))
var data: NSDictionary
if result == true {
if self.rtcPeerConnection.remoteDescription != nil {
data = [
"remoteDescription": [
"type": self.rtcPeerConnection.remoteDescription.type,
"sdp": self.rtcPeerConnection.remoteDescription.description
]
]
} else {
data = [
"remoteDescription": false
]
}
callback(data: data)
} else {
errback()
}
}
func addStream(pluginMediaStream: PluginMediaStream) -> Bool {
NSLog("PluginRTCPeerConnection#addStream()")
if self.rtcPeerConnection.signalingState.rawValue == RTCSignalingClosed.rawValue {
return false
}
return self.rtcPeerConnection.addStream(pluginMediaStream.rtcMediaStream)
}
func removeStream(pluginMediaStream: PluginMediaStream) {
NSLog("PluginRTCPeerConnection#removeStream()")
if self.rtcPeerConnection.signalingState.rawValue == RTCSignalingClosed.rawValue {
return
}
self.rtcPeerConnection.removeStream(pluginMediaStream.rtcMediaStream)
}
func createDataChannel(
dcId: Int,
label: String,
options: NSDictionary?,
eventListener: (data: NSDictionary) -> Void,
eventListenerForBinaryMessage: (data: NSData) -> Void
) {
NSLog("PluginRTCPeerConnection#createDataChannel()")
if self.rtcPeerConnection.signalingState.rawValue == RTCSignalingClosed.rawValue {
return
}
let pluginRTCDataChannel = PluginRTCDataChannel(
rtcPeerConnection: rtcPeerConnection,
label: label,
options: options,
eventListener: eventListener,
eventListenerForBinaryMessage: eventListenerForBinaryMessage
)
// Store the pluginRTCDataChannel into the dictionary.
self.pluginRTCDataChannels[dcId] = pluginRTCDataChannel
// Run it.
pluginRTCDataChannel.run()
}
func RTCDataChannel_setListener(
dcId: Int,
eventListener: (data: NSDictionary) -> Void,
eventListenerForBinaryMessage: (data: NSData) -> Void
) {
NSLog("PluginRTCPeerConnection#RTCDataChannel_setListener()")
let pluginRTCDataChannel = self.pluginRTCDataChannels[dcId]
if pluginRTCDataChannel == nil {
return;
}
// Set the eventListener.
pluginRTCDataChannel!.setListener(eventListener,
eventListenerForBinaryMessage: eventListenerForBinaryMessage
)
}
func close() {
NSLog("PluginRTCPeerConnection#close()")
if self.rtcPeerConnection.signalingState.rawValue == RTCSignalingClosed.rawValue {
return
}
self.rtcPeerConnection.close()
}
func RTCDataChannel_sendString(
dcId: Int,
data: String,
callback: (data: NSDictionary) -> Void
) {
NSLog("PluginRTCPeerConnection#RTCDataChannel_sendString()")
if self.rtcPeerConnection.signalingState.rawValue == RTCSignalingClosed.rawValue {
return
}
let pluginRTCDataChannel = self.pluginRTCDataChannels[dcId]
if pluginRTCDataChannel == nil {
return;
}
pluginRTCDataChannel!.sendString(data, callback: callback)
}
func RTCDataChannel_sendBinary(
dcId: Int,
data: NSData,
callback: (data: NSDictionary) -> Void
) {
NSLog("PluginRTCPeerConnection#RTCDataChannel_sendBinary()")
if self.rtcPeerConnection.signalingState.rawValue == RTCSignalingClosed.rawValue {
return
}
let pluginRTCDataChannel = self.pluginRTCDataChannels[dcId]
if pluginRTCDataChannel == nil {
return;
}
pluginRTCDataChannel!.sendBinary(data, callback: callback)
}
func RTCDataChannel_close(dcId: Int) {
NSLog("PluginRTCPeerConnection#RTCDataChannel_close()")
if self.rtcPeerConnection.signalingState.rawValue == RTCSignalingClosed.rawValue {
return
}
let pluginRTCDataChannel = self.pluginRTCDataChannels[dcId]
if pluginRTCDataChannel == nil {
return;
}
pluginRTCDataChannel!.close()
// Remove the pluginRTCDataChannel from the dictionary.
self.pluginRTCDataChannels[dcId] = nil
}
/**
* Methods inherited from RTCPeerConnectionDelegate.
*/
func peerConnection(peerConnection: RTCPeerConnection!,
signalingStateChanged newState: RTCSignalingState) {
let state_str = PluginRTCTypes.signalingStates[newState.rawValue] as String!
NSLog("PluginRTCPeerConnection | onsignalingstatechange [signalingState:\(state_str)]")
self.eventListener(data: [
"type": "signalingstatechange",
"signalingState": state_str
])
}
func peerConnection(peerConnection: RTCPeerConnection!,
iceGatheringChanged newState: RTCICEGatheringState) {
let state_str = PluginRTCTypes.iceGatheringStates[newState.rawValue] as String!
NSLog("PluginRTCPeerConnection | onicegatheringstatechange [iceGatheringState:\(state_str)]")
self.eventListener(data: [
"type": "icegatheringstatechange",
"iceGatheringState": state_str
])
if self.rtcPeerConnection.signalingState.rawValue == RTCSignalingClosed.rawValue {
return
}
// Emit an empty candidate if iceGatheringState is "complete".
if newState.rawValue == RTCICEGatheringComplete.rawValue && self.rtcPeerConnection.localDescription != nil {
self.eventListener(data: [
"type": "icecandidate",
// NOTE: Cannot set null as value.
"candidate": false,
"localDescription": [
"type": self.rtcPeerConnection.localDescription.type,
"sdp": self.rtcPeerConnection.localDescription.description
]
])
}
}
func peerConnection(peerConnection: RTCPeerConnection!,
gotICECandidate candidate: RTCICECandidate!) {
NSLog("PluginRTCPeerConnection | onicecandidate [sdpMid:\(candidate.sdpMid), sdpMLineIndex:\(candidate.sdpMLineIndex), candidate:\(candidate.sdp)]")
if self.rtcPeerConnection.signalingState.rawValue == RTCSignalingClosed.rawValue {
return
}
self.eventListener(data: [
"type": "icecandidate",
"candidate": [
"sdpMid": candidate.sdpMid,
"sdpMLineIndex": candidate.sdpMLineIndex,
"candidate": candidate.sdp
],
"localDescription": [
"type": self.rtcPeerConnection.localDescription.type,
"sdp": self.rtcPeerConnection.localDescription.description
]
])
}
func peerConnection(peerConnection: RTCPeerConnection!,
iceConnectionChanged newState: RTCICEConnectionState) {
let state_str = PluginRTCTypes.iceConnectionStates[newState.rawValue] as String!
NSLog("PluginRTCPeerConnection | oniceconnectionstatechange [iceConnectionState:\(state_str)]")
self.eventListener(data: [
"type": "iceconnectionstatechange",
"iceConnectionState": state_str
])
}
func peerConnection(rtcPeerConnection: RTCPeerConnection!,
addedStream rtcMediaStream: RTCMediaStream!) {
NSLog("PluginRTCPeerConnection | onaddstream")
let pluginMediaStream = PluginMediaStream(rtcMediaStream: rtcMediaStream)
pluginMediaStream.run()
// Let the plugin store it in its dictionary.
self.eventListenerForAddStream(pluginMediaStream: pluginMediaStream)
// Fire the 'addstream' event so the JS will create a new MediaStream.
self.eventListener(data: [
"type": "addstream",
"stream": pluginMediaStream.getJSON()
])
}
func peerConnection(rtcPeerConnection: RTCPeerConnection!,
removedStream rtcMediaStream: RTCMediaStream!) {
NSLog("PluginRTCPeerConnection | onremovestream")
// Let the plugin remove it from its dictionary.
self.eventListenerForRemoveStream(id: rtcMediaStream.label)
self.eventListener(data: [
"type": "removestream",
"streamId": rtcMediaStream.label // NOTE: No "id" property yet.
])
}
func peerConnectionOnRenegotiationNeeded(peerConnection: RTCPeerConnection!) {
NSLog("PluginRTCPeerConnection | onnegotiationeeded")
self.eventListener(data: [
"type": "negotiationneeded"
])
}
func peerConnection(peerConnection: RTCPeerConnection!,
didOpenDataChannel rtcDataChannel: RTCDataChannel!) {
NSLog("PluginRTCPeerConnection | ondatachannel")
let dcId = PluginUtils.randomInt(10000, max:99999)
let pluginRTCDataChannel = PluginRTCDataChannel(
rtcDataChannel: rtcDataChannel
)
// Store the pluginRTCDataChannel into the dictionary.
self.pluginRTCDataChannels[dcId] = pluginRTCDataChannel
// Run it.
pluginRTCDataChannel.run()
// Fire the 'datachannel' event so the JS will create a new RTCDataChannel.
self.eventListener(data: [
"type": "datachannel",
"channel": [
"dcId": dcId,
"label": rtcDataChannel.label,
"ordered": rtcDataChannel.isOrdered,
"maxPacketLifeTime": rtcDataChannel.maxRetransmitTime,
"maxRetransmits": rtcDataChannel.maxRetransmits,
"protocol": rtcDataChannel.`protocol`,
"negotiated": rtcDataChannel.isNegotiated,
"id": rtcDataChannel.streamId,
"readyState": PluginRTCTypes.dataChannelStates[rtcDataChannel.state.rawValue] as String!,
"bufferedAmount": rtcDataChannel.bufferedAmount
]
])
}
/**
* Methods inherited from RTCSessionDescriptionDelegate.
*/
func peerConnection(rtcPeerConnection: RTCPeerConnection!,
didCreateSessionDescription rtcSessionDescription: RTCSessionDescription!, error: NSError!) {
if error == nil {
self.onCreateDescriptionSuccessCallback(rtcSessionDescription: rtcSessionDescription)
} else {
self.onCreateDescriptionFailureCallback(error: error)
}
}
func peerConnection(peerConnection: RTCPeerConnection!,
didSetSessionDescriptionWithError error: NSError!) {
if error == nil {
self.onSetDescriptionSuccessCallback()
} else {
self.onSetDescriptionFailureCallback(error: error)
}
}
}
| mit | 310cf97ec9f60f683775ca3d87ce8a71 | 27.556537 | 150 | 0.755677 | 3.99481 | false | false | false | false |
wordpress-mobile/WordPress-iOS | WordPress/Classes/Extensions/Colors and Styles/WPStyleGuide+Search.swift | 1 | 3473 | import Foundation
import WordPressShared
import UIKit
extension WPStyleGuide {
fileprivate static let barTintColor: UIColor = .neutral(.shade10)
public class func configureSearchBar(_ searchBar: UISearchBar, backgroundColor: UIColor, returnKeyType: UIReturnKeyType) {
searchBar.accessibilityIdentifier = "Search"
searchBar.autocapitalizationType = .none
searchBar.autocorrectionType = .no
searchBar.isTranslucent = true
searchBar.backgroundImage = UIImage()
searchBar.backgroundColor = backgroundColor
searchBar.layer.borderWidth = 1.0
searchBar.returnKeyType = returnKeyType
}
/// configures a search bar with a default `.appBackground` color and a `.done` return key
@objc public class func configureSearchBar(_ searchBar: UISearchBar) {
configureSearchBar(searchBar, backgroundColor: .appBarBackground, returnKeyType: .done)
}
@objc public class func configureSearchBarAppearance() {
configureSearchBarTextAppearance()
// Cancel button
let barButtonItemAppearance = UIBarButtonItem.appearance(whenContainedInInstancesOf: [UISearchBar.self])
barButtonItemAppearance.tintColor = .neutral(.shade70)
let iconSizes = CGSize(width: 20, height: 20)
// We have to manually tint these images, as we want them
// a different color from the search bar's cursor (which uses `tintColor`)
let clearImage = UIImage.gridicon(.crossCircle, size: iconSizes).withTintColor(.searchFieldIcons).withRenderingMode(.alwaysOriginal)
let searchImage = UIImage.gridicon(.search, size: iconSizes).withTintColor(.searchFieldIcons).withRenderingMode(.alwaysOriginal)
UISearchBar.appearance().setImage(clearImage, for: .clear, state: UIControl.State())
UISearchBar.appearance().setImage(searchImage, for: .search, state: UIControl.State())
}
@objc public class func configureSearchBarTextAppearance() {
// Cancel button
let barButtonTitleAttributes: [NSAttributedString.Key: Any] = [.font: WPStyleGuide.fixedFont(for: .headline),
.foregroundColor: UIColor.neutral(.shade70)]
let barButtonItemAppearance = UIBarButtonItem.appearance(whenContainedInInstancesOf: [UISearchBar.self])
barButtonItemAppearance.setTitleTextAttributes(barButtonTitleAttributes, for: UIControl.State())
// Text field
let placeholderText = NSLocalizedString("Search", comment: "Placeholder text for the search bar")
let attributedPlaceholderText = NSAttributedString(string: placeholderText,
attributes: WPStyleGuide.defaultSearchBarTextAttributesSwifted(.searchFieldPlaceholderText))
UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).attributedPlaceholder =
attributedPlaceholderText
}
}
extension UISearchBar {
// Per Apple's documentation (https://developer.apple.com/documentation/xcode/supporting_dark_mode_in_your_interface),
// `cgColor` objects do not adapt to appearance changes (i.e. toggling light/dark mode).
// `tintColorDidChange` is called when the appearance changes, so re-set the border color when this occurs.
open override func tintColorDidChange() {
super.tintColorDidChange()
layer.borderColor = UIColor.appBarBackground.cgColor
}
}
| gpl-2.0 | dcff72bc956b4e09e14101d439e069ea | 52.430769 | 151 | 0.713792 | 5.702791 | false | true | false | false |
felipebv/AssetsAnalyser | Project/AssetsAnalyser/FileHelper.swift | 1 | 1373 | //
// FileHelper.swift
// AssetsAnalyser
//
// Created by Felipe Braunger Valio on 16/05/17.
// Copyright © 2017 Movile. All rights reserved.
//
import Cocoa
class FileHelper: NSObject {
func exclude(paths: [String], fromPaths: [String]) -> [String] {
return fromPaths.filter {
return !paths.contains($0)
}
}
func sourceCodesAt(projectPath: String) -> [String] {
return filepathsEndingWith(".swift", inPath: projectPath)
}
func interfaceFilesAt(projectPath: String) -> [String] {
return filepathsEndingWith(".swift", inPath: projectPath)
}
func filepathsEndingWith(_ suffix: String, inPath path: String) -> [String] {
guard let enumerator = FileManager().enumerator(atPath: path) else {
return []
}
var filepaths: [String] = []
for item in enumerator {
if let item = item as? String, item.hasSuffix(suffix) {
filepaths.append("\(path)/\(item)")
}
}
return filepaths
}
func openFileAt(_ path: String) -> String? {
let url = URL(fileURLWithPath: path)
guard let data = try? Data(contentsOf: url), let str = String(data: data, encoding: .utf8) else {
return nil
}
return str
}
}
| mit | 55553daceb61c37e446d61c102b8d22c | 25.384615 | 105 | 0.561953 | 4.2875 | false | false | false | false |
aschwaighofer/swift | test/IDE/complete_stmt_controlling_expr.swift | 2 | 27603 | // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=COND_GUARD_1 | %FileCheck %s -check-prefix=COND-WITH-RELATION
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=COND_IF_1 | %FileCheck %s -check-prefix=COND-WITH-RELATION
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=COND_IF_2 | %FileCheck %s -check-prefix=COND-WITH-RELATION
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=COND_IF_2B | %FileCheck %s -check-prefix=COND-WITH-RELATION
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=COND_IF_3 | %FileCheck %s -check-prefix=COND_COMMON
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=COND_IF_4 | %FileCheck %s -check-prefix=COND_COMMON
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=COND_IF_ELSE_IF_1 | %FileCheck %s -check-prefix=COND-WITH-RELATION
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=COND_IF_ELSE_IF_2 | %FileCheck %s -check-prefix=COND-WITH-RELATION
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=COND_IF_ELSE_IF_3 | %FileCheck %s -check-prefix=COND-WITH-RELATION
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=COND_IF_ELSE_IF_4 | %FileCheck %s -check-prefix=COND-WITH-RELATION
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=COND_IF_ELSE_IF_5 | %FileCheck %s -check-prefix=COND_COMMON
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=COND_IF_ELSE_IF_6 | %FileCheck %s -check-prefix=COND_COMMON
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=COND_WHILE_1 | %FileCheck %s -check-prefix=COND-WITH-RELATION
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=COND_WHILE_2 | %FileCheck %s -check-prefix=COND-WITH-RELATION
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=COND_WHILE_2B | %FileCheck %s -check-prefix=COND-WITH-RELATION
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=COND_WHILE_3 | %FileCheck %s -check-prefix=COND_COMMON
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=COND_WHILE_4 | %FileCheck %s -check-prefix=COND_COMMON
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=COND_DO_WHILE_1 | %FileCheck %s -check-prefix=COND-WITH-RELATION
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=COND_DO_WHILE_2 | %FileCheck %s -check-prefix=COND-WITH-RELATION1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=C_STYLE_FOR_INIT_1 | %FileCheck %s -check-prefix=COND_NONE
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=C_STYLE_FOR_INIT_2 | %FileCheck %s -check-prefix=COND_COMMON
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=C_STYLE_FOR_INIT_3 | %FileCheck %s -check-prefix=COND_COMMON
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=C_STYLE_FOR_COND_1 | %FileCheck %s -check-prefix=COND_COMMON
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=C_STYLE_FOR_COND_2 | %FileCheck %s -check-prefix=COND_COMMON
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=C_STYLE_FOR_COND_3 | %FileCheck %s -check-prefix=COND_COMMON
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=C_STYLE_FOR_COND_I_1 | %FileCheck %s -check-prefix=COND_COMMON
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=C_STYLE_FOR_COND_I_2 | %FileCheck %s -check-prefix=COND_COMMON
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=C_STYLE_FOR_COND_I_E_1 | %FileCheck %s -check-prefix=COND_COMMON
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=C_STYLE_FOR_INCR_1 | %FileCheck %s -check-prefix=COND_COMMON
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=C_STYLE_FOR_INCR_2 | %FileCheck %s -check-prefix=COND_COMMON
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=C_STYLE_FOR_INCR_I_1 | %FileCheck %s -check-prefix=COND_COMMON
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=C_STYLE_FOR_INCR_I_2 | %FileCheck %s -check-prefix=COND_COMMON
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=C_STYLE_FOR_INCR_I_3 | %FileCheck %s -check-prefix=COND_COMMON
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=C_STYLE_FOR_INCR_I_4 | %FileCheck %s -check-prefix=COND_COMMON
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=C_STYLE_FOR_INCR_I_E_1 | %FileCheck %s -check-prefix=COND_COMMON
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=C_STYLE_FOR_BODY_I_1 > %t.body.txt
// RUN: %FileCheck %s -check-prefix=COND_COMMON < %t.body.txt
// RUN: %FileCheck %s -check-prefix=WITH_I_ERROR_LOCAL < %t.body.txt
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=C_STYLE_FOR_BODY_I_2 > %t.body.txt
// RUN: %FileCheck %s -check-prefix=COND_COMMON < %t.body.txt
// RUN: %FileCheck %s -check-prefix=WITH_I_ERROR_LOCAL < %t.body.txt
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=C_STYLE_FOR_BODY_I_3 > %t.body.txt
// RUN: %FileCheck %s -check-prefix=COND_COMMON < %t.body.txt
// RUN: %FileCheck %s -check-prefix=WITH_I_ERROR_LOCAL < %t.body.txt
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=C_STYLE_FOR_BODY_I_4 > %t.body.txt
// RUN: %FileCheck %s -check-prefix=COND_COMMON < %t.body.txt
// RUN: %FileCheck %s -check-prefix=WITH_I_ERROR_LOCAL < %t.body.txt
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=C_STYLE_FOR_BODY_I_5 > %t.body.txt
// RUN: %FileCheck %s -check-prefix=COND_COMMON < %t.body.txt
// RUN: %FileCheck %s -check-prefix=WITH_I_ERROR_LOCAL < %t.body.txt
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=C_STYLE_FOR_BODY_I_6 > %t.body.txt
// RUN: %FileCheck %s -check-prefix=COND_COMMON < %t.body.txt
// RUN: %FileCheck %s -check-prefix=WITH_I_ERROR_LOCAL < %t.body.txt
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FOR_EACH_EXPR_1 | %FileCheck %s -check-prefix=COND_COMMON
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FOR_EACH_EXPR_2 | %FileCheck %s -check-prefix=COND_COMMON
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=SWITCH_EXPR_1 | %FileCheck %s -check-prefix=COND_COMMON
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=SWITCH_EXPR_2 | %FileCheck %s -check-prefix=COND_COMMON
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=SWITCH_CASE_WHERE_EXPR_1 | %FileCheck %s -check-prefix=COND_COMMON
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=SWITCH_CASE_WHERE_EXPR_2 | %FileCheck %s -check-prefix=COND_COMMON
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=SWITCH_CASE_WHERE_EXPR_3 | %FileCheck %s -check-prefix=COND_COMMON
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=SWITCH_CASE_WHERE_EXPR_I_1 > %t.where.txt
// RUN: %FileCheck %s -check-prefix=COND_COMMON < %t.where.txt
// RUN: %FileCheck %s -check-prefix=WITH_I_INT_LOCAL < %t.where.txt
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=SWITCH_CASE_WHERE_EXPR_I_2 > %t.where.txt
// RUN: %FileCheck %s -check-prefix=COND_COMMON < %t.where.txt
// RUN: %FileCheck %s -check-prefix=WITH_I_INT_LOCAL < %t.where.txt
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=SWITCH_CASE_WHERE_EXPR_I_J_1 > %t.where.txt
// RUN: %FileCheck %s -check-prefix=COND_COMMON < %t.where.txt
// RUN: %FileCheck %s -check-prefix=WITH_I_INT_LOCAL < %t.where.txt
// RUN: %FileCheck %s -check-prefix=WITH_J_INT < %t.where.txt
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=UNRESOLVED_IF_1 | %FileCheck %s -check-prefix=UNRESOLVED_B
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=UNRESOLVED_IF_2 | %FileCheck %s -check-prefix=UNRESOLVED_B
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=UNRESOLVED_IF_3 | %FileCheck %s -check-prefix=UNRESOLVED_B
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=UNRESOLVED_IF_4 | %FileCheck %s -check-prefix=UNRESOLVED_B
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=UNRESOLVED_WHILE_1 | %FileCheck %s -check-prefix=UNRESOLVED_B
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=UNRESOLVED_WHILE_2 | %FileCheck %s -check-prefix=UNRESOLVED_B
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=UNRESOLVED_WHILE_3 | %FileCheck %s -check-prefix=UNRESOLVED_B
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=UNRESOLVED_WHILE_4 | %FileCheck %s -check-prefix=UNRESOLVED_B
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=UNRESOLVED_GUARD_1 | %FileCheck %s -check-prefix=UNRESOLVED_B
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=UNRESOLVED_GUARD_2 | %FileCheck %s -check-prefix=UNRESOLVED_B
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=UNRESOLVED_GUARD_3 | %FileCheck %s -check-prefix=UNRESOLVED_B
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=UNRESOLVED_GUARD_4 | %FileCheck %s -check-prefix=UNRESOLVED_B
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=UNRESOLVED_GUARD_5 | %FileCheck %s -check-prefix=UNRESOLVED_B
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=UNRESOLVED_GUARD_6 | %FileCheck %s -check-prefix=UNRESOLVED_B
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=UNRESOLVED_GUARD_7 | %FileCheck %s -check-prefix=UNRESOLVED_B
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IF_LET_BIND_1 | %FileCheck %s -check-prefix=FOOSTRUCT_DOT_BOOL
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IF_LET_BIND_2 | %FileCheck %s -check-prefix=FOOSTRUCT_DOT_BOOL
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IF_LET_BIND_3 | %FileCheck %s -check-prefix=FOOSTRUCT_DOT
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IF_LET_BIND_4 | %FileCheck %s -check-prefix=FOOSTRUCT_NODOT
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=GUARD_LET_BIND_1 | %FileCheck %s -check-prefix=FOOSTRUCT_DOT_BOOL
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=GUARD_LET_BIND_2 | %FileCheck %s -check-prefix=FOOSTRUCT_DOT_BOOL
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=GUARD_LET_BIND_3 | %FileCheck %s -check-prefix=FOOSTRUCT_DOT_BOOL
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=GUARD_LET_BIND_4 | %FileCheck %s -check-prefix=FOOSTRUCT_DOT_BOOL
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=GUARD_LET_BIND_5 | %FileCheck %s -check-prefix=FOOSTRUCT_DOT
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=GUARD_LET_BIND_6 | %FileCheck %s -check-prefix=FOOSTRUCT_NODOT
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=GUARD_LET_BIND_7 | %FileCheck %s -check-prefix=FOOSTRUCT_LOCALVAL
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=GUARD_LET_BIND_8 | %FileCheck %s -check-prefix=FOOSTRUCT_LOCALVAL
struct FooStruct {
var instanceVar : Int
init(_: Int = 0) { }
func boolGen() -> Bool { return false }
func intGen() -> Int { return 1 }
}
func testGuard1(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
guard #^COND_GUARD_1^#
}
func testIf1(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
if #^COND_IF_1^#
}
func testIf2(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
if #^COND_IF_2^# {
}
}
func testIf2b(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
if true, #^COND_IF_2B^# {
}
}
func testIf3(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
if var z = #^COND_IF_3^# {
}
}
func testIf4(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
if var z = #^COND_IF_4^# {
}
}
func testIfElseIf1(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
if true {
} else if #^COND_IF_ELSE_IF_1^#
}
func testIfElseIf2(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
if true {
} else if #^COND_IF_ELSE_IF_2^# {
}
}
func testIfElseIf3(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
if true {
} else if true {
} else if #^COND_IF_ELSE_IF_3^#
}
func testIfElseIf4(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
if true {
} else if true {
} else if #^COND_IF_ELSE_IF_4^# {
}
}
func testIfElseIf5(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
if true {
} else if var z = #^COND_IF_ELSE_IF_5^#
}
func testIfElseIf6(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
if true {
} else if let z = #^COND_IF_ELSE_IF_6^# {
}
}
func testWhile1(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
while #^COND_WHILE_1^#
}
func testWhile2(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
while #^COND_WHILE_2^# {
}
}
func testWhile2b(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
while true, #^COND_WHILE_2B^# {
}
}
func testWhile3(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
while var z = #^COND_WHILE_3^#
}
func testWhile4(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
while let z = #^COND_WHILE_4^#
}
func testRepeatWhile1(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
repeat {
} while #^COND_DO_WHILE_1^#
}
func testRepeatWhile2(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
repeat {
} while localFooObject.#^COND_DO_WHILE_2^#
}
func testCStyleForInit1(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
for #^C_STYLE_FOR_INIT_1^#
}
func testCStyleForInit2(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
for #^C_STYLE_FOR_INIT_2^#;
}
func testCStyleForInit3(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
for #^C_STYLE_FOR_INIT_3^# ;
}
func testCStyleForCond1(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
for ; #^C_STYLE_FOR_COND_1^#
}
func testCStyleForCond2(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
for ; #^C_STYLE_FOR_COND_2^#;
}
func testCStyleForCond3(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
for ; #^C_STYLE_FOR_COND_3^# ;
}
func testCStyleForCondI1(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
for var i = 0; #^C_STYLE_FOR_COND_I_1^#
}
func testCStyleForCondI2(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
for var i = unknown_var; #^C_STYLE_FOR_COND_I_2^#
}
func testCStyleForCondIE1(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
for var i = 0, e = 10; true; #^C_STYLE_FOR_COND_I_E_1^#
}
func testCStyleForIncr1(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
for ; ; #^C_STYLE_FOR_INCR_1^#
}
func testCStyleForIncr2(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
for ; ; #^C_STYLE_FOR_INCR_2^# {
}
}
func testCStyleForIncrI1(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
for var i = 0; true; #^C_STYLE_FOR_INCR_I_1^#
}
func testCStyleForIncrI2(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
for var i = 0; i != 10; #^C_STYLE_FOR_INCR_I_2^#
}
func testCStyleForIncrI3(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
for var i = 0; unknown_var != 10; #^C_STYLE_FOR_INCR_I_3^#
}
func testCStyleForIncrI4(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
for var i = unknown_var; unknown_var != 10; #^C_STYLE_FOR_INCR_I_4^#
}
func testCStyleForIncrIE1(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
for var i = 0, e = 10; true; #^C_STYLE_FOR_INCR_I_E_1^#
}
func testCStyleForBodyI1(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
for var i = 0 {
#^C_STYLE_FOR_BODY_I_1^#
}
}
func testCStyleForBodyI2(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
for var i = 0; {
#^C_STYLE_FOR_BODY_I_2^#
}
}
func testCStyleForBodyI3(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
for var i = unknown_var; {
#^C_STYLE_FOR_BODY_I_3^#
}
}
func testCStyleForBodyI4(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
for var i = 0; ; {
#^C_STYLE_FOR_BODY_I_4^#
}
}
func testCStyleForBodyI5(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
for var i = 0; unknown_var != 10; {
#^C_STYLE_FOR_BODY_I_5^#
}
}
func testCStyleForBodyI6(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
for var i = 0; ; unknown_var++ {
#^C_STYLE_FOR_BODY_I_6^#
}
}
func testForEachExpr1(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
for i in #^FOR_EACH_EXPR_1^#
}
func testForEachExpr2(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
for i in #^FOR_EACH_EXPR_2^# {
}
}
func testSwitchExpr1(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
switch #^SWITCH_EXPR_1^#
}
func testSwitchExpr2(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
switch #^SWITCH_EXPR_2^# {
}
}
func testSwitchCaseWhereExpr1(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
switch (0, 42) {
case (0, 0) where #^SWITCH_CASE_WHERE_EXPR_1^#
}
}
func testSwitchCaseWhereExpr2(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
switch (0, 42) {
case (0, 0) where #^SWITCH_CASE_WHERE_EXPR_2^#:
}
}
func testSwitchCaseWhereExpr3(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
switch (0, 42) {
case (0, 0) where #^SWITCH_CASE_WHERE_EXPR_3^# :
}
}
func testSwitchCaseWhereExprI1(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
switch (0, 42) {
case (var i, 0) where #^SWITCH_CASE_WHERE_EXPR_I_1^#
}
}
func testSwitchCaseWhereExprI2(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
switch (0, 42) {
case (0, var i) where #^SWITCH_CASE_WHERE_EXPR_I_2^#
}
}
func testSwitchCaseWhereExprIJ1(_ fooObject: FooStruct) {
var localInt = 42
var localFooObject = FooStruct(localInt)
switch (0, 42) {
case (var i, var j) where #^SWITCH_CASE_WHERE_EXPR_I_J_1^#
}
}
// COND_NONE-NOT: Begin completions
// COND_NONE-NOT: End completions
// COND_COMMON: Begin completions
// COND_COMMON-DAG: Literal[Boolean]/None: true[#Bool#]{{; name=.+$}}
// COND_COMMON-DAG: Literal[Boolean]/None: false[#Bool#]{{; name=.+$}}
// COND_COMMON-DAG: Decl[LocalVar]/Local: fooObject[#FooStruct#]{{; name=.+$}}
// COND_COMMON-DAG: Decl[LocalVar]/Local: localInt[#Int#]{{; name=.+$}}
// COND_COMMON-DAG: Decl[LocalVar]/Local: localFooObject[#FooStruct#]{{; name=.+$}}
// COND_COMMON-DAG: Decl[Struct]/CurrModule: FooStruct[#FooStruct#]{{; name=.+$}}
// COND_COMMON: End completions
// COND-WITH-RELATION: Begin completions
// COND-WITH-RELATION-DAG: Literal[Boolean]/None/TypeRelation[Identical]: true[#Bool#]{{; name=.+$}}
// COND-WITH-RELATION-DAG: Literal[Boolean]/None/TypeRelation[Identical]: false[#Bool#]{{; name=.+$}}
// COND-WITH-RELATION-DAG: Decl[LocalVar]/Local: fooObject[#FooStruct#]{{; name=.+$}}
// COND-WITH-RELATION-DAG: Decl[LocalVar]/Local: localInt[#Int#]{{; name=.+$}}
// COND-WITH-RELATION-DAG: Decl[LocalVar]/Local: localFooObject[#FooStruct#]{{; name=.+$}}
// COND-WITH-RELATION-DAG: Decl[Struct]/CurrModule: FooStruct[#FooStruct#]{{; name=.+$}}
// COND-WITH-RELATION-DAG: Decl[FreeFunction]/CurrModule/TypeRelation[Invalid]: testIf2({#(fooObject): FooStruct#})[#Void#]{{; name=.+$}}
// COND-WITH-RELATION-DAG: Decl[FreeFunction]/CurrModule/TypeRelation[Invalid]: testWhile3({#(fooObject): FooStruct#})[#Void#]{{; name=.+$}}
// COND-WITH-RELATION-DAG: Decl[FreeFunction]/CurrModule/TypeRelation[Invalid]: testIfElseIf5({#(fooObject): FooStruct#})[#Void#]{{; name=.+$}}
// COND-WITH-RELATION-DAG: Decl[FreeFunction]/CurrModule/TypeRelation[Invalid]: testCStyleForIncrIE1({#(fooObject): FooStruct#})[#Void#]{{; name=.+$}}
// COND-WITH-RELATION1: Begin completions
// COND-WITH-RELATION1-DAG: Decl[InstanceVar]/CurrNominal: instanceVar[#Int#]{{; name=.+$}}
// COND-WITH-RELATION1-DAG: Decl[InstanceMethod]/CurrNominal/TypeRelation[Identical]: boolGen()[#Bool#]{{; name=.+$}}
// COND-WITH-RELATION1-DAG: Decl[InstanceMethod]/CurrNominal: intGen()[#Int#]{{; name=.+$}}
// COND-WITH-RELATION1: End completions
// WITH_I_INT_LOCAL: Decl[LocalVar]/Local: i[#Int#]{{; name=.+$}}
// WITH_I_ERROR_LOCAL: Decl[LocalVar]/Local: i[#<<error type>>#]{{; name=.+$}}
// WITH_J_INT: Decl[LocalVar]/Local: j[#Int#]{{; name=.+$}}
enum A { case aaa }
enum B { case bbb }
// UNRESOLVED_B-NOT: aaa
// UNRESOLVED_B: Decl[EnumElement]/CurrNominal/TypeRelation[Identical]: bbb[#B#]; name=bbb
// UNRESOLVED_B-NOT: aaa
struct AA {
func takeEnum(_: A) {}
}
struct BB {
func takeEnum(_: B) {}
}
func testUnresolvedIF1(x: BB) {
if x.takeEnum(.#^UNRESOLVED_IF_1^#)
}
func testUnresolvedIF2(x: BB) {
if true, x.takeEnum(.#^UNRESOLVED_IF_2^#)
}
func testUnresolvedIF3(x: BB) {
if true, x.takeEnum(.#^UNRESOLVED_IF_3^#) {}
}
func testUnresolvedIF4(x: BB) {
if let x.takeEnum(.#^UNRESOLVED_IF_4^#)
}
func testUnresolvedWhile1(x: BB) {
while x.takeEnum(.#^UNRESOLVED_WHILE_1^#)
}
func testUnresolvedWhile2(x: BB) {
while true, x.takeEnum(.#^UNRESOLVED_WHILE_2^#)
}
func testUnresolvedWhile3(x: BB) {
while let x.takeEnum(.#^UNRESOLVED_WHILE_3^#)
}
func testUnresolvedWhile4(x: BB) {
while true, x.takeEnum(.#^UNRESOLVED_WHILE_4^#) {}
}
func testUnresolvedGuard1(x: BB) {
guard x.takeEnum(.#^UNRESOLVED_GUARD_1^#)
}
func testUnresolvedGuard2(x: BB) {
guard x.takeEnum(.#^UNRESOLVED_GUARD_2^#) {}
}
func testUnresolvedGuard3(x: BB) {
guard x.takeEnum(.#^UNRESOLVED_GUARD_3^#) else
}
func testUnresolvedGuard4(x: BB) {
guard x.takeEnum(.#^UNRESOLVED_GUARD_4^#) else {}
}
func testUnresolvedGuard5(x: BB) {
guard true, x.takeEnum(.#^UNRESOLVED_GUARD_5^#)
}
func testUnresolvedGuard6(x: BB) {
guard let x.takeEnum(.#^UNRESOLVED_GUARD_6^#)
}
func testUnresolvedGuard7(x: BB) {
guard let x.takeEnum(.#^UNRESOLVED_GUARD_7^#) else {}
}
func testIfLetBinding1(x: FooStruct?) {
if let y = x, y.#^IF_LET_BIND_1^# {}
}
func testIfLetBinding2(x: FooStruct?) {
if let y = x, y.#^IF_LET_BIND_2^#
}
func testIfLetBinding3(x: FooStruct?) {
if let y = x, let z = y.#^IF_LET_BIND_3^# {}
}
func testIfLetBinding3(x: FooStruct?) {
if let y = x, let z = y#^IF_LET_BIND_4^# {}
}
func testGuardLetBinding1(x: FooStruct?) {
guard let y = x, y.#^GUARD_LET_BIND_1^# else {}
}
func testGuardLetBinding2(x: FooStruct?) {
guard let y = x, y.#^GUARD_LET_BIND_2^#
}
func testGuardLetBinding3(x: FooStruct?) {
guard let y = x, y.#^GUARD_LET_BIND_3^# else
}
func testGuardLetBinding4(x: FooStruct?) {
guard let y = x, y.#^GUARD_LET_BIND_4^# {}
}
func testGuardLetBinding5(x: FooStruct?) {
guard let y = x, let z = y.#^GUARD_LET_BIND_5^# else {}
}
func testGuardLetBinding5(x: FooStruct?) {
guard let y = x, z = y#^GUARD_LET_BIND_6^# else {}
}
func testGuardLetBinding7(x: FooStruct?) {
guard let boundVal = x, let other = #^GUARD_LET_BIND_7^# else {}
}
func testGuardLetBinding8(_ x: FooStruct?) {
guard let boundVal = x, let other = testGuardLetBinding8(#^GUARD_LET_BIND_8^#) else {}
}
// FOOSTRUCT_DOT: Begin completions
// FOOSTRUCT_DOT-DAG: Decl[InstanceVar]/CurrNominal: instanceVar[#Int#];
// FOOSTRUCT_DOT-DAG: Decl[InstanceMethod]/CurrNominal: boolGen()[#Bool#];
// FOOSTRUCT_DOT-DAG: Decl[InstanceMethod]/CurrNominal: intGen()[#Int#];
// FOOSTRUCT_DOT: End completions
// FOOSTRUCT_DOT_BOOL: Begin completions
// FOOSTRUCT_DOT_BOOL-DAG: Decl[InstanceVar]/CurrNominal: instanceVar[#Int#];
// FOOSTRUCT_DOT_BOOL-DAG: Decl[InstanceMethod]/CurrNominal/TypeRelation[Identical]: boolGen()[#Bool#];
// FOOSTRUCT_DOT_BOOL-DAG: Decl[InstanceMethod]/CurrNominal: intGen()[#Int#];
// FOOSTRUCT_DOT_BOOL: End completions
// FOOSTRUCT_NODOT: Begin completions
// FOOSTRUCT_NODOT-DAG: Decl[InstanceVar]/CurrNominal: .instanceVar[#Int#];
// FOOSTRUCT_NODOT-DAG: Decl[InstanceMethod]/CurrNominal: .boolGen()[#Bool#];
// FOOSTRUCT_NODOT-DAG: Decl[InstanceMethod]/CurrNominal: .intGen()[#Int#];
// FOOSTRUCT_NODOT: End completions
// FOOSTRUCT_LOCALVAL: Begin completions
// FOOSTRUCT_LOCALVAL-DAG: Decl[LocalVar]/Local{{(/TypeRelation\[Convertible\])?}}: boundVal[#FooStruct#];
// FOOSTRUCT_LOCALVAL: End completions
| apache-2.0 | 7992f4233d6ef76564e909577f1e65b1 | 42.33281 | 157 | 0.709923 | 3.194052 | false | true | false | false |
Alienson/Bc | source-code/Parketovanie/ParquetDuo.swift | 1 | 1814 | //
// ParquetDuo.swift
// Parketovanie
//
// Created by Adam Turna on 19.4.2016.
// Copyright © 2016 Adam Turna. All rights reserved.
//
import Foundation
import SpriteKit
class ParquetDuo: Parquet {
init(parent: SKSpriteNode, position: CGPoint){
super.init(imageNamed: "2-duo", position: position)
let abstractCell = Cell()
let height = abstractCell.frame.height
// self.arrayOfCells.append(Cell(position: CGPoint(x: self.frame.minX, y: self.frame.maxY-height), parent: parent))
// self.arrayOfCells.append(Cell(position: CGPoint(x: self.frame.minX, y: self.frame.maxY-height*2), parent: parent))
// self.arrayOfCells.append(Cell(position: CGPoint(x: self.frame.minX, y: self.frame.maxY-height*3), parent: parent))
// self.arrayOfCells.append(Cell(position: CGPoint(x: self.frame.minX+height, y: self.frame.maxY-height*3), parent: parent))
self.arrayOfCells.append(Cell(position: CGPoint(x: 0, y: -height/2), parent: parent))
self.arrayOfCells.append(Cell(position: CGPoint(x: 0, y: height/2), parent: parent))
//let cell1 = Cell(row: 1, collumn: 1, isEmpty: true, parent: parent)
for cell in self.arrayOfCells {
//parent.addChild(cell)
self.addChild(cell)
cell.anchorPoint = CGPoint(x: 0.5, y: 0.5)
cell.alpha = CGFloat(1)
cell.barPosition = cell.position
}
super.alpha = CGFloat(0.5)
//self.arrayOfCells = [[Cell(position: CGPoint(self.frame.),parent: parent), nil],[Cell(parent: parent), nil],[Cell(parent: parent), Cell(parent: parent)]]
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| apache-2.0 | c853fb6d2bfe4882d8d764ee6d611197 | 39.288889 | 163 | 0.626034 | 3.677485 | false | false | false | false |
GenerallyHelpfulSoftware/Scalar2D | Views/Cocoa/Sources/PathView+Mac.swift | 1 | 2895 | //
// PathView+Mac.swift
// Scalar2D
//
// Created by Glenn Howes on 8/17/16.
// Copyright © 2016-2019 Generally Helpful Software. All rights reserved.
//
//
// The MIT License (MIT)
// Copyright (c) 2016-2019 Generally Helpful Software
// 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.
//
//
#if os(OSX)
import Cocoa
import CoreGraphics
import Scalar2D_CoreViews
import Foundation
import Cocoa
@IBDesignable public class PathView: NSView, ShapeView {
public required init?(coder: NSCoder) {
super.init(coder: coder)
self.wantsLayer = true
let myLayer = PathViewLayer()
self.layer = myLayer
}
@IBInspectable public var svgPath: String?
{
didSet
{
self.setPathString(pathString: svgPath)
}
}
@IBInspectable public var lineWidth: CGFloat = 1
{
didSet
{
self.shapeLayer.lineWidth = lineWidth
}
}
@IBInspectable public var fillColor: NSColor?
{
didSet
{
self.shapeLayer.fillColor = fillColor?.cgColor
}
}
@IBInspectable public var strokeColor: NSColor?
{
didSet
{
self.shapeLayer.strokeColor = strokeColor?.cgColor
}
}
@IBInspectable public var strokeStart : CGFloat = 0.0
{
didSet
{
self.shapeLayer.strokeStart = self.strokeStart
}
}
@IBInspectable public var strokeEnd : CGFloat = 1.0
{
didSet
{
self.shapeLayer.strokeEnd = self.strokeEnd
}
}
override public var isFlipped: Bool // to be like the iOS version
{
return true
}
public var shapeLayer: CAShapeLayer
{
return (self.layer as! PathViewLayer).shapeLayer
}
}
#endif
| mit | 2c90b009498ac1c3c723f44a33d7c59e | 25.309091 | 81 | 0.643055 | 4.543171 | false | false | false | false |
ello/ello-ios | Specs/Controllers/Stream/Cells/StreamImageCellSpec.swift | 1 | 2227 | ////
/// StreamImageCellSpec.swift
//
@testable import Ello
import Quick
import Nimble
class StreamImageCellSpec: QuickSpec {
override func spec() {
describe("StreamImageCell") {
let image = UIImage.imageWithColor(.blue, size: CGSize(width: 500, height: 300))!
let expectations: [(listView: Bool, isComment: Bool, isRepost: Bool, buyButton: Bool)] =
[
(listView: true, isComment: false, isRepost: false, buyButton: false),
(listView: true, isComment: false, isRepost: false, buyButton: true),
(listView: true, isComment: false, isRepost: true, buyButton: false),
(listView: true, isComment: false, isRepost: true, buyButton: true),
(listView: true, isComment: true, isRepost: false, buyButton: false),
(listView: false, isComment: false, isRepost: false, buyButton: false),
(listView: false, isComment: false, isRepost: false, buyButton: true),
(listView: false, isComment: false, isRepost: true, buyButton: false),
(listView: false, isComment: false, isRepost: true, buyButton: true),
(listView: false, isComment: true, isRepost: false, buyButton: false),
]
for (listView, isComment, isRepost, buyButton) in expectations {
it(
"\(listView ? "list" : "grid") view \(isComment ? "comment" : (isRepost ? "repost" : "post"))\(buyButton ? " with buy button" : "") should match snapshot"
) {
let subject = StreamImageCell.loadFromNib() as StreamImageCell
subject.frame = CGRect(origin: .zero, size: CGSize(width: 375, height: 225))
subject.isGridView = !listView
subject.marginType = (isComment ? .comment : (isRepost ? .repost : .post))
subject.setImage(image)
if buyButton {
subject.buyButtonURL = URL(string: "http://ello.co")
}
expectValidSnapshot(subject)
}
}
}
}
}
| mit | c6a7d680b393836b0d45c5b90be85293 | 48.488889 | 174 | 0.545128 | 4.688421 | false | false | false | false |
huangboju/Moots | 算法学习/LeetCode/LeetCode/FourSumCount.swift | 1 | 611 | //
// FourSumCount.swift
// LeetCode
//
// Created by xiAo_Ju on 2019/9/29.
// Copyright © 2019 伯驹 黄. All rights reserved.
//
import Foundation
func fourSumCount(_ A: [Int], _ B: [Int], _ C: [Int], _ D: [Int]) -> Int {
var map: [Int: Int] = [:]
for a in A {
for b in B {
let sum = a + b
map[sum, default: 0] += 1
}
}
var count = 0
for c in C {
for d in D {
let sum = c + d
if let negativeOfSum = map[-sum] {
count += negativeOfSum
}
}
}
return count
}
| mit | 1cd494efa29066096c83371c6185b8eb | 18.483871 | 74 | 0.440397 | 3.337017 | false | false | false | false |
tectijuana/patrones | Bloque1SwiftArchivado/PracticasSwift/JuanAlv/programa 11.swift | 1 | 875 | //Title: Problema 11 Filename: programa 11.swift
//Author: Alvarado Rodriguez Juan Manuel Date: 22 - Feb - 2017
//Description: introducir un conjunto de 25 numeros. determinar la cantidad de numeros positivos y negativos del conjunto
//Input: 25 numeros
//Output: cantidad de numeros negativos y positivos
//random
func randomInt(min: Int, max:Int) -> Int {
return min + Int(arc4random_uniform(UInt32(max - min + 1)))
}
//arreglo
var arreglo=[Int]()
var contNeg : Int = 0
var contPos : Int = 0
//llenado de 25 datos en el arreglo
for i in 0..<24{
arreglo.append(randomInt(min: -100, max:100))
if arreglo[i]>=0{
contPos+=1
}
else{
contNeg+=1
}
}
//impresion de cantidad de numeros negativos y positivos
print("cantidad de numeros positivos: \(contPos)")
print("cantidad de numeros negativos: \(contNeg)")
| gpl-3.0 | af458407bd492c15b085973247414b49 | 27.166667 | 121 | 0.673143 | 2.804487 | false | false | false | false |
CalebeEmerick/Checkout | Source/Checkout/StoresController.swift | 1 | 3388 | //
// StoresController.swift
// Checkout
//
// Created by Calebe Emerick on 30/11/16.
// Copyright © 2016 CalebeEmerick. All rights reserved.
//
import UIKit
// MARK: - Variables & Outlets -
final class StoresController : UIViewController {
@IBOutlet fileprivate weak var container: UIView!
@IBOutlet fileprivate weak var collectionView: UICollectionView!
@IBOutlet fileprivate weak var activityIndicator: UIActivityIndicatorView!
fileprivate let storeError = StoreError.makeXib()
fileprivate let dataSource = StoreDataSource()
fileprivate let delegate = StoreDelegate()
fileprivate let layout = StoreLayout()
fileprivate var presenter: StorePresenter?
}
// MARK: - Life Cycle -
extension StoresController {
override func viewDidLoad() {
super.viewDidLoad()
changeNavigationBarBackButton()
presenter = StorePresenter(storeView: self)
delegate.selectedStore = { [weak self] store in self?.openTransactionController(with: store) }
layout.setupCollectionView(for: collectionView, dataSource: dataSource, delegate: delegate)
setErrorViewConstraints()
presenter?.getStores()
}
}
// MARK: - Methods -
extension StoresController {
fileprivate func setErrorViewConstraints() {
DispatchQueue.main.async {
self.storeError.alpha = 0
self.storeError.triedAgain = { self.tryLoadStoresAgain() }
self.view.addSubview(self.storeError)
self.storeError.translatesAutoresizingMaskIntoConstraints = false
self.storeError.topAnchor.constraint(equalTo: self.view.topAnchor, constant: 50).isActive = true
self.storeError.leadingAnchor.constraint(equalTo: self.view.leadingAnchor, constant: 8).isActive = true
self.storeError.trailingAnchor.constraint(equalTo: self.view.trailingAnchor, constant: -8).isActive = true
self.storeError.heightAnchor.constraint(equalToConstant: self.storeError.bounds.height).isActive = true
}
}
fileprivate func changeStoreError(alpha: CGFloat) {
UIView.animate(withDuration: 0.4) {
self.storeError.alpha = alpha
}
}
}
// MARK: - StoresView Protocol -
extension StoresController : StoresView {
func showLoading() {
activityIndicator.startAnimating()
}
func hideLoading() {
activityIndicator.stopAnimating()
}
func showContainer() {
hideLoading()
UIView.animate(withDuration: 0.4) {
self.container.alpha = 1
}
}
func update(stores: [Store]) {
DispatchQueue.main.async {
self.dataSource.stores = stores
self.collectionView.reloadData()
}
}
func showError(message: String) {
storeError.message = message
changeStoreError(alpha: 1)
}
func hideError() {
changeStoreError(alpha: 0)
}
func tryLoadStoresAgain() {
hideError()
showLoading()
presenter?.getStores()
}
func openTransactionController(with store: Store) {
TransactionRouter.openCreditCardTransactionController(from: self, with: store)
}
}
| mit | 2aaa9e8547acf6d7b348d774bb509ea0 | 26.314516 | 118 | 0.633009 | 5.06278 | false | false | false | false |
jpush/jchat-swift | JChat/Src/UserModule/ViewController/JCSignatureViewController.swift | 1 | 4339 | //
// JCSignatureViewController.swift
// JChat
//
// Created by JIGUANG on 2017/3/29.
// Copyright © 2017年 HXHG. All rights reserved.
//
import UIKit
import JMessage
class JCSignatureViewController: UIViewController {
var signature: String!
override func viewDidLoad() {
super.viewDidLoad()
_init()
signatureTextView.text = signature
var count = 30 - signature.count
count = count < 0 ? 0 : count
tipLabel.text = "\(count)"
}
private var topOffset: CGFloat {
if isIPhoneX {
return 88
}
return 64
}
private lazy var saveButton: UIButton = {
var saveButton = UIButton()
saveButton.setTitle("提交", for: .normal)
let colorImage = UIImage.createImage(color: UIColor(netHex: 0x2dd0cf), size: CGSize(width: self.view.width - 30, height: 40))
saveButton.setBackgroundImage(colorImage, for: .normal)
saveButton.addTarget(self, action: #selector(_saveSignature), for: .touchUpInside)
return saveButton
}()
private lazy var bgView: UIView = {
let bgView = UIView(frame: CGRect(x: 0, y: self.topOffset, width: self.view.width, height: 120))
bgView.backgroundColor = .white
return bgView
}()
private lazy var signatureTextView: UITextView = {
let signatureTextView = UITextView(frame: CGRect(x: 15, y: 15, width: self.view.width - 30, height: 90))
signatureTextView.delegate = self
signatureTextView.font = UIFont.systemFont(ofSize: 16)
signatureTextView.backgroundColor = .white
return signatureTextView
}()
fileprivate lazy var tipLabel: UILabel = {
let tipLabel = UILabel(frame: CGRect(x: self.bgView.width - 15 - 50, y: self.bgView.height - 24, width: 50, height: 12))
tipLabel.textColor = UIColor(netHex: 0x999999)
tipLabel.font = UIFont.systemFont(ofSize: 12)
tipLabel.textAlignment = .right
return tipLabel
}()
private lazy var navRightButton: UIBarButtonItem = UIBarButtonItem(title: "保存", style: .plain, target: self, action: #selector(_saveSignature))
//MARK: - private func
private func _init() {
self.title = "个性签名"
automaticallyAdjustsScrollViewInsets = false;
view.backgroundColor = UIColor(netHex: 0xe8edf3)
view.addSubview(saveButton)
view.addSubview(bgView)
bgView.addSubview(signatureTextView)
bgView.addSubview(tipLabel)
view.addConstraint(_JCLayoutConstraintMake(saveButton, .left, .equal, view, .left, 15))
view.addConstraint(_JCLayoutConstraintMake(saveButton, .right, .equal, view, .right, -15))
view.addConstraint(_JCLayoutConstraintMake(saveButton, .top, .equal, bgView, .bottom, 15))
view.addConstraint(_JCLayoutConstraintMake(saveButton, .height, .equal, nil, .notAnAttribute, 40))
_setupNavigation()
}
private func _setupNavigation() {
navigationItem.rightBarButtonItem = navRightButton
}
//MARK: - click func
@objc func _saveSignature() {
signatureTextView.resignFirstResponder()
JMSGUser.updateMyInfo(withParameter: signatureTextView.text!, userFieldType: .fieldsSignature) { (resultObject, error) -> Void in
if error == nil {
NotificationCenter.default.post(name: Notification.Name(rawValue: kUpdateUserInfo), object: nil)
self.navigationController?.popViewController(animated: true)
} else {
print("error:\(String(describing: error?.localizedDescription))")
}
}
}
}
extension JCSignatureViewController: UITextViewDelegate {
func textViewDidChange(_ textView: UITextView) {
if textView.markedTextRange == nil {
let text = textView.text!
if text.count > 30 {
let range = text.startIndex ..< text.index(text.startIndex, offsetBy: 30)
//let range = Range<String.Index>(text.startIndex ..< text.index(text.startIndex, offsetBy: 30))
let subText = text.substring(with: range)
textView.text = subText
}
let count = 30 - (textView.text?.count)!
tipLabel.text = "\(count)"
}
}
}
| mit | 0c6c14cd558dcfaf3dfbe52eab1148fa | 37.230088 | 147 | 0.635648 | 4.566596 | false | false | false | false |
googleapis/google-auth-library-swift | Sources/OAuth2/ServiceAccountTokenProvider/ServiceAccountTokenProvider.swift | 1 | 4179 | // Copyright 2019 Google LLC. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import Foundation
#if canImport(FoundationNetworking)
import FoundationNetworking
#endif
struct ServiceAccountCredentials : Codable {
let CredentialType : String
let ProjectId : String
let PrivateKeyId : String
let PrivateKey : String
let ClientEmail : String
let ClientID : String
let AuthURI : String
let TokenURI : String
let AuthProviderX509CertURL : String
let ClientX509CertURL : String
enum CodingKeys: String, CodingKey {
case CredentialType = "type"
case ProjectId = "project_id"
case PrivateKeyId = "private_key_id"
case PrivateKey = "private_key"
case ClientEmail = "client_email"
case ClientID = "client_id"
case AuthURI = "auth_uri"
case TokenURI = "token_uri"
case AuthProviderX509CertURL = "auth_provider_x509_cert_url"
case ClientX509CertURL = "client_x509_cert_url"
}
}
public class ServiceAccountTokenProvider : TokenProvider {
public var token: Token?
var credentials : ServiceAccountCredentials
var scopes : [String]
var rsaKey : RSAKey
public init?(credentialsData:Data, scopes:[String]) {
let decoder = JSONDecoder()
guard let credentials = try? decoder.decode(ServiceAccountCredentials.self,
from: credentialsData)
else {
return nil
}
self.credentials = credentials
self.scopes = scopes
guard let rsaKey = RSAKey(privateKey:credentials.PrivateKey)
else {
return nil
}
self.rsaKey = rsaKey
}
convenience public init?(credentialsURL:URL, scopes:[String]) {
guard let credentialsData = try? Data(contentsOf:credentialsURL, options:[]) else {
return nil
}
self.init(credentialsData:credentialsData, scopes:scopes)
}
public func withToken(_ callback:@escaping (Token?, Error?) -> Void) throws {
// leave spare at least one second :)
if let token = token, token.timeToExpiry() > 1 {
callback(token, nil)
return
}
let iat = Date()
let exp = iat.addingTimeInterval(3600)
let jwtClaimSet = JWTClaimSet(Issuer:credentials.ClientEmail,
Audience:credentials.TokenURI,
Scope: scopes.joined(separator: " "),
IssuedAt: Int(iat.timeIntervalSince1970),
Expiration: Int(exp.timeIntervalSince1970))
let jwtHeader = JWTHeader(Algorithm: "RS256",
Format: "JWT")
let msg = try JWT.encodeWithRS256(jwtHeader:jwtHeader,
jwtClaimSet:jwtClaimSet,
rsaKey:rsaKey)
let json: [String: Any] = ["grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer",
"assertion": msg]
let data = try JSONSerialization.data(withJSONObject: json)
var urlRequest = URLRequest(url:URL(string:credentials.TokenURI)!)
urlRequest.httpMethod = "POST"
urlRequest.httpBody = data
urlRequest.setValue("application/json", forHTTPHeaderField:"Content-Type")
let session = URLSession(configuration: URLSessionConfiguration.default)
let task: URLSessionDataTask = session.dataTask(with:urlRequest)
{(data, response, error) -> Void in
if let data = data,
let token = try? JSONDecoder().decode(Token.self, from: data) {
self.token = token
self.token?.CreationTime = Date()
callback(self.token, error)
} else {
callback(nil, error)
}
}
task.resume()
}
}
| apache-2.0 | 263b4f59e03f3751b0fa43475d110b37 | 34.415254 | 91 | 0.651113 | 4.403583 | false | false | false | false |
kousun12/RxSwift | RxSwift/Observables/Implementations/Range.swift | 8 | 1557 | //
// Range.swift
// Rx
//
// Created by Krunoslav Zaher on 9/13/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
class RangeProducer<_CompilerWorkaround> : Producer<Int> {
private let _start: Int
private let _count: Int
private let _scheduler: ImmediateSchedulerType
init(start: Int, count: Int, scheduler: ImmediateSchedulerType) {
if count < 0 {
rxFatalError("count can't be negative")
}
if start &+ (count - 1) < start {
rxFatalError("overflow of count")
}
_start = start
_count = count
_scheduler = scheduler
}
override func run<O : ObserverType where O.E == Int>(observer: O) -> Disposable {
let sink = RangeSink(parent: self, observer: observer)
sink.disposable = sink.run()
return sink
}
}
class RangeSink<_CompilerWorkaround, O: ObserverType where O.E == Int> : Sink<O> {
typealias Parent = RangeProducer<_CompilerWorkaround>
private let _parent: Parent
init(parent: Parent, observer: O) {
_parent = parent
super.init(observer: observer)
}
func run() -> Disposable {
return _parent._scheduler.scheduleRecursive(0) { i, recurse in
if i < self._parent._count {
self.forwardOn(.Next(self._parent._start + i))
recurse(i + 1)
}
else {
self.forwardOn(.Completed)
self.dispose()
}
}
}
} | mit | fbfcca8084728aec068e1586805f1b79 | 25.389831 | 85 | 0.566838 | 4.358543 | false | false | false | false |
DevaLee/LYCSwiftDemo | LYCSwiftDemo/Classes/live/ViewModel/LYCGifViewModel.swift | 1 | 1706 | //
// LYCGifViewModel.swift
// LYCSwiftDemo
//
// Created by yuchen.li on 2017/6/13.
// Copyright © 2017年 zsc. All rights reserved.
//
import UIKit
private let urlString = "http://qf.56.com/pay/v4/giftList.ios"
class LYCGifViewModel: NSObject {
static var shareInstance : LYCGifViewModel = LYCGifViewModel()
var gifPackage : [LYCGifModel] = []
override init (){
}
init(array : Array<[String : Any]>) {
for dict in array {
gifPackage.append(LYCGifModel(dict: dict))
}
}
}
extension LYCGifViewModel {
func loadGifData(finishCallBack : @escaping () -> ()){
gifPackage.removeAll()
LYCNetworkTool.loadData(type: .GET, urlString: urlString, parameter: ["type" : 0,"page" : 1 , "rows" : 150]) { (response) in
guard let responseResult = response as? [String : Any] else{
print("数据出错")
return
}
guard let type1Dict = responseResult["message"] as? [String : Any] else{
print("数据出错 message")
return
}
guard let listDict = type1Dict["type1"] as? [String : Any] else{
print("数据出错 list")
return
}
guard let listArray = listDict["list"] as? [[String : Any]] else{
print("数据出错 Array")
return
}
print("获取礼物列表成功")
for gifDict in listArray{
self.gifPackage.append(LYCGifModel(dict : gifDict))
}
finishCallBack()
}
}
}
| mit | 98ef5abb068d58f48b3d8cea4cfb77e5 | 24.859375 | 132 | 0.515408 | 4.211196 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | Modules/DelegatedSelfCustody/Tests/DelegatedSelfCustodyDataTests/BuildTxResponseTests.swift | 1 | 4922 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
@testable import DelegatedSelfCustodyData
import ToolKit
import XCTest
// swiftlint:disable line_length
final class BuildTxResponseTests: XCTestCase {
func testDecodes() throws {
guard let jsonData = json.data(using: .utf8) else {
XCTFail("Failed to read data.")
return
}
let response = try JSONDecoder().decode(BuildTxResponse.self, from: jsonData)
XCTAssertEqual(response.summary.relativeFee, "1")
XCTAssertEqual(response.summary.absoluteFeeMaximum, "2")
XCTAssertEqual(response.summary.absoluteFeeEstimate, "3")
XCTAssertEqual(response.summary.amount, "4")
XCTAssertEqual(response.summary.balance, "5")
XCTAssertEqual(response.preImages.count, 1)
let preImage = response.preImages[0]
XCTAssertEqual(preImage.preImage, "1")
XCTAssertEqual(preImage.signingKey, "2")
XCTAssertEqual(preImage.signatureAlgorithm, .secp256k1)
XCTAssertNil(preImage.descriptor)
let payloadJsonValue: JSONValue = .dictionary([
"version": .number(0),
"auth": .dictionary([
"authType": .number(4),
"spendingCondition": .dictionary([
"hashMode": .number(0),
"signer": .string("71cb17c2d7f5e2ba71fab0aa6172f02d7265ff14"),
"nonce": .string("0"),
"fee": .string("600"),
"keyEncoding": .number(0),
"signature": .dictionary([
"type": .number(9),
"data": .string("0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000")
])
])
]),
"payload": .dictionary([
"type": .number(8),
"payloadType": .number(0),
"recipient": .dictionary([
"type": .number(5),
"address": .dictionary([
"type": .number(0),
"version": .number(22),
"hash160": .string("afc896bb4b998cd40dd885b31d7446ef86b04eb0")
])
]),
"amount": .string("1"),
"memo": .dictionary([
"type": .number(3),
"content": .string("")
])
]),
"chainId": .number(1),
"postConditionMode": .number(2),
"postConditions": .dictionary([
"type": .number(7),
"lengthPrefixBytes": .number(4),
"values": .array([])
]),
"anchorMode": .number(3)
])
let rawTxJsonValue: JSONValue = .dictionary(
[
"version": .number(1),
"payload": payloadJsonValue
]
)
XCTAssertEqual(response.rawTx, rawTxJsonValue)
}
}
private let json = """
{
"summary": {
"relativeFee": "1",
"absoluteFeeMaximum": "2",
"absoluteFeeEstimate": "3",
"amount": "4",
"balance": "5"
},
"rawTx": {
"version": 1,
"payload": {
"version": 0,
"auth": {
"authType": 4,
"spendingCondition": {
"hashMode": 0,
"signer": "71cb17c2d7f5e2ba71fab0aa6172f02d7265ff14",
"nonce": "0",
"fee": "600",
"keyEncoding": 0,
"signature": {
"type": 9,
"data": "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
}
}
},
"payload": {
"type": 8,
"payloadType": 0,
"recipient": {
"type": 5,
"address": {
"type": 0,
"version": 22,
"hash160": "afc896bb4b998cd40dd885b31d7446ef86b04eb0"
}
},
"amount": "1",
"memo": {
"type": 3,
"content": ""
}
},
"chainId": 1,
"postConditionMode": 2,
"postConditions": {
"type": 7,
"lengthPrefixBytes": 4,
"values": []
},
"anchorMode": 3
}
},
"preImages": [
{
"preImage": "1",
"signingKey": "2",
"descriptor": null,
"signatureAlgorithm": "secp256k1"
}
]
}
"""
| lgpl-3.0 | ac6b79630ad9679f792692cb98fd11ab | 32.25 | 173 | 0.456411 | 4.745419 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | Modules/Platform/Sources/PlatformKit/Models/OrderDirection.swift | 1 | 626 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
public enum OrderDirection: String, Codable {
/// From non-custodial to non-custodial
case onChain = "ON_CHAIN"
/// From non-custodial to custodial
case fromUserKey = "FROM_USERKEY"
/// From custodial to non-custodial
case toUserKey = "TO_USERKEY"
/// From custodial to custodial
case `internal` = "INTERNAL"
}
extension OrderDirection {
public var isFromCustodial: Bool {
self == .toUserKey || self == .internal
}
public var isToCustodial: Bool {
self == .fromUserKey || self == .internal
}
}
| lgpl-3.0 | aea184bc6a28e256fbda87148d7d4720 | 26.173913 | 62 | 0.6528 | 3.930818 | false | false | false | false |
overtake/TelegramSwift | Telegram-Mac/WidgetController.swift | 1 | 9654 | //
// WidgetController.swift
// Telegram
//
// Created by Mikhail Filimonov on 06.07.2021.
// Copyright © 2021 Telegram. All rights reserved.
//
import Foundation
import TGUIKit
import SwiftSignalKit
private final class WidgetNavigationButton : Control {
enum Direction {
case left
case right
}
private let textView = TextView()
private let imageView = ImageView()
private let view = View()
private let visualEffect = VisualEffect()
required init(frame frameRect: NSRect) {
super.init(frame: frameRect)
addSubview(visualEffect)
addSubview(view)
view.addSubview(textView)
view.addSubview(imageView)
imageView.isEventLess = true
textView.userInteractionEnabled = false
textView.isSelectable = false
self.layer?.cornerRadius = 16
scaleOnClick = true
}
override func updateLocalizationAndTheme(theme: PresentationTheme) {
super.updateLocalizationAndTheme(theme: theme)
let theme = theme as! TelegramPresentationTheme
self.background = theme.shouldBlurService ? .clear : theme.chatServiceItemColor
self.visualEffect.bgColor = theme.blurServiceColor
self.visualEffect.isHidden = !theme.shouldBlurService
}
private var direction: Direction?
func setup(_ text: String, image: CGImage, direction: Direction) {
self.direction = direction
let layout = TextViewLayout(.initialize(string: text, color: theme.chatServiceItemTextColor, font: .medium(.text)))
layout.measure(width: .greatestFiniteMagnitude)
textView.update(layout)
imageView.image = image
imageView.sizeToFit()
updateLocalizationAndTheme(theme: theme)
}
override func layout() {
super.layout()
visualEffect.frame = bounds
view.setFrameSize(NSMakeSize(textView.frame.width + 4 + imageView.frame.width, frame.height))
view.center()
if let direction = direction {
switch direction {
case .left:
imageView.centerY(x: 0)
textView.centerY(x: imageView.frame.maxX + 4)
case .right:
textView.centerY(x: 0)
imageView.centerY(x: textView.frame.maxX + 4)
}
}
}
func size() -> NSSize {
return NSMakeSize(28 + textView.frame.width + 4 + imageView.frame.width, 32)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
final class WidgetListView: View {
enum PresentMode {
case immidiate
case leftToRight
case rightToLeft
var animated: Bool {
return self != .immidiate
}
}
private let documentView = View()
private var controller: ViewController?
private var prev: WidgetNavigationButton?
private var next: WidgetNavigationButton?
required init(frame frameRect: NSRect) {
super.init(frame: frameRect)
addSubview(documentView)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
var _next:(()->Void)?
var _prev:(()->Void)?
func present(controller: ViewController, hasNext: Bool, hasPrev: Bool, mode: PresentMode) {
let previous = self.controller
self.controller = controller
let duration: Double = 0.5
if let previous = previous {
if mode.animated {
previous.view._change(opacity: 0, duration: duration, timingFunction: .spring, completion: { [weak previous] completed in
if completed {
previous?.removeFromSuperview()
}
})
} else {
previous.removeFromSuperview()
}
}
documentView.addSubview(controller.view)
controller.view.centerX(y: 0)
controller.view._change(opacity: 1, animated: mode.animated, duration: duration, timingFunction: .spring)
if mode.animated {
let to = controller.view.frame.origin
let from: NSPoint
switch mode {
case .leftToRight:
from = NSMakePoint(to.x - 50, to.y)
case .rightToLeft:
from = NSMakePoint(to.x + 50, to.y)
default:
from = to
}
controller.view.layer?.animatePosition(from: from, to: to, duration: duration, timingFunction: .spring)
}
if hasPrev {
if self.prev == nil {
self.prev = .init(frame: .zero)
if let prev = prev {
addSubview(prev)
}
prev?.layer?.animateAlpha(from: 0, to: 1, duration: 0.2)
self.prev?.set(handler: { [weak self] _ in
self?._prev?()
}, for: .Click)
}
} else if let prev = self.prev {
prev.userInteractionEnabled = false
performSubviewRemoval(prev, animated: mode.animated)
self.prev = nil
}
if hasNext {
if self.next == nil {
self.next = .init(frame: .zero)
if let next = next {
addSubview(next)
}
next?.layer?.animateAlpha(from: 0, to: 1, duration: 0.2)
self.next?.set(handler: { [weak self] _ in
self?._next?()
}, for: .Click)
}
} else if let next = self.next {
next.userInteractionEnabled = false
performSubviewRemoval(next, animated: mode.animated)
self.next = nil
}
updateLocalizationAndTheme(theme: theme)
needsLayout = true
}
override func updateLocalizationAndTheme(theme: PresentationTheme) {
super.updateLocalizationAndTheme(theme: theme)
backgroundColor = .clear
documentView.backgroundColor = .clear
let theme = theme as! TelegramPresentationTheme
if let prev = prev {
prev.setup(strings().emptyChatNavigationPrev, image: theme.emptyChatNavigationPrev, direction: .left)
prev.setFrameSize(prev.size())
}
if let next = next {
next.setup(strings().emptyChatNavigationNext, image: theme.emptyChatNavigationNext, direction: .right)
next.setFrameSize(next.size())
}
needsLayout = true
}
override func layout() {
super.layout()
documentView.frame = NSMakeRect(0, 0, frame.width, 320)
guard let controller = controller else {
return
}
controller.view.centerX(y: 0)
if let prev = prev {
prev.setFrameOrigin(NSMakePoint(controller.frame.minX, documentView.frame.maxY + 10))
}
if let next = next {
next.setFrameOrigin(NSMakePoint(controller.frame.maxX - next.frame.width, documentView.frame.maxY + 10))
}
}
}
final class WidgetController : TelegramGenericViewController<WidgetListView> {
private var controllers:[ViewController] = []
private var selected: Int = 0
override init(_ context: AccountContext) {
super.init(context)
self.bar = .init(height: 0)
}
private func loadController(_ controller: ViewController) {
controller._frameRect = NSMakeRect(0, 0, 320, 320)
controller.bar = .init(height: 0)
controller.loadViewIfNeeded()
}
private func presentSelected(_ mode: WidgetListView.PresentMode) {
let controller = controllers[selected]
loadController(controller)
genericView.present(controller: controller, hasNext: controllers.count - 1 > selected, hasPrev: selected > 0, mode: mode)
}
override func backKeyAction() -> KeyHandlerResult {
if prev() {
return .invoked
}
return .rejected
}
override func nextKeyAction() -> KeyHandlerResult {
if next() {
return .invoked
}
return .rejected
}
@discardableResult private func next() -> Bool {
if selected < controllers.count - 1 {
selected += 1
presentSelected(.rightToLeft)
return true
}
return false
}
@discardableResult private func prev() -> Bool {
if selected > 0 {
selected -= 1
presentSelected(.leftToRight)
return true
}
return false
}
override func viewDidLoad() {
super.viewDidLoad()
controllers.append(WidgetAppearanceController(context))
controllers.append(WidgetRecentPeersController(context))
controllers.append(WidgetStorageController(context))
controllers.append(WidgetStickersController(context))
let current = controllers[selected]
loadController(current)
ready.set(current.ready.get())
genericView.present(controller: current, hasNext: controllers.count - 1 > selected, hasPrev: selected > 0, mode: .immidiate)
genericView._next = { [weak self] in
self?.next()
}
genericView._prev = { [weak self] in
self?.prev()
}
}
deinit {
var bp = 0
bp += 1
}
}
| gpl-2.0 | ae068f825480dedff660d4e3e99f4edb | 29.939103 | 137 | 0.570911 | 5.051282 | false | false | false | false |
vishalvshekkar/ArchivingSwiftStructures | ArchivingSwiftStructures3.playground/Contents.swift | 1 | 3900 | //: Playground - noun: a place where people can play
import UIKit
// MARK: - The structure that is to be archived.
struct Movie {
let name: String
let director: String
let releaseYear: Int
}
// MARK: - The protocol, when implemented by a structure makes the structure archive-able
protocol Dictionariable {
func dictionaryRepresentation() -> NSDictionary
init?(dictionaryRepresentation: NSDictionary?)
}
// MARK: - Implementation of the Dictionariable protocol by Movie struct
extension Movie: Dictionariable {
func dictionaryRepresentation() -> NSDictionary {
let representation: [String: AnyObject] = [
"name": name,
"director": director,
"releaseYear": releaseYear
]
return representation
}
init?(dictionaryRepresentation: NSDictionary?) {
guard let values = dictionaryRepresentation else {return nil}
if let name = values["name"] as? String,
director = values["director"] as? String,
releaseYear = values["releaseYear"] as? Int {
self.name = name
self.director = director
self.releaseYear = releaseYear
} else {
return nil
}
}
}
// MARK: - Methods aiding in archiving and unarchiving the structures
//Single Structure Instances
func extractStructureFromArchive<T: Dictionariable>() -> T? {
guard let encodedDict = NSKeyedUnarchiver.unarchiveObjectWithFile(path()) as? NSDictionary else {return nil}
return T(dictionaryRepresentation: encodedDict)
}
func archiveStructure<T: Dictionariable>(structure: T) {
let encodedValue = structure.dictionaryRepresentation()
NSKeyedArchiver.archiveRootObject(encodedValue, toFile: path())
}
//Multiple Structure Instances
func extractStructuresFromArchive<T: Dictionariable>() -> [T] {
guard let encodedArray = NSKeyedUnarchiver.unarchiveObjectWithFile(path()) as? [AnyObject] else {return []}
return encodedArray.map{$0 as? NSDictionary}.flatMap{T(dictionaryRepresentation: $0)}
}
func archiveStructureInstances<T: Dictionariable>(structures: [T]) {
let encodedValues = structures.map{$0.dictionaryRepresentation()}
NSKeyedArchiver.archiveRootObject(encodedValues, toFile: path())
}
//Metjod to get path to encode stuctures to
func path() -> String {
let documentsPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).first
let path = documentsPath?.stringByAppendingString("/Movie")
return path!
}
// MARK: - Testing Code
//Single Structure Instances
let movie = Movie(name: "Avatar", director: "James Cameron", releaseYear: 2009)
archiveStructure(movie)
let someMovie: Movie? = extractStructureFromArchive()
someMovie?.director
//Multiple Structure Instances
let movies = [
Movie(name: "Avatar", director: "James Cameron", releaseYear: 2009),
Movie(name: "The Dark Knight", director: "Christopher Nolan", releaseYear: 2008)
]
archiveStructureInstances(movies)
let someArray: [Movie] = extractStructuresFromArchive()
someArray[0].director
//Nested Structures
struct Actor {
let name: String
let firstMovie: Movie
}
extension Actor: Dictionariable {
func dictionaryRepresentation() -> NSDictionary {
let representation: [String: AnyObject] = [
"name": name,
"firstMovie": firstMovie.dictionaryRepresentation(),
]
return representation
}
init?(dictionaryRepresentation: NSDictionary?) {
guard let values = dictionaryRepresentation else {return nil}
if let name = values["name"] as? String,
let someMovie: Movie = extractStructureFromDictionary() {
self.name = name
self.firstMovie = someMovie
} else {
return nil
}
}
} | mit | c70ae1ef3e39cd1ffdbea5be879dfd7f | 30.208 | 151 | 0.689231 | 4.773562 | false | false | false | false |
glennposadas/gpkit-ios | GPKit/Categories/String+GPKit.swift | 1 | 5454 | //
// String+GPKit.swift
// GPKit
//
// Created by Glenn Posadas on 5/10/17.
// Copyright © 2017 Citus Labs. All rights reserved.
//
import UIKit
public extension String {
/** Format the 24 hour string into 12 hour.
*/
public func format24HrStringTo12Hr() -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "H:mm:ss"
if let inDate = dateFormatter.date(from: self) {
dateFormatter.dateFormat = "h:mm a"
let outTime = dateFormatter.string(from:inDate)
return "\(outTime)"
}
return self
}
/** Identical to the extension of UITextField's hasValue()
*/
public func hasValidValue() -> Bool {
let whitespaceSet = CharacterSet.whitespaces
if self == "" || self == " " {
return false
}
if self.trimmingCharacters(in: whitespaceSet).isEmpty
|| self.trimmingCharacters(in: whitespaceSet).isEmpty {
return false
}
return true
}
/** Clever function to add/append paths as strings just like in Firebase.
*/
public func append(path: String) -> String {
return "\(self)\(path)"
}
/** Checks if the input email is valid or not
*/
public func isValidEmail() -> Bool {
let emailFormat = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}"
let emailPredicate = NSPredicate(format:"SELF MATCHES %@", emailFormat)
return emailPredicate.evaluate(with: self)
}
/** Handles string conversion into the usual default format of the MySQL Database.
* @params Self = string of date (e.g. 2017-04-11 13:21:05)
* @return Date = 2017-04-11 13:21:05
*/
public func convertToDate() -> Date? {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let date = dateFormatter.date(from: self)
return date
}
/** Handles date formatiing from String to String
* Input: Self. Ex: "2017-01-11 07:10:36"
* Returns: String: "Jan 2017"
*/
public func convertToReadableDateFormat() -> String {
let dateFormatter = DateFormatter()
let geoDriveDateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
geoDriveDateFormatter.dateFormat = "MMM yyyy"
let date = dateFormatter.date(from: self)
return geoDriveDateFormatter.string(from: date!)
}
/** Extract month from a string
*/
public func extractMonth() -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
if let myDate = dateFormatter.date(from: self) {
dateFormatter.dateFormat = "MM"
let finalMonth = dateFormatter.string(from: myDate)
if let monthInt = Int(finalMonth) {
let monthName = dateFormatter.monthSymbols[monthInt - 1]
return monthName
}
}
return ""
}
/** Extract year from a string
*/
public func extractYear() -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
if let myDate = dateFormatter.date(from: self) {
dateFormatter.dateFormat = "yyyy"
let finalDate = dateFormatter.string(from: myDate)
return finalDate
}
return ""
}
/** Extract readable date string from a string
*/
public func extractReableDashDate() -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
if let myDate = dateFormatter.date(from: self) {
dateFormatter.dateFormat = "dd/MM/yyyy"
let finalDate = dateFormatter.string(from: myDate)
return finalDate
}
return ""
}
/** Convert a String (month symbol) to Int String
* January --> "1"
*/
public func convertMonthSymbolToInt() -> String {
return "\(DateFormatter().monthSymbols.index(of: self)! + 1)"
}
/** Generates random alphanumeric string for image key
*/
public static func random(length: Int = 20) -> String {
let base = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
var randomString: String = ""
for _ in 0..<length {
let randomValue = arc4random_uniform(UInt32(base.count))
randomString += "\(base[base.index(base.startIndex, offsetBy: Int(randomValue))])"
}
return randomString
}
public var removedFirstCharacter: String {
mutating get {
self.remove(at: self.startIndex)
return self
}
}
}
public class GPKitString {
/** Returns the cool format for Date and Time now.
*/
public class func dateTimeNowString() -> String {
let dateformatter = DateFormatter()
dateformatter.dateStyle = DateFormatter.Style.short
dateformatter.timeStyle = DateFormatter.Style.short
let now = dateformatter.string(from: Date())
return now
}
}
| mit | f4605a4ad99df10df4e3351dcf266705 | 27.549738 | 94 | 0.569045 | 4.754141 | false | false | false | false |
nalexn/ViewInspector | Sources/ViewInspector/Modifiers/AccessibilityModifiers.swift | 1 | 17501 | import SwiftUI
// MARK: - Accessibility
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
public extension InspectableView {
func accessibilityLabel() throws -> InspectableView<ViewType.Text> {
let text: Text
let call = "accessibilityLabel"
if #available(iOS 16.0, macOS 13.0, tvOS 16.0, watchOS 9.0, *) {
text = try v3AccessibilityElement(
path: "some|text", type: Text.self,
call: call, { $0.accessibilityLabel("") })
} else if #available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *) {
text = try v3AccessibilityElement(
type: Text.self, call: call, { $0.accessibilityLabel("") })
} else {
text = try v2AccessibilityElement("LabelKey", type: Text.self, call: call)
}
let medium = content.medium.resettingViewModifiers()
return try .init(try Inspector.unwrap(content: Content(text, medium: medium)), parent: self)
}
func accessibilityValue() throws -> InspectableView<ViewType.Text> {
let text: Text
let call = "accessibilityValue"
if #available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *) {
text = try v3AccessibilityElement(
path: "some|description|some", type: Text.self,
call: call, { $0.accessibilityValue("") })
} else {
text = try v2AccessibilityElement(
"TypedValueKey", path: "value|some|description|some", type: Text.self, call: call)
}
let medium = content.medium.resettingViewModifiers()
return try .init(try Inspector.unwrap(content: Content(text, medium: medium)), parent: self)
}
func accessibilityHint() throws -> InspectableView<ViewType.Text> {
let text: Text
let call = "accessibilityHint"
if #available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *) {
text = try v3AccessibilityElement(
type: Text.self, call: call, { $0.accessibilityHint("") })
} else {
text = try v2AccessibilityElement("HintKey", type: Text.self, call: call)
}
let medium = content.medium.resettingViewModifiers()
return try .init(try Inspector.unwrap(content: Content(text, medium: medium)), parent: self)
}
func accessibilityHidden() throws -> Bool {
let call = "accessibilityHidden"
if #available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *) {
let value = try v3AccessibilityElement(
path: "value|rawValue", type: UInt32.self,
call: call, { $0.accessibilityHidden(true) })
return value != 0
} else {
let visibility = try v2AccessibilityElement(
"VisibilityKey", path: "value", type: (Any?).self, call: call)
switch visibility {
case let .some(value):
return String(describing: value) == "hidden"
case .none:
return false
}
}
}
func accessibilityIdentifier() throws -> String {
let call = "accessibilityIdentifier"
if #available(iOS 16.0, macOS 13.0, tvOS 16.0, watchOS 9.0, *) {
return try v3AccessibilityElement(
path: "some|rawValue", type: String.self,
call: call, { $0.accessibilityIdentifier("") })
} else if #available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *) {
return try v3AccessibilityElement(
type: String.self, call: call, { $0.accessibilityIdentifier("") })
} else {
return try v2AccessibilityElement("IdentifierKey", type: String.self, call: call)
}
}
func accessibilitySortPriority() throws -> Double {
let call = "accessibilitySortPriority"
if #available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *) {
return try v3AccessibilityElement(
type: Double.self, call: call, { $0.accessibilitySortPriority(0) })
} else {
return try v2AccessibilityElement("SortPriorityKey", type: Double.self, call: call)
}
}
@available(iOS, deprecated, introduced: 13.0)
@available(macOS, deprecated, introduced: 10.15)
@available(tvOS, deprecated, introduced: 13.0)
@available(watchOS, deprecated, introduced: 6)
func accessibilitySelectionIdentifier() throws -> AnyHashable {
return try v2AccessibilityElement(
"SelectionIdentifierKey", type: AnyHashable.self,
call: "accessibility(selectionIdentifier:)")
}
func accessibilityActivationPoint() throws -> UnitPoint {
if #available(iOS 16.0, macOS 13.0, tvOS 16.0, watchOS 9.0, *) {
return try v3AccessibilityElement(
path: "some|activate|some|unitPoint", type: UnitPoint.self,
call: "accessibilityIdentifier", { $0.accessibilityActivationPoint(.center) })
} else if #available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *) {
return try v3AccessibilityElement(
path: "some|unitPoint", type: UnitPoint.self,
call: "accessibilityIdentifier", { $0.accessibilityActivationPoint(.center) })
} else {
return try v2AccessibilityElement(
"ActivationPointKey", path: "value|some|unitPoint",
type: UnitPoint.self, call: "accessibility(activationPoint:)")
}
}
func callAccessibilityAction<S>(_ named: S) throws where S: StringProtocol {
try callAccessibilityAction(AccessibilityActionKind(named: Text(named)))
}
func callAccessibilityAction(_ kind: AccessibilityActionKind) throws {
let shortName: String = {
if let name = try? kind.name().string() {
return "named: \"\(name)\""
}
return "." + String(describing: kind)
.components(separatedBy: CharacterSet(charactersIn: ".)"))
.filter { $0.count > 0 }.last!
}()
let call = "accessibilityAction(\(shortName))"
typealias Callback = (()) -> Void
let callback: Callback
if #available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *) {
callback = try v3AccessibilityAction(kind: kind, type: Callback.self, call: call)
} else {
callback = try v2AccessibilityAction(kind: kind, type: Callback.self, call: call)
}
callback(())
}
func callAccessibilityAdjustableAction(_ direction: AccessibilityAdjustmentDirection = .increment) throws {
typealias Callback = (AccessibilityAdjustmentDirection) -> Void
let callback: Callback
if #available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *) {
callback = try v3AccessibilityAction(
name: "AccessibilityAdjustableAction",
type: Callback.self,
call: "accessibilityAdjustableAction")
} else {
callback = try v2AccessibilityAction(
name: "AccessibilityAdjustableAction()",
type: Callback.self,
call: "accessibilityAdjustableAction")
}
callback(direction)
}
func callAccessibilityScrollAction(_ edge: Edge) throws {
typealias Callback = (Edge) -> Void
let callback: Callback
if #available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *) {
callback = try v3AccessibilityAction(
name: "AccessibilityScrollAction",
type: Callback.self,
call: "accessibilityScrollAction")
} else {
callback = try v2AccessibilityAction(
name: "AccessibilityScrollAction()",
type: Callback.self,
call: "accessibilityScrollAction")
}
callback(edge)
}
}
// MARK: - Private
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
private extension AccessibilityActionKind {
func name() throws -> InspectableView<ViewType.Text> {
let view: Any = try {
if let view = try? Inspector.attribute(path: "kind|named", value: self) {
return view
}
return try Inspector.attribute(path: "kind|custom", value: self)
}()
return try .init(Content(view), parent: nil, index: nil)
}
func isEqual(to other: AccessibilityActionKind) -> Bool {
if let lhsName = try? self.name().string(),
let rhsName = try? other.name().string() {
return lhsName == rhsName
}
return self == other
}
}
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
private struct AccessibilityProperty {
let keyPointerValue: UInt64
let value: Any
init(property: Any) throws {
self.keyPointerValue = try Inspector.attribute(
path: "super|key|rawValue|pointerValue", value: property, type: UInt64.self)
self.value = try Inspector.attribute(path: "super|value", value: property)
}
init(key: UInt64, value: Any) throws {
self.keyPointerValue = key
self.value = try Inspector.attribute(path: "typedValue", value: value)
}
static var noisePointerValues: Set<UInt64> = {
let view1 = EmptyView().accessibility(label: Text(""))
let view2 = EmptyView().accessibility(hint: Text(""))
do {
let props1 = try view1.inspect()
.v3v4AccessibilityProperties(call: "")
.map { $0.keyPointerValue }
let props2 = try view2.inspect()
.v3v4AccessibilityProperties(call: "")
.map { $0.keyPointerValue }
return Set(props1).intersection(Set(props2))
} catch { return .init() }
}()
}
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
private extension InspectableView {
func v3AccessibilityElement<V, T>(
path: String? = nil, type: T.Type, call: String, _ reference: (EmptyView) -> V
) throws -> T where V: SwiftUI.View {
let noiseValues = AccessibilityProperty.noisePointerValues
guard let referenceValue = try reference(EmptyView()).inspect()
.v3v4AccessibilityProperties(call: call)
.map({ $0.keyPointerValue })
.first(where: { !noiseValues.contains($0) }),
let property = try v3v4AccessibilityProperties(call: call)
.first(where: { $0.keyPointerValue == referenceValue })
else {
throw InspectionError
.modifierNotFound(parent: Inspector.typeName(value: content.view),
modifier: call, index: 0)
}
if let path = path {
return try Inspector.attribute(path: path, value: property.value, type: T.self)
}
return try Inspector.cast(value: property.value, type: T.self)
}
func v3AccessibilityAction<T>(kind: AccessibilityActionKind, type: T.Type, call: String) throws -> T {
return try v3AccessibilityAction(trait: { action in
try Inspector.attribute(
path: "action|kind", value: action, type: AccessibilityActionKind.self)
.isEqual(to: kind)
}, type: type, call: call)
}
func v3AccessibilityAction<T>(name: String, type: T.Type, call: String) throws -> T {
return try v3AccessibilityAction(trait: { action in
Inspector.typeName(value: action).contains(name)
}, type: type, call: call)
}
func v3AccessibilityAction<T>(trait: (Any) throws -> Bool, type: T.Type, call: String) throws -> T {
let actions = try v3AccessibilityActions(call: call)
guard let action = actions.first(where: { (try? trait($0)) == true }) else {
throw InspectionError
.modifierNotFound(parent: Inspector.typeName(value: content.view),
modifier: call, index: 0)
}
if #available(iOS 16.0, macOS 13.0, tvOS 16.0, watchOS 9.0, *) {
throw InspectionError.notSupported(
"""
Accessibility actions are currently unavailable for \
inspection on iOS 16. Situation may change with a minor \
OS version update. In the meanwhile, please add XCTSkip \
for iOS 16 and use an earlier OS version for testing.
""")
}
return try Inspector.attribute(label: "handler", value: action, type: T.self)
}
func v3AccessibilityActions(call: String) throws -> [Any] {
let noiseValues = AccessibilityProperty.noisePointerValues
guard let referenceValue = try EmptyView().accessibilityAction(.default, { })
.inspect()
.v3v4AccessibilityProperties(call: call)
.map({ $0.keyPointerValue })
.first(where: { !noiseValues.contains($0) })
else {
throw InspectionError
.modifierNotFound(parent: Inspector.typeName(value: content.view),
modifier: call, index: 0)
}
return try v3v4AccessibilityProperties(call: call)
.filter({ $0.keyPointerValue == referenceValue })
.compactMap { $0.value as? [Any] }
.flatMap { $0 }
.map { try Inspector.attribute(path: "base|base", value: $0) }
}
func v3v4AccessibilityProperties(call: String) throws -> [AccessibilityProperty] {
if #available(iOS 16.0, macOS 13.0, tvOS 16.0, watchOS 9.0, *) {
return try modifierAttribute(
modifierName: "AccessibilityAttachmentModifier",
path: "modifier|storage|value|properties|storage",
type: AccessibilityKeyValues.self, call: call)
.accessibilityKeyValues()
.map { try AccessibilityProperty(key: $0.key, value: $0.value) }
} else {
return try modifierAttribute(
modifierName: "AccessibilityAttachmentModifier",
path: "modifier|storage|propertiesComponent",
type: [Any].self, call: call)
.map { try AccessibilityProperty(property: $0) }
}
}
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
protocol AccessibilityKeyValues {
func accessibilityKeyValues() throws -> [(key: UInt64, value: Any)]
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
extension Dictionary: AccessibilityKeyValues {
func accessibilityKeyValues() throws -> [(key: UInt64, value: Any)] {
return try self.keys.compactMap { key -> (key: UInt64, value: Any)? in
guard let value = self[key] else { return nil }
let keyPointerValue = try Inspector.attribute(
path: "rawValue|pointerValue", value: key, type: UInt64.self)
return (key: keyPointerValue, value: value as Any)
}
}
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
private extension InspectableView {
func v2AccessibilityElement<T>(_ name: String, path: String = "value|some",
type: T.Type, call: String) throws -> T {
let item = try modifierAttribute(
modifierName: "AccessibilityAttachmentModifier",
path: "modifier|attachment|some|properties|plist|elements|some",
type: Any.self, call: call)
guard let attribute = v2LookupAttributeWithName(name, item: item),
let value = try? Inspector.attribute(path: path, value: attribute) as? T else {
throw InspectionError.modifierNotFound(parent:
Inspector.typeName(value: content.view), modifier: call, index: 0)
}
return value
}
func v2LookupAttributeWithName(_ name: String, item: Any) -> Any? {
if Inspector.typeName(value: item).contains(name) {
return item
}
if let nextItem = try? Inspector.attribute(path: "super|after|some", value: item) {
return v2LookupAttributeWithName(name, item: nextItem)
}
return nil
}
func v2AccessibilityAction<T>(kind: AccessibilityActionKind, type: T.Type, call: String) throws -> T {
return try v2AccessibilityAction(type: type, call: call, trait: { handler in
try Inspector.attribute(path: "box|action|kind", value: handler, type: AccessibilityActionKind.self)
.isEqual(to: kind)
})
}
func v2AccessibilityAction<T>(name: String, type: T.Type, call: String) throws -> T {
return try v2AccessibilityAction(type: type, call: call, trait: { handler in
let actionName = try Inspector.attribute(path: "box|action", value: handler)
return name == String(describing: actionName)
})
}
func v2AccessibilityAction<T>(type: T.Type, call: String, trait: (Any) throws -> Bool) throws -> T {
let actionHandlers = try v2AccessibilityElement(
"ActionsKey", path: "value",
type: [Any].self, call: call)
guard let handler = actionHandlers.first(where: { (try? trait($0)) == true }),
let callback = try? Inspector.attribute(path: "box|handler", value: handler) as? T
else {
throw InspectionError.modifierNotFound(parent:
Inspector.typeName(value: content.view), modifier: call, index: 0)
}
return callback
}
}
| mit | 3c436ac6c5b7735f337f39ffd2effdd0 | 42.972362 | 112 | 0.593052 | 4.381823 | false | false | false | false |
tjw/swift | stdlib/public/core/SipHash.swift | 1 | 4886 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
/// This file implements SipHash-2-4 and SipHash-1-3
/// (https://131002.net/siphash/).
///
/// This file is based on the reference C implementation, which was released
/// to public domain by:
///
/// * Jean-Philippe Aumasson <[email protected]>
/// * Daniel J. Bernstein <[email protected]>
//===----------------------------------------------------------------------===//
private struct _SipHashState {
// "somepseudorandomlygeneratedbytes"
fileprivate var v0: UInt64 = 0x736f6d6570736575
fileprivate var v1: UInt64 = 0x646f72616e646f6d
fileprivate var v2: UInt64 = 0x6c7967656e657261
fileprivate var v3: UInt64 = 0x7465646279746573
@inline(__always)
fileprivate init(seed: (UInt64, UInt64)) {
v3 ^= seed.1
v2 ^= seed.0
v1 ^= seed.1
v0 ^= seed.0
}
@inline(__always)
fileprivate
static func _rotateLeft(_ x: UInt64, by amount: UInt64) -> UInt64 {
return (x &<< amount) | (x &>> (64 - amount))
}
@inline(__always)
fileprivate mutating func _round() {
v0 = v0 &+ v1
v1 = _SipHashState._rotateLeft(v1, by: 13)
v1 ^= v0
v0 = _SipHashState._rotateLeft(v0, by: 32)
v2 = v2 &+ v3
v3 = _SipHashState._rotateLeft(v3, by: 16)
v3 ^= v2
v0 = v0 &+ v3
v3 = _SipHashState._rotateLeft(v3, by: 21)
v3 ^= v0
v2 = v2 &+ v1
v1 = _SipHashState._rotateLeft(v1, by: 17)
v1 ^= v2
v2 = _SipHashState._rotateLeft(v2, by: 32)
}
@inline(__always)
fileprivate func _extract() -> UInt64 {
return v0 ^ v1 ^ v2 ^ v3
}
}
internal struct _SipHash13Core: _HasherCore {
private var _state: _SipHashState
@inline(__always)
internal init(seed: (UInt64, UInt64)) {
_state = _SipHashState(seed: seed)
}
@inline(__always)
internal mutating func compress(_ m: UInt64) {
_state.v3 ^= m
_state._round()
_state.v0 ^= m
}
@inline(__always)
internal mutating func finalize(tailAndByteCount: UInt64) -> UInt64 {
compress(tailAndByteCount)
_state.v2 ^= 0xff
for _ in 0..<3 {
_state._round()
}
return _state._extract()
}
}
internal struct _SipHash24Core: _HasherCore {
private var _state: _SipHashState
@inline(__always)
internal init(seed: (UInt64, UInt64)) {
_state = _SipHashState(seed: seed)
}
@inline(__always)
internal mutating func compress(_ m: UInt64) {
_state.v3 ^= m
_state._round()
_state._round()
_state.v0 ^= m
}
@inline(__always)
internal mutating func finalize(tailAndByteCount: UInt64) -> UInt64 {
compress(tailAndByteCount)
_state.v2 ^= 0xff
for _ in 0..<4 {
_state._round()
}
return _state._extract()
}
}
// FIXME: This type only exists to facilitate testing.
public // @testable
struct _SipHash13 {
internal typealias Core = _BufferingHasher<_SipHash13Core>
internal var _core: Core
public init(seed: (UInt64, UInt64)) { _core = Core(seed: seed) }
public mutating func _combine(_ v: UInt) { _core.combine(v) }
public mutating func _combine(_ v: UInt64) { _core.combine(v) }
public mutating func _combine(_ v: UInt32) { _core.combine(v) }
public mutating func _combine(_ v: UInt16) { _core.combine(v) }
public mutating func _combine(_ v: UInt8) { _core.combine(v) }
public mutating func combine(bytes v: UInt64, count: Int) {
_core.combine(bytes: v, count: count)
}
public mutating func combine(bytes: UnsafeRawBufferPointer) {
_core.combine(bytes: bytes)
}
public mutating func finalize() -> UInt64 { return _core.finalize() }
}
// FIXME: This type only exists to facilitate testing.
public // @testable
struct _SipHash24 {
internal typealias Core = _BufferingHasher<_SipHash24Core>
internal var _core: Core
public init(seed: (UInt64, UInt64)) { _core = Core(seed: seed) }
public mutating func _combine(_ v: UInt) { _core.combine(v) }
public mutating func _combine(_ v: UInt64) { _core.combine(v) }
public mutating func _combine(_ v: UInt32) { _core.combine(v) }
public mutating func _combine(_ v: UInt16) { _core.combine(v) }
public mutating func _combine(_ v: UInt8) { _core.combine(v) }
public mutating func combine(bytes v: UInt64, count: Int) {
_core.combine(bytes: v, count: count)
}
public mutating func combine(bytes: UnsafeRawBufferPointer) {
_core.combine(bytes: bytes)
}
public mutating func finalize() -> UInt64 { return _core.finalize() }
}
| apache-2.0 | a945328044ef7ea69f10669866a588ac | 28.97546 | 80 | 0.623209 | 3.383657 | false | false | false | false |
FRA7/FJWeibo | FJWeibo/AppDelegate.swift | 1 | 1831 | //
// AppDelegate.swift
// FJWeibo
//
// Created by Francis on 16/2/26.
// Copyright © 2016年 FRAJ. All rights reserved.
//
import UIKit
import AFNetworking
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var defaultViewController: UIViewController{
let isLogin = UserAccountViewModel.shareInstance.isLogin
return isLogin ? WelcomeViewController() :UIStoryboard(name: "Main", bundle: nil).instantiateInitialViewController()!
}
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// // 0.设置AFN属性
// let cache = NSURLCache(memoryCapacity: 4 * 1024 * 1024, diskCapacity: 20 * 1024 * 1024, diskPath: nil)
// NSURLCache.setSharedURLCache(cache)
// AFNetworkActivityIndicatorManager.sharedManager().enabled = true
//设置导航条和工具条全局属性
UINavigationBar.appearance().tintColor = UIColor.orangeColor()
UITabBar.appearance().tintColor = UIColor.orangeColor()
//1.创建窗口
window = UIWindow(frame: UIScreen.mainScreen().bounds)
window?.backgroundColor = UIColor.whiteColor()
//2.设置窗口根视图
// window?.rootViewController = MainViewController()
window?.rootViewController = defaultViewController
//3.显示窗口
window?.makeKeyAndVisible()
return true
}
}
//MARK: - 自定义Log
func FJLog<T>(message : T, file : String = __FILE__, lineNum : Int = __LINE__) {
#if DEBUG
let filePath = (file as NSString).lastPathComponent
print("\(filePath)-[\(lineNum)]:\(message)")
#endif
}
| mit | 21010d3f869489a648429231baa2a6be | 26.46875 | 127 | 0.634812 | 4.98017 | false | false | false | false |
lolgear/JWT | Example/JWTDesktopSwift/JWTDesktopSwift/ViewController+Model.swift | 2 | 2551 | //
// ViewController+Model.swift
// JWTDesktopSwift
//
// Created by Lobanov Dmitry on 30.10.2017.
// Copyright © 2017 JWTIO. All rights reserved.
//
import Foundation
import JWT
import JWTDesktopSwiftToolkit
extension ViewController {
class Model {
var appearance: TokenTextAppearance = .init()
var decoder: TokenDecoder = .init()
var signatureValidation: SignatureValidationType = .unknown
}
enum DataSeedType {
case hs256
case rs256
struct DataSeed {
var algorithmName: String
var secret: String
var token: String
}
var dataSeed: DataSeed {
switch self {
case .hs256:
let algorithmName = JWTAlgorithmNameHS256
let secret = "secret"
let token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ"
return .init(algorithmName: algorithmName, secret: secret, token: token)
case .rs256:
let algorithmName = JWTAlgorithmNameRS256
let secret = "-----BEGIN PUBLIC KEY-----MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAoPryo3IisfK3a028bwgso/CW5kB84mk6Y7rO76FxJRTWnOAla0Uf0OpIID7go4Qck66yT4/uPpiOQIR0oW0plTekkDP75EG3d/2mtzhiCtELV4F1r9b/InCN5dYYK8USNkKXgjbeVyatdUvCtokz10/ibNZ9qikgKf58qXnn2anGvpE6ded5FOUEukOjr7KSAfD0KDNYWgZcG7HZBxn/3N7ND9D0ATu2vxlJsNGOkH6WL1EmObo/QygBXzuZm5o0N0W15EXpWVbl4Ye7xqPnvc1i2DTKxNUcyhXfDbLw1ee2d9T/WU5895Ko2bQ/O/zPwUSobM3m+fPMW8kp5914kwIDAQAB-----END PUBLIC KEY-----"
let token = "eyJraWQiOiJqd3RfdWF0X2tleXMiLCJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJzdWIiOiI1MDAxIiwiaXNzIjoiQ0xNIiwiZXhwIjoxNTA4MjQ5NTU3LCJqdGkiOiI2MjcyM2E4Yi0zOTZmLTQxYmYtOTljMi02NWRkMzk2MDNiNjQifQ.Cej8RJ6e2HEU27rh_TyHZBoMI1jErmhOfSFY4SRzRoijSP628hM82XxjDX24HsKqIsK1xeeGI1yg1bed4RPhnmDGt4jAY73nqguZ1oqZ2DTcfZ5olxCXyLLaytl2XH7-62M_mFUcGj7I2mwts1DQkHWnFky2i4uJXlksHFkUg2xZoGEjVHo0bxCxgQ5yQiOpxC5VodN5rAPM3A5yMG6EijOp-dvUThjoJ4RFTGKozw_x_Qg6RLGDusNcmLIMbHasTsyZAZle6RFkwO0Sij1k6z6_xssbOl-Q57m7CeYgVHMORdzy4Smkmh-0gzeiLsGbCL4fhgdHydpIFajW-eOXMw"
return .init(algorithmName: algorithmName, secret: secret, token: token)
}
}
}
}
// JWT
extension ViewController.Model {
var availableAlgorithms: [JWTAlgorithm] {
JWTAlgorithmFactory.algorithms
}
var availableAlgorithmsNames: [String] {
self.availableAlgorithms.map(\.name)
}
}
| mit | 1f1008abf2b78990bcc95eaa4bd822cb | 45.363636 | 556 | 0.747843 | 2.512315 | false | false | false | false |
pNre/Kingfisher | Sources/ImageDownloader.swift | 11 | 30301 | //
// ImageDownloader.swift
// Kingfisher
//
// Created by Wei Wang on 15/4/6.
//
// Copyright (c) 2018 Wei Wang <[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.
#if os(macOS)
import AppKit
#else
import UIKit
#endif
/// Progress update block of downloader.
public typealias ImageDownloaderProgressBlock = DownloadProgressBlock
/// Completion block of downloader.
public typealias ImageDownloaderCompletionHandler = ((_ image: Image?, _ error: NSError?, _ url: URL?, _ originalData: Data?) -> Void)
/// Download task.
public struct RetrieveImageDownloadTask {
let internalTask: URLSessionDataTask
/// Downloader by which this task is initialized.
public private(set) weak var ownerDownloader: ImageDownloader?
/// Cancel this download task. It will trigger the completion handler with an NSURLErrorCancelled error.
/// If you want to cancel all downloading tasks, call `cancelAll()` of `ImageDownloader` instance.
public func cancel() {
ownerDownloader?.cancel(self)
}
/// The original request URL of this download task.
public var url: URL? {
return internalTask.originalRequest?.url
}
/// The relative priority of this download task.
/// It represents the `priority` property of the internal `NSURLSessionTask` of this download task.
/// The value for it is between 0.0~1.0. Default priority is value of 0.5.
/// See documentation on `priority` of `NSURLSessionTask` for more about it.
public var priority: Float {
get {
return internalTask.priority
}
set {
internalTask.priority = newValue
}
}
}
///The code of errors which `ImageDownloader` might encountered.
public enum KingfisherError: Int {
/// badData: The downloaded data is not an image or the data is corrupted.
case badData = 10000
/// notModified: The remote server responded a 304 code. No image data downloaded.
case notModified = 10001
/// The HTTP status code in response is not valid. If an invalid
/// code error received, you could check the value under `KingfisherErrorStatusCodeKey`
/// in `userInfo` to see the code.
case invalidStatusCode = 10002
/// notCached: The image requested is not in cache but .onlyFromCache is activated.
case notCached = 10003
/// The URL is invalid.
case invalidURL = 20000
/// The downloading task is cancelled before started.
case downloadCancelledBeforeStarting = 30000
}
/// Key will be used in the `userInfo` of `.invalidStatusCode`
public let KingfisherErrorStatusCodeKey = "statusCode"
/// Protocol of `ImageDownloader`.
public protocol ImageDownloaderDelegate: AnyObject {
/**
Called when the `ImageDownloader` object will start downloading an image from specified URL.
- parameter downloader: The `ImageDownloader` object finishes the downloading.
- parameter url: URL of the original request URL.
- parameter response: The request object for the download process.
*/
func imageDownloader(_ downloader: ImageDownloader, willDownloadImageForURL url: URL, with request: URLRequest?)
/**
Called when the `ImageDownloader` completes a downloading request with success or failure.
- parameter downloader: The `ImageDownloader` object finishes the downloading.
- parameter url: URL of the original request URL.
- parameter response: The response object of the downloading process.
- parameter error: The error in case of failure.
*/
func imageDownloader(_ downloader: ImageDownloader, didFinishDownloadingImageForURL url: URL, with response: URLResponse?, error: Error?)
/**
Called when the `ImageDownloader` object successfully downloaded an image from specified URL.
- parameter downloader: The `ImageDownloader` object finishes the downloading.
- parameter image: Downloaded image.
- parameter url: URL of the original request URL.
- parameter response: The response object of the downloading process.
*/
func imageDownloader(_ downloader: ImageDownloader, didDownload image: Image, for url: URL, with response: URLResponse?)
/**
Check if a received HTTP status code is valid or not.
By default, a status code between 200 to 400 (excluded) is considered as valid.
If an invalid code is received, the downloader will raise an .invalidStatusCode error.
It has a `userInfo` which includes this statusCode and localizedString error message.
- parameter code: The received HTTP status code.
- parameter downloader: The `ImageDownloader` object asking for validate status code.
- returns: Whether this HTTP status code is valid or not.
- Note: If the default 200 to 400 valid code does not suit your need,
you can implement this method to change that behavior.
*/
func isValidStatusCode(_ code: Int, for downloader: ImageDownloader) -> Bool
/**
Called when the `ImageDownloader` object successfully downloaded image data from specified URL.
- parameter downloader: The `ImageDownloader` object finishes data downloading.
- parameter data: Downloaded data.
- parameter url: URL of the original request URL.
- returns: The data from which Kingfisher should use to create an image.
- Note: This callback can be used to preprocess raw image data
before creation of UIImage instance (i.e. decrypting or verification).
*/
func imageDownloader(_ downloader: ImageDownloader, didDownload data: Data, for url: URL) -> Data?
}
extension ImageDownloaderDelegate {
public func imageDownloader(_ downloader: ImageDownloader, willDownloadImageForURL url: URL, with request: URLRequest?) {}
public func imageDownloader(_ downloader: ImageDownloader, didFinishDownloadingImageForURL url: URL, with response: URLResponse?, error: Error?) {}
public func imageDownloader(_ downloader: ImageDownloader, didDownload image: Image, for url: URL, with response: URLResponse?) {}
public func isValidStatusCode(_ code: Int, for downloader: ImageDownloader) -> Bool {
return (200..<400).contains(code)
}
public func imageDownloader(_ downloader: ImageDownloader, didDownload data: Data, for url: URL) -> Data? {
return data
}
}
/// Protocol indicates that an authentication challenge could be handled.
public protocol AuthenticationChallengeResponsable: AnyObject {
/**
Called when an session level authentication challenge is received.
This method provide a chance to handle and response to the authentication challenge before downloading could start.
- parameter downloader: The downloader which receives this challenge.
- parameter challenge: An object that contains the request for authentication.
- parameter completionHandler: A handler that your delegate method must call.
- Note: This method is a forward from `URLSessionDelegate.urlSession(:didReceiveChallenge:completionHandler:)`. Please refer to the document of it in `URLSessionDelegate`.
*/
func downloader(_ downloader: ImageDownloader, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void)
/**
Called when an session level authentication challenge is received.
This method provide a chance to handle and response to the authentication challenge before downloading could start.
- parameter downloader: The downloader which receives this challenge.
- parameter task: The task whose request requires authentication.
- parameter challenge: An object that contains the request for authentication.
- parameter completionHandler: A handler that your delegate method must call.
- Note: This method is a forward from `URLSessionTaskDelegate.urlSession(:task:didReceiveChallenge:completionHandler:)`. Please refer to the document of it in `URLSessionTaskDelegate`.
*/
func downloader(_ downloader: ImageDownloader, task: URLSessionTask, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void)
}
extension AuthenticationChallengeResponsable {
func downloader(_ downloader: ImageDownloader, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {
if let trustedHosts = downloader.trustedHosts, trustedHosts.contains(challenge.protectionSpace.host) {
let credential = URLCredential(trust: challenge.protectionSpace.serverTrust!)
completionHandler(.useCredential, credential)
return
}
}
completionHandler(.performDefaultHandling, nil)
}
func downloader(_ downloader: ImageDownloader, task: URLSessionTask, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
completionHandler(.performDefaultHandling, nil)
}
}
/// `ImageDownloader` represents a downloading manager for requesting the image with a URL from server.
open class ImageDownloader {
class ImageFetchLoad {
var contents = [(callback: CallbackPair, options: KingfisherOptionsInfo)]()
var responseData = NSMutableData()
var downloadTaskCount = 0
var downloadTask: RetrieveImageDownloadTask?
var cancelSemaphore: DispatchSemaphore?
}
// MARK: - Public property
/// The duration before the download is timeout. Default is 15 seconds.
open var downloadTimeout: TimeInterval = 15.0
/// A set of trusted hosts when receiving server trust challenges. A challenge with host name contained in this set will be ignored.
/// You can use this set to specify the self-signed site. It only will be used if you don't specify the `authenticationChallengeResponder`.
/// If `authenticationChallengeResponder` is set, this property will be ignored and the implementation of `authenticationChallengeResponder` will be used instead.
open var trustedHosts: Set<String>?
/// Use this to set supply a configuration for the downloader. By default, NSURLSessionConfiguration.ephemeralSessionConfiguration() will be used.
/// You could change the configuration before a downloading task starts. A configuration without persistent storage for caches is requested for downloader working correctly.
open var sessionConfiguration = URLSessionConfiguration.ephemeral {
didSet {
session?.invalidateAndCancel()
session = URLSession(configuration: sessionConfiguration, delegate: sessionHandler, delegateQueue: nil)
}
}
/// Whether the download requests should use pipline or not. Default is false.
open var requestsUsePipelining = false
fileprivate let sessionHandler: ImageDownloaderSessionHandler
fileprivate var session: URLSession?
/// Delegate of this `ImageDownloader` object. See `ImageDownloaderDelegate` protocol for more.
open weak var delegate: ImageDownloaderDelegate?
/// A responder for authentication challenge.
/// Downloader will forward the received authentication challenge for the downloading session to this responder.
open weak var authenticationChallengeResponder: AuthenticationChallengeResponsable?
// MARK: - Internal property
let barrierQueue: DispatchQueue
let processQueue: DispatchQueue
let cancelQueue: DispatchQueue
typealias CallbackPair = (progressBlock: ImageDownloaderProgressBlock?, completionHandler: ImageDownloaderCompletionHandler?)
var fetchLoads = [URL: ImageFetchLoad]()
// MARK: - Public method
/// The default downloader.
public static let `default` = ImageDownloader(name: "default")
/**
Init a downloader with name.
- parameter name: The name for the downloader. It should not be empty.
*/
public init(name: String) {
if name.isEmpty {
fatalError("[Kingfisher] You should specify a name for the downloader. A downloader with empty name is not permitted.")
}
barrierQueue = DispatchQueue(label: "com.onevcat.Kingfisher.ImageDownloader.Barrier.\(name)", attributes: .concurrent)
processQueue = DispatchQueue(label: "com.onevcat.Kingfisher.ImageDownloader.Process.\(name)", attributes: .concurrent)
cancelQueue = DispatchQueue(label: "com.onevcat.Kingfisher.ImageDownloader.Cancel.\(name)")
sessionHandler = ImageDownloaderSessionHandler(name: name)
// Provide a default implement for challenge responder.
authenticationChallengeResponder = sessionHandler
session = URLSession(configuration: sessionConfiguration, delegate: sessionHandler, delegateQueue: .main)
}
deinit {
session?.invalidateAndCancel()
}
func fetchLoad(for url: URL) -> ImageFetchLoad? {
var fetchLoad: ImageFetchLoad?
barrierQueue.sync(flags: .barrier) { fetchLoad = fetchLoads[url] }
return fetchLoad
}
/**
Download an image with a URL and option.
- parameter url: Target URL.
- parameter retrieveImageTask: The task to cooperate with cache. Pass `nil` if you are not trying to use downloader and cache.
- parameter options: The options could control download behavior. See `KingfisherOptionsInfo`.
- parameter progressBlock: Called when the download progress updated.
- parameter completionHandler: Called when the download progress finishes.
- returns: A downloading task. You could call `cancel` on it to stop the downloading process.
*/
@discardableResult
open func downloadImage(with url: URL,
retrieveImageTask: RetrieveImageTask? = nil,
options: KingfisherOptionsInfo? = nil,
progressBlock: ImageDownloaderProgressBlock? = nil,
completionHandler: ImageDownloaderCompletionHandler? = nil) -> RetrieveImageDownloadTask?
{
if let retrieveImageTask = retrieveImageTask, retrieveImageTask.cancelledBeforeDownloadStarting {
completionHandler?(nil, NSError(domain: KingfisherErrorDomain, code: KingfisherError.downloadCancelledBeforeStarting.rawValue, userInfo: nil), nil, nil)
return nil
}
let timeout = self.downloadTimeout == 0.0 ? 15.0 : self.downloadTimeout
// We need to set the URL as the load key. So before setup progress, we need to ask the `requestModifier` for a final URL.
var request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: timeout)
request.httpShouldUsePipelining = requestsUsePipelining
if let modifier = options?.modifier {
guard let r = modifier.modified(for: request) else {
completionHandler?(nil, NSError(domain: KingfisherErrorDomain, code: KingfisherError.downloadCancelledBeforeStarting.rawValue, userInfo: nil), nil, nil)
return nil
}
request = r
}
// There is a possibility that request modifier changed the url to `nil` or empty.
guard let url = request.url, !url.absoluteString.isEmpty else {
completionHandler?(nil, NSError(domain: KingfisherErrorDomain, code: KingfisherError.invalidURL.rawValue, userInfo: nil), nil, nil)
return nil
}
var downloadTask: RetrieveImageDownloadTask?
setup(progressBlock: progressBlock, with: completionHandler, for: url, options: options) {(session, fetchLoad) -> Void in
if fetchLoad.downloadTask == nil {
let dataTask = session.dataTask(with: request)
fetchLoad.downloadTask = RetrieveImageDownloadTask(internalTask: dataTask, ownerDownloader: self)
dataTask.priority = options?.downloadPriority ?? URLSessionTask.defaultPriority
self.delegate?.imageDownloader(self, willDownloadImageForURL: url, with: request)
dataTask.resume()
// Hold self while the task is executing.
self.sessionHandler.downloadHolder = self
}
fetchLoad.downloadTaskCount += 1
downloadTask = fetchLoad.downloadTask
retrieveImageTask?.downloadTask = downloadTask
}
return downloadTask
}
}
// MARK: - Download method
extension ImageDownloader {
// A single key may have multiple callbacks. Only download once.
func setup(progressBlock: ImageDownloaderProgressBlock?, with completionHandler: ImageDownloaderCompletionHandler?, for url: URL, options: KingfisherOptionsInfo?, started: @escaping ((URLSession, ImageFetchLoad) -> Void)) {
func prepareFetchLoad() {
barrierQueue.sync(flags: .barrier) {
let loadObjectForURL = fetchLoads[url] ?? ImageFetchLoad()
let callbackPair = (progressBlock: progressBlock, completionHandler: completionHandler)
loadObjectForURL.contents.append((callbackPair, options ?? KingfisherEmptyOptionsInfo))
fetchLoads[url] = loadObjectForURL
if let session = session {
started(session, loadObjectForURL)
}
}
}
if let fetchLoad = fetchLoad(for: url), fetchLoad.downloadTaskCount == 0 {
if fetchLoad.cancelSemaphore == nil {
fetchLoad.cancelSemaphore = DispatchSemaphore(value: 0)
}
cancelQueue.async {
_ = fetchLoad.cancelSemaphore?.wait(timeout: .distantFuture)
fetchLoad.cancelSemaphore = nil
prepareFetchLoad()
}
} else {
prepareFetchLoad()
}
}
private func cancelTaskImpl(_ task: RetrieveImageDownloadTask, fetchLoad: ImageFetchLoad? = nil, ignoreTaskCount: Bool = false) {
func getFetchLoad(from task: RetrieveImageDownloadTask) -> ImageFetchLoad? {
guard let URL = task.internalTask.originalRequest?.url,
let imageFetchLoad = self.fetchLoads[URL] else
{
return nil
}
return imageFetchLoad
}
guard let imageFetchLoad = fetchLoad ?? getFetchLoad(from: task) else {
return
}
imageFetchLoad.downloadTaskCount -= 1
if ignoreTaskCount || imageFetchLoad.downloadTaskCount == 0 {
task.internalTask.cancel()
}
}
func cancel(_ task: RetrieveImageDownloadTask) {
barrierQueue.sync(flags: .barrier) { cancelTaskImpl(task) }
}
/// Cancel all downloading tasks. It will trigger the completion handlers for all not-yet-finished
/// downloading tasks with an NSURLErrorCancelled error.
///
/// If you need to only cancel a certain task, call `cancel()` on the `RetrieveImageDownloadTask`
/// returned by the downloading methods.
public func cancelAll() {
barrierQueue.sync(flags: .barrier) {
fetchLoads.forEach { v in
let fetchLoad = v.value
guard let task = fetchLoad.downloadTask else { return }
cancelTaskImpl(task, fetchLoad: fetchLoad, ignoreTaskCount: true)
}
}
}
}
// MARK: - NSURLSessionDataDelegate
/// Delegate class for `NSURLSessionTaskDelegate`.
/// The session object will hold its delegate until it gets invalidated.
/// If we use `ImageDownloader` as the session delegate, it will not be released.
/// So we need an additional handler to break the retain cycle.
// See https://github.com/onevcat/Kingfisher/issues/235
final class ImageDownloaderSessionHandler: NSObject, URLSessionDataDelegate, AuthenticationChallengeResponsable {
private let downloaderQueue: DispatchQueue
// The holder will keep downloader not released while a data task is being executed.
// It will be set when the task started, and reset when the task finished.
private var _downloadHolder: ImageDownloader?
var downloadHolder: ImageDownloader? {
get {
return downloaderQueue.sync { _downloadHolder }
}
set {
downloaderQueue.sync { _downloadHolder = newValue }
}
}
init(name: String) {
downloaderQueue = DispatchQueue(label: "com.onevcat.Kingfisher.ImageDownloader.SessionHandler.\(name)")
super.init()
}
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse, completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) {
guard let downloader = downloadHolder else {
completionHandler(.cancel)
return
}
var disposition = URLSession.ResponseDisposition.allow
if let statusCode = (response as? HTTPURLResponse)?.statusCode,
let url = dataTask.originalRequest?.url,
!(downloader.delegate ?? downloader).isValidStatusCode(statusCode, for: downloader)
{
let error = NSError(domain: KingfisherErrorDomain,
code: KingfisherError.invalidStatusCode.rawValue,
userInfo: [KingfisherErrorStatusCodeKey: statusCode, NSLocalizedDescriptionKey: HTTPURLResponse.localizedString(forStatusCode: statusCode)])
// Needs to be called before callCompletionHandlerFailure() because it removes downloadHolder
if let downloader = downloadHolder {
downloader.delegate?.imageDownloader(downloader, didFinishDownloadingImageForURL: url, with: response, error: error)
}
callCompletionHandlerFailure(error: error, url: url)
disposition = .cancel
}
completionHandler(disposition)
}
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
guard let downloader = downloadHolder else {
return
}
if let url = dataTask.originalRequest?.url, let fetchLoad = downloader.fetchLoad(for: url) {
fetchLoad.responseData.append(data)
if let expectedLength = dataTask.response?.expectedContentLength {
for content in fetchLoad.contents {
DispatchQueue.main.async {
content.callback.progressBlock?(Int64(fetchLoad.responseData.length), expectedLength)
}
}
}
}
}
func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
guard let url = task.originalRequest?.url else {
return
}
if let downloader = downloadHolder {
downloader.delegate?.imageDownloader(downloader, didFinishDownloadingImageForURL: url, with: task.response, error: error)
}
guard error == nil else {
callCompletionHandlerFailure(error: error!, url: url)
return
}
processImage(for: task, url: url)
}
/**
This method is exposed since the compiler requests. Do not call it.
*/
func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
guard let downloader = downloadHolder else {
return
}
downloader.authenticationChallengeResponder?.downloader(downloader, didReceive: challenge, completionHandler: completionHandler)
}
func urlSession(_ session: URLSession, task: URLSessionTask, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
guard let downloader = downloadHolder else {
return
}
downloader.authenticationChallengeResponder?.downloader(downloader, task: task, didReceive: challenge, completionHandler: completionHandler)
}
private func cleanFetchLoad(for url: URL) {
guard let downloader = downloadHolder else {
return
}
downloader.barrierQueue.sync(flags: .barrier) {
downloader.fetchLoads.removeValue(forKey: url)
if downloader.fetchLoads.isEmpty {
downloadHolder = nil
}
}
}
private func callCompletionHandlerFailure(error: Error, url: URL) {
guard let downloader = downloadHolder, let fetchLoad = downloader.fetchLoad(for: url) else {
return
}
// We need to clean the fetch load first, before actually calling completion handler.
cleanFetchLoad(for: url)
var leftSignal: Int
repeat {
leftSignal = fetchLoad.cancelSemaphore?.signal() ?? 0
} while leftSignal != 0
for content in fetchLoad.contents {
content.options.callbackDispatchQueue.safeAsync {
content.callback.completionHandler?(nil, error as NSError, url, nil)
}
}
}
private func processImage(for task: URLSessionTask, url: URL) {
guard let downloader = downloadHolder else {
return
}
// We are on main queue when receiving this.
downloader.processQueue.async {
guard let fetchLoad = downloader.fetchLoad(for: url) else {
return
}
self.cleanFetchLoad(for: url)
let data: Data?
let fetchedData = fetchLoad.responseData as Data
if let delegate = downloader.delegate {
data = delegate.imageDownloader(downloader, didDownload: fetchedData, for: url)
} else {
data = fetchedData
}
// Cache the processed images. So we do not need to re-process the image if using the same processor.
// Key is the identifier of processor.
var imageCache: [String: Image] = [:]
for content in fetchLoad.contents {
let options = content.options
let completionHandler = content.callback.completionHandler
let callbackQueue = options.callbackDispatchQueue
let processor = options.processor
var image = imageCache[processor.identifier]
if let data = data, image == nil {
image = processor.process(item: .data(data), options: options)
// Add the processed image to cache.
// If `image` is nil, nothing will happen (since the key is not existing before).
imageCache[processor.identifier] = image
}
if let image = image {
downloader.delegate?.imageDownloader(downloader, didDownload: image, for: url, with: task.response)
let imageModifier = options.imageModifier
let finalImage = imageModifier.modify(image)
if options.backgroundDecode {
let decodedImage = finalImage.kf.decoded
callbackQueue.safeAsync { completionHandler?(decodedImage, nil, url, data) }
} else {
callbackQueue.safeAsync { completionHandler?(finalImage, nil, url, data) }
}
} else {
if let res = task.response as? HTTPURLResponse , res.statusCode == 304 {
let notModified = NSError(domain: KingfisherErrorDomain, code: KingfisherError.notModified.rawValue, userInfo: nil)
completionHandler?(nil, notModified, url, nil)
continue
}
let badData = NSError(domain: KingfisherErrorDomain, code: KingfisherError.badData.rawValue, userInfo: nil)
callbackQueue.safeAsync { completionHandler?(nil, badData, url, nil) }
}
}
}
}
}
// Placeholder. For retrieving extension methods of ImageDownloaderDelegate
extension ImageDownloader: ImageDownloaderDelegate {}
| mit | 3e441c834e82feb6f75bc4292fa3d38e | 43.757755 | 227 | 0.661661 | 5.701035 | false | false | false | false |
nicolas-miari/Kanji-Checker | Code/KanjiChecker/View/CheckerViewController.swift | 1 | 1775 | //
// MainViewController.swift
// KanjiChecker
//
// Created by Nicolás Miari on 2020/04/08.
// Copyright © 2020 Nicolás Miari. All rights reserved.
//
import Cocoa
class CheckerViewController: NSViewController {
// MARK: - GUI
@IBOutlet private weak var textView: NSTextView!
@IBOutlet private weak var audiencePopupButton: NSPopUpButton!
@IBOutlet private weak var checkButton: NSButton!
var progressViewController: ProgressViewController?
let checker = Checker()
// MARK: - NSViewController
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
// MARK: - Control Actions
@IBAction func check(_ sender: Any) {
guard let storyboard = self.storyboard else {
fatalError("FUCK YOU")
}
guard let progress = storyboard.instantiateController(withIdentifier: "Progress") as? ProgressViewController else {
fatalError("Fuck You")
}
let text = textView.attributedString()
let grade = audiencePopupButton.indexOfSelectedItem
progress.appearHandler = { [unowned self] in
// Begin task...
self.checker.highlightInput(text, grade: grade, progress: { (value) in
progress.setProgress(value)
}, completion: {[unowned self](result) in
self.textView.textStorage?.setAttributedString(result)
self.dismiss(progress)
})
}
progress.cancelHandler = { [unowned self] in
self.dismiss(progress)
}
presentAsSheet(progress)
}
@IBAction func audienceChanged(_ sender: Any) {
textView.string = textView.attributedString().string
}
}
| mit | e83d5241d333ba89f62af84157d1a8fa | 27.126984 | 123 | 0.634876 | 4.977528 | false | false | false | false |
attackFromCat/LivingTVDemo | LivingTVDemo/LivingTVDemo/Classes/Home/Controller/AmuseViewController.swift | 1 | 1519 | //
// AmuseViewController.swift
// LivingTVDemo
//
// Created by 李翔 on 2017/1/9.
// Copyright © 2017年 Lee Xiang. All rights reserved.
//
import UIKit
fileprivate let kMenuViewH : CGFloat = 200
class AmuseViewController: BaseAnchorViewController {
// MARK: 懒加载属性
fileprivate lazy var amuseVM : AmuseViewModel = AmuseViewModel()
fileprivate lazy var menuView : AmuseMenuView = {
let menuView = AmuseMenuView.amuseMenuView()
menuView.frame = CGRect(x: 0, y: -kMenuViewH, width: kScreenW, height: kMenuViewH)
return menuView
}()
}
// MARK:- 设置UI界面
extension AmuseViewController {
override func setupUI() {
super.setupUI()
// 将菜单的View添加到collectionView中
collectionView.addSubview(menuView)
collectionView.contentInset = UIEdgeInsets(top: kMenuViewH, left: 0, bottom: 0, right: 0)
}
}
// MARK:- 请求数据
extension AmuseViewController {
override func loadData() {
// 1.给父类中ViewModel进行赋值
baseVM = amuseVM
// 2.请求数据
amuseVM.loadAmuseData {
// 2.1.刷新表格
self.collectionView.reloadData()
// 2.2.调整数据
var tempGroups = self.amuseVM.anchorGroups
tempGroups.removeFirst()
self.menuView.groups = tempGroups
// 3.数据请求完成
self.loadDataFinished()
}
}
}
| mit | ce97f0819fc71f0c0dd9a2d76d239d48 | 24.321429 | 97 | 0.606488 | 4.664474 | false | false | false | false |
NGeenLibraries/NGeen | Example/App/Configuration/Constant.swift | 1 | 1498 | //
// Constant.swift
// Copyright (c) 2014 NGeen
//
// 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.
let kDropBoxAppKey: String = "x30coecna5t1osq"
let kDropBoxSecretKey: String = "t5rpdejos1xveik"
let kDropBoxServer: String = "__DropBoxServer"
let kMarvelServer: String = "__MarvelServer"
let kMarvelPrivateKey: String = "ddd8ee63a2f05578b48ae39e7b17bdffdccde476"
let kMarvelPublicKey: String = "71764b1899e4612a9ecf8b59ea727ec7"
let kParseServer: String = "__ParseServer"
| mit | 0d3ffee9bd86f2496fca8a80b2104901 | 50.655172 | 80 | 0.775701 | 3.841026 | false | false | false | false |
abring/sample_ios | Abring/ABRLoginViewController.swift | 1 | 21099 | //
// AbLoginViewController.swift
// KhabarVarzeshi
//
// Created by Hosein Abbaspour on 3/22/1396 AP.
// Copyright © 1396 AP Sanjaqak. All rights reserved.
//
import UIKit
@objc public protocol ABRLoginDelegate {
func userDidLogin(_ player : ABRPlayer)
@objc optional func userDismissScreen()
@objc optional func errorOccured(_ errorType : ABRErrorType)
}
public enum ABRLoginViewStyle {
case lightBlur
case extraLightBlur
case darkBlur
case darken
case lighten
}
enum LoginType {
case justPhone
case justUserPass
case both
}
class ABRTimer : Timer {
@discardableResult class func countDownFrom(_ time : Int , actionBlock : @escaping (_ current : Int) -> Void , finished completion : @escaping () -> Void) -> Timer {
var timerCount = time
let timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true, block: { timer in
timerCount -= 1
actionBlock(timerCount)
if timerCount == 0 {
timer.invalidate()
completion()
}
})
print("d")
return timer
}
}
class ABRLoginViewController: UIViewController {
private var inset : CGFloat = 10
var isFullScreen = false {
didSet {
if isFullScreen == true {
loginView.transform = .identity
loginView.alpha = 1
loginView.backgroundColor = .clear
dismissButton.removeFromSuperview()
view.backgroundColor = UIColor.white
loginView.frame.origin.x = 0
loginView.frame.size.width = view.frame.size.width
inset = 40
refreshLayout()
}
}
}
var style : ABRLoginViewStyle = .darken
private var dismissButton : UIButton!
private var mainScrollView : UIScrollView!
private var innerScrollView : UIScrollView!
private var phoneTf : UITextField!
private var codeTf : UITextField!
private var visualEffectBlurView = UIVisualEffectView()
private var loginView : UIView!
private var confirmPhoneBtn = UIButton()
private var confirmCodeBtn = UIButton()
private var otherWaysBtn = UIButton()
private var backBtn = UIButton()
private var inputPhoneLabel : UILabel!
private var inputCodeLabel : UILabel!
private var timerLabel : UILabel!
var delegate : ABRLoginDelegate?
//MARK: Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: .UIKeyboardWillShow, object: nil)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if !isFullScreen {
presentAnimation()
} else {
}
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
NotificationCenter.default.removeObserver(self, name: .UIKeyboardWillShow, object: nil)
}
convenience init() {
self.init(nibName: nil, bundle: nil)
view.isOpaque = false
view.backgroundColor = UIColor.clear
setupDismissButton()
setupLoginView()
setupScrollView()
setupTextField()
setupButtons()
setupLabels()
}
@objc private func keyboardWillShow(notification: NSNotification) {
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
let keyboardHeight = keyboardSize.height
mainScrollView.setContentOffset(CGPoint.init(x: 0, y: keyboardHeight/2), animated: true)
}
}
//MARK: Animations
private func presentAnimation() {
switch style {
case .darken:
UIView.animate(withDuration: 0.3, animations: {
self.view.backgroundColor = UIColor(white: 0, alpha: 0.4)
})
case .lighten:
UIView.animate(withDuration: 0.3, animations: {
self.view.backgroundColor = UIColor(white: 1, alpha: 0.4)
})
case .lightBlur:
visualEffectBlurView.frame = view.bounds
view.insertSubview(visualEffectBlurView, at: 0)
visualEffectBlurView.alpha = 1
UIView.animate(withDuration: 0.3 , animations: {
self.visualEffectBlurView.effect = UIBlurEffect(style: .light)
})
case .extraLightBlur:
visualEffectBlurView.frame = view.bounds
view.insertSubview(visualEffectBlurView, at: 0)
visualEffectBlurView.alpha = 1
UIView.animate(withDuration: 0.3 , animations: {
self.visualEffectBlurView.effect = UIBlurEffect(style: .extraLight)
})
case .darkBlur:
visualEffectBlurView.frame = view.bounds
view.insertSubview(visualEffectBlurView, at: 0)
visualEffectBlurView.alpha = 1
UIView.animate(withDuration: 0.3 , animations: {
self.visualEffectBlurView.effect = UIBlurEffect(style: .dark)
})
}
UIView.animate(withDuration: 0.4, delay: 0, usingSpringWithDamping: 0.7 , initialSpringVelocity: 20 , options: .curveLinear, animations: {
self.loginView.transform = .identity
self.loginView.alpha = 1
}, completion: nil)
}
private func dismissAnimation(completion : @escaping () -> Void) {
switch style {
case .darken , .lighten:
UIView.animate(withDuration: 0.3, animations: {
self.view.backgroundColor = UIColor.clear
})
case .lightBlur , .extraLightBlur , .darkBlur:
UIView.animate(withDuration: 0.2 , animations: {
self.visualEffectBlurView.effect = nil
})
}
UIView.animate(withDuration: 0.4, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: .curveLinear, animations: {
self.loginView.transform = CGAffineTransform(scaleX: 0.85, y: 0.85)
self.loginView.alpha = 0
}, completion: { finished in
completion()
})
}
//MARK: setup ui
private func setupTextField() {
if ABRAppConfig.textField != nil {
phoneTf = ABRAppConfig.textField
phoneTf.frame = CGRect(x: 30, y: loginView.bounds.size.height / 2 - 25, width: loginView.bounds.size.width - 60, height: 30)
codeTf = ABRAppConfig.textField
codeTf.frame = CGRect(x: loginView.bounds.size.width + 30, y: loginView.bounds.size.height / 2 - 25, width: loginView.bounds.size.width - 60, height: 30)
} else {
phoneTf = ABRUITextField(frame: CGRect(x: 30, y: loginView.bounds.size.height / 2 - 25, width: loginView.bounds.size.width - 60, height: 30))
phoneTf.placeholder = ABRAppConfig.textFieldsPlaceHolders.phoneTextFieldPlaceHolder
phoneTf.keyboardType = .phonePad
codeTf = ABRUITextField(frame: CGRect(x: loginView.bounds.size.width + 30, y: loginView.bounds.size.height / 2 - 25, width: loginView.bounds.size.width - 60, height: 30))
codeTf.placeholder = ABRAppConfig.textFieldsPlaceHolders.codeTextFieldPlaceHolder
codeTf.keyboardType = .numberPad
}
innerScrollView.addSubview(phoneTf)
innerScrollView.addSubview(codeTf)
}
private func setupButtons() {
if ABRAppConfig.mainButton != nil {
confirmPhoneBtn = ABRAppConfig.mainButton
confirmPhoneBtn.frame = CGRect(x: 30, y: loginView.bounds.size.height - 60 , width: loginView.bounds.size.width - 60 , height: 34)
} else {
confirmPhoneBtn = UIButton(type: .system)
confirmPhoneBtn.frame = CGRect(x: 30, y: loginView.bounds.size.height - 60 , width: loginView.bounds.size.width - 60 , height: 34)
confirmPhoneBtn.backgroundColor = ABRAppConfig.tintColor
confirmPhoneBtn.layer.cornerRadius = 4
confirmPhoneBtn.setTitle(ABRAppConfig.buttonsTitles.loginSendCodeToPhoneButtonTitle , for: .normal)
confirmPhoneBtn.tintColor = UIColor.white
confirmPhoneBtn.titleLabel?.font = ABRAppConfig.font
}
confirmPhoneBtn.addTarget(self, action: #selector(sendCodeAction), for: .touchUpInside)
innerScrollView.addSubview(confirmPhoneBtn)
if ABRAppConfig.mainButton != nil {
confirmCodeBtn = ABRAppConfig.mainButton
confirmCodeBtn.frame = CGRect(x: loginView.bounds.size.width + 30, y: loginView.bounds.size.height - 60 , width: loginView.bounds.size.width - 60 , height: 34)
} else {
confirmCodeBtn = UIButton(type: .system)
confirmCodeBtn.frame = CGRect(x: loginView.bounds.size.width + 30, y: loginView.bounds.size.height - 60 , width: loginView.bounds.size.width - 60 , height: 34)
confirmCodeBtn.backgroundColor = ABRAppConfig.tintColor
confirmCodeBtn.layer.cornerRadius = 4
confirmCodeBtn.setTitle(ABRAppConfig.buttonsTitles.loginConfirmCodeButtonTitle , for: .normal)
confirmCodeBtn.tintColor = UIColor.white
confirmCodeBtn.titleLabel?.font = ABRAppConfig.font
}
confirmCodeBtn.addTarget(self, action: #selector(verifyCodeAction), for: .touchUpInside)
innerScrollView.addSubview(confirmCodeBtn)
// if ABAppConfig.secondaryButton != nil {
// otherWaysBtn = ABAppConfig.mainButton
// otherWaysBtn.frame = CGRect(x: 30, y: loginView.bounds.size.height - 80 , width: loginView.bounds.size.width - 60 , height: 34)
// } else {
// otherWaysBtn = UIButton(type: .system)
// otherWaysBtn.frame = CGRect(x: 30, y: loginView.bounds.size.height - 40 , width: loginView.bounds.size.width - 60 , height: 34)
// otherWaysBtn.backgroundColor = UIColor.clear
// otherWaysBtn.setTitle(ABAppConfig.buttonsTitles.loginOtherWaysButtonTitle , for: .normal)
// otherWaysBtn.setTitleColor(ABAppConfig.tintColor, for: .normal)
// otherWaysBtn.titleLabel?.font = ABAppConfig.font
// }
// innerScrollView.addSubview(otherWaysBtn)
backBtn = UIButton(type: .system)
backBtn.frame = CGRect(x: loginView.bounds.width, y: 4, width: 30, height: 30)
let img = UIImage(named: "AbringKit.bundle/images/back", in: Bundle.init(for: ABRApp.self), compatibleWith: nil) ?? UIImage()
img.withRenderingMode(.alwaysTemplate)
backBtn.setImage(img, for: .normal)
backBtn.tintColor = ABRAppConfig.tintColor
backBtn.addTarget(self, action: #selector(backToInputPhone), for: .touchUpInside)
innerScrollView.addSubview(backBtn)
}
private func setupLabels() {
inputPhoneLabel = UILabel(frame: CGRect(x: 10, y: 10, width: loginView.bounds.size.width - 20 , height: 80))
inputPhoneLabel.text = ABRAppConfig.texts.inputPhoneText
innerScrollView.addSubview(inputPhoneLabel)
inputCodeLabel = UILabel(frame: CGRect(x: loginView.bounds.size.width + 10, y: 10, width: loginView.bounds.size.width - 20 , height: 80))
inputCodeLabel.text = ABRAppConfig.texts.inputCodeText
innerScrollView.addSubview(inputCodeLabel)
timerLabel = UILabel(frame: CGRect(x: loginView.bounds.size.width + 10, y: loginView.bounds.size.height - 90, width: loginView.bounds.size.width - 20 , height: 20))
innerScrollView.addSubview(timerLabel)
for label in [inputCodeLabel , inputPhoneLabel , timerLabel] {
if ABRAppConfig.font != nil {
label?.font = UIFont(name: ABRAppConfig.font!.fontName, size: ABRAppConfig.font!.pointSize - 2)
}
label?.numberOfLines = 3
label?.textColor = ABRAppConfig.labelsColor
label?.textAlignment = .center
}
}
private func setupScrollView() {
mainScrollView = UIScrollView(frame: view.frame)
mainScrollView.addSubview(dismissButton)
mainScrollView.addSubview(loginView)
mainScrollView.contentSize = view.frame.size
view.addSubview(mainScrollView)
innerScrollView = UIScrollView(frame: loginView.bounds)
innerScrollView.contentSize = CGSize(width: loginView.bounds.size.width * 2 , height: loginView.bounds.size.height)
innerScrollView.showsVerticalScrollIndicator = false
innerScrollView.showsHorizontalScrollIndicator = false
innerScrollView.isScrollEnabled = false
loginView.addSubview(innerScrollView)
}
private func setupDismissButton() {
dismissButton = UIButton(frame: CGRect(x: 0, y: 0, width: view.bounds.size.width, height: view.bounds.size.height))
dismissButton.setTitle(nil, for: .normal)
dismissButton.addTarget(self, action: #selector(dismissAction), for: .touchDown)
view.addSubview(dismissButton)
view.bringSubview(toFront: dismissButton)
}
private func setupLoginView() {
loginView = UIView(frame: CGRect(x: view.bounds.size.width / 2 - 120 ,
y: view.bounds.size.height / 2 - 120 ,
width: 240,
height: 240))
loginView.backgroundColor = UIColor.white
loginView.clipsToBounds = true
loginView.layer.cornerRadius = 10
view.addSubview(loginView)
view.bringSubview(toFront: loginView)
loginView.alpha = 0
loginView.transform = CGAffineTransform(scaleX: 0.7, y: 0.7)
}
private func refreshLayout() {
innerScrollView.frame = loginView.bounds
innerScrollView.contentSize = CGSize(width: loginView.bounds.size.width * 2 , height: loginView.bounds.size.height)
inputPhoneLabel.frame = CGRect(x: inset, y: 10, width: loginView.bounds.size.width - (inset * 2) , height: 80)
inputCodeLabel.frame = CGRect(x: loginView.bounds.size.width + inset, y: 10, width: loginView.bounds.size.width - inset * 2 , height: 80)
confirmPhoneBtn.frame = CGRect(x: inset + 20, y: loginView.bounds.size.height - 60 , width: loginView.bounds.size.width - (inset * 2 + 40) , height: 34)
confirmCodeBtn.frame = CGRect(x: loginView.bounds.size.width + inset + 20, y: loginView.bounds.size.height - 60 , width: loginView.bounds.size.width - (inset * 2 + 40) , height: 34)
backBtn.frame = CGRect(x: loginView.bounds.width, y: 4, width: 30, height: 30)
phoneTf.frame = CGRect(x: inset + 20, y: loginView.bounds.size.height / 2 - 25, width: loginView.bounds.size.width - (inset * 2 + 40), height: 30)
codeTf.frame = CGRect(x: loginView.bounds.size.width + inset + 20, y: loginView.bounds.size.height / 2 - 25 , width: loginView.bounds.size.width - (inset * 2 + 40) , height: 30)
}
//MARK: button selectors
@objc private func sendCodeAction() {
if (phoneTf.text?.characters.count)! == 11 {
confirmPhoneBtn.setTitle(nil, for: .normal)
confirmPhoneBtn.isEnabled = false
let activity = UIActivityIndicatorView(activityIndicatorStyle: .white)
loginView.addSubview(activity)
activity.center = confirmPhoneBtn.center
activity.startAnimating()
ABRPlayer.requestRegisterCode(phoneNumber: phoneTf.text!.englishNumbers()! , completion: {[unowned self] (success, errorType) in
activity.stopAnimating()
activity.removeFromSuperview()
self.confirmPhoneBtn.setTitle(ABRAppConfig.buttonsTitles.loginSendCodeToPhoneButtonTitle, for: .normal)
self.confirmPhoneBtn.isEnabled = true
if success {
self.timer()
self.innerScrollView.setContentOffset(CGPoint(x: self.loginView.bounds.size.width , y:0) , animated: true)
self.codeTf.becomeFirstResponder()
} else {
if ABRAppConfig.loginHasBuiltinErrorMessages {
self.loginView.showOverlayError(errorType!)
}
self.delegate?.errorOccured!(errorType!)
}
})
} else {
print("Phone number is empty")
confirmPhoneBtn.shake()
}
}
@objc private func verifyCodeAction() {
if confirmCodeBtn.tag == 0 {
if (codeTf.text?.characters.count)! == 5 {
confirmCodeBtn.setTitle(nil, for: .normal)
confirmCodeBtn.isEnabled = false
let activity = UIActivityIndicatorView(activityIndicatorStyle: .white)
loginView.addSubview(activity)
loginView.bringSubview(toFront: activity)
activity.center = CGPoint(x: confirmCodeBtn.center.x - loginView.frame.size.width, y: confirmCodeBtn.center.y)
activity.startAnimating()
ABRPlayer.verifyRegisterCode(phoneNumber: phoneTf.text!, code: codeTf.text!, completion: { (success, player , errorType) in
activity.stopAnimating()
activity.removeFromSuperview()
self.confirmCodeBtn.setTitle(ABRAppConfig.buttonsTitles.loginConfirmCodeButtonTitle, for: .normal)
self.confirmCodeBtn.isEnabled = true
if success {
self.view.endEditing(true)
if self.isFullScreen {
self.delegate?.userDidLogin(player!)
} else {
self.dismissAnimation {
self.dismiss(animated: false, completion: nil)
self.delegate?.userDidLogin(player!)
}
}
} else {
if ABRAppConfig.loginHasBuiltinErrorMessages {
self.loginView.showOverlayError(errorType!)
}
self.delegate?.errorOccured!(errorType!)
}
})
} else {
print("code field's length is not 5")
confirmCodeBtn.shake()
}
} else {
ABRPlayer.resendRegisterCode(phoneNumber: phoneTf.text!.englishNumbers()!, completion: { (success, errorType) in
if success {
self.confirmCodeBtn.tag = 0
self.confirmCodeBtn.setTitle("ورود به حساب", for: .normal)
self.timer()
} else {
if ABRAppConfig.loginHasBuiltinErrorMessages {
self.loginView.showOverlayError(errorType!)
}
self.delegate?.errorOccured!(errorType!)
}
})
}
}
@objc private func backToInputPhone() {
innerScrollView.setContentOffset(CGPoint(x: 0 , y: 0), animated: true)
codeTf.text = nil
phoneTf.becomeFirstResponder()
}
@objc private func dismissAction() {
view.endEditing(true)
self.delegate?.userDismissScreen!()
dismissAnimation {
self.dismiss(animated: false, completion: nil)
}
}
//MARK: Timer
func timer() {
var timerCounter = 150
let mins = timerCounter / 60 == 0 ? "0" : "0\(timerCounter / 60)"
let secs = timerCounter % 60 < 10 ? "0\(timerCounter % 60)" : "\(timerCounter % 60)"
timerLabel.text = mins + " : " + secs
ABRTimer.countDownFrom(150, actionBlock: {(current) in
timerCounter -= 1
let mins = timerCounter / 60 == 0 ? "0" : "0\(timerCounter / 60)"
let secs = timerCounter % 60 < 10 ? "0\(timerCounter % 60)" : "\(timerCounter % 60)"
self.timerLabel.text = mins + " : " + secs
}, finished: {
self.timerLabel.text = ""
self.confirmCodeBtn.setTitle("ارسال مجدد کد", for: .normal)
self.confirmCodeBtn.tag = 1
})
}
}
fileprivate extension UIView {
func shake() {
let shake = CAKeyframeAnimation(keyPath: "transform.translation.x")
shake.duration = 0.6
shake.keyTimes = [0, 0.125, 0.25, 0.375, 0.5, 0.625, 0.75, 0.875, 1]
shake.values = [-10 , 10 , -10 , 10 , -7 , 7 , -4 , 0]
self.layer.add(shake, forKey: "shake")
}
}
| mit | 975e3b4702318dd178164413d6878f82 | 40.327451 | 189 | 0.60018 | 4.652759 | false | true | false | false |
Rehsco/StyledAuthenticationView | StyledAuthenticationView/Model/AuthStateMachine.swift | 1 | 2397 | //
// AuthStateMachine.swift
// StyledAuthenticationView
//
// Created by Martin Rehder on 02.02.2017.
/*
* Copyright 2017-present Martin Jacob Rehder.
* http://www.rehsco.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
import Foundation
enum AuthenticationStateType {
case touchID
case pin
case password
}
class AuthStateMachine {
var currentState: AuthenticationStateType = .touchID
var useTouchID: Bool = false
var usePin: Bool = false
var usePassword: Bool = false
func initiate() -> Bool {
if useTouchID {
currentState = .touchID
return true
}
else if usePin {
currentState = .pin
return true
}
else if usePassword {
currentState = .password
return true
}
return false
}
func next() -> Bool {
if currentState == .password {
return false
}
if currentState == .touchID {
currentState = .pin
if !self.usePin {
return self.next()
}
return true
}
if currentState == .pin {
currentState = .password
if !self.usePassword {
return self.next()
}
return true
}
return false
}
}
| mit | 29ee5c12dc4eac80d79384ece890c2af | 28.9625 | 80 | 0.63204 | 4.813253 | false | false | false | false |
nmdias/FeedKit | Sources/FeedKit/Models/Namespaces/Media/MediaCopyright.swift | 2 | 2848 | //
// MediaCopyright.swift
//
// Copyright (c) 2016 - 2018 Nuno Manuel Dias
//
// 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
/// Copyright information for the media object. It has one optional attribute.
public class MediaCopyright {
/// The element's attributes.
public class Attributes {
/// The URL for a terms of use page or additional copyright information.
/// If the media is operating under a Creative Commons license, the
/// Creative Commons module should be used instead. It is an optional
/// attribute.
public var url: String?
}
/// The element's attributes.
public var attributes: Attributes?
/// The element's value.
public var value: String?
public init() { }
}
// MARK: - Initializers
extension MediaCopyright {
convenience init(attributes attributeDict: [String : String]) {
self.init()
self.attributes = MediaCopyright.Attributes(attributes: attributeDict)
}
}
extension MediaCopyright.Attributes {
convenience init?(attributes attributeDict: [String : String]) {
if attributeDict.isEmpty {
return nil
}
self.init()
self.url = attributeDict["url"]
}
}
// MARK: - Equatable
extension MediaCopyright: Equatable {
public static func ==(lhs: MediaCopyright, rhs: MediaCopyright) -> Bool {
return
lhs.value == rhs.value &&
lhs.attributes == rhs.attributes
}
}
extension MediaCopyright.Attributes: Equatable {
public static func ==(lhs: MediaCopyright.Attributes, rhs: MediaCopyright.Attributes) -> Bool {
return lhs.url == rhs.url
}
}
| mit | 5bc56a2517437ce8e0c30c07b26beda5 | 28.360825 | 99 | 0.663975 | 4.707438 | false | false | false | false |
trupin/Beaver | BeaverTestKit/Type/ViewControllerMock.swift | 2 | 853 | import Beaver
public final class ViewControllerStub<StateType: State, ParentStateType: State, AUIActionType: Action>: ViewController<StateType, ParentStateType, AUIActionType> {
public private(set) var stateDidUpdateCallCount = 0
public private(set) var source: ActionEnvelop?
public private(set) var oldState: StateType?
public private(set) var newState: StateType?
public override func stateDidUpdate(oldState: StateType?,
newState: StateType,
completion: @escaping () -> ()) {
self.oldState = oldState
self.newState = newState
stateDidUpdateCallCount += 1
completion()
}
public func clear() {
stateDidUpdateCallCount = 0
source = nil
oldState = nil
newState = nil
}
}
| mit | d148f38fec30f112ea9caf284510f5c8 | 30.592593 | 163 | 0.622509 | 5.265432 | false | false | false | false |
per-dalsgaard/20-apps-in-20-weeks | App 04 - SwappingScreens/SwappingScreens/MusicListVC.swift | 1 | 954 | //
// MusicListVC.swift
// SwappingScreens
//
// Created by Per Kristensen on 02/04/2017.
// Copyright © 2017 Per Dalsgaard. All rights reserved.
//
import UIKit
class MusicListVC: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
view.backgroundColor = UIColor.blue
}
@IBAction func backButtonPressed(_ sender: Any) {
dismiss(animated: true, completion: nil)
}
@IBAction func load3rdScreenPressed(_ sender: Any) {
let songTitle = "Quit Playing Games With My Heart"
performSegue(withIdentifier: "PlaySongVC", sender: songTitle)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let destination = segue.destination as? PlaySongVC {
if let song = sender as? String {
destination.selectedTitle = song
}
}
}
}
| mit | 6e837202a27537875b142319139527b1 | 26.228571 | 71 | 0.634837 | 4.37156 | false | false | false | false |
1yvT0s/XWebView | XWebView/XWVInvocation.swift | 1 | 12436 | /*
Copyright 2015 XWebView
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import Foundation
import ObjectiveC
private let _NSInvocation: AnyClass = NSClassFromString("NSInvocation")!
private let _NSMethodSignature: AnyClass = NSClassFromString("NSMethodSignature")!
public class XWVInvocation {
public final let target: AnyObject
public init(target: AnyObject) {
self.target = target
}
public func call(selector: Selector, withArguments arguments: [Any!]) -> Any! {
let method = class_getInstanceMethod(target.dynamicType, selector)
if method == nil {
// TODO: supports forwordingTargetForSelector: of NSObject?
(target as? NSObject)?.doesNotRecognizeSelector(selector)
// Not an NSObject, mimic the behavior of NSObject
let reason = "-[\(target.dynamicType) \(selector)]: unrecognized selector sent to instance \(unsafeAddressOf(target))"
withVaList([reason]) { NSLogv("%@", $0) }
NSException(name: NSInvalidArgumentException, reason: reason, userInfo: nil).raise()
}
let sig = _NSMethodSignature.signatureWithObjCTypes(method_getTypeEncoding(method))!
let inv = _NSInvocation.invocationWithMethodSignature(sig)
// Setup arguments
assert(arguments.count + 2 <= Int(sig.numberOfArguments), "Too many arguments for calling -[\(target.dynamicType) \(selector)]")
var args = [[Word]](count: arguments.count, repeatedValue: [])
for var i = 0; i < arguments.count; ++i {
let type = sig.getArgumentTypeAtIndex(i + 2)
let typeChar = Character(UnicodeScalar(UInt8(type[0])))
// Convert argument type to adapte requirement of method.
// Firstly, convert argument to appropriate object type.
var argument: Any! = self.dynamicType.convertToObjectFromAnyValue(arguments[i])
assert(argument != nil || arguments[i] == nil, "Can't convert '\(arguments[i].dynamicType)' to object type")
if typeChar != "@", let obj: AnyObject = argument as? AnyObject {
// Convert back to scalar type as method requires.
argument = self.dynamicType.convertFromObject(obj, toObjCType: type)
}
if typeChar == "f", let float = argument as? Float {
// Float type shouldn't be promoted to double if it is not variadic.
args[i] = [ Word(unsafeBitCast(float, UInt32.self)) ]
} else if let val = argument as? CVarArgType {
// Scalar(except float), pointer and Objective-C object types
args[i] = val.encode()
} else if let obj: AnyObject = argument as? AnyObject {
// Pure swift object type
args[i] = [ unsafeBitCast(unsafeAddressOf(obj), Word.self) ]
} else {
// Nil or unsupported type
assert(argument == nil, "Unsupported argument type '\(String(UTF8String: type))'")
var align: Int = 0
NSGetSizeAndAlignment(sig.getArgumentTypeAtIndex(i), nil, &align)
args[i] = [Word](count: align / sizeof(Word.self), repeatedValue: 0)
}
args[i].withUnsafeBufferPointer() {
inv.setArgument(UnsafeMutablePointer($0.baseAddress), atIndex: i + 2)
}
}
inv.selector = selector
inv.invokeWithTarget(target)
if sig.methodReturnLength == 0 { return Void() }
// Fetch the return value
// TODO: Methods with 'ns_returns_retained' attribute cause leak of returned object.
let count = (sig.methodReturnLength + sizeof(Word.self) - 1) / sizeof(Word.self)
var words = [Word](count: count, repeatedValue: 0)
words.withUnsafeMutableBufferPointer() {
(inout buf: UnsafeMutableBufferPointer<Word>)->Void in
inv.getReturnValue(buf.baseAddress)
}
if sig.methodReturnLength <= sizeof(Word) {
// TODO: handle 64 bit type on 32-bit OS
return bitCastWord(words[0], toObjCType: sig.methodReturnType)
}
assertionFailure("Unsupported return type '\(String(UTF8String: sig.methodReturnType))'");
return Void()
}
public func call(selector: Selector, withArguments arguments: Any!...) -> Any! {
return call(selector, withArguments: arguments)
}
// Helper for Objective-C, accept ObjC 'id' instead of Swift 'Any' type for in/out parameters .
@objc public func call(selector: Selector, withObjects objects: [AnyObject]?) -> AnyObject! {
let args: [Any!] = objects?.map() { $0 !== NSNull() ? ($0 as Any) : nil } ?? []
let result = call(selector, withArguments: args)
return self.dynamicType.convertToObjectFromAnyValue(result)
}
// Syntactic sugar for calling method
public subscript (selector: Selector) -> (Any!...)->Any! {
return {
(args: Any!...)->Any! in
self.call(selector, withArguments: args)
}
}
}
extension XWVInvocation {
// Property accessor
public func getProperty(name: String) -> Any! {
let getter = getterOfName(name)
assert(getter != Selector(), "Property '\(name)' does not exist")
return getter != Selector() ? call(getter) : Void()
}
public func setValue(value: Any!, forProperty name: String) {
let setter = setterOfName(name)
assert(setter != Selector(), "Property '\(name)' " +
(getterOfName(name) == nil ? "does not exist" : "is readonly"))
assert(!(value is Void))
if setter != Selector() {
call(setter, withArguments: value)
}
}
// Syntactic sugar for accessing property
public subscript (name: String) -> Any! {
get {
return getProperty(name)
}
set {
setValue(newValue, forProperty: name)
}
}
private func getterOfName(name: String) -> Selector {
var getter = Selector()
let property = class_getProperty(self.target.dynamicType, name)
if property != nil {
let attr = property_copyAttributeValue(property, "G")
getter = Selector(attr == nil ? name : String(UTF8String: attr)!)
free(attr)
}
return getter
}
private func setterOfName(name: String) -> Selector {
var setter = Selector()
let property = class_getProperty(self.target.dynamicType, name)
if property != nil {
var attr = property_copyAttributeValue(property, "R")
if attr == nil {
attr = property_copyAttributeValue(property, "S")
if attr == nil {
setter = Selector("set\(String(first(name)!).uppercaseString)\(dropFirst(name)):")
} else {
setter = Selector(String(UTF8String: attr)!)
}
}
free(attr)
}
return setter
}
}
extension XWVInvocation {
// Type casting and conversion, reference:
// https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/ObjCRuntimeGuide/Articles/ocrtTypeEncodings.html
// Cast Word value to specified Objective-C type (not support 32-bit)
private func bitCastWord(word: Word, toObjCType type: UnsafePointer<Int8>) -> Any? {
switch Character(UnicodeScalar(UInt8(type[0]))) {
case "c": return CChar(truncatingBitPattern: word)
case "i": return CInt(truncatingBitPattern: word)
case "s": return CShort(truncatingBitPattern: word)
case "l": return Int32(truncatingBitPattern: word)
case "q": return CLongLong(word)
case "C": return CUnsignedChar(truncatingBitPattern: word)
case "I": return CUnsignedInt(truncatingBitPattern: word)
case "S": return CUnsignedShort(truncatingBitPattern: word)
case "L": return UInt32(truncatingBitPattern: word)
case "Q": return unsafeBitCast(word, CUnsignedLongLong.self)
case "f": return unsafeBitCast(UInt32(truncatingBitPattern: word), CFloat.self)
case "d": return unsafeBitCast(word, CDouble.self)
case "B": return unsafeBitCast(UInt8(truncatingBitPattern: word), CBool.self)
case "v": return unsafeBitCast(word, Void.self)
case "*": return unsafeBitCast(word, UnsafePointer<CChar>.self)
case "@": return word != 0 ? unsafeBitCast(word, AnyObject.self) : nil
case "#": return unsafeBitCast(word, AnyClass.self)
case ":": return unsafeBitCast(word, Selector.self)
case "^", "?": return unsafeBitCast(word, COpaquePointer.self)
default: assertionFailure("Unknown Objective-C type encoding '\(String(UTF8String: type))'")
}
return Void()
}
// Convert AnyObject to appropriate Objective-C type
private class func convertFromObject(object: AnyObject, toObjCType type: UnsafePointer<Int8>) -> Any! {
let num = object as? NSNumber
switch Character(UnicodeScalar(UInt8(type[0]))) {
case "c": return num?.charValue
case "i": return num?.intValue
case "s": return num?.shortValue
case "l": return num?.intValue
case "q": return num?.longLongValue
case "C": return num?.unsignedCharValue
case "I": return num?.unsignedIntValue
case "S": return num?.unsignedShortValue
case "L": return num?.unsignedIntValue
case "Q": return num?.unsignedLongLongValue
case "f": return num?.floatValue
case "d": return num?.doubleValue
case "B": return num?.boolValue
case "v": return Void()
case "*": return (object as? String)?.nulTerminatedUTF8.withUnsafeBufferPointer({ COpaquePointer($0.baseAddress) })
case ":": return object is String ? Selector(object as! String) : Selector()
case "@": return object
case "#": return object
case "^", "?": return (object as? NSValue)?.pointerValue()
default: assertionFailure("Unknown Objective-C type encoding '\(String(UTF8String: type))'")
}
return nil
}
// Convert Any value to appropriate Objective-C object
public class func convertToObjectFromAnyValue(value: Any!) -> AnyObject! {
if value == nil || value is AnyObject {
// Some scalar types (Int, UInt, Bool, Float and Double) can be converted automatically by runtime.
return value as? AnyObject
}
if let i8 = value as? Int8 { return NSNumber(char: i8) } else
if let i16 = value as? Int16 { return NSNumber(short: i16) } else
if let i32 = value as? Int32 { return NSNumber(int: i32) } else
if let i64 = value as? Int64 { return NSNumber(longLong: i64) } else
if let u8 = value as? UInt8 { return NSNumber(unsignedChar: u8) } else
if let u16 = value as? UInt16 { return NSNumber(unsignedShort: u16) } else
if let u32 = value as? UInt32 { return NSNumber(unsignedInt: u32) } else
if let u64 = value as? UInt64 { return NSNumber(unsignedLongLong: u64) } else
if let us = value as? UnicodeScalar { return NSNumber(unsignedInt: us.value) } else
if let sel = value as? Selector { return sel.description } else
if let ptr = value as? COpaquePointer { return NSValue(pointer: UnsafePointer<Void>(ptr)) }
//assertionFailure("Can't convert '\(value.dynamicType)' to AnyObject")
return nil
}
}
// Additional Swift types which can be represented in C type.
extension Bool: CVarArgType {
public func encode() -> [Word] {
return [ Word(self) ]
}
}
extension UnicodeScalar: CVarArgType {
public func encode() -> [Word] {
return [ Word(self.value) ]
}
}
extension Selector: CVarArgType {
public func encode() -> [Word] {
return [ unsafeBitCast(self, Word.self) ]
}
}
| apache-2.0 | 4bd9e9e39775b84353b9afd9b5288417 | 44.386861 | 136 | 0.627211 | 4.585546 | false | false | false | false |
intelygenz/NetClient-iOS | URLSession/NetURLSessionDelegate.swift | 1 | 5296 | //
// NetURLSessionDelegate.swift
// Net
//
// Created by Alex Rupérez on 17/3/17.
//
//
import Foundation
class NetURLSessionDelegate: NSObject {
weak var netURLSession: NetURLSession?
final var tasks = [URLSessionTask: NetTask]()
init(_ urlSession: NetURLSession) {
netURLSession = urlSession
super.init()
}
func add(_ task: URLSessionTask, _ netTask: NetTask?) {
tasks[task] = netTask
}
deinit {
tasks.removeAll()
netURLSession = nil
}
}
extension NetURLSessionDelegate: URLSessionDelegate {}
extension NetURLSessionDelegate: URLSessionTaskDelegate {
func urlSession(_ session: URLSession, task: URLSessionTask, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Swift.Void) {
handle(challenge, tasks[task], completion: completionHandler)
}
@available(iOS 10.0, tvOS 10.0, watchOS 3.0, macOS 10.12, *)
func urlSession(_ session: URLSession, task: URLSessionTask, didFinishCollecting taskMetrics: URLSessionTaskMetrics) {
if let netTask = tasks[task] {
netTask.metrics = NetTaskMetrics(taskMetrics, request: netTask.request, response: netTask.response)
tasks[task] = nil
}
}
@available(iOS 11.0, tvOS 11.0, watchOS 4.0, macOS 10.13, *)
func urlSession(_ session: URLSession, task: URLSessionTask, willBeginDelayedRequest request: URLRequest, completionHandler: @escaping (URLSession.DelayedRequestDisposition, URLRequest?) -> Void) {
completionHandler(.continueLoading, nil)
}
@available(iOS 11.0, tvOS 11.0, watchOS 4.0, macOS 10.13, *)
func urlSession(_ session: URLSession, taskIsWaitingForConnectivity task: URLSessionTask) {
if let netTask = tasks[task] {
netTask.state = .waitingForConnectivity
}
}
func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
if let netTask = tasks[task] {
let netError = netURLSession?.netError(error, netTask.response?.responseObject, task.response)
netURLSession?.process(netTask, netTask.response, netError)
tasks[task] = nil
}
}
}
extension NetURLSessionDelegate: URLSessionDataDelegate {
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
if let netTask = tasks[dataTask] {
guard let response = netTask.response, var oldData = try? response.object() as Data else {
tasks[dataTask]?.response = netURLSession?.netResponse(dataTask.response, netTask, data)
return
}
tasks[dataTask]?.response = netURLSession?.netResponse(dataTask.response, netTask, oldData.append(data))
}
}
}
extension NetURLSessionDelegate: URLSessionDownloadDelegate {
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {}
}
@available(iOS 9.0, *)
extension NetURLSessionDelegate: URLSessionStreamDelegate {}
extension NetURLSessionDelegate {
func handle(_ challenge: URLAuthenticationChallenge, _ netTask: NetTask? = nil, completion: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Swift.Void) {
guard let authChallenge = netURLSession?.authChallenge else {
guard challenge.previousFailureCount == 0 else {
challenge.sender?.cancel(challenge)
if let realm = challenge.protectionSpace.realm {
print(realm)
print(challenge.protectionSpace.authenticationMethod)
}
completion(.cancelAuthenticationChallenge, nil)
return
}
var credential: URLCredential? = challenge.proposedCredential
if credential?.hasPassword != true, challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodHTTPBasic || challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodHTTPDigest, let request = netTask?.request {
switch request.authorization {
case .basic(let user, let password):
credential = URLCredential(user: user, password: password, persistence: .forSession)
default:
break
}
}
if credential == nil, challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust, let serverTrust = challenge.protectionSpace.serverTrust {
let host = challenge.protectionSpace.host
if let policy = netURLSession?.serverTrust[host] {
if policy.evaluate(serverTrust, host: host) {
credential = URLCredential(trust: serverTrust)
} else {
credential = nil
}
} else {
credential = URLCredential(trust: serverTrust)
}
}
completion(credential != nil ? .useCredential : .cancelAuthenticationChallenge, credential)
return
}
authChallenge(challenge, completion)
}
}
| mit | 09d426309c26f418c91008e89578da6a | 37.093525 | 255 | 0.651747 | 5.28971 | false | false | false | false |
koher/Alamofire | Tests/TLSEvaluationTests.swift | 1 | 17070 | // DownloadTests.swift
//
// Copyright (c) 2014–2015 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 Alamofire
import Foundation
import XCTest
private struct TestCertificates {
static let RootCA = TestCertificates.certificateWithFileName("root-ca-disig")
static let IntermediateCA = TestCertificates.certificateWithFileName("intermediate-ca-disig")
static let Leaf = TestCertificates.certificateWithFileName("testssl-expire.disig.sk")
static func certificateWithFileName(fileName: String) -> SecCertificate {
class Bundle {}
let filePath = NSBundle(forClass: Bundle.self).pathForResource(fileName, ofType: "cer")!
let data = NSData(contentsOfFile: filePath)!
let certificate = SecCertificateCreateWithData(nil, data).takeRetainedValue()
return certificate
}
}
// MARK: -
private struct TestPublicKeys {
static let RootCA = TestPublicKeys.publicKeyForCertificate(TestCertificates.RootCA)
static let IntermediateCA = TestPublicKeys.publicKeyForCertificate(TestCertificates.IntermediateCA)
static let Leaf = TestPublicKeys.publicKeyForCertificate(TestCertificates.Leaf)
static func publicKeyForCertificate(certificate: SecCertificate) -> SecKey {
let policy = SecPolicyCreateBasicX509().takeRetainedValue()
var unmanagedTrust: Unmanaged<SecTrust>?
let trustCreationStatus = SecTrustCreateWithCertificates(certificate, policy, &unmanagedTrust)
let trust = unmanagedTrust!.takeRetainedValue()
let publicKey = SecTrustCopyPublicKey(trust).takeRetainedValue()
return publicKey
}
}
// MARK: -
class TLSEvaluationExpiredLeafCertificateTestCase: BaseTestCase {
let URL = "https://testssl-expire.disig.sk/"
let host = "testssl-expire.disig.sk"
var configuration: NSURLSessionConfiguration!
// MARK: Setup and Teardown
override func setUp() {
super.setUp()
self.configuration = NSURLSessionConfiguration.ephemeralSessionConfiguration()
}
// MARK: Default Behavior Tests
func testThatExpiredCertificateRequestFailsWithNoServerTrustPolicy() {
// Given
let expectation = expectationWithDescription("\(self.URL)")
let manager = Manager(configuration: self.configuration)
var error: NSError?
// When
manager.request(.GET, self.URL)
.response { _, _, _, responseError in
error = responseError
expectation.fulfill()
}
waitForExpectationsWithTimeout(self.defaultTimeout, handler: nil)
// Then
XCTAssertNotNil(error, "error should not be nil")
XCTAssertEqual(error?.code ?? -1, NSURLErrorServerCertificateUntrusted, "error should be NSURLErrorServerCertificateUntrusted")
}
// MARK: Server Trust Policy - Perform Default Tests
func testThatExpiredCertificateRequestFailsWithDefaultServerTrustPolicy() {
// Given
let policies = [self.host: ServerTrustPolicy.PerformDefaultEvaluation(validateHost: true)]
let manager = Manager(
configuration: self.configuration,
serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
)
let expectation = expectationWithDescription("\(self.URL)")
var error: NSError?
// When
manager.request(.GET, self.URL)
.response { _, _, _, responseError in
error = responseError
expectation.fulfill()
}
waitForExpectationsWithTimeout(self.defaultTimeout, handler: nil)
// Then
XCTAssertNotNil(error, "error should not be nil")
XCTAssertEqual(error?.code ?? -1, NSURLErrorCancelled, "error should be NSURLErrorCancelled")
}
// MARK: Server Trust Policy - Certificate Pinning Tests
func testThatExpiredCertificateRequestFailsWhenPinningLeafCertificateWithCertificateChainValidation() {
// Given
let certificates = [TestCertificates.Leaf]
let policies: [String: ServerTrustPolicy] = [
self.host: .PinCertificates(certificates: certificates, validateCertificateChain: true, validateHost: true)
]
let manager = Manager(
configuration: self.configuration,
serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
)
let expectation = expectationWithDescription("\(self.URL)")
var error: NSError?
// When
manager.request(.GET, self.URL)
.response { _, _, _, responseError in
error = responseError
expectation.fulfill()
}
waitForExpectationsWithTimeout(self.defaultTimeout, handler: nil)
// Then
XCTAssertNotNil(error, "error should not be nil")
XCTAssertEqual(error?.code ?? -1, NSURLErrorCancelled, "error should be NSURLErrorCancelled")
}
func testThatExpiredCertificateRequestFailsWhenPinningAllCertificatesWithCertificateChainValidation() {
// Given
let certificates = [TestCertificates.Leaf, TestCertificates.IntermediateCA, TestCertificates.RootCA]
let policies: [String: ServerTrustPolicy] = [
self.host: .PinCertificates(certificates: certificates, validateCertificateChain: true, validateHost: true)
]
let manager = Manager(
configuration: self.configuration,
serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
)
let expectation = expectationWithDescription("\(self.URL)")
var error: NSError?
// When
manager.request(.GET, self.URL)
.response { _, _, _, responseError in
error = responseError
expectation.fulfill()
}
waitForExpectationsWithTimeout(self.defaultTimeout, handler: nil)
// Then
XCTAssertNotNil(error, "error should not be nil")
XCTAssertEqual(error?.code ?? -1, NSURLErrorCancelled, "error should be NSURLErrorCancelled")
}
func testThatExpiredCertificateRequestSucceedsWhenPinningLeafCertificateWithoutCertificateChainValidation() {
// Given
let certificates = [TestCertificates.Leaf]
let policies: [String: ServerTrustPolicy] = [
self.host: .PinCertificates(certificates: certificates, validateCertificateChain: false, validateHost: true)
]
let manager = Manager(
configuration: self.configuration,
serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
)
let expectation = expectationWithDescription("\(self.URL)")
var error: NSError?
// When
manager.request(.GET, self.URL)
.response { _, _, _, responseError in
error = responseError
expectation.fulfill()
}
waitForExpectationsWithTimeout(self.defaultTimeout, handler: nil)
// Then
XCTAssertNil(error, "error should be nil")
}
func testThatExpiredCertificateRequestSucceedsWhenPinningIntermediateCACertificateWithoutCertificateChainValidation() {
// Given
let certificates = [TestCertificates.IntermediateCA]
let policies: [String: ServerTrustPolicy] = [
self.host: .PinCertificates(certificates: certificates, validateCertificateChain: false, validateHost: true)
]
let manager = Manager(
configuration: self.configuration,
serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
)
let expectation = expectationWithDescription("\(self.URL)")
var error: NSError?
// When
manager.request(.GET, self.URL)
.response { _, _, _, responseError in
error = responseError
expectation.fulfill()
}
waitForExpectationsWithTimeout(self.defaultTimeout, handler: nil)
// Then
XCTAssertNil(error, "error should be nil")
}
func testThatExpiredCertificateRequestSucceedsWhenPinningRootCACertificateWithoutCertificateChainValidation() {
// Given
let certificates = [TestCertificates.RootCA]
let policies: [String: ServerTrustPolicy] = [
self.host: .PinCertificates(certificates: certificates, validateCertificateChain: false, validateHost: true)
]
let manager = Manager(
configuration: self.configuration,
serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
)
let expectation = expectationWithDescription("\(self.URL)")
var error: NSError?
// When
manager.request(.GET, self.URL)
.response { _, _, _, responseError in
error = responseError
expectation.fulfill()
}
waitForExpectationsWithTimeout(self.defaultTimeout, handler: nil)
// Then
XCTAssertNil(error, "error should be nil")
}
// MARK: Server Trust Policy - Public Key Pinning Tests
func testThatExpiredCertificateRequestFailsWhenPinningLeafPublicKeyWithCertificateChainValidation() {
// Given
let publicKeys = [TestPublicKeys.Leaf]
let policies: [String: ServerTrustPolicy] = [
self.host: .PinPublicKeys(publicKeys: publicKeys, validateCertificateChain: true, validateHost: true)
]
let manager = Manager(
configuration: self.configuration,
serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
)
let expectation = expectationWithDescription("\(self.URL)")
var error: NSError?
// When
manager.request(.GET, self.URL)
.response { _, _, _, responseError in
error = responseError
expectation.fulfill()
}
waitForExpectationsWithTimeout(self.defaultTimeout, handler: nil)
// Then
XCTAssertNotNil(error, "error should not be nil")
XCTAssertEqual(error?.code ?? -1, NSURLErrorCancelled, "error should be NSURLErrorCancelled")
}
func testThatExpiredCertificateRequestSucceedsWhenPinningLeafPublicKeyWithoutCertificateChainValidation() {
// Given
let publicKeys = [TestPublicKeys.Leaf]
let policies: [String: ServerTrustPolicy] = [
self.host: .PinPublicKeys(publicKeys: publicKeys, validateCertificateChain: false, validateHost: true)
]
let manager = Manager(
configuration: self.configuration,
serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
)
let expectation = expectationWithDescription("\(self.URL)")
var error: NSError?
// When
manager.request(.GET, self.URL)
.response { _, _, _, responseError in
error = responseError
expectation.fulfill()
}
waitForExpectationsWithTimeout(self.defaultTimeout, handler: nil)
// Then
XCTAssertNil(error, "error should be nil")
}
func testThatExpiredCertificateRequestSucceedsWhenPinningIntermediateCAPublicKeyWithoutCertificateChainValidation() {
// Given
let publicKeys = [TestPublicKeys.IntermediateCA]
let policies: [String: ServerTrustPolicy] = [
self.host: .PinPublicKeys(publicKeys: publicKeys, validateCertificateChain: false, validateHost: true)
]
let manager = Manager(
configuration: self.configuration,
serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
)
let expectation = expectationWithDescription("\(self.URL)")
var error: NSError?
// When
manager.request(.GET, self.URL)
.response { _, _, _, responseError in
error = responseError
expectation.fulfill()
}
waitForExpectationsWithTimeout(self.defaultTimeout, handler: nil)
// Then
XCTAssertNil(error, "error should be nil")
}
func testThatExpiredCertificateRequestSucceedsWhenPinningRootCAPublicKeyWithoutCertificateChainValidation() {
// Given
let publicKeys = [TestPublicKeys.RootCA]
let policies: [String: ServerTrustPolicy] = [
self.host: .PinPublicKeys(publicKeys: publicKeys, validateCertificateChain: false, validateHost: true)
]
let manager = Manager(
configuration: self.configuration,
serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
)
let expectation = expectationWithDescription("\(self.URL)")
var error: NSError?
// When
manager.request(.GET, self.URL)
.response { _, _, _, responseError in
error = responseError
expectation.fulfill()
}
waitForExpectationsWithTimeout(self.defaultTimeout, handler: nil)
// Then
XCTAssertNil(error, "error should be nil")
}
// MARK: Server Trust Policy - Disabling Evaluation Tests
func testThatExpiredCertificateRequestSucceedsWhenDisablingEvaluation() {
// Given
let policies = [self.host: ServerTrustPolicy.DisableEvaluation]
let manager = Manager(
configuration: self.configuration,
serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
)
let expectation = expectationWithDescription("\(self.URL)")
var error: NSError?
// When
manager.request(.GET, self.URL)
.response { _, _, _, responseError in
error = responseError
expectation.fulfill()
}
waitForExpectationsWithTimeout(self.defaultTimeout, handler: nil)
// Then
XCTAssertNil(error, "error should be nil")
}
// MARK: Server Trust Policy - Custom Evaluation Tests
func testThatExpiredCertificateRequestSucceedsWhenCustomEvaluationReturnsTrue() {
// Given
let policies = [
self.host: ServerTrustPolicy.CustomEvaluation { _, _ in
// Implement a custom evaluation routine here...
return true
}
]
let manager = Manager(
configuration: self.configuration,
serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
)
let expectation = expectationWithDescription("\(self.URL)")
var error: NSError?
// When
manager.request(.GET, self.URL)
.response { _, _, _, responseError in
error = responseError
expectation.fulfill()
}
waitForExpectationsWithTimeout(self.defaultTimeout, handler: nil)
// Then
XCTAssertNil(error, "error should be nil")
}
func testThatExpiredCertificateRequestFailsWhenCustomEvaluationReturnsFalse() {
// Given
let policies = [
self.host: ServerTrustPolicy.CustomEvaluation { _, _ in
// Implement a custom evaluation routine here...
return false
}
]
let manager = Manager(
configuration: self.configuration,
serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
)
let expectation = expectationWithDescription("\(self.URL)")
var error: NSError?
// When
manager.request(.GET, self.URL)
.response { _, _, _, responseError in
error = responseError
expectation.fulfill()
}
waitForExpectationsWithTimeout(self.defaultTimeout, handler: nil)
// Then
XCTAssertNotNil(error, "error should not be nil")
XCTAssertEqual(error?.code ?? -1, NSURLErrorCancelled, "error should be NSURLErrorCancelled")
}
}
| mit | 9eb25af164e13a7847c4c0ecf67c5ffe | 35.237792 | 135 | 0.654675 | 6.00563 | false | true | false | false |
caronae/caronae-ios | Caronae/Ride/RideCell.swift | 1 | 2861 | import UIKit
class RideCell: UITableViewCell {
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var arrivalDateTimeLabel: UILabel!
@IBOutlet weak var driverNameLabel: UILabel!
@IBOutlet weak var photo: UIImageView!
@IBOutlet weak var badgeLabel: UILabel!
var ride: Ride!
var color: UIColor! {
didSet {
titleLabel.textColor = color
arrivalDateTimeLabel.textColor = color
driverNameLabel.textColor = color
photo.layer.borderColor = color.cgColor
tintColor = color
}
}
var badgeCount: Int! {
didSet {
if badgeCount > 0 {
badgeLabel.text = String(badgeCount)
badgeLabel.isHidden = false
} else {
badgeLabel.isHidden = true
}
}
}
let dateFormatter = DateFormatter()
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
dateFormatter.dateFormat = "HH:mm | E | dd/MM"
}
/// Configures the cell with a Ride object, updating the cell's labels and style accordingly.
///
/// - parameter ride: A Ride object.
func configureCell(with ride: Ride) {
configureBasicCell(with: ride)
accessoryType = .disclosureIndicator
if ride.going {
arrivalDateTimeLabel.text = String(format: "Chegando às %@", dateString())
} else {
arrivalDateTimeLabel.text = String(format: "Saindo às %@", dateString())
}
}
/// Configures the cell with a Ride object which belongs to a user's ride history, updating the cell's labels and style accordingly.
///
/// - parameter ride: A Ride object.
func configureHistoryCell(with ride: Ride) {
configureBasicCell(with: ride)
accessoryType = .none
if ride.going {
arrivalDateTimeLabel.text = String(format: "Chegou às %@", dateString())
} else {
arrivalDateTimeLabel.text = String(format: "Saiu às %@", dateString())
}
}
func configureBasicCell(with ride: Ride) {
self.ride = ride
titleLabel.text = ride.title.uppercased()
driverNameLabel.text = ride.driver.shortName
updatePhoto()
color = PlaceService.instance.color(forZone: ride.region)
badgeLabel.isHidden = true
}
func dateString() -> String {
return dateFormatter.string(from: ride.date).capitalized(after: "|")
}
func updatePhoto() {
if let profilePictureURL = ride.driver.profilePictureURL, !profilePictureURL.isEmpty {
photo.crn_setImage(with: URL(string: profilePictureURL))
} else {
photo.image = UIImage(named: CaronaePlaceholderProfileImage)
}
}
}
| gpl-3.0 | ecf5f8d65a3ad1b02ce47d4080db3c6e | 31.101124 | 136 | 0.59678 | 4.900515 | false | true | false | false |
kildevaeld/Sockets | Pod/Classes/DNS/in_addr.swift | 1 | 2067 | //
// in_addr.swift
// Sock
//
// Created by Rasmus Kildevæld on 27/07/15.
// Copyright © 2015 Rasmus Kildevæld . All rights reserved.
//
import Foundation
public extension in_addr {
public init() {
s_addr = INADDR_ANY.s_addr
}
public init(string: String?) {
if let s = string {
if s.isEmpty {
s_addr = INADDR_ANY.s_addr
}
else {
var buf = INADDR_ANY // Swift wants some initialization
s.withCString { cs in inet_pton(AF_INET, cs, &buf) }
s_addr = buf.s_addr
}
}
else {
s_addr = INADDR_ANY.s_addr
}
}
public var asString: String {
if self == INADDR_ANY {
return "*.*.*.*"
}
let len = Int(INET_ADDRSTRLEN) + 2
var buf = [CChar](count: len, repeatedValue: 0)
var selfCopy = self // &self doesn't work, because it can be const?
let cs = inet_ntop(AF_INET, &selfCopy, &buf, socklen_t(len))
return String.fromCString(cs)!
}
}
public func ==(lhs: in_addr, rhs: in_addr) -> Bool {
return __uint32_t(lhs.s_addr) == __uint32_t(rhs.s_addr)
}
extension in_addr : Equatable, Hashable {
public var hashValue: Int {
// Knuth?
return Int(UInt32(s_addr) * 2654435761 % (2^32))
}
}
extension in_addr: StringLiteralConvertible {
// this allows you to do: let addr : in_addr = "192.168.0.1"
public init(stringLiteral value: StringLiteralType) {
self.init(string: value)
}
public init(extendedGraphemeClusterLiteral v: ExtendedGraphemeClusterType) {
self.init(string: v)
}
public init(unicodeScalarLiteral value: String) {
// FIXME: doesn't work with UnicodeScalarLiteralType?
self.init(string: value)
}
}
extension in_addr: CustomStringConvertible {
public var description: String {
return asString
}
}
| mit | f9de29bcf55cb2aba3be75b81ece125e | 21.933333 | 80 | 0.541667 | 3.923954 | false | false | false | false |
zjjzmw1/speedxSwift | speedxSwift/Pods/Log/Source/Theme.swift | 1 | 2915 | //
// Theme.swift
//
// Copyright (c) 2015-2016 Damien (http://delba.io)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
public class Themes {}
public class Theme: Themes {
/// The theme colors.
internal var colors: [Level: String]
/// The theme textual representation.
internal var description: String {
return colors.keys.sort().map {
$0.description.withColor(colors[$0]!)
}.joinWithSeparator(" ")
}
/**
Creates and returns a theme with the specified colors.
- parameter trace: The color for the trace level.
- parameter debug: The color for the debug level.
- parameter info: The color for the info level.
- parameter warning: The color for the warning level.
- parameter error: The color for the error level.
- returns: A theme with the specified colors.
*/
public init(trace: String, debug: String, info: String, warning: String, error: String) {
self.colors = [
.Trace: Theme.formatHex(trace),
.Debug: Theme.formatHex(debug),
.Info: Theme.formatHex(info),
.Warning: Theme.formatHex(warning),
.Error: Theme.formatHex(error)
]
}
/**
Returns a string representation of the hex color.
- parameter hex: The hex color.
- returns: A string representation of the hex color.
*/
private static func formatHex(hex: String) -> String {
let scanner = NSScanner(string: hex)
var hex: UInt32 = 0
scanner.charactersToBeSkipped = NSCharacterSet(charactersInString: "#")
scanner.scanHexInt(&hex)
let r = (hex & 0xFF0000) >> 16
let g = (hex & 0xFF00) >> 8
let b = (hex & 0xFF)
return [r, g, b].map({ String($0) }).joinWithSeparator(",")
}
} | mit | 910a60eb7f4f9b2674857e81b38c5f2a | 35.911392 | 93 | 0.649057 | 4.443598 | false | false | false | false |
PlutoMa/EmployeeCard | EmployeeCard/EmployeeCard/Model/WeddingModel.swift | 1 | 1006 | //
// WeddingModel.swift
// EmployeeCard
//
// Created by PlutoMa on 2017/4/7.
// Copyright © 2017年 PlutoMa. All rights reserved.
//
import Foundation
class WeddingModel {
let mid: String
let mdepart: String
let mname: String
let wname: String
let shortdate: String
let lxr: String
let email: String
let marrydate: String
let hotel: String
let photo: String
let type: String
init(mid: String?, mdepart: String?, mname: String?, wname: String?, shortdate: String?, lxr: String?, email: String?, marrydate: String?, hotel: String?, photo: String?, type: String?) {
self.mid = mid ?? ""
self.mdepart = mdepart ?? ""
self.mname = mname ?? ""
self.wname = wname ?? ""
self.shortdate = shortdate ?? ""
self.lxr = lxr ?? ""
self.email = email ?? ""
self.marrydate = marrydate ?? ""
self.hotel = hotel ?? ""
self.photo = photo ?? ""
self.type = type ?? ""
}
}
| mit | a8f325de67f8f7a6fa9500213861058c | 26.108108 | 191 | 0.575274 | 3.569395 | false | false | false | false |
ustwo/formvalidator-swift | Sources/Protocols/Form.swift | 1 | 3163 | //
// Form.swift
// FormValidatorSwift
//
// Created by Aaron McTavish on 14/01/2016.
// Copyright © 2016 ustwo Fampany Ltd. All rights reserved.
//
import Foundation
/**
* A form to assist in validating `ValidatorControl` objects' current states.
*/
public protocol Form {
// MARK: - Properties
/// Entries in the form.
var entries: [FormEntry] { get set }
/// Whether or not the entire form is valid.
var isValid: Bool { get }
// MARK: - Initializers
/**
Creates an empty `Form`.
*/
init()
/**
Creates a `Form` where each `Validatable` uses its own `Validator` for validation.
- parameter validatables: Array of `Validatable`.
*/
init(validatables: [ValidatorControl])
/**
Creates a `Form` where each `Validatable` uses a custom `Validator` for validation. If `validatables` and `validators` have a different number of elements then returns `nil`.
- parameter validatables: Array of `Validatable`.
- parameter validators: Array of `Validator`.
*/
init?(validatables: [ValidatorControl], validators: [Validator])
// MARK: - Manipulate Entry
mutating func addEntry(_ control: ValidatorControl)
mutating func removeControlAtIndex(_ index: Int) -> ValidatorControl?
// MARK: - Check
/**
Checks the text from each entry in `entries`.
- returns: An array of conditions that were violated. If no conditions were violated then `nil` is returned.
*/
func checkConditions() -> [Condition]?
}
// Default implementation for `isValid`, `init(validatables:)`, `init?(validatables:validators:)`, and `checkConditions`.
public extension Form {
// MARK: - Properties
var isValid: Bool {
return checkConditions() == nil
}
// MARK: - Initializers
init(validatables: [ValidatorControl]) {
self.init()
entries = validatables.map { FormEntry(validatable: $0, validator: $0.validator) }
}
init?(validatables: [ValidatorControl], validators: [Validator]) {
guard validatables.count == validators.count else {
return nil
}
self.init()
var entries = [FormEntry]()
for index in 0 ..< validatables.count {
entries.append(FormEntry(validatable: validatables[index], validator: validators[index]))
}
self.entries = entries
}
// MARK: - Manipulate Entry
mutating func addEntry(_ control: ValidatorControl) {
entries.append(FormEntry(validatable: control, validator: control.validator))
}
mutating func removeControlAtIndex(_ index: Int) -> ValidatorControl? {
let entry = entries.remove(at: index)
return entry.validatable
}
// MARK: - Check
func checkConditions() -> [Condition]? {
let violatedConditions = entries.map { $0.checkConditions() }.filter { $0 != nil }.map { $0! }.flatMap { $0 }
return violatedConditions.isEmpty ? nil : violatedConditions
}
}
| mit | ef4c55bac67fe6b92f87336e63bbdcd3 | 25.79661 | 179 | 0.610689 | 4.497866 | false | false | false | false |
openbuild-sheffield/jolt | Sources/RouteAuth/repository.UserLinkRole.swift | 1 | 2642 | import OpenbuildMysql
import OpenbuildRepository
import OpenbuildSingleton
public class RepositoryUserLinkRole: OpenbuildMysql.OBMySQL {
public init() throws {
guard let connectionDetails = OpenbuildSingleton.Manager.getConnectionDetails(
module: "auth",
name: "role",
type: "mysql"
)else{
throw RepoError.connection(
messagePublic: "Connection details not found for RouteAuth:Auth",
messageDev: "Connection details not found for RouteAuth:Auth auth:role:mysql"
)
}
try super.init(
connectionParams: connectionDetails.connectionParams as! MySQLConnectionParams,
database: connectionDetails.connectionDetails.db
)
}
public func install() throws -> Bool {
let installed = try super.tableExists(table: "userLinkRole")
if installed == false {
print("installed: \(installed)")
let installSQL = String(current: #file, path: "SQL/userLinkRole.sql")
print("DOING CREATE TABLE:")
print(installSQL!)
let created = try super.tableCreate(statement: installSQL!)
print("created: \(created)")
let insertSQL = String(current: #file, path: "SQL/userLinkRoleInsert.sql")
print("INSERT DATA:")
print(insertSQL!)
let results = insert(
statement: insertSQL!
)
print(results)
} else {
print("installed: \(installed)")
}
//TODO - upgrades
return true
}
public func addRole(user: ModelUserPlainMin, role: ModelRole) -> ModelRole{
let results = insert(
statement: "INSERT INTO userLinkRole (user_id, role_id) VALUES (?, ?)",
params: [user.user_id!, role.role_id!]
)
if results.error == true {
role.errors["insert"] = results.errorMessage
} else if results.affectedRows! != 1 {
role.errors["insert"] = "Failed to insert."
}
return role
}
public func deleteRole(user: ModelUserPlainMin, role: ModelRole) -> ModelRole{
let results = insert(
statement: "DELETE FROM userLinkRole WHERE user_id = ? AND role_id = ?",
params: [user.user_id!, role.role_id!]
)
if results.error == true {
role.errors["delete"] = results.errorMessage
} else if results.affectedRows! != 1 {
role.errors["delete"] = "Failed to insert."
}
return role
}
} | gpl-2.0 | ca03c40907b152795783be43a9bdd4a3 | 25.168317 | 95 | 0.569644 | 4.659612 | false | false | false | false |
DataBreweryIncubator/StructuredQuery | Tests/RelationTests/RelationTests.swift | 1 | 8210 | import XCTest
@testable import Relation
@testable import Schema
@testable import Types
// TODO: Base Tables!!!
let events = Relation.table(Table("events",
Column("id", INTEGER),
Column("name", TEXT),
Column("value", INTEGER)
))
let contacts = Relation.table(Table("contacts",
Column("id", INTEGER),
Column("address", TEXT),
Column("city", TEXT),
Column("country", TEXT)
))
let a = Relation.table(Table("a", Column("id", INTEGER)))
let b = Relation.table(Table("b", Column("id", INTEGER)))
let c = Relation.table(Table("c", Column("id", INTEGER)))
class ProjectionTestCase: XCTestCase {
func testProjectionFromNothing(){
//
// SELECT 1
//
let list: [Expression] = [1]
var rel: Relation = Relation.projection(list, .none)
// Relation Conformance
XCTAssertEqual(rel.projectedExpressions, list)
XCTAssertEqual(rel.attributeReferences, [
AttributeReference(index:.concrete(0), name: nil, relation: rel)
])
//
// SELECT 1 as scalar
//
let expr = Expression.integer(1).label(as: "scalar")
rel = Relation.projection([expr], .none)
XCTAssertEqual(rel.attributeReferences, [
AttributeReference(index:.concrete(0), name: "scalar", relation: rel)
])
}
// Table
// -----
func testSelectAllFromOneTable() {
//
// SELECT id, name, value FROM events
//
let p1: Relation
let p2: Relation
let exprs = events.projectedExpressions
p1 = .projection(exprs, events.relation)
XCTAssertEqual(p1.attributeReferences, [
AttributeReference(index:.concrete(0), name: "id", relation: p1),
AttributeReference(index:.concrete(1), name: "name", relation: p1),
AttributeReference(index:.concrete(2), name: "value", relation: p1)
])
// XCTAssertEqual(select.baseTables, [events])
//
// SELECT id, name, value FROM (SELECT id, name, value FROM events)
//
p2 = events.project()
XCTAssertEqual(p2.attributeReferences, [
AttributeReference(index:.concrete(0), name: "id", relation: p2),
AttributeReference(index:.concrete(1), name: "name", relation: p2),
AttributeReference(index:.concrete(2), name: "value", relation: p2)
])
XCTAssertEqual(p1, p2)
}
func testSelectSomethingFromTable() {
//
// SELECT id, name FROM events
//
let p: Relation
let list: [Expression] = [events["name"], events["id"]]
p = .projection(list, events.relation)
XCTAssertEqual(p.attributeReferences, [
AttributeReference(index:.concrete(0), name: "name", relation: p),
AttributeReference(index:.concrete(1), name: "id", relation: p)
])
}
}
class AliasTestCase: XCTestCase {
// Alias
// -----
func testSelectFromAlias() {
let p: Relation
let alias: Relation
p = events.project()
alias = p.alias(as:"renamed")
XCTAssertEqual(alias.attributeReferences, [
AttributeReference(index:.concrete(0), name: "id", relation: alias),
AttributeReference(index:.concrete(1), name: "name", relation: alias),
AttributeReference(index:.concrete(2), name: "value", relation: alias)
])
}
}
class JoinTestCase: XCTestCase {
// Join
// ----
func testJoin() {
let joined: Relation
let left = events.alias(as: "left")
let right = events.alias(as: "right")
joined = left.join(right)
XCTAssertEqual(joined.attributeReferences, [
AttributeReference(index:.concrete(0), name: "id", relation: left),
AttributeReference(index:.concrete(1), name: "name", relation: left),
AttributeReference(index:.concrete(2), name: "value", relation: left),
AttributeReference(index:.concrete(0), name: "id", relation: right),
AttributeReference(index:.concrete(1), name: "name", relation: right),
AttributeReference(index:.concrete(2), name: "value", relation: right)
])
}
}
class RelationTestCase: XCTestCase {
// Attribute Reference Errors
// --------------------------
func testAmbiguousReference() {
var p: Relation
p = events.project([events["id"], events["id"]])
XCTAssertEqual(p.attributeReferences, [
AttributeReference(index:.ambiguous, name: "id", relation: p),
AttributeReference(index:.ambiguous, name: "id", relation: p)
])
p = events.project([events["name"].label(as: "other"),
events["value"].label(as: "other")])
XCTAssertEqual(p.attributeReferences, [
AttributeReference(index:.ambiguous, name: "other", relation: p),
AttributeReference(index:.ambiguous, name: "other", relation: p)
])
}
// Errors
// ------
// Select column from nothing
// SELECT id
// SELECT events.id FROM contacts
func testInvalidColumn() {
// let p = Relation.projection([events["id"]], Relation.none)
}
func assertEqual(_ lhs: [Relation], _ rhs: [Relation], file: StaticString = #file, line: UInt = #line) {
if lhs.count != rhs.count
|| zip(lhs, rhs).first(where: { l, r in l != r }) != nil {
XCTFail("Relation lists are not equal: left: \(lhs) right: \(rhs)",
file: file, line: line)
}
}
// Children and bases
//
func testChildren() {
var rel: Relation
var x: Relation
// SELECT * FROM a
// C: a
// B: a
rel = a.project()
assertEqual(rel.immediateRelations, [a])
assertEqual(rel.baseRelations, [a])
//
// SELECT * FROM a JOIN b
// C: a, b
// B: a, b
rel = a.join(b)
assertEqual(rel.immediateRelations, [a, b])
assertEqual(rel.baseRelations, [a, b])
rel = a.join(b).project()
assertEqual(rel.immediateRelations, [a, b])
assertEqual(rel.baseRelations, [a, b])
// SELECT * FROM a AS x
//
x = a.alias(as: "x")
rel = x.project()
assertEqual(rel.immediateRelations, [x])
assertEqual(rel.baseRelations, [a])
// SELECT * FROM (SELECT * FROM a) AS x)
x = a.project().alias(as: "x")
rel = a.join(b).project()
assertEqual(rel.immediateRelations, [a, b])
assertEqual(rel.baseRelations, [a, b])
//
// SELECT * FROM (SELECT * FROM a JOIN b) x
// C: x
// B: a, b
x = a.join(b).alias(as: "x")
rel = x.project()
assertEqual(rel.immediateRelations, [x])
assertEqual(rel.baseRelations, [a, b])
//
// SELECT * FROM a JOIN b JOIN c
// C: a, b, c
// B: a, b, c
rel = a.join(b).join(c)
assertEqual(rel.immediateRelations, [a, b, c])
assertEqual(rel.baseRelations, [a, b, c])
//
// SELECT * FROM a JOIN b JOIN c AS x
// C: a, b, x
// B: a, b, c
x = c.alias(as: "x")
rel = a.join(b).join(x)
assertEqual(rel.immediateRelations, [a, b, x])
assertEqual(rel.baseRelations, [a, b, c])
}
/*
func testSelectAliasColumns() {
let list = [
events["name"].label(as:"type"),
(events["value"] * 100).label(as: "greater_value"),
]
let p = events.select(list)
XCTAssertEqual(alias.attributes, [
AttributeReference(index:.concrete(0), name: "type", relation: p),
AttributeReference(index:.concrete(1), name: "greater_value", relation: p),
])
}
*/
func testInvalidRelationReference() {
// SELECT a.id FROM b
var rel: Relation
rel = b.project([a["id"]])
if rel.error == nil {
XCTFail("Invalid reference should cause an error: \(rel)")
}
}
// TODO: SELECT x.? FROM y
}
| mit | 7b64ad53015f93a5682563055b7748b0 | 29.520446 | 108 | 0.552497 | 4.082546 | false | true | false | false |
seeRead/roundware-ios-framework-v2 | Pod/Classes/RWFrameworkTags.swift | 1 | 5609 | //
// RWFrameworkTags.swift
// RWFramework
//
// Created by Joe Zobkiw on 2/12/15.
// Copyright (c) 2015 Roundware. All rights reserved.
//
import Foundation
extension RWFramework {
// MARK: get/set tags/values
/*
var a: AnyObject? = getListenTags() // if needed to get various codes, etc.
var b: AnyObject? = getListenTagsCurrent("gender")
var ba = (b as? NSArray) as Array?
if (ba != nil) {
ba!.append(5)
setListenTagsCurrent("gender", value: ba!)
}
var c: AnyObject? = getListenTagsCurrent("gender")
println("\(b) \(c)")
*/
// MARK: Listen Tags
// /// Returns an array of dictionaries of listen information
// public func getListenTags() -> AnyObject? {
// return NSUserDefaults.standardUserDefaults().objectForKey("tags_listen")
// }
//
// /// Sets the array of dictionaries as listen information
// public func setListenTags(value: AnyObject) {
// NSUserDefaults.standardUserDefaults().setObject(value, forKey: "tags_listen")
// }
//
// /// Get the current values for the listen tags code
// public func getListenTagsCurrent(code: String) -> AnyObject? {
// let defaultsKeyName = "tags_listen_\(code)_current"
// return NSUserDefaults.standardUserDefaults().objectForKey(defaultsKeyName)
// }
//
// /// Set the current values for the listen tags code
// public func setListenTagsCurrent(code: String, value: AnyObject) {
// let defaultsKeyName = "tags_listen_\(code)_current"
// NSUserDefaults.standardUserDefaults().setObject(value, forKey: defaultsKeyName)
// }
//
// /// Get all the current values for the listen tags
// public func getAllListenTagsCurrent() -> AnyObject? {
// var allListenTagsCurrentArray = [AnyObject]()
// if let listenTagsArray = getListenTags() as! NSArray? {
// for d in listenTagsArray {
// let code = d["code"] as! String
// if let tagsForCode = getListenTagsCurrent(code) as! [AnyObject]? {
// allListenTagsCurrentArray += tagsForCode
// }
// }
// }
// return allListenTagsCurrentArray
// }
//
// /// Get all the current values for the listen tags as a comma-separated string
// public func getAllListenTagsCurrentAsString() -> String {
// var tag_ids = ""
// if let allListenTagsArray = getAllListenTagsCurrent() as! NSArray? {
// for tag in allListenTagsArray {
// if (tag_ids != "") { tag_ids += "," }
// tag_ids += tag.description
// }
// }
// return tag_ids
// }
// MARK: Speak Tags
//
// /// Returns an array of dictionaries of speak information
// public func getSpeakTags() -> AnyObject? {
// return NSUserDefaults.standardUserDefaults().objectForKey("tags_speak")
// }
//
// /// Sets the array of dictionaries of speak information
// public func setSpeakTags(value: AnyObject) {
// NSUserDefaults.standardUserDefaults().setObject(value, forKey: "tags_speak")
// }
//
// /// Get the current values for the speak tags code
// public func getSpeakTagsCurrent(code: String) -> AnyObject? {
// let defaultsKeyName = "tags_speak_\(code)_current"
// return NSUserDefaults.standardUserDefaults().objectForKey(defaultsKeyName)
// }
//
// /// Set the current values for the speak tags code
// public func setSpeakTagsCurrent(code: String, value: AnyObject) {
// let defaultsKeyName = "tags_speak_\(code)_current"
// NSUserDefaults.standardUserDefaults().setObject(value, forKey: defaultsKeyName)
// }
//
// /// Get all the current values for the speak tags
// public func getAllSpeakTagsCurrent() -> AnyObject? {
// var allSpeakTagsCurrentArray = [AnyObject]()
// if let speakTagsArray = getSpeakTags() as! NSArray? {
// for d in speakTagsArray {
// let code = d["code"] as! String
// if let tagsForCode = getSpeakTagsCurrent(code) as! [AnyObject]? {
// allSpeakTagsCurrentArray += tagsForCode
// }
// }
// }
// return allSpeakTagsCurrentArray
// }
//
// /// Get all the current values for the speak tags as a comma-separated string
// public func getAllSpeakTagsCurrentAsString() -> String {
// if let allSpeakTagsArray = getAllSpeakTagsCurrent() as! NSArray? {
// var tags = ""
// for tag in allSpeakTagsArray {
// if (tags != "") { tags += "," }
// tags += tag.description
// }
// return tags
// }
// return ""
// }
// MARK: submit tags
/// Submit all current listen tags to the server
// public func submitListenTags() {
// let tag_ids = getAllListenTagsCurrentAsString()
// apiPatchStreamsIdWithTags(tag_ids)
// }
public func submitTags(tagIdsAsString: String) {
apiPatchStreamsIdWithTags(tag_ids: tagIdsAsString)
}
// MARK: edit tags
//
// /// Edit the Listen tags in a web view
// public func editListenTags() {
// editTags("tags_listen", title:LS("Listen Tags"))
// }
//
// /// Edit the Speak tags in a web view
// public func editSpeakTags() {
// editTags("tags_speak", title:LS("Speak Tags"))
// }
//
// /// Edit the Listen or Speak tags in a web view
// func editTags(type: String, title: String) {
// println("editing tags not yet supported but coming soon via WKWebView")
// }
}
| mit | 2774772b1851b7d498262b5cfd42a6c1 | 34.726115 | 89 | 0.603851 | 3.992171 | false | false | false | false |
BPForEveryone/BloodPressureForEveryone | BPApp/Shared/Patient.swift | 1 | 6606 | //
// Patient.swift
// BPApp
//
// Created by MiningMarsh on 9/26/17.
// Copyright © 2017 BlackstoneBuilds. All rights reserved.
//
// Implements a patient instance that supports serialization to be encoded and decoded.
import Foundation
import os.log
public class Patient: NSObject, NSCoding {
public enum Sex {
case male
case female
}
var firstName: String
var lastName: String
var birthDate: Date
var height: Height
private var sexInBoolean: Bool
private var bloodPressureMeasurementsSorted: [BloodPressureMeasurement]! = []
public var bloodPressureMeasurements: [BloodPressureMeasurement] {
get {
return self.bloodPressureMeasurementsSorted
}
set(newBloodPressureMeasurements) {
self.bloodPressureMeasurementsSorted = newBloodPressureMeasurements.sorted {
return $0.measurementDate > $1.measurementDate
}
}
}
public var norms: BPNormsEntry {
get {
return BPNormsTable.index(patient: self)
}
}
public var normsArray: [BPNormsEntry] {
get {
return BPNormsTable.indexForArray(patient: self)
}
}
public var percentile: Int {
get {
let norms = self.norms
if self.bloodPressureMeasurements.count == 0 {
return 0
}
let measurement = self.bloodPressureMeasurements[0]
if norms.diastolic95 < measurement.diastolic {
return 95
} else if norms.diastolic90 < measurement.diastolic {
return 90
} else if norms.diastolic50 < measurement.diastolic {
return 50
}
return 0
}
}
public var diastolic: Int {
if self.bloodPressureMeasurements.count == 0 {
return 0
}
return self.bloodPressureMeasurements[0].diastolic
}
public var systolic: Int {
if self.bloodPressureMeasurements.count == 0 {
return 0
}
return self.bloodPressureMeasurements[0].systolic
}
public var sex: Patient.Sex {
get {
if self.sexInBoolean {
return Patient.Sex.male
} else {
return Patient.Sex.female
}
}
set(newSex) {
switch newSex {
case .male: self.sexInBoolean = true
case .female: self.sexInBoolean = false
}
}
}
// The properties to save for a patients, make sure this reflects with the properties patients have.
struct PropertyKey {
static let firstName = "firstName"
static let lastName = "lastName"
static let birthDate = "birthDate"
static let heightInMeters = "heightInMeters"
static let sexInBoolean = "sexInBoolean"
static let bloodPressureMeasurementsSorted = "bloodPressureMeasurementsSorted"
}
// Create a new patient
init?(firstName: String, lastName: String, birthDate: Date, height: Height, sex: Patient.Sex, bloodPressureMeasurements: [BloodPressureMeasurement]) {
// The names must not be empty
guard !firstName.isEmpty else {
return nil
}
guard !lastName.isEmpty else {
return nil
}
// Height must be positive.
guard height.meters >= 0.0 else {
return nil
}
self.firstName = firstName
self.lastName = lastName
self.birthDate = birthDate
self.height = height
switch sex {
case .male: self.sexInBoolean = true
case .female: self.sexInBoolean = false
}
self.bloodPressureMeasurementsSorted = bloodPressureMeasurements.sorted {
return $0.measurementDate < $1.measurementDate
}
}
// Encoder used to store a patient.
public func encode(with encoder: NSCoder) {
encoder.encode(firstName, forKey: PropertyKey.firstName)
encoder.encode(lastName, forKey: PropertyKey.lastName)
encoder.encode(birthDate, forKey: PropertyKey.birthDate)
encoder.encode(height.meters, forKey: PropertyKey.heightInMeters)
encoder.encode(sexInBoolean, forKey: PropertyKey.sexInBoolean)
encoder.encode(bloodPressureMeasurementsSorted, forKey: PropertyKey.bloodPressureMeasurementsSorted)
}
public required convenience init?(coder decoder: NSCoder) {
// First name is required
guard let lastName = decoder.decodeObject(forKey: PropertyKey.lastName) as? String else {
os_log("Unable to decode the first name for a Patient object.", log: OSLog.default, type: .debug)
return nil
}
// Last name is required.
guard let firstName = decoder.decodeObject(forKey: PropertyKey.firstName) as? String else {
os_log("Unable to decode the last name for a Patient object.", log: OSLog.default, type: .debug)
return nil
}
// Age is required.
guard let birthDate = decoder.decodeObject(forKey: PropertyKey.birthDate) as? Date else {
os_log("Unable to decode the birth date for a Patient object.", log: OSLog.default, type: .debug)
return nil
}
let heightInMeters = decoder.decodeDouble(forKey: PropertyKey.heightInMeters)
let sexInBoolean = decoder.decodeBool(forKey: PropertyKey.sexInBoolean)
var sex: Patient.Sex = Patient.Sex.male
if sexInBoolean {
sex = Patient.Sex.male
} else {
sex = Patient.Sex.female
}
// Blood pressure log is required.
guard let bloodPressureMeasurementsSorted = decoder.decodeObject(forKey: PropertyKey.bloodPressureMeasurementsSorted) as? [BloodPressureMeasurement] else {
os_log("Unable to decode the blood pressure log for a Patient object.", log: OSLog.default, type: .debug)
return nil
}
// Initialize with decoded values.
self.init(
firstName: firstName,
lastName: lastName,
birthDate: birthDate,
height: Height(heightInMeters: heightInMeters),
sex: sex,
bloodPressureMeasurements: bloodPressureMeasurementsSorted
)
}
}
| mit | 48745683e612d5fda157ea67dd0ffdc8 | 31.536946 | 163 | 0.59349 | 5.128106 | false | false | false | false |
hryk224/PCLBlurEffectAlert | Sources/PCLBlurEffectAlert+TransitionAnimator.swift | 1 | 5108 | //
// PCLBlurEffectAlertController+Tr.swift
// PCLBlurEffectAlert
//
// Created by hiroyuki yoshida on 2017/02/26.
//
//
import UIKit
public typealias PCLBlurEffectAlertTransitionAnimator = PCLBlurEffectAlert.TransitionAnimator
extension PCLBlurEffectAlert {
// MARK: - TransitionAnimator
open class TransitionAnimator: NSObject, UIViewControllerAnimatedTransitioning {
fileprivate typealias TransitionAnimator = PCLBlurEffectAlert.TransitionAnimator
fileprivate static let presentBackAnimationDuration: TimeInterval = 0.45
fileprivate static let dismissBackAnimationDuration: TimeInterval = 0.35
fileprivate var goingPresent: Bool!
init(present: Bool) {
super.init()
goingPresent = present
}
open func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
if goingPresent == true {
return TransitionAnimator.presentBackAnimationDuration
} else {
return TransitionAnimator.dismissBackAnimationDuration
}
}
open func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
if goingPresent == true {
presentAnimation(transitionContext)
} else {
dismissAnimation(transitionContext)
}
}
}
}
// MARK: - Extension
private extension PCLBlurEffectAlert.TransitionAnimator {
func presentAnimation(_ transitionContext: UIViewControllerContextTransitioning) {
guard let alertController = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to) as? PCLBlurEffectAlertController else {
transitionContext.completeTransition(false)
return
}
let containerView = transitionContext.containerView
containerView.backgroundColor = .clear
containerView.addSubview(alertController.view)
alertController.overlayView.alpha = 0
let animations: (() -> Void)
switch alertController.style {
case .actionSheet:
alertController.alertView.transform = CGAffineTransform(translationX: 0,
y: alertController.alertView.frame.height)
animations = {
alertController.overlayView.alpha = 1
alertController.alertView.transform = CGAffineTransform(translationX: 0, y: -10)
}
default:
alertController.cornerView.subviews.forEach { $0.alpha = 0 }
alertController.alertView.center = alertController.view.center
alertController.alertView.transform = CGAffineTransform(scaleX: 0.5, y: 0.5)
animations = {
alertController.overlayView.alpha = 1
alertController.cornerView.subviews.forEach { $0.alpha = 1 }
alertController.alertView.transform = CGAffineTransform(scaleX: 1.05, y: 1.05)
}
}
UIView.animate(withDuration: transitionDuration(using: transitionContext) * (5 / 9), animations: animations) { finished in
guard finished else { return }
let animations = {
alertController.alertView.transform = CGAffineTransform.identity
}
UIView.animate(withDuration: self.transitionDuration(using: transitionContext) * (4 / 9), animations: animations) { finished in
guard finished else { return }
let cancelled = transitionContext.transitionWasCancelled
if cancelled {
alertController.view.removeFromSuperview()
}
transitionContext.completeTransition(!cancelled)
}
}
}
func dismissAnimation(_ transitionContext: UIViewControllerContextTransitioning) {
guard let alertController = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from) as? PCLBlurEffectAlertController else {
transitionContext.completeTransition(false)
return
}
let animations = {
alertController.overlayView.alpha = 0
switch alertController.style {
case .actionSheet:
alertController.containerView.transform = CGAffineTransform(translationX: 0,
y: alertController.alertView.frame.height)
default:
alertController.alertView.transform = CGAffineTransform(scaleX: 0.8, y: 0.8)
alertController.cornerView.subviews.forEach { $0.alpha = 0 }
}
}
UIView.animate(withDuration: transitionDuration(using: transitionContext), delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 0, options: UIViewAnimationOptions(), animations: animations) { finished in
guard finished else { return }
transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
}
}
}
| mit | 3d4ec98aa778ac142b798da3f7de71eb | 46.738318 | 218 | 0.649178 | 6.229268 | false | false | false | false |
niklassaers/PackStream-Swift | Sources/PackStream/Int.swift | 1 | 9012 | import Foundation
#if swift(>=4.0)
#elseif swift(>=3.0)
typealias BinaryInteger = Integer
#endif
extension PackProtocol {
public func intValue() -> Int64? {
if let i = self as? Int8 {
return Int64(i)
} else if let i = self as? Int16 {
return Int64(i)
} else if let i = self as? Int32 {
return Int64(i)
} else if let i = self as? Int64 {
return i
} else if let i = self as? UInt8 {
return Int64(i)
} else if let i = self as? UInt16 {
return Int64(i)
} else if let i = self as? UInt32 {
return Int64(i)
}
return nil
}
public func uintValue() -> UInt64? {
if let i = self as? UInt64 {
return i
} else if let i = self.intValue() {
if i < 0 {
return nil
} else {
return UInt64(i)
}
}
return nil
}
}
extension Int8: PackProtocol {
struct Constants {
static let byteMarker: Byte = 0xC8
}
public func pack() throws -> [Byte] {
switch self {
case -0x10 ... 0x7F:
return packInt8(withByteMarker: false)
default:
return packInt8(withByteMarker: true)
}
}
public static func unpack(_ bytes: ArraySlice<Byte>) throws -> Int8 {
switch bytes.count {
case 1:
return try unpackInt8(bytes, withMarker: false)
case 2:
return try unpackInt8(bytes, withMarker: true)
default:
throw UnpackError.incorrectNumberOfBytes
}
}
private func packInt8(withByteMarker: Bool) -> [Byte] {
if withByteMarker == true {
return [ Constants.byteMarker, Byte(bitPattern: self) ]
} else {
return [ Byte(bitPattern: self) ]
}
}
private static func unpackInt8(_ bytes: ArraySlice<Byte>, withMarker: Bool) throws -> Int8 {
guard let firstByte = bytes.first else {
throw UnpackError.incorrectNumberOfBytes
}
if withMarker == false {
return Int8(bitPattern: firstByte)
} else {
if firstByte != Constants.byteMarker {
throw UnpackError.unexpectedByteMarker
}
if bytes.count != 2 {
throw UnpackError.incorrectNumberOfBytes
}
let byte: Byte = bytes[bytes.startIndex + 1]
return Int8(bitPattern: byte)
}
}
}
extension Int16: PackProtocol {
struct Constants {
static let byteMarker: Byte = 0xC9
}
public func pack() throws -> [Byte] {
let nv: Int16 = Int16(self).bigEndian
let uNv = UInt16(bitPattern: nv)
let second = UInt8(uNv >> 8)
let first = UInt8(uNv & 0x00ff)
return [ Constants.byteMarker, first, second ]
}
public static func unpack(_ bytes: ArraySlice<Byte>) throws -> Int16 {
guard let firstByte = bytes.first else {
throw UnpackError.incorrectNumberOfBytes
}
if firstByte != Constants.byteMarker {
throw UnpackError.unexpectedByteMarker
}
if bytes.count != 3 {
throw UnpackError.incorrectNumberOfBytes
}
let data = NSData(bytes: Array(bytes), length: 3)
let i: Int16 = Int.readInteger(data: data, start: 1)
return Int16(bigEndian: i)
}
}
extension UInt8 {
func pack() throws -> [Byte] {
return [ self ]
}
static func unpack(_ bytes: ArraySlice<Byte>) throws -> UInt8 {
if bytes.count != 1 {
throw UnpackError.incorrectNumberOfBytes
}
return bytes[bytes.startIndex]
}
}
extension UInt16 {
public func pack() throws -> [Byte] {
var i: UInt16 = UInt16(self).bigEndian
let data = NSData(bytes: &i, length: MemoryLayout<UInt16>.size)
let length = data.length
var bytes = [Byte](repeating: 0, count: length)
data.getBytes(&bytes, length: length)
return bytes
}
public static func unpack(_ bytes: ArraySlice<Byte>) throws -> UInt16 {
if bytes.count != 2 {
throw UnpackError.incorrectNumberOfBytes
}
let data = NSData(bytes: Array(bytes), length: 2)
let i: UInt16 = Int.readInteger(data: data, start: 0)
return UInt16(bigEndian: i)
}
}
extension UInt32 {
func pack() throws -> [Byte] {
var i: UInt32 = UInt32(self).bigEndian
let data = NSData(bytes: &i, length: MemoryLayout<UInt32>.size)
let length = data.length
var bytes = [Byte](repeating: 0, count: length)
data.getBytes(&bytes, length: length)
return bytes
}
public static func unpack(_ bytes: ArraySlice<Byte>) throws -> UInt32 {
if bytes.count != 4 {
throw UnpackError.incorrectNumberOfBytes
}
let data = NSData(bytes: Array(bytes), length: 4)
let i: UInt32 = Int.readInteger(data: data, start: 0)
return UInt32(bigEndian: i)
}
}
extension Int32: PackProtocol {
struct Constants {
static let byteMarker: Byte = 0xCA
}
public func pack() throws -> [Byte] {
var i: Int32 = Int32(self).bigEndian
let data = NSData(bytes: &i, length: MemoryLayout<Int32>.size)
let length = data.length
var bytes = [Byte](repeating: 0, count: length)
data.getBytes(&bytes, length: length)
return [Constants.byteMarker] + bytes
}
public static func unpack(_ bytes: ArraySlice<Byte>) throws -> Int32 {
guard let firstByte = bytes.first else {
throw UnpackError.incorrectNumberOfBytes
}
if firstByte != Constants.byteMarker {
throw UnpackError.unexpectedByteMarker
}
if bytes.count != 5 {
throw UnpackError.incorrectNumberOfBytes
}
let data = NSData(bytes: Array(bytes), length: 5)
let i: Int32 = Int.readInteger(data: data, start: 1)
return Int32(bigEndian: i)
}
}
extension Int64: PackProtocol {
struct Constants {
static let byteMarker: Byte = 0xCB
}
public func pack() throws -> [Byte] {
var i: Int64 = Int64(self).bigEndian
let data = NSData(bytes: &i, length: MemoryLayout<Int64>.size)
let length = data.length
var bytes = [Byte](repeating: 0, count: length)
data.getBytes(&bytes, length: length)
return [Constants.byteMarker] + bytes
}
public static func unpack(_ bytes: ArraySlice<Byte>) throws -> Int64 {
guard let firstByte = bytes.first else {
throw UnpackError.incorrectNumberOfBytes
}
if firstByte != Constants.byteMarker {
throw UnpackError.unexpectedByteMarker
}
if bytes.count != 9 {
throw UnpackError.incorrectNumberOfBytes
}
let data = NSData(bytes: Array(bytes), length: 9)
let i: Int64 = Int.readInteger(data: data, start: 1)
return Int64(bigEndian: i)
}
}
extension Int: PackProtocol {
public func pack() throws -> [Byte] {
#if __LP64__ || os(Linux)
switch self {
case -0x10 ... 0x7F:
return try Int8(self).pack()
case -0x7F ..< -0x7F:
return try Int8(self).pack()
case -0x8000 ..< 0x8000:
return try Int16(self).pack()
case -0x80000000 ... 0x7fffffff:
return try Int32(self).pack()
case -0x8000000000000000 ... (0x800000000000000 - 1):
return try Int64(self).pack()
default:
throw PackError.notPackable
}
#else
switch self {
case -0x10 ... 0x7F:
return try Int8(self).pack()
case -0x7F ..< -0x7F:
return try Int8(self).pack()
case -0x8000 ..< 0x8000:
return try Int16(self).pack()
case -0x80000000 ... 0x7fffffff:
return try Int32(self).pack()
default:
throw PackError.notPackable
}
#endif
}
public static func unpack(_ bytes: ArraySlice<Byte>) throws -> Int {
switch bytes.count {
case 1:
return Int(try Int8.unpack(bytes))
case 2:
return Int(try Int8.unpack(bytes))
case 3:
return Int(try Int16.unpack(bytes))
case 5:
return Int(try Int32.unpack(bytes))
case 9:
return Int(try Int64.unpack(bytes))
default:
throw UnpackError.incorrectNumberOfBytes
}
}
static func readInteger<T: BinaryInteger>(data: NSData, start: Int) -> T {
var d: T = 0 as T
data.getBytes(&d, range: NSRange(location: start, length: MemoryLayout<T>.size))
return d
}
}
| bsd-3-clause | 4c74b1e0abc5b18fdcf51c162513b66b | 25.901493 | 96 | 0.55415 | 4.11883 | false | false | false | false |
jinSasaki/Vulcan | Sources/Vulcan/UIImageView+Vulcan.swift | 1 | 609 | //
// UIImageView+Vulcan.swift
// Vulcan
//
// Created by Jin Sasaki on 2017/04/23
// Copyright © 2017年 Sasakky. All rights reserved.
//
import UIKit
private var kVulcanKey: UInt = 0
public extension UIImageView {
public var vl: Vulcan {
if let vulcan = objc_getAssociatedObject(self, &kVulcanKey) as? Vulcan {
return vulcan
}
let vulcan = Vulcan()
if vulcan.imageView == nil {
vulcan.imageView = self
}
objc_setAssociatedObject(self, &kVulcanKey, vulcan, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
return vulcan
}
}
| mit | da2687f38a4a1809fe024bbc895969dd | 22.307692 | 95 | 0.627063 | 3.54386 | false | false | false | false |
phillfarrugia/appstore-clone | AppStoreClone/PresentStoryViewAnimationController.swift | 1 | 2157 | //
// StoryViewAnimationController.swift
// AppStoreClone
//
// Created by Phillip Farrugia on 6/17/17.
// Copyright © 2017 Phill Farrugia. All rights reserved.
//
import UIKit
internal class PresentStoryViewAnimationController: NSObject, UIViewControllerAnimatedTransitioning {
internal var selectedCardFrame: CGRect = .zero
// MARK: - UIViewControllerAnimatedTransitioning
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
// 1
let containerView = transitionContext.containerView
guard let fromViewController = transitionContext.viewController(forKey: .from) as? TodayViewController,
let toViewController = transitionContext.viewController(forKey: .to) as? StoryDetailViewController else {
return
}
// 2
containerView.addSubview(toViewController.view)
toViewController.positionContainer(left: 20.0,
right: 20.0,
top: selectedCardFrame.origin.y + 20.0,
bottom: 0.0)
toViewController.setHeaderHeight(self.selectedCardFrame.size.height - 40.0)
toViewController.configureRoundedCorners(shouldRound: true)
// 3
let duration = transitionDuration(using: transitionContext)
UIView.animate(withDuration: duration, animations: {
toViewController.positionContainer(left: 0.0,
right: 0.0,
top: 0.0,
bottom: 0.0)
toViewController.setHeaderHeight(500)
toViewController.view.backgroundColor = .white
toViewController.configureRoundedCorners(shouldRound: false)
}) { (_) in
transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
}
}
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return 0.1
}
}
| mit | e59479836498e4ab7b395311b29ebecb | 38.925926 | 113 | 0.612245 | 6.125 | false | false | false | false |
cconeil/Standard-Template-Protocols | STP/BlockGestureRecognizer.swift | 1 | 1720 | //
// BlockGestureRecognizer.swift
// STP
//
// Created by Chris O'Neil on 10/11/15.
// Copyright © 2015 Because. All rights reserved.
//
private class MultiDelegate : NSObject, UIGestureRecognizerDelegate {
@objc func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
}
extension UIGestureRecognizer {
struct PropertyKeys {
static var blockKey = "BCBlockPropertyKey"
static var multiDelegateKey = "BCMultiDelegateKey"
}
private var block:((recognizer:UIGestureRecognizer) -> Void) {
get {
return Associator.getAssociatedObject(self, associativeKey:&PropertyKeys.blockKey)!
}
set {
Associator.setAssociatedObject(self, value: newValue, associativeKey:&PropertyKeys.blockKey, policy: .OBJC_ASSOCIATION_RETAIN)
}
}
private var multiDelegate:MultiDelegate {
get {
return Associator.getAssociatedObject(self, associativeKey:&PropertyKeys.multiDelegateKey)!
}
set {
Associator.setAssociatedObject(self, value: newValue, associativeKey:&PropertyKeys.multiDelegateKey, policy: .OBJC_ASSOCIATION_RETAIN)
}
}
convenience init(block:(recognizer:UIGestureRecognizer) -> Void) {
self.init()
self.block = block
self.multiDelegate = MultiDelegate()
self.delegate = self.multiDelegate
self.addTarget(self, action: "didInteractWithGestureRecognizer:")
}
@objc func didInteractWithGestureRecognizer(sender:UIGestureRecognizer) {
self.block(recognizer: sender)
}
}
| mit | 4697357918660ed79387b59a3e29ebc9 | 32.057692 | 178 | 0.695172 | 5.041056 | false | false | false | false |
raycoast/FlowChartKit | FlowChartKit/FlowChart/FlowChartView+DrawShape.swift | 1 | 10637 | //
// FlowChartView+DrawShape.swift
// FlowChartKit
//
// Created by QiangRen on 11/5/15.
// Copyright (c) 2015 QiangRen. All rights reserved.
//
import UIKit
// MARK: - CoreGraphics Shapes
extension FlowChartView {
func drawShape(shape: FCShape, style: FCShapeStyle = FCShapeStyle.normal) {
let view: UIView
switch shape.type {
case .Circle:
view = drawCircle(shape, style: style)
case .Oval: // Terminal
view = drawOval(shape, style: style)
case .Ellipse:
view = drawEllipse(shape, style: style)
case .Square: // Process
view = drawSquare(shape, style: style)
case .Diamond: // Decision
view = drawDiamond(shape, style: style)
case .Quadangle: // Input/Output
view = drawQuadangle(shape, style: style)
case .Hexagon: // Preparation
view = drawHexagon(shape, style: style)
}
contentView.addSubview(view)
shape.draw(view, style: style)
}
func drawCircle(shape: FCShape, style: FCShapeStyle = FCShapeStyle.normal) -> UIView {
let d = min(shape.rect.size.width, shape.rect.size.height)
let dx = (shape.rect.size.width - d) / 2
let dy = (shape.rect.size.height - d) / 2
let rect = shape.rect.rectByInsetting(dx: dx, dy: dy)
let v = UIButton(frame: rect)
v.layer.cornerRadius = d / 2
v.layer.borderColor = style.borderColor
v.layer.borderWidth = style.borderWidth
v.setTitleColor(style.textColor, forState: .Normal)
v.setTitle(shape.title, forState: UIControlState.Normal)
return v
}
func drawOval(shape: FCShape, style: FCShapeStyle = FCShapeStyle.normal) -> UIView {
let v = UIButton(frame: shape.rect)
v.layer.cornerRadius = min(shape.rect.width, shape.rect.height) / 2
v.layer.borderColor = style.borderColor
v.layer.borderWidth = style.borderWidth
v.setTitleColor(style.textColor, forState: .Normal)
v.setTitle(shape.title, forState: UIControlState.Normal)
v.addTarget(self, action: "onTaped:", forControlEvents: .TouchUpInside)
for (i, s) in enumerate(shapes ?? []) {
if s.id == shape.id {
v.tag = i
break
}
}
return v
}
func drawEllipse(shape: FCShape, style: FCShapeStyle = FCShapeStyle.normal) -> UIView {
let v = UIView(frame: shape.rect)
var path = CGPathCreateMutable()
CGPathAddEllipseInRect(path, nil, CGRectMake(0, 0, shape.rect.width, shape.rect.height))
//CGPathCloseSubpath(path)
let layer = CAShapeLayer()
layer.frame = v.bounds
layer.path = path
layer.lineCap = "kCGLineCapRound"
layer.lineWidth = style.borderWidth
layer.strokeColor = style.borderColor
layer.fillColor = UIColor.clearColor().CGColor
v.layer.addSublayer(layer)
return v
}
func drawSquare(shape: FCShape, style: FCShapeStyle = FCShapeStyle.normal) -> UIView {
let v = UIButton(frame: shape.rect)
v.layer.cornerRadius = style.cornerRadius
v.layer.borderColor = style.borderColor
v.layer.borderWidth = style.borderWidth
v.setTitleColor(style.textColor, forState: .Normal)
v.setTitle(shape.title, forState: UIControlState.Normal)
v.addTarget(self, action: "onTaped:", forControlEvents: .TouchUpInside)
for (i, s) in enumerate(shapes ?? []) {
if s.id == shape.id {
v.tag = i
break
}
}
return v
}
func drawDiamond(shape: FCShape, style: FCShapeStyle = FCShapeStyle.normal) -> UIView {
let v = UIView(frame: shape.rect)
var path = CGPathCreateMutable()
let points = [
CGPointMake(shape.rect.width / 2, 0),
CGPointMake(shape.rect.width, shape.rect.height / 2),
CGPointMake(shape.rect.width / 2, shape.rect.height),
CGPointMake(0, shape.rect.height / 2),
CGPointMake(shape.rect.width / 2, 0),
]
//CGPathMoveToPoint(path, nil, shape.rect.midX, 0)
CGPathAddLines(path, nil, points, points.count)
CGPathCloseSubpath(path)
let layer = CAShapeLayer()
layer.frame = v.bounds
layer.path = path
layer.lineCap = "kCGLineCapRound"
layer.lineWidth = style.borderWidth
layer.strokeColor = style.borderColor
layer.fillColor = UIColor.clearColor().CGColor
v.layer.addSublayer(layer)
return v
}
func drawQuadangle(shape: FCShape, style: FCShapeStyle = FCShapeStyle.normal) -> UIView {
let v = UIView(frame: shape.rect)
var path = CGPathCreateMutable()
let halfHeight = shape.rect.size.height/2
let halfWidth = shape.rect.size.width/2
let oneQuarterHeight = shape.rect.size.height/4
let oneQuarterWidth = shape.rect.size.width/4
let threeQuarterHeight = oneQuarterHeight * 3
let threeQuarterWidth = oneQuarterWidth * 3
let fullHeight = shape.rect.size.height
let fullWidth = shape.rect.size.width
let originX: CGFloat = 0.0 //shape.rect.origin.x
let originY: CGFloat = 0.0 //shape.rect.origin.y
let radius:CGFloat = style.cornerRadius //fullHeight/9.0
//CENTERS
let leftBottom = CGPoint(x: originX, y: originY + fullHeight)
let rightTop = CGPoint(x: originX + fullWidth, y: originY)
//QUARTERS
let leftTopQuarter = CGPoint(x: originX + oneQuarterWidth, y: originY)
let rightBottomQuarter = CGPoint(x: originX + threeQuarterWidth, y: originY + fullHeight)
//Computed Start Point
let computedX = leftBottom.x + (leftTopQuarter.x - leftBottom.x)/2.0
let computedY = leftBottom.y - (leftBottom.y - leftTopQuarter.y)/2.0
//Start here (needs to be between first and last point
//This will be the top center of the view, so half way in (X) and full up (Y)
CGPathMoveToPoint(path, nil, computedX, computedY)
//Take it to that point, and point it at the next direction
CGPathAddArcToPoint(path, nil, leftTopQuarter.x, leftTopQuarter.y, rightTop.x, rightTop.y, radius)
CGPathAddArcToPoint(path, nil, rightTop.x, rightTop.y, rightBottomQuarter.x, rightBottomQuarter.y, radius)
CGPathAddArcToPoint(path, nil, rightBottomQuarter.x, rightBottomQuarter.y, leftBottom.x, leftBottom.y, radius)
CGPathAddArcToPoint(path, nil, leftBottom.x, leftBottom.y, leftTopQuarter.x, leftTopQuarter.y, radius)
CGPathCloseSubpath(path)
let layer = CAShapeLayer()
layer.frame = v.bounds
layer.path = path
layer.lineCap = "kCGLineCapRound"
layer.lineWidth = style.borderWidth
layer.strokeColor = style.borderColor
layer.fillColor = UIColor.clearColor().CGColor
v.layer.addSublayer(layer)
return v
}
func drawHexagon(shape: FCShape, style: FCShapeStyle = FCShapeStyle.normal) -> UIView {
let v = UIView(frame: shape.rect)
var path = CGPathCreateMutable()
let halfHeight = shape.rect.size.height/2
let halfWidth = shape.rect.size.width/2
let oneQuarterHeight = shape.rect.size.height/4
let oneQuarterWidth = shape.rect.size.width/4
let threeQuarterHeight = oneQuarterHeight * 3
let threeQuarterWidth = oneQuarterWidth * 3
let fullHeight = shape.rect.size.height
let fullWidth = shape.rect.size.width
let originX: CGFloat = 0.0 //shape.rect.origin.x
let originY: CGFloat = 0.0 //shape.rect.origin.y
let radius:CGFloat = style.cornerRadius //fullHeight/9.0
//CENTERS
let leftCenter = CGPoint(x: originX, y: originY + halfHeight)
let rightCenter = CGPoint(x: originX + fullWidth, y: originY + halfHeight)
//QUARTERS
let leftTopQuarter = CGPoint(x: originX + oneQuarterWidth, y: originY)
let leftBottomQuarter = CGPoint(x: originX + oneQuarterWidth, y: originY + fullHeight)
let rightTopQuarter = CGPoint(x: originX + threeQuarterWidth, y: originY)
let rightBottomQuarter = CGPoint(x: originX + threeQuarterWidth, y: originY + fullHeight)
//Computed Start Point
let computedX = leftCenter.x + (leftBottomQuarter.x - leftCenter.x)/2.0
let computedY = leftCenter.y - (leftBottomQuarter.y - leftCenter.y)/2.0
//Start here (needs to be between first and last point
//This will be the top center of the view, so half way in (X) and full up (Y)
CGPathMoveToPoint(path, nil, computedX, computedY)
//Take it to that point, and point it at the next direction
CGPathAddArcToPoint(path, nil, leftTopQuarter.x, leftTopQuarter.y, rightTopQuarter.x, rightTopQuarter.y, radius)
CGPathAddArcToPoint(path, nil, rightTopQuarter.x, rightTopQuarter.y, rightCenter.x, rightCenter.y, radius)
CGPathAddArcToPoint(path, nil, rightCenter.x, rightCenter.y, rightBottomQuarter.x, rightBottomQuarter.y, radius)
CGPathAddArcToPoint(path, nil, rightBottomQuarter.x, rightBottomQuarter.y, leftBottomQuarter.x, leftBottomQuarter.y, radius)
CGPathAddArcToPoint(path, nil, leftBottomQuarter.x, leftBottomQuarter.y, leftCenter.x, leftCenter.y, radius)
//
CGPathAddArcToPoint(path, nil, leftCenter.x, leftCenter.y, leftTopQuarter.x, leftTopQuarter.y, radius)
CGPathCloseSubpath(path)
let layer = CAShapeLayer()
layer.frame = v.bounds
layer.path = path
layer.lineCap = "kCGLineCapRound"
layer.lineWidth = style.borderWidth
layer.strokeColor = style.borderColor
layer.fillColor = UIColor.clearColor().CGColor
v.layer.addSublayer(layer)
return v
}
func onTaped(sender: UIButton) {
delegate?.flowChartView(self, didTaponShape: self.shapes?[sender.tag])
}
}
| bsd-2-clause | d294993007ac70d44950cf9a40bcad11 | 36.989286 | 132 | 0.610604 | 4.39909 | false | false | false | false |
Pocketbrain/nativeadslib-ios | PocketMediaNativeAds/DataSource/TableView/NativeAdTableViewDataSource.swift | 1 | 8396 | //
// UITableViewDataSourceAdapater.swift
// PocketMediaNativeAds
//
// Created by Kees Bank on 02/03/16.
// Copyright © 2016 PocketMedia. All rights reserved.
//
import UIKit
/**
Wraps around a datasource so it contains both a mix of ads and none ads.
*/
open class NativeAdTableViewDataSource: DataSource, UITableViewDataSource, UITableViewDataSourceWrapper {
/// Original datasource.
open var datasource: UITableViewDataSource
/// Original tableView.
open var tableView: UITableView
/// Original deglegate.
open var delegate: NativeAdTableViewDelegate?
// Ad position logic.
fileprivate var adPosition: AdPosition
/**
Hijacks the sent delegate and datasource and make it use our wrapper. Also registers the ad unit we'll be using.
- parameter controller: The controller to create NativeAdTableViewDelegate
- parameter tableView: The tableView this datasource is attached to.
- parameter adPosition: The instance that will define where ads are positioned.
*/
@objc
public required init(controller: UIViewController, tableView: UITableView, adPosition: AdPosition, customXib: UINib? = nil) {
if tableView.dataSource == nil {
preconditionFailure("Your tableview must have a dataSource set before use.")
}
self.datasource = tableView.dataSource!
self.adPosition = adPosition
self.tableView = tableView
super.init(type: AdUnit.UIType.TableView, customXib: customXib, adPosition: adPosition)
UITableView.swizzleNativeAds(tableView)
// Hijack the delegate and datasource and make it use our wrapper.
if tableView.delegate != nil {
self.delegate = NativeAdTableViewDelegate(datasource: self, controller: controller, delegate: tableView.delegate!)
tableView.delegate = self.delegate
}
tableView.dataSource = self
}
/**
Reset the datasource. if this wrapper is deinitialized.
*/
deinit {
self.tableView.dataSource = datasource
}
/**
This function checks if we have a cell registered with that name. If not we'll register it.
*/
public override func registerNib(nib: UINib?, identifier: String) {
let bundle = PocketMediaNativeAdsBundle.loadBundle()!
let registerNib = nib == nil ? UINib(nibName: identifier, bundle: bundle) : nib
tableView.register(registerNib, forCellReuseIdentifier: identifier)
}
/**
Return the cell of a identifier.
*/
public override func dequeueReusableCell(identifier: String, indexPath: IndexPath) -> UIView {
return tableView.dequeueReusableCell(withIdentifier: identifier, for: indexPath)
}
/**
Required. Asks the data source for a cell to insert in a particular location of the table view.
*/
@objc
open func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let listing = getNativeAdListing(indexPath) {
if let cell = getAdCell(listing.ad, indexPath: indexPath) as? UITableViewCell {
return cell
}
return UITableViewCell()
}
return datasource.tableView(tableView, cellForRowAt: getOriginalPositionForElement(indexPath))
}
/**
Returns the number of rows (table cells) in a specified section.
*/
@objc
open func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if let ads = adListingsPerSection[section]?.count {
return datasource.tableView(tableView, numberOfRowsInSection: section) + ads
}
return datasource.tableView(tableView, numberOfRowsInSection: section)
}
/**
Asks the data source for the title of the header of the specified section of the table view.
*/
@objc
open func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
if let string = datasource.tableView?(tableView, titleForHeaderInSection: section) {
return string
}
return nil
}
/**
Asks the data source for the title of the footer of the specified section of the table view.
*/
@objc
open func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? {
if let string = datasource.tableView?(tableView, titleForFooterInSection: section) {
return string
}
return nil
}
/**
Asks the data source to verify that the given row is editable.
*/
@objc
open func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
if datasource.responds(to: #selector(UITableViewDataSource.tableView(_:canEditRowAt:))) {
return datasource.tableView!(tableView, canEditRowAt: indexPath)
}
return true
}
/**
Asks the data source whether a given row can be moved to another location in the table view.
*/
@objc
open func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
if datasource.responds(to: #selector(UITableViewDataSource.tableView(_:canMoveRowAt:))) {
return datasource.tableView!(tableView, canMoveRowAt: indexPath)
}
return true
}
/**
Asks the data source to return the index of the section having the given title and section title index.
*/
@objc
open func tableView(_ tableView: UITableView, sectionForSectionIndexTitle title: String, at index: Int) -> Int {
if datasource.responds(to: #selector(UITableViewDataSource.tableView(_:sectionForSectionIndexTitle:at:))) {
return datasource.tableView!(tableView, sectionForSectionIndexTitle: title, at: index)
}
return 0
}
/**
Tells the data source to move a row at a specific location in the table view to another location.
*/
@objc
open func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
if datasource.responds(to: #selector(UITableViewDataSource.tableView(_:moveRowAt:to:))) {
datasource.tableView?(tableView, moveRowAt: sourceIndexPath, to: destinationIndexPath)
}
}
/**
Asks the data source to return the titles for the sections for a table view.
*/
public func sectionIndexTitles(for tableView: UITableView) -> [String]? {
return datasource.sectionIndexTitles?(for: tableView)
}
/**
default is UITableViewCellEditingStyleNone. This is set by UITableView using the delegate's value for cells who customize their appearance
*/
@objc
open func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
datasource.tableView?(tableView, commit: editingStyle, forRowAt: indexPath)
}
/**
Method that dictates what happens when a ad network request resulted successful. It should kick off what to do with this list of ads.
- important:
Abstract classes that a datasource should override. It's specific to the type of data source.
*/
open override func onAdRequestSuccess(_ ads: [NativeAd]) {
super.onAdRequestSuccess(ads)
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
self.tableView.reloadData()
}
}
/**
The actual important to a UITableView functions are down below here.
*/
@objc
open func numberOfSections(in tableView: UITableView) -> Int {
if let result = datasource.numberOfSections?(in: tableView) {
return result
}
return 1
}
public override func numberOfSections() -> Int {
return numberOfSections(in: self.tableView)
}
public override func numberOfRowsInSection(section: Int) -> Int {
return datasource.tableView(tableView, numberOfRowsInSection: section)
}
open override func reloadRowsAtIndexPaths(indexPaths: [IndexPath], animation: Bool) {
DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
self.tableView.beginUpdates()
self.tableView.reloadRows(at: indexPaths, with: animation ? UITableViewRowAnimation.automatic : UITableViewRowAnimation.none)
self.tableView.endUpdates()
}
}
}
| mit | affe7c8b5a63b0dd482d71b42ee3143d | 38.046512 | 143 | 0.679571 | 5.178902 | false | false | false | false |
mikewxk/DYLiveDemo_swift | DYLiveDemo/DYLiveDemo/Classes/Tools/Extension/UIBarButtonItem-Ext.swift | 1 | 1282 | //
// UIBarButtonItem-Ext.swift
// DYLiveDemo
//
// Created by xiaokui wu on 12/16/16.
// Copyright © 2016 wxk. All rights reserved.
//
import UIKit
extension UIBarButtonItem{
/* 类方法扩展,swift鼓励用构造函数
class func createItem(imageName: String, highImageName: String, size: CGSize) -> UIBarButtonItem{
let btn = UIButton()
btn.setImage(UIImage(named: imageName), forState: .Normal)
btn.setImage(UIImage(named: highImageName), forState: .Highlighted)
btn.frame = CGRect(origin: CGPointZero, size: size)
return UIBarButtonItem(customView: btn)
}
*/
// 在extension中只能扩展便捷构造函数, 1必须以convenience开头,2必须明确调用指定构造函数
convenience init(imageName: String, highImageName: String = "", size: CGSize = CGSizeZero) {
let btn = UIButton()
btn.setImage(UIImage(named: imageName), forState: .Normal)
if highImageName != "" {
btn.setImage(UIImage(named: highImageName), forState: .Highlighted)
}
if size == CGSizeZero {
btn.sizeToFit()
}else{
btn.frame = CGRect(origin: CGPointZero, size: size)
}
self.init(customView: btn)
}
}
| unlicense | ba561eb03622c804ee82010bee38aca9 | 30.394737 | 101 | 0.630344 | 4.113793 | false | false | false | false |
Liujlai/DouYuD | DYTV/DYTV/GameViewController.swift | 1 | 5682 | //
// GameViewController.swift
// DYTV
//
// Created by idea on 2017/8/12.
// Copyright © 2017年 idea. All rights reserved.
//
import UIKit
//边缘间距
private let kEdgeMargin :CGFloat = 10
private let kItemW : CGFloat = (kScreenW - 2 * kEdgeMargin) / 3
private let kItemH : CGFloat = kItemW * 6 / 5
private let kHeaderViewH : CGFloat = 50
private let kGameViewH: CGFloat = 90
private let kGameCellID = "kGameCellID"
private let kHeaderViewID = "kHeaderViewID"
class GameViewController: BaseViewController {
//MARK:懒加载属性
fileprivate lazy var gameVM :GameViewModel = GameViewModel()
fileprivate lazy var collectionView: UICollectionView = { [ unowned self ] in
// 1.创建布局
let layout = UICollectionViewFlowLayout()
layout.itemSize = CGSize(width: kItemW, height: kItemH)
layout.minimumLineSpacing = 0
// 最小间距为0
layout.minimumInteritemSpacing = 0
layout.sectionInset = UIEdgeInsets(top: 0, left: kEdgeMargin, bottom: 0, right: kEdgeMargin)
// 添加头部
layout.headerReferenceSize = CGSize(width: kScreenH, height: kHeaderViewH)
// 2. 创建UICollectionView
let collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout)
collectionView.backgroundColor = UIColor.white
collectionView.autoresizingMask = [.flexibleHeight,.flexibleWidth]
//为了让其显示,注册Cell
collectionView.register( UINib(nibName: "CollectionGameCell", bundle: nil), forCellWithReuseIdentifier: kGameCellID)
// 注册头部
collectionView.register(UINib(nibName: "CollectionHeaderView", bundle: nil), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: kHeaderViewID)
collectionView.dataSource = self
return collectionView
}()
fileprivate lazy var topHeaderView: CollectionHeaderView = {
let headerView = CollectionHeaderView.collectionHeaderView()
headerView.frame = CGRect(x: 0, y: -(kHeaderViewH + kGameViewH), width: kScreenW, height: kHeaderViewH)
headerView.iconImageView.image = UIImage(named: "shortvideo_column_dot")
headerView.titleLable.text = "常用"
// 把button隐藏起来
headerView.moreBtn.isHidden = true
return headerView
}()
fileprivate lazy var gameView: RecommendGameView = {
let gameView = RecommendGameView.recommendGameView()
gameView.frame = CGRect(x: 0, y: -kGameViewH, width: kScreenW, height: kGameViewH)
return gameView
}()
//MARK: 系统回调
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
loadData()
}
}
//MARK: 设置UI界面
extension GameViewController{
override func setupUI(){
// 添加加载动画
// 给contenView进行赋值
contenView = collectionView
// 1.添加UICollectionView
view.addSubview(collectionView)
// 2.添加顶部的HeaderView
collectionView.addSubview(topHeaderView)
// 3. 将常用游戏的View,添加到collectionView中
collectionView.addSubview(gameView)
// 为了不用往下拖动就显示,设置collectionView的内边距
collectionView.contentInset = UIEdgeInsets(top: kHeaderViewH + kGameViewH, left: 0, bottom: 0, right: 0)
super.setupUI()
}
}
//MARK: 请求数据
extension GameViewController{
fileprivate func loadData(){
gameVM.loadAllGameData {
// 1.显示全部游戏
self.collectionView.reloadData()
// 2.展示常用游戏
// var tempArray = [BaseGameModel]()
// for i in 0..<10{
// tempArray.append(self.gameVM.game[i])
// }
//
// self.gameView.groups = tempArray
self.gameView.groups = Array(self.gameVM.game[0..<10])
// 3.数据请求完成
self.loadDataFinished()
}
}
}
//MARK: 遵守UICollectionView 的数据源&代理
extension GameViewController : UICollectionViewDataSource{
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return gameVM.game.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
//1.获取cell
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kGameCellID, for: indexPath) as! CollectionGameCell
// 设置随机背景颜色
// cell.backgroundColor = UIColor.randomColor()
cell.baseGame = gameVM.game[indexPath.item]
return cell
}
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
// 1.取出HearderView
let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: kHeaderViewID, for: indexPath) as! CollectionHeaderView
// 2.给HeaderView设置属性
headerView.titleLable.text = "全部"
headerView.iconImageView.image = UIImage(named: "shortvideo_column_dot")
// 把button隐藏起来
headerView.moreBtn.isHidden = true
return headerView
}
}
| mit | 9c6fb0bfbbbecd33e6af3ae8fb00913e | 32.779874 | 186 | 0.637684 | 5.194391 | false | false | false | false |
Sage-Bionetworks/BridgeAppSDK | BridgeAppSDKTests/SBAActivityArchiveTests.swift | 1 | 12987 | //
// SBAActivityArchive.swift
// BridgeAppSDK
//
// Copyright © 2016 Sage Bionetworks. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation and/or
// other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder(s) nor the names of any contributors
// may be used to endorse or promote products derived from this software without
// specific prior written permission. No license is granted to the trademarks of
// the copyright holders even if such marks are included in this software.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
import XCTest
class SBAActivityArchive: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
// MARK: V1 Survey support
func testSingleChoiceQuestionResult() {
let result = ORKChoiceQuestionResult(identifier: "test")
result.questionType = .singleChoice
result.choiceAnswers = ["answer"]
guard let json = checkSharedArchiveKeys(result, stepIdentifier: "test", expectedFilename: "test.json") else {
XCTAssert(false)
return
}
// Check the values specific to this result type
XCTAssertEqual(json["item"] as? String, "test")
XCTAssertEqual(json["questionTypeName"] as? String, "SingleChoice")
guard let choiceAnswers = json["choiceAnswers"] as? [String] else {
XCTAssert(false, "\(String(describing: json["choiceAnswers"])) not of expected type")
return
}
XCTAssertEqual(choiceAnswers, ["answer"])
guard let answer = json["answer"] as? String else {
XCTAssert(false, "\(String(describing: json["answer"])) not of expected type")
return
}
XCTAssertEqual(answer, "answer")
}
func testMultipleChoiceQuestionResult() {
let result = ORKChoiceQuestionResult(identifier: "test")
result.questionType = .multipleChoice
result.choiceAnswers = ["A", "B"]
guard let json = checkSharedArchiveKeys(result, stepIdentifier: "test", expectedFilename: "test.json") else {
XCTAssert(false)
return
}
// Check the values specific to this result type
XCTAssertEqual(json["item"] as? String, "test")
XCTAssertEqual(json["questionTypeName"] as? String, "MultipleChoice")
guard let choiceAnswers = json["choiceAnswers"] as? [String] else {
XCTAssert(false, "\(String(describing: json["choiceAnswers"])) not of expected type")
return
}
XCTAssertEqual(choiceAnswers, ["A", "B"])
}
func testScaleQuestionResult() {
let result = ORKScaleQuestionResult(identifier: "test")
result.questionType = .scale
result.scaleAnswer = NSNumber(value: 5)
guard let json = checkSharedArchiveKeys(result, stepIdentifier: "test", expectedFilename: "test.json") else {
XCTAssert(false)
return
}
// Check the values specific to this result type
XCTAssertEqual(json["item"] as? String, "test")
XCTAssertEqual(json["questionTypeName"] as? String, "Scale")
XCTAssertEqual(json["scaleAnswer"] as? NSNumber, NSNumber(value: 5))
}
func testBooleanQuestionResult() {
let result = ORKBooleanQuestionResult(identifier: "test")
result.questionType = .boolean
result.booleanAnswer = NSNumber(value: true)
guard let json = checkSharedArchiveKeys(result, stepIdentifier: "test", expectedFilename: "test.json") else {
XCTAssert(false)
return
}
// Check the values specific to this result type
XCTAssertEqual(json["item"] as? String, "test")
XCTAssertEqual(json["questionTypeName"] as? String, "Boolean")
XCTAssertEqual(json["booleanAnswer"] as? NSNumber, NSNumber(value: true))
}
func testTextQuestionResult() {
let result = ORKTextQuestionResult(identifier: "test")
result.questionType = .text
result.textAnswer = "foo bar"
guard let json = checkSharedArchiveKeys(result, stepIdentifier: "test", expectedFilename: "test.json") else {
XCTAssert(false)
return
}
// Check the values specific to this result type
XCTAssertEqual(json["item"] as? String, "test")
XCTAssertEqual(json["questionTypeName"] as? String, "Text")
XCTAssertEqual(json["textAnswer"] as? String, "foo bar")
}
func testNumericQuestionResult_Integer() {
let result = ORKNumericQuestionResult(identifier: "test")
result.questionType = .integer
result.numericAnswer = NSNumber(value: 5)
guard let json = checkSharedArchiveKeys(result, stepIdentifier: "test", expectedFilename: "test.json") else {
XCTAssert(false)
return
}
// Check the values specific to this result type
XCTAssertEqual(json["item"] as? String, "test")
XCTAssertEqual(json["questionTypeName"] as? String, "Integer")
XCTAssertEqual(json["numericAnswer"] as? NSNumber, NSNumber(value: 5))
}
func testNumericQuestionResult_Decimal() {
let result = ORKNumericQuestionResult(identifier: "test")
result.questionType = .decimal
result.numericAnswer = NSNumber(value: 1.2)
guard let json = checkSharedArchiveKeys(result, stepIdentifier: "test", expectedFilename: "test.json") else {
XCTAssert(false)
return
}
// Check the values specific to this result type
XCTAssertEqual(json["item"] as? String, "test")
XCTAssertEqual(json["questionTypeName"] as? String, "Decimal")
XCTAssertEqual(json["numericAnswer"] as? NSNumber, NSNumber(value: 1.2))
}
func testTimeOfDayQuestionResult() {
let result = ORKTimeOfDayQuestionResult(identifier: "test")
result.questionType = .timeOfDay
result.dateComponentsAnswer = DateComponents()
result.dateComponentsAnswer?.hour = 5
result.dateComponentsAnswer?.minute = 32
guard let json = checkSharedArchiveKeys(result, stepIdentifier: "test", expectedFilename: "test.json") else {
XCTAssert(false)
return
}
// Check the values specific to this result type
XCTAssertEqual(json["item"] as? String, "test")
XCTAssertEqual(json["questionTypeName"] as? String, "TimeOfDay")
XCTAssertEqual(json["dateComponentsAnswer"] as? String, "05:32:00")
}
func testDateQuestionResult_Date() {
let result = ORKDateQuestionResult(identifier: "test")
result.questionType = .date
result.dateAnswer = date(year: 1969, month: 8, day: 3)
guard let json = checkSharedArchiveKeys(result, stepIdentifier: "test", expectedFilename: "test.json") else {
XCTAssert(false)
return
}
// Check the values specific to this result type
XCTAssertEqual(json["item"] as? String, "test")
XCTAssertEqual(json["questionTypeName"] as? String, "Date")
XCTAssertEqual(json["dateAnswer"] as? String, "1969-08-03")
}
func testDateQuestionResult_DateAndTime() {
let result = ORKDateQuestionResult(identifier: "test")
result.questionType = .dateAndTime
result.dateAnswer = date(year: 1969, month: 8, day: 3, hour: 4, minute: 10, second: 00)
guard let json = checkSharedArchiveKeys(result, stepIdentifier: "test", expectedFilename: "test.json") else {
XCTAssert(false)
return
}
// Check the values specific to this result type
XCTAssertEqual(json["item"] as? String, "test")
XCTAssertEqual(json["questionTypeName"] as? String, "Date")
let expectedAnswer = "1969-08-03T04:10:00.000" + timezoneString(for: result.dateAnswer!)
XCTAssertEqual(json["dateAnswer"] as? String, expectedAnswer)
}
func testTimeIntervalQuestionResult() {
// TODO: syoung 08/11/2016 Not currently used by any studies. The implementation that is available in RK
// is limited and does not match the format expected by the server. Revisit this when there is a need to
// support it.
}
// MARK: Helper methods
func checkSharedArchiveKeys(_ result: ORKResult, stepIdentifier: String, expectedFilename: String) -> [AnyHashable: Any]? {
result.startDate = date(year: 2016, month: 7, day: 4, hour: 8, minute: 29, second: 54)
result.endDate = date(year: 2016, month: 7, day: 4, hour: 8, minute: 30, second: 23)
// Create the archive
let archiveObject = result.bridgeData(stepIdentifier)
XCTAssertNotNil(archiveObject)
guard let archiveResult = archiveObject else { return nil }
XCTAssertEqual(archiveResult.filename, expectedFilename)
guard let json = archiveResult.result as? [AnyHashable: Any] else {
XCTAssert(false, "\(archiveResult.result) not of expected type")
return nil
}
// NSDate does not carry the timezone and thus, will always be
// represented in the current timezone
let expectedStart = "2016-07-04T08:29:54.000" + timezoneString(for: result.startDate)
let expectedEnd = "2016-07-04T08:30:23.000" + timezoneString(for: result.endDate)
let actualStart = json["startDate"] as? String
let actualEnd = json["endDate"] as? String
XCTAssertEqual(actualStart, expectedStart)
XCTAssertEqual(actualEnd, expectedEnd)
return json
}
func date(year: Int, month: Int, day: Int, hour: Int = 0, minute: Int = 0, second: Int = 0) -> Date {
let calendar = Calendar(identifier: Calendar.Identifier.gregorian)
var components = DateComponents()
components.day = day
components.month = month
components.year = year
components.hour = hour
components.minute = minute
components.second = second
return calendar.date(from: components)!
}
func timezoneString(for date: Date) -> String {
let calendar = Calendar(identifier: Calendar.Identifier.gregorian)
guard calendar.timeZone.secondsFromGMT() != 0 else {
return "Z" // At GMT, use a 'Z' rather than time zone offset
}
// Figure out what the timezone would be for different locations
// so that the unit test can use baked in times (that do not rely upon the formatter)
let minuteUnit = 60
let hoursUnit = 60 * minuteUnit
let isDST = calendar.timeZone.isDaylightSavingTime(for: date)
let isNowDST = calendar.timeZone.isDaylightSavingTime()
let timezoneNowHours: Int = calendar.timeZone.secondsFromGMT() / hoursUnit
let timezoneNowMinutes: Int = abs(calendar.timeZone.secondsFromGMT() / minuteUnit - timezoneNowHours * 60)
let timezoneHours: Int = timezoneNowHours + (isDST && !isNowDST ? 1 : 0) + (!isDST && isNowDST ? -1 : 0)
let timezone = String(format: "%+.2d:%.2d", timezoneHours, timezoneNowMinutes)
return timezone
}
}
| bsd-3-clause | 4e60e9164e6ef7dda22a60680f437c26 | 41.02589 | 127 | 0.642076 | 4.788348 | false | true | false | false |
alfiehanssen/ThreeSixtyPlayer | ThreeSixtyPlayer/Navigation/DeviceMotionController.swift | 2 | 3057 | //
// DeviceMotionController.swift
// ThreeSixtyPlayer
//
// Created by Alfred Hanssen on 9/25/16.
// Copyright © 2016 Alfie Hanssen. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
import CoreMotion
/// A controller that manages device motion updates.
class DeviceMotionController
{
/// The interval at which device motion updates will be reported.
fileprivate static let DeviceMotionUpdateInterval: TimeInterval = 1 / 60
/// The motion manager used to adjust camera position based on device motion.
fileprivate let motionManager = CMMotionManager()
/// Accessor for the current device motion.
var currentDeviceMotion: CMDeviceMotion?
{
return self.motionManager.deviceMotion
}
/// A boolean that starts and stops device motion updates, if device motion is available.
var enabled = false
{
didSet
{
guard self.motionManager.isDeviceMotionAvailable else
{
return
}
// Start and stop device motion reporting as appropriate.
if self.enabled
{
guard !self.motionManager.isDeviceMotionActive else
{
return
}
self.motionManager.startDeviceMotionUpdates(using: CMAttitudeReferenceFrame.xArbitraryZVertical)
}
else
{
guard self.motionManager.isDeviceMotionActive else
{
return
}
self.motionManager.stopDeviceMotionUpdates()
}
}
}
deinit
{
self.enabled = false
}
init()
{
guard self.motionManager.isDeviceMotionAvailable else
{
return
}
self.motionManager.deviceMotionUpdateInterval = type(of: self).DeviceMotionUpdateInterval
}
}
| mit | 9187b0e7aabc129c1b3df3a0255a1b90 | 32.217391 | 112 | 0.641688 | 5.278066 | false | false | false | false |
jjochen/JJFloatingActionButton | Example/Tests/Mocks/JJFloationgActionButtonDelegateMock.swift | 1 | 1851 | //
// JJFloationgActionButtonDelegateMock.swift
//
// Copyright (c) 2017-Present Jochen Pfeiffer
//
// 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.
//
@testable import JJFloatingActionButton
class JJFloatingActionButtonDelegateMock: JJFloatingActionButtonDelegate {
var willOpenCalled = false
var didOpenCalled = false
var willCloseCalled = false
var didCloseCalled = false
func floatingActionButtonWillOpen(_: JJFloatingActionButton) {
willOpenCalled = true
}
func floatingActionButtonDidOpen(_: JJFloatingActionButton) {
didOpenCalled = true
}
func floatingActionButtonWillClose(_: JJFloatingActionButton) {
willCloseCalled = true
}
func floatingActionButtonDidClose(_: JJFloatingActionButton) {
didCloseCalled = true
}
}
| mit | c191504c5d6e3b2744fdd048e2c0a9ad | 37.5625 | 81 | 0.746623 | 4.922872 | false | false | false | false |
LoopKit/LoopKit | LoopKitHostedTests/GlucoseStoreTests.swift | 1 | 41600 | //
// GlucoseStoreTests.swift
// LoopKitHostedTests
//
// Created by Darin Krauss on 10/12/20.
// Copyright © 2020 LoopKit Authors. All rights reserved.
//
import XCTest
import HealthKit
@testable import LoopKit
class GlucoseStoreTestsBase: PersistenceControllerTestCase, GlucoseStoreDelegate {
private static let device = HKDevice(name: "NAME", manufacturer: "MANUFACTURER", model: "MODEL", hardwareVersion: "HARDWAREVERSION", firmwareVersion: "FIRMWAREVERSION", softwareVersion: "SOFTWAREVERSION", localIdentifier: "LOCALIDENTIFIER", udiDeviceIdentifier: "UDIDEVICEIDENTIFIER")
internal let sample1 = NewGlucoseSample(date: Date(timeIntervalSinceNow: -.minutes(6)),
quantity: HKQuantity(unit: .milligramsPerDeciliter, doubleValue: 123.4),
condition: nil,
trend: nil,
trendRate: nil,
isDisplayOnly: true,
wasUserEntered: false,
syncIdentifier: "1925558F-E98F-442F-BBA6-F6F75FB4FD91",
syncVersion: 2,
device: device)
internal let sample2 = NewGlucoseSample(date: Date(timeIntervalSinceNow: -.minutes(2)),
quantity: HKQuantity(unit: .millimolesPerLiter, doubleValue: 7.4),
condition: nil,
trend: .flat,
trendRate: HKQuantity(unit: .millimolesPerLiterPerMinute, doubleValue: 0.0),
isDisplayOnly: false,
wasUserEntered: true,
syncIdentifier: "535F103C-3DFE-48F2-B15A-47313191E7B7",
syncVersion: 3,
device: device)
internal let sample3 = NewGlucoseSample(date: Date(timeIntervalSinceNow: -.minutes(4)),
quantity: HKQuantity(unit: .milligramsPerDeciliter, doubleValue: 400.0),
condition: .aboveRange,
trend: .upUpUp,
trendRate: HKQuantity(unit: .milligramsPerDeciliterPerMinute, doubleValue: 4.2),
isDisplayOnly: false,
wasUserEntered: false,
syncIdentifier: "E1624D2B-A971-41B8-B8A0-3A8212AC3D71",
syncVersion: 4,
device: device)
var healthStore: HKHealthStoreMock!
var glucoseStore: GlucoseStore!
var delegateCompletion: XCTestExpectation?
var authorizationStatus: HKAuthorizationStatus = .notDetermined
override func setUp() {
super.setUp()
let semaphore = DispatchSemaphore(value: 0)
cacheStore.onReady { error in
XCTAssertNil(error)
semaphore.signal()
}
semaphore.wait()
healthStore = HKHealthStoreMock()
healthStore.authorizationStatus = authorizationStatus
glucoseStore = GlucoseStore(healthStore: healthStore,
cacheStore: cacheStore,
cacheLength: .hours(1),
observationInterval: .minutes(30),
provenanceIdentifier: HKSource.default().bundleIdentifier)
glucoseStore.delegate = self
}
override func tearDown() {
let semaphore = DispatchSemaphore(value: 0)
glucoseStore.purgeAllGlucoseSamples(healthKitPredicate: HKQuery.predicateForObjects(from: HKSource.default())) { error in
XCTAssertNil(error)
semaphore.signal()
}
semaphore.wait()
delegateCompletion = nil
glucoseStore = nil
healthStore = nil
super.tearDown()
}
// MARK: - GlucoseStoreDelegate
func glucoseStoreHasUpdatedGlucoseData(_ glucoseStore: GlucoseStore) {
delegateCompletion?.fulfill()
}
}
class GlucoseStoreTestsAuthorizationRequired: GlucoseStoreTestsBase {
func testObserverQueryStartup() {
XCTAssert(glucoseStore.authorizationRequired);
XCTAssertNil(glucoseStore.observerQuery);
let authorizationCompletion = expectation(description: "authorization completion")
glucoseStore.authorize { (result) in
authorizationCompletion.fulfill()
}
waitForExpectations(timeout: 10)
XCTAssertNotNil(glucoseStore.observerQuery);
}
}
class GlucoseStoreTests: GlucoseStoreTestsBase {
override func setUp() {
authorizationStatus = .sharingAuthorized
super.setUp()
}
// MARK: - HealthKitSampleStore
func testHealthKitQueryAnchorPersistence() {
var observerQuery: HKObserverQueryMock? = nil
var anchoredObjectQuery: HKAnchoredObjectQueryMock? = nil
// Check that an observer query was registered even without authorize() being called.
XCTAssertFalse(glucoseStore.authorizationRequired);
XCTAssertNotNil(glucoseStore.observerQuery);
glucoseStore.createObserverQuery = { (sampleType, predicate, updateHandler) -> HKObserverQuery in
observerQuery = HKObserverQueryMock(sampleType: sampleType, predicate: predicate, updateHandler: updateHandler)
return observerQuery!
}
let authorizationCompletion = expectation(description: "authorization completion")
glucoseStore.authorize { (result) in
authorizationCompletion.fulfill()
}
waitForExpectations(timeout: 10)
XCTAssertNotNil(observerQuery)
let anchoredObjectQueryCreationExpectation = expectation(description: "anchored object query creation")
glucoseStore.createAnchoredObjectQuery = { (sampleType, predicate, anchor, limit, resultsHandler) -> HKAnchoredObjectQuery in
anchoredObjectQuery = HKAnchoredObjectQueryMock(type: sampleType, predicate: predicate, anchor: anchor, limit: limit, resultsHandler: resultsHandler)
anchoredObjectQueryCreationExpectation.fulfill()
return anchoredObjectQuery!
}
let observerQueryCompletionExpectation = expectation(description: "observer query completion")
let observerQueryCompletionHandler = {
observerQueryCompletionExpectation.fulfill()
}
// This simulates a signal marking the arrival of new HK Data.
observerQuery!.updateHandler(observerQuery!, observerQueryCompletionHandler, nil)
wait(for: [anchoredObjectQueryCreationExpectation], timeout: 10)
// Trigger results handler for anchored object query
let returnedAnchor = HKQueryAnchor(fromValue: 5)
anchoredObjectQuery!.resultsHandler(anchoredObjectQuery!, [], [], returnedAnchor, nil)
// Wait for observerQueryCompletionExpectation
waitForExpectations(timeout: 10)
XCTAssertNotNil(glucoseStore.queryAnchor)
cacheStore.managedObjectContext.performAndWait {}
// Create a new glucose store, and ensure it uses the last query anchor
let newGlucoseStore = GlucoseStore(healthStore: healthStore,
cacheStore: cacheStore,
provenanceIdentifier: HKSource.default().bundleIdentifier)
let newAuthorizationCompletion = expectation(description: "authorization completion")
observerQuery = nil
newGlucoseStore.createObserverQuery = { (sampleType, predicate, updateHandler) -> HKObserverQuery in
observerQuery = HKObserverQueryMock(sampleType: sampleType, predicate: predicate, updateHandler: updateHandler)
return observerQuery!
}
newGlucoseStore.authorize { (result) in
newAuthorizationCompletion.fulfill()
}
waitForExpectations(timeout: 10)
anchoredObjectQuery = nil
let newAnchoredObjectQueryCreationExpectation = expectation(description: "new anchored object query creation")
newGlucoseStore.createAnchoredObjectQuery = { (sampleType, predicate, anchor, limit, resultsHandler) -> HKAnchoredObjectQuery in
anchoredObjectQuery = HKAnchoredObjectQueryMock(type: sampleType, predicate: predicate, anchor: anchor, limit: limit, resultsHandler: resultsHandler)
newAnchoredObjectQueryCreationExpectation.fulfill()
return anchoredObjectQuery!
}
// This simulates a signal marking the arrival of new HK Data.
observerQuery!.updateHandler(observerQuery!, {}, nil)
waitForExpectations(timeout: 10)
// Assert new glucose store is querying with the last anchor that our HealthKit mock returned
XCTAssertEqual(returnedAnchor, anchoredObjectQuery?.anchor)
anchoredObjectQuery!.resultsHandler(anchoredObjectQuery!, [], [], returnedAnchor, nil)
}
// MARK: - Fetching
func testGetGlucoseSamples() {
let addGlucoseSamplesCompletion = expectation(description: "addGlucoseSamples")
glucoseStore.addGlucoseSamples([sample1, sample2, sample3]) { result in
switch result {
case .failure(let error):
XCTFail("Unexpected failure: \(error)")
case .success(let samples):
XCTAssertEqual(samples.count, 3)
}
addGlucoseSamplesCompletion.fulfill()
}
waitForExpectations(timeout: 10)
let getGlucoseSamples1Completion = expectation(description: "getGlucoseSamples1")
glucoseStore.getGlucoseSamples() { result in
switch result {
case .failure(let error):
XCTFail("Unexpected failure: \(error)")
case .success(let samples):
XCTAssertEqual(samples.count, 3)
XCTAssertNotNil(samples[0].uuid)
XCTAssertNil(samples[0].healthKitEligibleDate)
assertEqualSamples(samples[0], self.sample1)
XCTAssertNotNil(samples[1].uuid)
XCTAssertNil(samples[1].healthKitEligibleDate)
assertEqualSamples(samples[1], self.sample3)
XCTAssertNotNil(samples[2].uuid)
XCTAssertNil(samples[2].healthKitEligibleDate)
assertEqualSamples(samples[2], self.sample2)
}
getGlucoseSamples1Completion.fulfill()
}
waitForExpectations(timeout: 10)
let getGlucoseSamples2Completion = expectation(description: "getGlucoseSamples2")
glucoseStore.getGlucoseSamples(start: Date(timeIntervalSinceNow: -.minutes(5)), end: Date(timeIntervalSinceNow: -.minutes(3))) { result in
switch result {
case .failure(let error):
XCTFail("Unexpected failure: \(error)")
case .success(let samples):
XCTAssertEqual(samples.count, 1)
XCTAssertNotNil(samples[0].uuid)
XCTAssertNil(samples[0].healthKitEligibleDate)
assertEqualSamples(samples[0], self.sample3)
}
getGlucoseSamples2Completion.fulfill()
}
waitForExpectations(timeout: 10)
let purgeCachedGlucoseObjectsCompletion = expectation(description: "purgeCachedGlucoseObjects")
glucoseStore.purgeCachedGlucoseObjects() { error in
XCTAssertNil(error)
purgeCachedGlucoseObjectsCompletion.fulfill()
}
waitForExpectations(timeout: 10)
let getGlucoseSamples3Completion = expectation(description: "getGlucoseSamples3")
glucoseStore.getGlucoseSamples() { result in
switch result {
case .failure(let error):
XCTFail("Unexpected failure: \(error)")
case .success(let samples):
XCTAssertEqual(samples.count, 0)
}
getGlucoseSamples3Completion.fulfill()
}
waitForExpectations(timeout: 10)
}
enum Error: Swift.Error { case arbitrary }
func testGetGlucoseSamplesDelayedHealthKitStorage() {
glucoseStore.healthKitStorageDelay = .minutes(5)
var hkobjects = [HKObject]()
healthStore.setSaveHandler { o, _, _ in hkobjects = o }
let addGlucoseSamplesCompletion = expectation(description: "addGlucoseSamples")
glucoseStore.addGlucoseSamples([sample1, sample2, sample3]) { result in
switch result {
case .failure(let error):
XCTFail("Unexpected failure: \(error)")
case .success(let samples):
XCTAssertEqual(samples.count, 3)
}
addGlucoseSamplesCompletion.fulfill()
}
waitForExpectations(timeout: 10)
let getGlucoseSamples1Completion = expectation(description: "getGlucoseSamples1")
glucoseStore.getGlucoseSamples() { result in
switch result {
case .failure(let error):
XCTFail("Unexpected failure: \(error)")
case .success(let samples):
XCTAssertEqual(samples.count, 3)
// HealthKit storage is deferred, so the second 2 UUIDs are nil
XCTAssertNotNil(samples[0].uuid)
XCTAssertNil(samples[0].healthKitEligibleDate)
assertEqualSamples(samples[0], self.sample1)
XCTAssertNil(samples[1].uuid)
XCTAssertNotNil(samples[1].healthKitEligibleDate)
assertEqualSamples(samples[1], self.sample3)
XCTAssertNil(samples[2].uuid)
XCTAssertNotNil(samples[2].healthKitEligibleDate)
assertEqualSamples(samples[2], self.sample2)
}
getGlucoseSamples1Completion.fulfill()
}
waitForExpectations(timeout: 10)
XCTAssertEqual([sample1.quantitySample.description], hkobjects.map { $0.description })
}
func testGetGlucoseSamplesErrorHealthKitStorage() {
healthStore.saveError = Error.arbitrary
var hkobjects = [HKObject]()
healthStore.setSaveHandler { o, _, _ in hkobjects = o }
let addGlucoseSamplesCompletion = expectation(description: "addGlucoseSamples")
glucoseStore.addGlucoseSamples([sample1, sample2, sample3]) { result in
switch result {
case .failure(let error):
XCTFail("Unexpected failure: \(error)")
case .success(let samples):
XCTAssertEqual(samples.count, 3)
}
addGlucoseSamplesCompletion.fulfill()
}
waitForExpectations(timeout: 10)
let getGlucoseSamples1Completion = expectation(description: "getGlucoseSamples1")
glucoseStore.getGlucoseSamples() { result in
switch result {
case .failure(let error):
XCTFail("Unexpected failure: \(error)")
case .success(let samples):
XCTAssertEqual(samples.count, 3)
// HealthKit storage is deferred, so the second 2 UUIDs are nil
XCTAssertNil(samples[0].uuid)
XCTAssertNotNil(samples[0].healthKitEligibleDate)
assertEqualSamples(samples[0], self.sample1)
XCTAssertNil(samples[1].uuid)
XCTAssertNotNil(samples[1].healthKitEligibleDate)
assertEqualSamples(samples[1], self.sample3)
XCTAssertNil(samples[2].uuid)
XCTAssertNotNil(samples[2].healthKitEligibleDate)
assertEqualSamples(samples[2], self.sample2)
}
getGlucoseSamples1Completion.fulfill()
}
waitForExpectations(timeout: 10)
XCTAssertEqual(3, hkobjects.count)
}
func testGetGlucoseSamplesDeniedHealthKitStorage() {
healthStore.authorizationStatus = .sharingDenied
var hkobjects = [HKObject]()
healthStore.setSaveHandler { o, _, _ in hkobjects = o }
let addGlucoseSamplesCompletion = expectation(description: "addGlucoseSamples")
glucoseStore.addGlucoseSamples([sample1, sample2, sample3]) { result in
switch result {
case .failure(let error):
XCTFail("Unexpected failure: \(error)")
case .success(let samples):
XCTAssertEqual(samples.count, 3)
}
addGlucoseSamplesCompletion.fulfill()
}
waitForExpectations(timeout: 10)
let getGlucoseSamples1Completion = expectation(description: "getGlucoseSamples1")
glucoseStore.getGlucoseSamples() { result in
switch result {
case .failure(let error):
XCTFail("Unexpected failure: \(error)")
case .success(let samples):
XCTAssertEqual(samples.count, 3)
// HealthKit storage is denied, so all UUIDs are nil
XCTAssertNil(samples[0].uuid)
XCTAssertNil(samples[0].healthKitEligibleDate)
assertEqualSamples(samples[0], self.sample1)
XCTAssertNil(samples[1].uuid)
XCTAssertNil(samples[1].healthKitEligibleDate)
assertEqualSamples(samples[1], self.sample3)
XCTAssertNil(samples[2].uuid)
XCTAssertNil(samples[2].healthKitEligibleDate)
assertEqualSamples(samples[2], self.sample2)
}
getGlucoseSamples1Completion.fulfill()
}
waitForExpectations(timeout: 10)
XCTAssertTrue(hkobjects.isEmpty)
}
func testGetGlucoseSamplesSomeDeniedHealthKitStorage() {
glucoseStore.healthKitStorageDelay = 0
var hkobjects = [HKObject]()
healthStore.setSaveHandler { o, _, _ in hkobjects = o }
let addGlucoseSamples1Completion = expectation(description: "addGlucoseSamples1")
// Authorized
glucoseStore.addGlucoseSamples([sample1]) { result in
switch result {
case .failure(let error):
XCTFail("Unexpected failure: \(error)")
case .success(let samples):
XCTAssertEqual(samples.count, 1)
}
addGlucoseSamples1Completion.fulfill()
}
waitForExpectations(timeout: 10)
XCTAssertEqual(1, hkobjects.count)
hkobjects = []
healthStore.authorizationStatus = .sharingDenied
let addGlucoseSamples2Completion = expectation(description: "addGlucoseSamples2")
// Denied
glucoseStore.addGlucoseSamples([sample2]) { result in
switch result {
case .failure(let error):
XCTFail("Unexpected failure: \(error)")
case .success(let samples):
XCTAssertEqual(samples.count, 1)
}
addGlucoseSamples2Completion.fulfill()
}
waitForExpectations(timeout: 10)
XCTAssertEqual(0, hkobjects.count)
hkobjects = []
healthStore.authorizationStatus = .sharingAuthorized
let addGlucoseSamples3Completion = expectation(description: "addGlucoseSamples3")
// Authorized
glucoseStore.addGlucoseSamples([sample3]) { result in
switch result {
case .failure(let error):
XCTFail("Unexpected failure: \(error)")
case .success(let samples):
XCTAssertEqual(samples.count, 1)
}
addGlucoseSamples3Completion.fulfill()
}
waitForExpectations(timeout: 10)
XCTAssertEqual(1, hkobjects.count)
hkobjects = []
let getGlucoseSamples1Completion = expectation(description: "getGlucoseSamples1")
glucoseStore.getGlucoseSamples() { result in
switch result {
case .failure(let error):
XCTFail("Unexpected failure: \(error)")
case .success(let samples):
XCTAssertEqual(samples.count, 3)
XCTAssertNotNil(samples[0].uuid)
XCTAssertNil(samples[0].healthKitEligibleDate)
assertEqualSamples(samples[0], self.sample1)
XCTAssertNotNil(samples[1].uuid)
XCTAssertNil(samples[1].healthKitEligibleDate)
assertEqualSamples(samples[1], self.sample3)
XCTAssertNil(samples[2].uuid)
XCTAssertNil(samples[2].healthKitEligibleDate)
assertEqualSamples(samples[2], self.sample2)
}
getGlucoseSamples1Completion.fulfill()
}
waitForExpectations(timeout: 10)
}
func testLatestGlucose() {
XCTAssertNil(glucoseStore.latestGlucose)
let addGlucoseSamplesCompletion = expectation(description: "addGlucoseSamples")
glucoseStore.addGlucoseSamples([sample1, sample2, sample3]) { result in
switch result {
case .failure(let error):
XCTFail("Unexpected failure: \(error)")
case .success(let samples):
XCTAssertEqual(samples.count, 3)
assertEqualSamples(samples[0], self.sample1)
assertEqualSamples(samples[1], self.sample2)
assertEqualSamples(samples[2], self.sample3)
}
addGlucoseSamplesCompletion.fulfill()
}
waitForExpectations(timeout: 10)
XCTAssertNotNil(glucoseStore.latestGlucose)
XCTAssertEqual(glucoseStore.latestGlucose?.startDate, sample2.date)
XCTAssertEqual(glucoseStore.latestGlucose?.endDate, sample2.date)
XCTAssertEqual(glucoseStore.latestGlucose?.quantity, sample2.quantity)
XCTAssertEqual(glucoseStore.latestGlucose?.provenanceIdentifier, HKSource.default().bundleIdentifier)
XCTAssertEqual(glucoseStore.latestGlucose?.isDisplayOnly, sample2.isDisplayOnly)
XCTAssertEqual(glucoseStore.latestGlucose?.wasUserEntered, sample2.wasUserEntered)
let purgeCachedGlucoseObjectsCompletion = expectation(description: "purgeCachedGlucoseObjects")
glucoseStore.purgeCachedGlucoseObjects() { error in
XCTAssertNil(error)
purgeCachedGlucoseObjectsCompletion.fulfill()
}
waitForExpectations(timeout: 10)
XCTAssertNil(glucoseStore.latestGlucose)
}
// MARK: - Modification
func testAddGlucoseSamples() {
let addGlucoseSamples1Completion = expectation(description: "addGlucoseSamples1")
glucoseStore.addGlucoseSamples([sample1, sample2, sample3, sample1, sample2, sample3]) { result in
switch result {
case .failure(let error):
XCTFail("Unexpected failure: \(error)")
case .success(let samples):
XCTAssertEqual(samples.count, 3)
// Note: the HealthKit UUID is no longer updated before being returned as a result of addGlucoseSamples.
XCTAssertNil(samples[0].uuid)
XCTAssertNotNil(samples[0].healthKitEligibleDate)
assertEqualSamples(samples[0], self.sample1)
XCTAssertNil(samples[1].uuid)
XCTAssertNotNil(samples[1].healthKitEligibleDate)
assertEqualSamples(samples[1], self.sample2)
XCTAssertNil(samples[2].uuid)
XCTAssertNotNil(samples[2].healthKitEligibleDate)
assertEqualSamples(samples[2], self.sample3)
}
addGlucoseSamples1Completion.fulfill()
}
waitForExpectations(timeout: 10)
let getGlucoseSamples1Completion = expectation(description: "getGlucoseSamples1")
glucoseStore.getGlucoseSamples() { result in
switch result {
case .failure(let error):
XCTFail("Unexpected failure: \(error)")
case .success(let samples):
XCTAssertEqual(samples.count, 3)
XCTAssertNotNil(samples[0].uuid)
XCTAssertNil(samples[0].healthKitEligibleDate)
assertEqualSamples(samples[0], self.sample1)
XCTAssertNotNil(samples[1].uuid)
XCTAssertNil(samples[1].healthKitEligibleDate)
assertEqualSamples(samples[1], self.sample3)
XCTAssertNotNil(samples[2].uuid)
XCTAssertNil(samples[2].healthKitEligibleDate)
assertEqualSamples(samples[2], self.sample2)
}
getGlucoseSamples1Completion.fulfill()
}
waitForExpectations(timeout: 10)
let addGlucoseSamples2Completion = expectation(description: "addGlucoseSamples2")
glucoseStore.addGlucoseSamples([sample3, sample1, sample2]) { result in
switch result {
case .failure(let error):
XCTFail("Unexpected failure: \(error)")
case .success(let samples):
XCTAssertEqual(samples.count, 0)
}
addGlucoseSamples2Completion.fulfill()
}
waitForExpectations(timeout: 10)
let getGlucoseSamples2Completion = expectation(description: "getGlucoseSamples2Completion")
glucoseStore.getGlucoseSamples() { result in
switch result {
case .failure(let error):
XCTFail("Unexpected failure: \(error)")
case .success(let samples):
XCTAssertEqual(samples.count, 3)
XCTAssertNotNil(samples[0].uuid)
XCTAssertNil(samples[0].healthKitEligibleDate)
assertEqualSamples(samples[0], self.sample1)
XCTAssertNotNil(samples[1].uuid)
XCTAssertNil(samples[1].healthKitEligibleDate)
assertEqualSamples(samples[1], self.sample3)
XCTAssertNotNil(samples[2].uuid)
XCTAssertNil(samples[2].healthKitEligibleDate)
assertEqualSamples(samples[2], self.sample2)
}
getGlucoseSamples2Completion.fulfill()
}
waitForExpectations(timeout: 10)
}
func testAddGlucoseSamplesEmpty() {
let addGlucoseSamplesCompletion = expectation(description: "addGlucoseSamples")
glucoseStore.addGlucoseSamples([]) { result in
switch result {
case .failure(let error):
XCTFail("Unexpected failure: \(error)")
case .success(let samples):
XCTAssertEqual(samples.count, 0)
}
addGlucoseSamplesCompletion.fulfill()
}
waitForExpectations(timeout: 10)
}
func testAddGlucoseSamplesNotification() {
delegateCompletion = expectation(description: "delegate")
let glucoseSamplesDidChangeCompletion = expectation(description: "glucoseSamplesDidChange")
let observer = NotificationCenter.default.addObserver(forName: GlucoseStore.glucoseSamplesDidChange, object: glucoseStore, queue: nil) { notification in
glucoseSamplesDidChangeCompletion.fulfill()
}
let addGlucoseSamplesCompletion = expectation(description: "addGlucoseSamples")
glucoseStore.addGlucoseSamples([sample1, sample2, sample3]) { result in
switch result {
case .failure(let error):
XCTFail("Unexpected failure: \(error)")
case .success(let samples):
XCTAssertEqual(samples.count, 3)
}
addGlucoseSamplesCompletion.fulfill()
}
wait(for: [glucoseSamplesDidChangeCompletion, delegateCompletion!, addGlucoseSamplesCompletion], timeout: 10, enforceOrder: true)
NotificationCenter.default.removeObserver(observer)
delegateCompletion = nil
}
// MARK: - Watch Synchronization
func testSyncGlucoseSamples() {
var syncGlucoseSamples: [StoredGlucoseSample] = []
let addGlucoseSamplesCompletion = expectation(description: "addGlucoseSamples")
glucoseStore.addGlucoseSamples([sample1, sample2, sample3]) { result in
switch result {
case .failure(let error):
XCTFail("Unexpected failure: \(error)")
case .success(let samples):
XCTAssertEqual(samples.count, 3)
}
addGlucoseSamplesCompletion.fulfill()
}
waitForExpectations(timeout: 10)
let getSyncGlucoseSamples1Completion = expectation(description: "getSyncGlucoseSamples1")
glucoseStore.getSyncGlucoseSamples() { result in
switch result {
case .failure(let error):
XCTFail("Unexpected failure: \(error)")
case .success(let objects):
XCTAssertEqual(objects.count, 3)
XCTAssertNotNil(objects[0].uuid)
assertEqualSamples(objects[0], self.sample1)
XCTAssertNotNil(objects[1].uuid)
assertEqualSamples(objects[1], self.sample3)
XCTAssertNotNil(objects[2].uuid)
assertEqualSamples(objects[2], self.sample2)
syncGlucoseSamples = objects
}
getSyncGlucoseSamples1Completion.fulfill()
}
waitForExpectations(timeout: 10)
let getSyncGlucoseSamples2Completion = expectation(description: "getSyncGlucoseSamples2")
glucoseStore.getSyncGlucoseSamples(start: Date(timeIntervalSinceNow: -.minutes(5)), end: Date(timeIntervalSinceNow: -.minutes(3))) { result in
switch result {
case .failure(let error):
XCTFail("Unexpected failure: \(error)")
case .success(let objects):
XCTAssertEqual(objects.count, 1)
XCTAssertNotNil(objects[0].uuid)
assertEqualSamples(objects[0], self.sample3)
}
getSyncGlucoseSamples2Completion.fulfill()
}
waitForExpectations(timeout: 10)
let purgeCachedGlucoseObjectsCompletion = expectation(description: "purgeCachedGlucoseObjects")
glucoseStore.purgeCachedGlucoseObjects() { error in
XCTAssertNil(error)
purgeCachedGlucoseObjectsCompletion.fulfill()
}
waitForExpectations(timeout: 10)
let getSyncGlucoseSamples3Completion = expectation(description: "getSyncGlucoseSamples3")
glucoseStore.getSyncGlucoseSamples() { result in
switch result {
case .failure(let error):
XCTFail("Unexpected failure: \(error)")
case .success(let samples):
XCTAssertEqual(samples.count, 0)
}
getSyncGlucoseSamples3Completion.fulfill()
}
waitForExpectations(timeout: 10)
let setSyncGlucoseSamplesCompletion = expectation(description: "setSyncGlucoseSamples")
glucoseStore.setSyncGlucoseSamples(syncGlucoseSamples) { error in
XCTAssertNil(error)
setSyncGlucoseSamplesCompletion.fulfill()
}
waitForExpectations(timeout: 10)
let getSyncGlucoseSamples4Completion = expectation(description: "getSyncGlucoseSamples4")
glucoseStore.getSyncGlucoseSamples() { result in
switch result {
case .failure(let error):
XCTFail("Unexpected failure: \(error)")
case .success(let objects):
XCTAssertEqual(objects.count, 3)
XCTAssertNotNil(objects[0].uuid)
assertEqualSamples(objects[0], self.sample1)
XCTAssertNotNil(objects[1].uuid)
assertEqualSamples(objects[1], self.sample3)
XCTAssertNotNil(objects[2].uuid)
assertEqualSamples(objects[2], self.sample2)
syncGlucoseSamples = objects
}
getSyncGlucoseSamples4Completion.fulfill()
}
waitForExpectations(timeout: 10)
}
// MARK: - Cache Management
func testEarliestCacheDate() {
XCTAssertEqual(glucoseStore.earliestCacheDate.timeIntervalSinceNow, -.hours(1), accuracy: 1)
}
func testPurgeAllGlucoseSamples() {
let addGlucoseSamplesCompletion = expectation(description: "addGlucoseSamples")
glucoseStore.addGlucoseSamples([sample1, sample2, sample3]) { result in
switch result {
case .failure(let error):
XCTFail("Unexpected failure: \(error)")
case .success(let samples):
XCTAssertEqual(samples.count, 3)
}
addGlucoseSamplesCompletion.fulfill()
}
waitForExpectations(timeout: 10)
let getGlucoseSamples1Completion = expectation(description: "getGlucoseSamples1")
glucoseStore.getGlucoseSamples() { result in
switch result {
case .failure(let error):
XCTFail("Unexpected failure: \(error)")
case .success(let samples):
XCTAssertEqual(samples.count, 3)
}
getGlucoseSamples1Completion.fulfill()
}
waitForExpectations(timeout: 10)
let purgeAllGlucoseSamplesCompletion = expectation(description: "purgeAllGlucoseSamples")
glucoseStore.purgeAllGlucoseSamples(healthKitPredicate: HKQuery.predicateForObjects(from: HKSource.default())) { error in
XCTAssertNil(error)
purgeAllGlucoseSamplesCompletion.fulfill()
}
waitForExpectations(timeout: 10)
let getGlucoseSamples2Completion = expectation(description: "getGlucoseSamples2")
glucoseStore.getGlucoseSamples() { result in
switch result {
case .failure(let error):
XCTFail("Unexpected failure: \(error)")
case .success(let samples):
XCTAssertEqual(samples.count, 0)
}
getGlucoseSamples2Completion.fulfill()
}
waitForExpectations(timeout: 10)
}
func testPurgeExpiredGlucoseObjects() {
let expiredSample = NewGlucoseSample(date: Date(timeIntervalSinceNow: -.hours(2)),
quantity: HKQuantity(unit: .milligramsPerDeciliter, doubleValue: 198.7),
condition: nil,
trend: nil,
trendRate: nil,
isDisplayOnly: false,
wasUserEntered: false,
syncIdentifier: "6AB8C7F3-A2CE-442F-98C4-3D0514626B5F",
syncVersion: 3)
let addGlucoseSamplesCompletion = expectation(description: "addGlucoseSamples")
glucoseStore.addGlucoseSamples([sample1, sample2, sample3, expiredSample]) { result in
switch result {
case .failure(let error):
XCTFail("Unexpected failure: \(error)")
case .success(let samples):
XCTAssertEqual(samples.count, 4)
}
addGlucoseSamplesCompletion.fulfill()
}
waitForExpectations(timeout: 10)
let getGlucoseSamplesCompletion = expectation(description: "getGlucoseSamples")
glucoseStore.getGlucoseSamples() { result in
switch result {
case .failure(let error):
XCTFail("Unexpected failure: \(error)")
case .success(let samples):
XCTAssertEqual(samples.count, 3)
}
getGlucoseSamplesCompletion.fulfill()
}
waitForExpectations(timeout: 10)
}
func testPurgeCachedGlucoseObjects() {
let addGlucoseSamplesCompletion = expectation(description: "addGlucoseSamples")
glucoseStore.addGlucoseSamples([sample1, sample2, sample3]) { result in
switch result {
case .failure(let error):
XCTFail("Unexpected failure: \(error)")
case .success(let samples):
XCTAssertEqual(samples.count, 3)
}
addGlucoseSamplesCompletion.fulfill()
}
waitForExpectations(timeout: 10)
let getGlucoseSamples1Completion = expectation(description: "getGlucoseSamples1")
glucoseStore.getGlucoseSamples() { result in
switch result {
case .failure(let error):
XCTFail("Unexpected failure: \(error)")
case .success(let samples):
XCTAssertEqual(samples.count, 3)
}
getGlucoseSamples1Completion.fulfill()
}
waitForExpectations(timeout: 10)
let purgeCachedGlucoseObjects1Completion = expectation(description: "purgeCachedGlucoseObjects1")
glucoseStore.purgeCachedGlucoseObjects(before: Date(timeIntervalSinceNow: -.minutes(5))) { error in
XCTAssertNil(error)
purgeCachedGlucoseObjects1Completion.fulfill()
}
waitForExpectations(timeout: 10)
let getGlucoseSamples2Completion = expectation(description: "getGlucoseSamples2")
glucoseStore.getGlucoseSamples() { result in
switch result {
case .failure(let error):
XCTFail("Unexpected failure: \(error)")
case .success(let samples):
XCTAssertEqual(samples.count, 2)
}
getGlucoseSamples2Completion.fulfill()
}
waitForExpectations(timeout: 10)
let purgeCachedGlucoseObjects2Completion = expectation(description: "purgeCachedGlucoseObjects2")
glucoseStore.purgeCachedGlucoseObjects() { error in
XCTAssertNil(error)
purgeCachedGlucoseObjects2Completion.fulfill()
}
waitForExpectations(timeout: 10)
let getGlucoseSamples3Completion = expectation(description: "getGlucoseSamples3")
glucoseStore.getGlucoseSamples() { result in
switch result {
case .failure(let error):
XCTFail("Unexpected failure: \(error)")
case .success(let samples):
XCTAssertEqual(samples.count, 0)
}
getGlucoseSamples3Completion.fulfill()
}
waitForExpectations(timeout: 10)
}
func testPurgeCachedGlucoseObjectsNotification() {
let addGlucoseSamplesCompletion = expectation(description: "addGlucoseSamples")
glucoseStore.addGlucoseSamples([sample1, sample2, sample3]) { result in
switch result {
case .failure(let error):
XCTFail("Unexpected failure: \(error)")
case .success(let samples):
XCTAssertEqual(samples.count, 3)
}
addGlucoseSamplesCompletion.fulfill()
}
waitForExpectations(timeout: 10)
delegateCompletion = expectation(description: "delegate")
let glucoseSamplesDidChangeCompletion = expectation(description: "glucoseSamplesDidChange")
let observer = NotificationCenter.default.addObserver(forName: GlucoseStore.glucoseSamplesDidChange, object: glucoseStore, queue: nil) { notification in
glucoseSamplesDidChangeCompletion.fulfill()
}
let purgeCachedGlucoseObjectsCompletion = expectation(description: "purgeCachedGlucoseObjects")
glucoseStore.purgeCachedGlucoseObjects() { error in
XCTAssertNil(error)
purgeCachedGlucoseObjectsCompletion.fulfill()
}
wait(for: [glucoseSamplesDidChangeCompletion, delegateCompletion!, purgeCachedGlucoseObjectsCompletion], timeout: 10, enforceOrder: true)
NotificationCenter.default.removeObserver(observer)
delegateCompletion = nil
}
}
fileprivate func assertEqualSamples(_ storedGlucoseSample: StoredGlucoseSample,
_ newGlucoseSample: NewGlucoseSample,
provenanceIdentifier: String = HKSource.default().bundleIdentifier,
file: StaticString = #file,
line: UInt = #line) {
XCTAssertEqual(storedGlucoseSample.provenanceIdentifier, provenanceIdentifier, file: file, line: line)
XCTAssertEqual(storedGlucoseSample.syncIdentifier, newGlucoseSample.syncIdentifier, file: file, line: line)
XCTAssertEqual(storedGlucoseSample.syncVersion, newGlucoseSample.syncVersion, file: file, line: line)
XCTAssertEqual(storedGlucoseSample.startDate, newGlucoseSample.date, file: file, line: line)
XCTAssertEqual(storedGlucoseSample.quantity, newGlucoseSample.quantity, file: file, line: line)
XCTAssertEqual(storedGlucoseSample.isDisplayOnly, newGlucoseSample.isDisplayOnly, file: file, line: line)
XCTAssertEqual(storedGlucoseSample.wasUserEntered, newGlucoseSample.wasUserEntered, file: file, line: line)
XCTAssertEqual(storedGlucoseSample.device, newGlucoseSample.device, file: file, line: line)
XCTAssertEqual(storedGlucoseSample.condition, newGlucoseSample.condition, file: file, line: line)
XCTAssertEqual(storedGlucoseSample.trend, newGlucoseSample.trend, file: file, line: line)
XCTAssertEqual(storedGlucoseSample.trendRate, newGlucoseSample.trendRate, file: file, line: line)
}
| mit | f12bab3003f221d4a2f81c83a3ff3d67 | 44.020563 | 288 | 0.622539 | 5.437778 | false | false | false | false |
AndreMuis/Algorithms | RotateArray.playground/Contents.swift | 1 | 225 |
// Rotate an array to the right
let numbers = [1, 2, 3, 4, 5, 6, 7]
let steps = 3
let first = numbers[0 ..< numbers.count - steps]
let last = numbers[numbers.count - steps ..< numbers.count]
let result = last + first
| mit | b57c71937f8f3dbe1b81b1990ae2de3b | 15.071429 | 59 | 0.635556 | 3 | false | false | false | false |
Egibide-DAM/swift | 02_ejemplos/07_ciclo_vida/03_arc/06_referencias_ciclicas_clausuras.playground/Contents.swift | 1 | 878 | class HTMLElement {
let name: String
let text: String?
lazy var asHTML: () -> String = {
if let text = self.text {
return "<\(self.name)>\(text)</\(self.name)>"
} else {
return "<\(self.name) />"
}
}
init(name: String, text: String? = nil) {
self.name = name
self.text = text
}
deinit {
print("\(name) is being deinitialized")
}
}
let heading = HTMLElement(name: "h1")
let defaultText = "some default text"
heading.asHTML = {
return "<\(heading.name)>\(heading.text ?? defaultText)</\(heading.name)>"
}
print(heading.asHTML())
// Prints "<h1>some default text</h1>"
var paragraph: HTMLElement? = HTMLElement(name: "p", text: "hello, world")
print(paragraph!.asHTML())
// Prints "<p>hello, world</p>"
paragraph = nil
// no muestra el deinit()
| apache-2.0 | 9367e50610fdefd09168bd4bb9f3fb19 | 22.105263 | 78 | 0.558087 | 3.784483 | false | false | false | false |
tokyovigilante/CesiumKit | CesiumKit/Core/Matrix3.swift | 1 | 31282 | //
// Matrix3.swift
// CesiumKit
//
// Created by Ryan Walklin on 8/09/14.
// Copyright (c) 2014 Test Toast. All rights reserved.
//
import Foundation
import simd
/**
* A 3x3 matrix, indexable as a column-major order array.
* Constructor parameters are in row-major order for code readability.
* @alias Matrix3
* @constructor
*
* @param {Number} [column0Row0=0.0] The value for column 0, row 0.
* @param {Number} [column1Row0=0.0] The value for column 1, row 0.
* @param {Number} [column2Row0=0.0] The value for column 2, row 0.
* @param {Number} [column0Row1=0.0] The value for column 0, row 1.
* @param {Number} [column1Row1=0.0] The value for column 1, row 1.
* @param {Number} [column2Row1=0.0] The value for column 2, row 1.
* @param {Number} [column0Row2=0.0] The value for column 0, row 2.
* @param {Number} [column1Row2=0.0] The value for column 1, row 2.
* @param {Number} [column2Row2=0.0] The value for column 2, row 2.
*
* @see Matrix3.fromColumnMajorArray
* @see Matrix3.fromRowMajorArray
* @see Matrix3.fromQuaternion
* @see Matrix3.fromScale
* @see Matrix3.fromUniformScale
* @see Matrix2
* @see Matrix4
*/
public struct Matrix3 {
fileprivate (set) internal var simdType: double3x3
var floatRepresentation: float3x3 {
return float3x3([
simd_float(simdType[0]),
simd_float(simdType[1]),
simd_float(simdType[2])
])
}
public init(_ column0Row0: Double, _ column1Row0: Double, _ column2Row0: Double,
_ column0Row1: Double, _ column1Row1: Double, _ column2Row1: Double,
_ column0Row2: Double, _ column1Row2: Double, _ column2Row2: Double) {
simdType = double3x3(rows: [
double3(column0Row0, column1Row0, column2Row0),
double3(column0Row1, column1Row1, column2Row1),
double3(column0Row2, column1Row2, column2Row2),
])
}
/**
* Computes a 3x3 rotation matrix from the provided quaternion.
*
* @param {Quaternion} quaternion the quaternion to use.
* @returns {Matrix3} The 3x3 rotation matrix from this quaternion.
*/
public init(quaternion: Quaternion) {
let x2 = quaternion.x * quaternion.x
let xy = quaternion.x * quaternion.y
let xz = quaternion.x * quaternion.z
let xw = quaternion.x * quaternion.w
let y2 = quaternion.y * quaternion.y
let yz = quaternion.y * quaternion.z
let yw = quaternion.y * quaternion.w
let z2 = quaternion.z * quaternion.z
let zw = quaternion.z * quaternion.w
let w2 = quaternion.w * quaternion.w
let m00 = x2 - y2 - z2 + w2
let m01 = 2.0 * (xy - zw)
let m02 = 2.0 * (xz + yw)
let m10 = 2.0 * (xy + zw)
let m11 = -x2 + y2 - z2 + w2
let m12 = 2.0 * (yz - xw)
let m20 = 2.0 * (xz - yw)
let m21 = 2.0 * (yz + xw)
let m22 = -x2 - y2 + z2 + w2
self.init(
m00, m01, m02,
m10, m11, m12,
m20, m21, m22
)
}
init (fromMatrix4 matrix: Matrix4) {
let m4col0 = matrix[0]
let m4col1 = matrix[1]
let m4col2 = matrix[2]
self.init(
m4col0.x, m4col0.y, m4col0.z,
m4col0.w, m4col1.x, m4col1.y,
m4col1.z, m4col1.w, m4col2.x
)
}
public init (simd: double3x3) {
simdType = simd
}
public init (_ scalar: Double = 0.0) {
simdType = double3x3(scalar)
}
public init (diagonal: double3) {
simdType = double3x3(diagonal: diagonal)
}
public subscript (column: Int) -> Cartesian3 {
assert(column >= 0 && column <= 3, "column index out of range")
return Cartesian3(simd: simdType[column])
}
/// Access to individual elements.
public subscript (column: Int, row: Int) -> Double {
assert(column >= 0 && column <= 3, "column index out of range")
assert(row >= 0 && row <= 3, "row index out of range")
return simdType[column][row]
}
/*
/**
* Creates a Matrix3 instance from a column-major order array.
*
* @param {Number[]} values The column-major order array.
* @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
* @returns The modified result parameter, or a new Matrix3 instance if one was not provided.
*/
Matrix3.fromColumnMajorArray = function(values, result) {
//>>includeStart('debug', pragmas.debug);
if (!defined(values)) {
throw new DeveloperError('values parameter is required');
}
//>>includeEnd('debug');
return Matrix3.clone(values, result);
};
*/
/**
* Creates a Matrix3 instance from a row-major order array.
* The resulting matrix will be in column-major order.
*
* @param {Number[]} values The row-major order array.
* @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
* @returns The modified result parameter, or a new Matrix3 instance if one was not provided.
*/
public init(rows: [Cartesian3]) {
assert(rows.count == 3, "invalid row array")
simdType = double3x3(rows: [rows[0].simdType, rows[1].simdType, rows[2].simdType])
}
/**
* Computes a Matrix3 instance representing a non-uniform scale.
*
* @param {Cartesian3} scale The x, y, and z scale factors.
* @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
* @returns The modified result parameter, or a new Matrix3 instance if one was not provided.
*
* @example
* // Creates
* // [7.0, 0.0, 0.0]
* // [0.0, 8.0, 0.0]
* // [0.0, 0.0, 9.0]
* var m = Cesium.Matrix3.fromScale(new Cesium.Cartesian3(7.0, 8.0, 9.0));
*/
init (scale: Cartesian3) {
self.init(simd: double3x3(diagonal: scale.simdType))
}
/*
/**
* Computes a Matrix3 instance representing a uniform scale.
*
* @param {Number} scale The uniform scale factor.
* @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
* @returns The modified result parameter, or a new Matrix3 instance if one was not provided.
*
* @example
* // Creates
* // [2.0, 0.0, 0.0]
* // [0.0, 2.0, 0.0]
* // [0.0, 0.0, 2.0]
* var m = Cesium.Matrix3.fromUniformScale(2.0);
*/
Matrix3.fromUniformScale = function(scale, result) {
//>>includeStart('debug', pragmas.debug);
if (typeof scale !== 'number') {
throw new DeveloperError('scale is required.');
}
//>>includeEnd('debug');
if (!defined(result)) {
return new Matrix3(
scale, 0.0, 0.0,
0.0, scale, 0.0,
0.0, 0.0, scale);
}
result[0] = scale;
result[1] = 0.0;
result[2] = 0.0;
result[3] = 0.0;
result[4] = scale;
result[5] = 0.0;
result[6] = 0.0;
result[7] = 0.0;
result[8] = scale;
return result;
};
/**
* Computes a Matrix3 instance representing the cross product equivalent matrix of a Cartesian3 vector.
*
* @param {Cartesian3} the vector on the left hand side of the cross product operation.
* @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
* @returns The modified result parameter, or a new Matrix3 instance if one was not provided.
*
* @example
* // Creates
* // [0.0, -9.0, 8.0]
* // [9.0, 0.0, -7.0]
* // [-8.0, 7.0, 0.0]
* var m = Cesium.Matrix3.fromCrossProduct(new Cesium.Cartesian3(7.0, 8.0, 9.0));
*/
Matrix3.fromCrossProduct = function(vector, result) {
//>>includeStart('debug', pragmas.debug);
if (!defined(vector)) {
throw new DeveloperError('vector is required.');
}
//>>includeEnd('debug');
if (!defined(result)) {
return new Matrix3(
0.0, -vector.z, vector.y,
vector.z, 0.0, -vector.x,
-vector.y, vector.x, 0.0);
}
result[0] = 0.0;
result[1] = vector.z;
result[2] = -vector.y;
result[3] = -vector.z;
result[4] = 0.0;
result[5] = vector.x;
result[6] = vector.y;
result[7] = -vector.x;
result[8] = 0.0;
return result;
};
*/
/**
* Creates a rotation matrix around the x-axis.
*
* @param {Number} angle The angle, in radians, of the rotation. Positive angles are counterclockwise.
* @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
* @returns The modified result parameter, or a new Matrix3 instance if one was not provided.
*
* @example
* // Rotate a point 45 degrees counterclockwise around the x-axis.
* var p = new Cesium.Cartesian3(5, 6, 7);
* var m = Cesium.Matrix3.fromRotationX(Cesium.Math.toRadians(45.0));
* var rotated = Cesium.Matrix3.multiplyByVector(m, p);
*/
init (rotationX angle: Double) {
let cosAngle = cos(angle)
let sinAngle = sin(angle)
self.init(
1.0, 0.0, 0.0,
0.0, cosAngle, -sinAngle,
0.0, sinAngle, cosAngle
)
}
/**
* Creates a rotation matrix around the y-axis.
*
* @param {Number} angle The angle, in radians, of the rotation. Positive angles are counterclockwise.
* @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
* @returns The modified result parameter, or a new Matrix3 instance if one was not provided.
*
* @example
* // Rotate a point 45 degrees counterclockwise around the y-axis.
* var p = new Cesium.Cartesian3(5, 6, 7);
* var m = Cesium.Matrix3.fromRotationY(Cesium.Math.toRadians(45.0));
* var rotated = Cesium.Matrix3.multiplyByVector(m, p);
*/
init (rotationY angle: Double) {
let cosAngle = cos(angle)
let sinAngle = sin(angle)
self.init(
cosAngle, 0.0, sinAngle,
0.0, 1.0, 0.0,
-sinAngle, 0.0, cosAngle
)
}
/**
* Creates a rotation matrix around the z-axis.
*
* @param {Number} angle The angle, in radians, of the rotation. Positive angles are counterclockwise.
* @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
* @returns The modified result parameter, or a new Matrix3 instance if one was not provided.
*
* @example
* // Rotate a point 45 degrees counterclockwise around the z-axis.
* var p = new Cesium.Cartesian3(5, 6, 7);
* var m = Cesium.Matrix3.fromRotationZ(Cesium.Math.toRadians(45.0));
* var rotated = Cesium.Matrix3.multiplyByVector(m, p);
*/
init (rotationZ angle: Double) {
let cosAngle: Double = cos(angle)
let sinAngle: Double = sin(angle)
self.init(
cosAngle, -sinAngle, 0.0,
sinAngle, cosAngle, 0.0,
0.0, 0.0, 1.0
)
}
/*
/**
* Computes the array index of the element at the provided row and column.
*
* @param {Number} row The zero-based index of the row.
* @param {Number} column The zero-based index of the column.
* @returns {Number} The index of the element at the provided row and column.
*
* @exception {DeveloperError} row must be 0, 1, or 2.
* @exception {DeveloperError} column must be 0, 1, or 2.
*
* @example
* var myMatrix = new Cesium.Matrix3();
* var column1Row0Index = Cesium.Matrix3.getElementIndex(1, 0);
* var column1Row0 = myMatrix[column1Row0Index]
* myMatrix[column1Row0Index] = 10.0;
*/
Matrix3.getElementIndex = function(column, row) {
//>>includeStart('debug', pragmas.debug);
if (typeof row !== 'number' || row < 0 || row > 2) {
throw new DeveloperError('row must be 0, 1, or 2.');
}
if (typeof column !== 'number' || column < 0 || column > 2) {
throw new DeveloperError('column must be 0, 1, or 2.');
}
//>>includeEnd('debug');
return column * 3 + row;
};
*/
/**
* Retrieves a copy of the matrix column at the provided index as a Cartesian3 instance.
*
* @param {Matrix3} matrix The matrix to use.
* @param {Number} index The zero-based index of the column to retrieve.
* @param {Cartesian3} result The object onto which to store the result.
* @returns {Cartesian3} The modified result parameter.
*
* @exception {DeveloperError} index must be 0, 1, or 2.
*/
func column (_ index: Int) -> Cartesian3 {
assert(index >= 0 && index <= 2, "index must be 0, 1, or 2.")
return Cartesian3(simd: simdType[index])
}
/**
* Computes a new matrix that replaces the specified column in the provided matrix with the provided Cartesian3 instance.
*
* @param {Matrix3} matrix The matrix to use.
* @param {Number} index The zero-based index of the column to set.
* @param {Cartesian3} cartesian The Cartesian whose values will be assigned to the specified column.
* @returns {Matrix3} The modified result parameter.
*
* @exception {DeveloperError} index must be 0, 1, or 2.
*/
func setColumn (_ index: Int, cartesian: Cartesian3) -> Matrix3 {
assert(index >= 0 && index <= 2, "index must be 0, 1, or 2.")
var result = simdType
result[index] = cartesian.simdType
return Matrix3(simd: result)
}
/*
/**
* Retrieves a copy of the matrix row at the provided index as a Cartesian3 instance.
*
* @param {Matrix3} matrix The matrix to use.
* @param {Number} index The zero-based index of the row to retrieve.
* @param {Cartesian3} result The object onto which to store the result.
* @returns {Cartesian3} The modified result parameter.
*
* @exception {DeveloperError} index must be 0, 1, or 2.
*/
Matrix3.getRow = function(matrix, index, result) {
//>>includeStart('debug', pragmas.debug);
if (!defined(matrix)) {
throw new DeveloperError('matrix is required.');
}
if (typeof index !== 'number' || index < 0 || index > 2) {
throw new DeveloperError('index must be 0, 1, or 2.');
}
if (!defined(result)) {
throw new DeveloperError('result is required,');
}
//>>includeEnd('debug');
var x = matrix[index];
var y = matrix[index + 3];
var z = matrix[index + 6];
result.x = x;
result.y = y;
result.z = z;
return result;
};
/**
* Computes a new matrix that replaces the specified row in the provided matrix with the provided Cartesian3 instance.
*
* @param {Matrix3} matrix The matrix to use.
* @param {Number} index The zero-based index of the row to set.
* @param {Cartesian3} cartesian The Cartesian whose values will be assigned to the specified row.
* @param {Cartesian3} result The object onto which to store the result.
* @returns {Matrix3} The modified result parameter.
*
* @exception {DeveloperError} index must be 0, 1, or 2.
*/
Matrix3.setRow = function(matrix, index, cartesian, result) {
//>>includeStart('debug', pragmas.debug);
if (!defined(matrix)) {
throw new DeveloperError('matrix is required');
}
if (!defined(cartesian)) {
throw new DeveloperError('cartesian is required');
}
if (typeof index !== 'number' || index < 0 || index > 2) {
throw new DeveloperError('index must be 0, 1, or 2.');
}
if (!defined(result)) {
throw new DeveloperError('result is required,');
}
//>>includeEnd('debug');
result = Matrix3.clone(matrix, result);
result[index] = cartesian.x;
result[index + 3] = cartesian.y;
result[index + 6] = cartesian.z;
return result;
};
var scratchColumn = new Cartesian3();
/**
* Extracts the non-uniform scale assuming the matrix is an affine transformation.
*
* @param {Matrix3} matrix The matrix.
* @param {Cartesian3} result The object onto which to store the result.
* @returns {Cartesian3} The modified result parameter.
*/
Matrix3.getScale = function(matrix, result) {
//>>includeStart('debug', pragmas.debug);
if (!defined(matrix)) {
throw new DeveloperError('matrix is required.');
}
if (!defined(result)) {
throw new DeveloperError('result is required,');
}
//>>includeEnd('debug');
result.x = Cartesian3.magnitude(Cartesian3.fromElements(matrix[0], matrix[1], matrix[2], scratchColumn));
result.y = Cartesian3.magnitude(Cartesian3.fromElements(matrix[3], matrix[4], matrix[5], scratchColumn));
result.z = Cartesian3.magnitude(Cartesian3.fromElements(matrix[6], matrix[7], matrix[8], scratchColumn));
return result;
};
var scratchScale = new Cartesian3();
/**
* Computes the maximum scale assuming the matrix is an affine transformation.
* The maximum scale is the maximum length of the column vectors.
*
* @param {Matrix3} matrix The matrix.
* @returns {Number} The maximum scale.
*/
Matrix3.getMaximumScale = function(matrix) {
Matrix3.getScale(matrix, scratchScale);
return Cartesian3.maximumComponent(scratchScale);
};
*/
/*
/**
* Computes the sum of two matrices.
*
* @param {Matrix3} left The first matrix.
* @param {Matrix3} right The second matrix.
* @param {Matrix3} result The object onto which to store the result.
* @returns {Matrix3} The modified result parameter.
*/
Matrix3.add = function(left, right, result) {
//>>includeStart('debug', pragmas.debug);
if (!defined(left)) {
throw new DeveloperError('left is required');
}
if (!defined(right)) {
throw new DeveloperError('right is required');
}
if (!defined(result)) {
throw new DeveloperError('result is required,');
}
//>>includeEnd('debug');
result[0] = left[0] + right[0];
result[1] = left[1] + right[1];
result[2] = left[2] + right[2];
result[3] = left[3] + right[3];
result[4] = left[4] + right[4];
result[5] = left[5] + right[5];
result[6] = left[6] + right[6];
result[7] = left[7] + right[7];
result[8] = left[8] + right[8];
return result;
};
/**
* Computes the difference of two matrices.
*
* @param {Matrix3} left The first matrix.
* @param {Matrix3} right The second matrix.
* @param {Matrix3} result The object onto which to store the result.
* @returns {Matrix3} The modified result parameter.
*/
Matrix3.subtract = function(left, right, result) {
//>>includeStart('debug', pragmas.debug);
if (!defined(left)) {
throw new DeveloperError('left is required');
}
if (!defined(right)) {
throw new DeveloperError('right is required');
}
if (!defined(result)) {
throw new DeveloperError('result is required,');
}
//>>includeEnd('debug');
result[0] = left[0] - right[0];
result[1] = left[1] - right[1];
result[2] = left[2] - right[2];
result[3] = left[3] - right[3];
result[4] = left[4] - right[4];
result[5] = left[5] - right[5];
result[6] = left[6] - right[6];
result[7] = left[7] - right[7];
result[8] = left[8] - right[8];
return result;
};
*/
/**
* Computes the product of a matrix and a column vector.
*
* @param {Matrix3} matrix The matrix.
* @param {Cartesian3} cartesian The column.
* @param {Cartesian3} result The object onto which to store the result.
* @returns {Cartesian3} The modified result parameter.
*/
public func multiplyByVector (_ cartesian: Cartesian3) -> Cartesian3 {
return Cartesian3(simd: simdType * cartesian.simdType)
}
/*
/**
* Computes the product of a matrix and a scalar.
*
* @param {Matrix3} matrix The matrix.
* @param {Number} scalar The number to multiply by.
* @param {Matrix3} result The object onto which to store the result.
* @returns {Matrix3} The modified result parameter.
*/
Matrix3.multiplyByScalar = function(matrix, scalar, result) {
//>>includeStart('debug', pragmas.debug);
if (!defined(matrix)) {
throw new DeveloperError('matrix is required');
}
if (typeof scalar !== 'number') {
throw new DeveloperError('scalar must be a number');
}
if (!defined(result)) {
throw new DeveloperError('result is required,');
}
//>>includeEnd('debug');
result[0] = matrix[0] * scalar;
result[1] = matrix[1] * scalar;
result[2] = matrix[2] * scalar;
result[3] = matrix[3] * scalar;
result[4] = matrix[4] * scalar;
result[5] = matrix[5] * scalar;
result[6] = matrix[6] * scalar;
result[7] = matrix[7] * scalar;
result[8] = matrix[8] * scalar;
return result;
};
*/
/**
* Computes the product of a matrix times a (non-uniform) scale, as if the scale were a scale matrix.
*
* @param {Matrix3} matrix The matrix on the left-hand side.
* @param {Cartesian3} scale The non-uniform scale on the right-hand side.
* @param {Matrix3} result The object onto which to store the result.
* @returns {Matrix3} The modified result parameter.
*
* @see Matrix3.fromScale
* @see Matrix3.multiplyByUniformScale
*
* @example
* // Instead of Cesium.Matrix3.multiply(m, Cesium.Matrix3.fromScale(scale), m);
* Cesium.Matrix3.multiplyByScale(m, scale, m);
*/
func multiplyByScale (_ scale: Cartesian3) -> Matrix3 {
var grid = toArray()
grid[0] *= scale.x
grid[1] *= scale.x
grid[2] *= scale.x
grid[3] *= scale.y
grid[4] *= scale.y
grid[5] *= scale.y
grid[6] *= scale.z
grid[7] *= scale.z
grid[8] *= scale.z
return Matrix3(array: grid)
}
/**
* Computes the product of two matrices.
*
* @param {MatrixType} self The first matrix.
* @param {MatrixType} other The second matrix.
* @returns {MatrixType} The modified result parameter.
*/
public func multiply(_ other: Matrix3) -> Matrix3 {
return Matrix3(simd: simdType * other.simdType)
}
public var negate: Matrix3 {
return Matrix3(simd: -simdType)
}
public var transpose: Matrix3 {
return Matrix3(simd: simdType.transpose)
}
public func equals(_ other: Matrix3) -> Bool {
return simd_equal(simdType, other.simdType)
}
/**
* Compares the provided matrices componentwise and returns
* <code>true</code> if they are within the provided epsilon,
* <code>false</code> otherwise.
*
* @param {MatrixType} [left] The first matrix.
* @param {MatrixType} [right] The second matrix.
* @param {Number} epsilon The epsilon to use for equality testing.
* @returns {Boolean} <code>true</code> if left and right are within the provided epsilon, <code>false</code> otherwise.
*/
func equalsEpsilon(_ other: Matrix3, epsilon: Double) -> Bool {
return simd_almost_equal_elements(simdType, other.simdType, epsilon)
}
/**
* Compares this matrix to the provided matrix componentwise and returns
* <code>true</code> if they are equal, <code>false</code> otherwise.
*
* @param {MatrixType} [right] The right hand side matrix.
* @returns {Boolean} <code>true</code> if they are equal, <code>false</code> otherwise.
*/
/*
function computeFrobeniusNorm(matrix) {
var norm = 0.0;
for (var i = 0; i < 9; ++i) {
var temp = matrix[i];
norm += temp * temp;
}
return Math.sqrt(norm);
}
var rowVal = [1, 0, 0];
var colVal = [2, 2, 1];
function offDiagonalFrobeniusNorm(matrix) {
// Computes the "off-diagonal" Frobenius norm.
// Assumes matrix is symmetric.
var norm = 0.0;
for (var i = 0; i < 3; ++i) {
var temp = matrix[Matrix3.getElementIndex(colVal[i], rowVal[i])];
norm += 2.0 * temp * temp;
}
return Math.sqrt(norm);
}
function shurDecomposition(matrix, result) {
// This routine was created based upon Matrix Computations, 3rd ed., by Golub and Van Loan,
// section 8.4.2 The 2by2 Symmetric Schur Decomposition.
//
// The routine takes a matrix, which is assumed to be symmetric, and
// finds the largest off-diagonal term, and then creates
// a matrix (result) which can be used to help reduce it
var tolerance = CesiumMath.EPSILON15;
var maxDiagonal = 0.0;
var rotAxis = 1;
// find pivot (rotAxis) based on max diagonal of matrix
for (var i = 0; i < 3; ++i) {
var temp = Math.abs(matrix[Matrix3.getElementIndex(colVal[i], rowVal[i])]);
if (temp > maxDiagonal) {
rotAxis = i;
maxDiagonal = temp;
}
}
var c = 1.0;
var s = 0.0;
var p = rowVal[rotAxis];
var q = colVal[rotAxis];
if (Math.abs(matrix[Matrix3.getElementIndex(q, p)]) > tolerance) {
var qq = matrix[Matrix3.getElementIndex(q, q)];
var pp = matrix[Matrix3.getElementIndex(p, p)];
var qp = matrix[Matrix3.getElementIndex(q, p)];
var tau = (qq - pp) / 2.0 / qp;
var t;
if (tau < 0.0) {
t = -1.0 / (-tau + Math.sqrt(1.0 + tau * tau));
} else {
t = 1.0 / (tau + Math.sqrt(1.0 + tau * tau));
}
c = 1.0 / Math.sqrt(1.0 + t * t);
s = t * c;
}
result = Matrix3.clone(Matrix3.IDENTITY, result);
result[Matrix3.getElementIndex(p, p)] = result[Matrix3.getElementIndex(q, q)] = c;
result[Matrix3.getElementIndex(q, p)] = s;
result[Matrix3.getElementIndex(p, q)] = -s;
return result;
}
var jMatrix = new Matrix3();
var jMatrixTranspose = new Matrix3();
/**
* Computes the eigenvectors and eigenvalues of a symmetric matrix.
* <p>
* Returns a diagonal matrix and unitary matrix such that:
* <code>matrix = unitary matrix * diagonal matrix * transpose(unitary matrix)</code>
* </p>
* <p>
* The values along the diagonal of the diagonal matrix are the eigenvalues. The columns
* of the unitary matrix are the corresponding eigenvectors.
* </p>
*
* @param {Matrix3} matrix The matrix to decompose into diagonal and unitary matrix. Expected to be symmetric.
* @param {Object} [result] An object with unitary and diagonal properties which are matrices onto which to store the result.
* @returns {Object} An object with unitary and diagonal properties which are the unitary and diagonal matrices, respectively.
*
* @example
* var a = //... symetric matrix
* var result = {
* unitary : new Cesium.Matrix3(),
* diagonal : new Cesium.Matrix3()
* };
* Cesium.Matrix3.computeEigenDecomposition(a, result);
*
* var unitaryTranspose = Cesium.Matrix3.transpose(result.unitary);
* var b = Cesium.Matrix3.multiply(result.unitary, result.diagonal);
* Cesium.Matrix3.multiply(b, unitaryTranspose, b); // b is now equal to a
*
* var lambda = Cesium.Matrix3.getColumn(result.diagonal, 0).x; // first eigenvalue
* var v = Cesium.Matrix3.getColumn(result.unitary, 0); // first eigenvector
* var c = Cesium.Cartesian3.multiplyBy(scalar: v, lambda, new Cartesian3()); // equal to Cesium.Matrix3.multiplyByVector(a, v)
*/
Matrix3.computeEigenDecomposition = function(matrix, result) {
//>>includeStart('debug', pragmas.debug);
if (!defined(matrix)) {
throw new DeveloperError('matrix is required.');
}
//>>includeEnd('debug');
// This routine was created based upon Matrix Computations, 3rd ed., by Golub and Van Loan,
// section 8.4.3 The Classical Jacobi Algorithm
var tolerance = CesiumMath.EPSILON20;
var maxSweeps = 10;
var count = 0;
var sweep = 0;
if (!defined(result)) {
result = {};
}
var unitaryMatrix = result.unitary = Matrix3.clone(Matrix3.IDENTITY, result.unitary);
var diagMatrix = result.diagonal = Matrix3.clone(matrix, result.diagonal);
var epsilon = tolerance * computeFrobeniusNorm(diagMatrix);
while (sweep < maxSweeps && offDiagonalFrobeniusNorm(diagMatrix) > epsilon) {
shurDecomposition(diagMatrix, jMatrix);
Matrix3.transpose(jMatrix, jMatrixTranspose);
Matrix3.multiply(diagMatrix, jMatrix, diagMatrix);
Matrix3.multiply(jMatrixTranspose, diagMatrix, diagMatrix);
Matrix3.multiply(unitaryMatrix, jMatrix, unitaryMatrix);
if (++count > 2) {
++sweep;
count = 0;
}
}
return result;
};
/**
* Computes a matrix, which contains the absolute (unsigned) values of the provided matrix's elements.
*
* @param {Matrix3} matrix The matrix with signed elements.
* @param {Matrix3} result The object onto which to store the result.
* @returns {Matrix3} The modified result parameter.
*/
Matrix3.abs = function(matrix, result) {
//>>includeStart('debug', pragmas.debug);
if (!defined(matrix)) {
throw new DeveloperError('matrix is required');
}
if (!defined(result)) {
throw new DeveloperError('result is required,');
}
//>>includeEnd('debug');
result[0] = Math.abs(matrix[0]);
result[1] = Math.abs(matrix[1]);
result[2] = Math.abs(matrix[2]);
result[3] = Math.abs(matrix[3]);
result[4] = Math.abs(matrix[4]);
result[5] = Math.abs(matrix[5]);
result[6] = Math.abs(matrix[6]);
result[7] = Math.abs(matrix[7]);
result[8] = Math.abs(matrix[8]);
return result;
};
*/
/**
* An immutable Matrix3 instance initialized to the identity matrix.
*
* @type {Matrix3}
* @constant
*/
public static let identity = Matrix3(1.0)
/**
* An immutable Matrix3 instance initialized to the zero matrix.
*
* @type {Matrix3}
* @constant
*/
public static let zero = Matrix3()
}
extension Matrix3: Packable {
var length: Int {
return Matrix3.packedLength()
}
public static func packedLength() -> Int {
return 9
}
public init(array: [Double], startingIndex: Int = 0) {
self.init(
array[startingIndex], array[startingIndex+3], array[startingIndex+6],
array[startingIndex+1], array[startingIndex+4], array[startingIndex+7],
array[startingIndex+2], array[startingIndex+5], array[startingIndex+8]
)
}
func toArray() -> [Double] {
let col0 = simdType[0]
let col1 = simdType[1]
let col2 = simdType[2]
return [
col0.x, col0.y, col0.z,
col1.x, col1.y, col1.z,
col2.x, col2.y, col2.z
]
}
}
extension Matrix3: Equatable {}
public func == (left: Matrix3, right: Matrix3) -> Bool {
return left.equals(right)
}
| apache-2.0 | d5344b8dbc44f384aa0d1c763146a4f5 | 32.34968 | 137 | 0.606994 | 3.652306 | false | false | false | false |
ontouchstart/swift3-playground | Learn to Code 2.playgroundbook/Contents/Chapters/Document9.playgroundchapter/Pages/Challenge1.playgroundpage/Sources/Assessments.swift | 1 | 1381 | //
// Assessments.swift
//
// Copyright (c) 2016 Apple Inc. All Rights Reserved.
//
let hints = [
"Just like in the previous exercise, you need to update the value of the `gemCounter` variable each time Byte collects a gem.",
"Collect a gem, and then use the assignment operator to set a new `gemCounter` value. \nExample: `gemCounter = 3`",
"After Byte collects all the gems, the value of the `gemCounter` variable should be 5.",
"This puzzle is a **Challenge** and has no provided solution. Strengthen your coding skills by creating your own approach to solve it."
]
let solution: String? = nil
public func assessmentPoint() -> AssessmentResults {
let success: String
if finalGemCount == 5 {
success = "### Excellent work! \nBy continuously updating the `gemCounter` value, you can track that value as it changes over time. Next, you'll learn a more efficient way to do this.\n\n[**Next Page**](@next)"
}
else {
success = "You collected all the gems, but didn't track them correctly. Your `gemCounter` variable has a value of `\(finalGemCount)`, but it should have a value of `5`. Try adjusting the code to accurately track how many gems Byte has collected."
}
return updateAssessment(successMessage: success, failureHints: hints, solution: solution)
}
| mit | 77c6cae121715d76494ed9ff7b923eb3 | 46.62069 | 254 | 0.677046 | 4.275542 | false | false | false | false |
Connorrr/ParticleAlarm | IOS/Alarm/LabelEditViewController.swift | 1 | 1166 | //
// labelEditViewController.swift
// Alarm-ios8-swift
//
// Created by longyutao on 15/10/21.
// Copyright (c) 2015年 LongGames. All rights reserved.
//
import UIKit
class LabelEditViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var labelTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
labelTextField.becomeFirstResponder()
// Do any additional setup after loading the view.
self.labelTextField.delegate = self
labelTextField.text = Global.label
//defined in UITextInputTraits protocol
labelTextField.returnKeyType = UIReturnKeyType.done
labelTextField.enablesReturnKeyAutomatically = true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
Global.label = textField.text!
//Becuase segue push is used
//navigationController?.popViewController(animated: true)
return false
}
}
| mit | 5169f0b6cb1504834612a0005eb33059 | 25.454545 | 70 | 0.668385 | 5.315068 | false | false | false | false |
aamays/Rotten-Tomatoes | Rotten Tomatoes/RTUtilities.swift | 1 | 1330 | //
// RTUtilities.swift
// Rotten Tomatoes
//
// Created by Amay Singhal on 9/19/15.
// Copyright © 2015 ple. All rights reserved.
//
import Foundation
import UIKit
class RTUitilities {
static func updateTextAndTintColorForNavBar(navController: UINavigationController?, tintColor: UIColor?, textColor: UIColor?) {
navController?.navigationBar.barTintColor = tintColor ?? RTConstants.ApplicationBarTintColor
navController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: textColor ?? UIColor.darkGrayColor()]
}
static func getAttributedStringForAlertMessage(message: String, withIconSize size: CGFloat = 17, andBaseLine baseline: CGFloat = -3) -> NSAttributedString {
let attributedString = NSMutableAttributedString()
if let font = UIFont(name: "fontastic", size: size) {
let attrs = [NSFontAttributeName : font,
NSBaselineOffsetAttributeName: baseline]
let cautionSign = NSMutableAttributedString(string: "a", attributes: attrs)
attributedString.appendAttributedString(cautionSign)
attributedString.appendAttributedString(NSAttributedString(string: " "))
}
attributedString.appendAttributedString(NSAttributedString(string: message))
return attributedString
}
} | mit | ba30b731600102dbec8c4435c6644da7 | 39.30303 | 160 | 0.72611 | 5.469136 | false | false | false | false |
ben-ng/swift | test/IDE/print_types.swift | 6 | 5974 | // This file should not have any syntax or type checker errors.
// RUN: %target-typecheck-verify-swift
// RUN: %target-swift-ide-test -print-types -source-filename %s -fully-qualified-types=false | %FileCheck %s -strict-whitespace
// RUN: %target-swift-ide-test -print-types -source-filename %s -fully-qualified-types=true | %FileCheck %s -check-prefix=FULL -strict-whitespace
typealias MyInt = Int
// CHECK: TypeAliasDecl '''MyInt''' MyInt.Type{{$}}
// FULL: TypeAliasDecl '''MyInt''' swift_ide_test.MyInt.Type{{$}}
func testVariableTypes(_ param: Int, param2: inout Double) {
// CHECK: FuncDecl '''testVariableTypes''' (Int, inout Double) -> (){{$}}
// FULL: FuncDecl '''testVariableTypes''' (Swift.Int, inout Swift.Double) -> (){{$}}
var a1 = 42
// CHECK: VarDecl '''a1''' Int{{$}}
// CHECK: IntegerLiteralExpr:[[@LINE-2]] '''42''' Int2048{{$}}
// FULL: VarDecl '''a1''' Swift.Int{{$}}
// FULL: IntegerLiteralExpr:[[@LINE-4]] '''42''' Builtin.Int2048{{$}}
a1 = 17; _ = a1
var a2 : Int = 42
// CHECK: VarDecl '''a2''' Int{{$}}
// CHECK: IntegerLiteralExpr:[[@LINE-2]] '''42''' Int2048{{$}}
// FULL: VarDecl '''a2''' Swift.Int{{$}}
// FULL: IntegerLiteralExpr:[[@LINE-4]] '''42''' Builtin.Int2048{{$}}
a2 = 17; _ = a2
var a3 = Int16(42)
// CHECK: VarDecl '''a3''' Int16{{$}}
// CHECK: IntegerLiteralExpr:[[@LINE-2]] '''42''' Int2048{{$}}
// FULL: VarDecl '''a3''' Swift.Int16{{$}}
// FULL: IntegerLiteralExpr:[[@LINE-4]] '''42''' Builtin.Int2048{{$}}
a3 = 17; _ = a3
var a4 = Int32(42)
// CHECK: VarDecl '''a4''' Int32{{$}}
// CHECK: IntegerLiteralExpr:[[@LINE-2]] '''42''' Int2048{{$}}
// FULL: VarDecl '''a4''' Swift.Int32{{$}}
// FULL: IntegerLiteralExpr:[[@LINE-4]] '''42''' Builtin.Int2048{{$}}
a4 = 17; _ = a4
var a5 : Int64 = 42
// CHECK: VarDecl '''a5''' Int64{{$}}
// CHECK: IntegerLiteralExpr:[[@LINE-2]] '''42''' Int2048{{$}}
// FULL: VarDecl '''a5''' Swift.Int64{{$}}
// FULL: IntegerLiteralExpr:[[@LINE-4]] '''42''' Builtin.Int2048{{$}}
a5 = 17; _ = a5
var typealias1 : MyInt = 42
// CHECK: VarDecl '''typealias1''' MyInt{{$}}
// CHECK: IntegerLiteralExpr:[[@LINE-2]] '''42''' Int2048{{$}}
// FULL: VarDecl '''typealias1''' swift_ide_test.MyInt{{$}}
// FULL: IntegerLiteralExpr:[[@LINE-4]] '''42''' Builtin.Int2048{{$}}
_ = typealias1 ; typealias1 = 1
var optional1 = Optional<Int>.none
// CHECK: VarDecl '''optional1''' Optional<Int>{{$}}
// FULL: VarDecl '''optional1''' Swift.Optional<Swift.Int>{{$}}
_ = optional1 ; optional1 = nil
var optional2 = Optional<[Int]>.none
_ = optional2 ; optional2 = nil
// CHECK: VarDecl '''optional2''' Optional<[Int]>{{$}}
// FULL: VarDecl '''optional2''' Swift.Optional<[Swift.Int]>{{$}}
}
func testFuncType1() {}
// CHECK: FuncDecl '''testFuncType1''' () -> (){{$}}
// FULL: FuncDecl '''testFuncType1''' () -> (){{$}}
func testFuncType2() -> () {}
// CHECK: FuncDecl '''testFuncType2''' () -> (){{$}}
// FULL: FuncDecl '''testFuncType2''' () -> (){{$}}
func testFuncType3() -> Void {}
// CHECK: FuncDecl '''testFuncType3''' () -> Void{{$}}
// FULL: FuncDecl '''testFuncType3''' () -> Swift.Void{{$}}
func testFuncType4() -> MyInt {}
// CHECK: FuncDecl '''testFuncType4''' () -> MyInt{{$}}
// FULL: FuncDecl '''testFuncType4''' () -> swift_ide_test.MyInt{{$}}
func testFuncType5() -> (Int) {}
// CHECK: FuncDecl '''testFuncType5''' () -> (Int){{$}}
// FULL: FuncDecl '''testFuncType5''' () -> (Swift.Int){{$}}
func testFuncType6() -> (Int, Int) {}
// CHECK: FuncDecl '''testFuncType6''' () -> (Int, Int){{$}}
// FULL: FuncDecl '''testFuncType6''' () -> (Swift.Int, Swift.Int){{$}}
func testFuncType7(_ a: Int, withFloat b: Float) {}
// CHECK: FuncDecl '''testFuncType7''' (Int, Float) -> (){{$}}
// FULL: FuncDecl '''testFuncType7''' (Swift.Int, Swift.Float) -> (){{$}}
func testVariadicFuncType(_ a: Int, b: Float...) {}
// CHECK: FuncDecl '''testVariadicFuncType''' (Int, Float...) -> (){{$}}
// FULL: FuncDecl '''testVariadicFuncType''' (Swift.Int, Swift.Float...) -> (){{$}}
func testCurriedFuncType1(_ a: Int) -> (_ b: Float) -> () {}
// CHECK: FuncDecl '''testCurriedFuncType1''' (Int) -> (Float) -> (){{$}}
// FULL: FuncDecl '''testCurriedFuncType1''' (Swift.Int) -> (Swift.Float) -> (){{$}}
protocol FooProtocol {}
protocol BarProtocol {}
protocol QuxProtocol { associatedtype Qux }
struct GenericStruct<A, B : FooProtocol> {}
func testInGenericFunc1<A, B : FooProtocol, C : FooProtocol & BarProtocol>(_ a: A, b: B, c: C) {
// CHECK: FuncDecl '''testInGenericFunc1''' <A, B, C where B : FooProtocol, C : BarProtocol, C : FooProtocol> (A, b: B, c: C) -> (){{$}}
// FULL: FuncDecl '''testInGenericFunc1''' <A, B, C where B : FooProtocol, C : BarProtocol, C : FooProtocol> (A, b: B, c: C) -> (){{$}}
var a1 = a
_ = a1; a1 = a
// CHECK: VarDecl '''a1''' A{{$}}
// FULL: VarDecl '''a1''' A{{$}}
var b1 = b
_ = b1; b1 = b
// CHECK: VarDecl '''b1''' B{{$}}
// FULL: VarDecl '''b1''' B{{$}}
var gs1 = GenericStruct<A, B>()
_ = gs1; gs1 = GenericStruct<A, B>()
// CHECK: VarDecl '''gs1''' GenericStruct<A, B>{{$}}
// CHECK: CallExpr:[[@LINE-2]] '''GenericStruct<A, B>()''' GenericStruct<A, B>{{$}}
// CHECK: ConstructorRefCallExpr:[[@LINE-3]] '''GenericStruct<A, B>''' () -> GenericStruct<A, B>
// FULL: VarDecl '''gs1''' swift_ide_test.GenericStruct<A, B>{{$}}
// FULL: CallExpr:[[@LINE-6]] '''GenericStruct<A, B>()''' swift_ide_test.GenericStruct<A, B>{{$}}
// FULL: ConstructorRefCallExpr:[[@LINE-7]] '''GenericStruct<A, B>''' () -> swift_ide_test.GenericStruct<A, B>
}
func testInGenericFunc2<T : QuxProtocol, U : QuxProtocol>() where T.Qux == U.Qux {}
// CHECK: FuncDecl '''testInGenericFunc2''' <T, U where T : QuxProtocol, U : QuxProtocol, T.Qux == U.Qux> () -> (){{$}}
// FULL: FuncDecl '''testInGenericFunc2''' <T, U where T : QuxProtocol, U : QuxProtocol, T.Qux == U.Qux> () -> (){{$}}
| apache-2.0 | 0dbfe123623e4556d6097017381d25fc | 41.671429 | 145 | 0.57767 | 3.507927 | false | true | false | false |
billyburton/SwiftMySql | Sources/SwiftMySql/MySqlFactory.swift | 1 | 3814 | //
// MySqlFactory.swift
// SwiftMySql
//
// Created by William Burton on 08/02/2017.
//
//
import Foundation
public class MySqlFactory {
//MARK: connection factory
static var connectionClosure: (String, String, String, String) throws -> (MySqlConnectionProtocol) = {
server, database, user, password in
return try MySqlConnection(server: server, database: database, user: user, password: password)
}
/**
Factory method for creating a MySqlConnectionProtocol instance.
- throws:
An error of type MySqlError.InvalidConnection.
- parameters:
- server: Name of the MySql server.
- database: Name of the MySql database.
- user: Name of user that will be used to access the database.
- password: Password of the MySql user.
- returns:
An instance of MySqlConnectionProtocol.
*/
public class func createConnection(server: String, database: String, user: String, password: String) throws -> MySqlConnectionProtocol {
return try connectionClosure(server, database, user, password)
}
//MARK: Transaction factory
static var transactionClosure: (MySqlConnectionProtocol) -> (MySqlTransactionProtocol) = {
connection in
return MySqlTransaction(connection: connection)
}
/**
Factory method for creating a MySqlTransactionProtocol instance
- parameters:
- connection: An instance of MySqlConnectionProtocol created using the createConnection method.
- returns:
An instance of MySqlTransactionProtocol
*/
public class func createTransaction(connection: MySqlConnectionProtocol) -> (MySqlTransactionProtocol) {
return transactionClosure(connection)
}
//MARK: reader factory
static var readerClosure: (MySqlConnectionProtocol) throws -> (MySqlReaderProtocol) = {
connection in
return try MySqlReader(connection: connection)
}
/**
Factory method for creating a MySqlReaderProtocol
- throws:
An error of type MySqlError.ReaderError
- parameters:
- connection: An instance of MySqlConnectionProtocol created using the createConnection method.
- returns:
An instance of MySqlReaderProtocol
*/
class func createReader(connection: MySqlConnectionProtocol) throws -> MySqlReaderProtocol {
return try readerClosure(connection)
}
//MARK: command factory
static var commandClosure: (String, MySqlConnectionProtocol) -> (MySqlCommandProtocol) = {
command, connection in
return MySqlCommand(command: command, connection: connection)
}
/**
Factory method for creating a MySqlCommandProtocol
- parameters:
- command: Sql query command.
- connection: An instance of MySqlConnectionProtocol created using the createConnection method
- returns:
An instance of MySqlCommandProtocol
*/
public class func createCommand(command: String, connection: MySqlConnectionProtocol) -> MySqlCommandProtocol {
return commandClosure(command, connection)
}
//MARK: schema factory
static var schemaClosure: (MySqlResultsProtocol) -> (MySqlSchemaProtocol) = {
results in
return MySqlSchema(results)
}
/**
Factory method for creating a MySqlSchemaProtocol
- parameters:
- results: An instance of MySqlResultsProtocol, that contains a resultset returned from the MySql database.
- returns:
An instance of MySqlSchemaProtocol
*/
class func createSchema(results: MySqlResultsProtocol) -> MySqlSchemaProtocol {
return schemaClosure(results)
}
}
| apache-2.0 | ab08ab7541c8ff2fbd58c05bcccfa41f | 30.783333 | 140 | 0.6699 | 4.940415 | false | false | false | false |
sigito/material-components-ios | catalog/MDCCatalog/AppDelegate.swift | 1 | 3027 | /*
Copyright 2015-present the Material Components for iOS authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import UIKit
import CatalogByConvention
import MaterialComponents.MaterialBottomAppBar
import MaterialComponents.MDCActivityIndicatorColorThemer
import MaterialComponents.MDCBottomNavigationBarColorThemer
import MaterialComponents.MDCBottomAppBarColorThemer
import MaterialComponents.MDCButtonBarColorThemer
import MaterialComponents.MDCButtonColorThemer
import MaterialComponents.MDCAlertColorThemer
import MaterialComponents.MDCFeatureHighlightColorThemer
import MaterialComponents.MDCFlexibleHeaderColorThemer
import MaterialComponents.MDCHeaderStackViewColorThemer
import MaterialComponents.MDCNavigationBarColorThemer
import MaterialComponents.MDCPageControlColorThemer
import MaterialComponents.MDCProgressViewColorThemer
import MaterialComponents.MDCSliderColorThemer
import MaterialComponents.MDCTabBarColorThemer
import MaterialComponents.MaterialTextFields
import MaterialComponents.MDCTextFieldColorThemer
import MaterialComponents.MaterialThemes
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions
launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
self.window = MDCCatalogWindow(frame: UIScreen.main.bounds)
UIApplication.shared.statusBarStyle = .lightContent
// The navigation tree will only take examples that implement
// and return YES to catalogIsPresentable.
let tree = CBCCreatePresentableNavigationTree()
let rootNodeViewController = MDCCatalogComponentsController(node: tree)
let navigationController = UINavigationController(rootViewController: rootNodeViewController)
// In the event that an example view controller hides the navigation bar we generally want to
// ensure that the edge-swipe pop gesture can still take effect. This may be overly-assumptive
// but we'll explore other alternatives when we have a concrete example of this approach causing
// problems.
navigationController.interactivePopGestureRecognizer?.delegate = navigationController
self.window?.rootViewController = navigationController
self.window?.makeKeyAndVisible()
return true
}
}
extension UINavigationController: UIGestureRecognizerDelegate {
public func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
return viewControllers.count > 1
}
}
| apache-2.0 | 2f8f13cf0091210f4c66761ae9ed74f8 | 39.905405 | 100 | 0.831186 | 5.493648 | false | false | false | false |
MegaManX32/CD | CD/CD/View Controllers/SignupYourInterestsViewController.swift | 1 | 5753 | //
// SignupYourInterestsViewController.swift
// CustomDeal
//
// Created by Vladislav Simovic on 9/28/16.
// Copyright © 2016 Vladislav Simovic. All rights reserved.
//
import UIKit
import MBProgressHUD
fileprivate let sectionInsets = UIEdgeInsets(top: 20.0, left: 20.0, bottom: 30.0, right: 20.0)
fileprivate let itemsPerRow: CGFloat = 3
fileprivate let heightOfRow: CGFloat = 100
class SignupYourInterestsViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
// MARK: - Properties
@IBOutlet weak var collectionView : UICollectionView!
var userID : String!
var interestsArray : [(interest : Interest, checked : Bool)] = [(Interest, Bool)]()
// MARK: - View Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
// fetch interests
MBProgressHUD.showAdded(to: self.view, animated: true)
NetworkManager.sharedInstance.getAllInterests(
success: { [unowned self] in
let context = CoreDataManager.sharedInstance.mainContext
let interests = Interest.findAllInterests(context: context)
for interest in interests {
self.interestsArray.append((interest, false))
}
self.collectionView.reloadData()
MBProgressHUD.hide(for: self.view, animated: true)
},
failure: { [unowned self] (errorMessage) in
print(errorMessage)
MBProgressHUD.hide(for: self.view, animated: true)
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - User Actions
@IBAction func nextAction(sender: UIButton) {
// try to update interests on user
var selectedInterestsIDArray = [String]()
for interestOption in self.interestsArray {
if interestOption.checked {
selectedInterestsIDArray.append(interestOption.interest.uid!)
}
}
// at least 3 interests must be selected
if selectedInterestsIDArray.count < 4 {
CustomAlert.presentAlert(message: "At least 4 interests must be selected", controller: self)
return
}
MBProgressHUD.showAdded(to: self.view, animated: true)
let context = CoreDataManager.sharedInstance.createScratchpadContext(onMainThread: false)
context.perform {
[unowned self] in
// find user
let user = User.findUserWith(uid: self.userID, context: context)!
// update user with interests
for interestID in selectedInterestsIDArray {
user.addToInterests(Interest.findInterestWith(id: interestID, context: context)!)
}
// create of or update user
NetworkManager.sharedInstance.createOrUpdate(user: user, context: context, success: { [unowned self] (userID) in
let controller = self.storyboard?.instantiateViewController(withIdentifier: "SignupCongratulationsViewController") as! SignupCongratulationsViewController
controller.userID = userID
self.show(controller, sender: self)
MBProgressHUD.hide(for: self.view, animated: true)
}, failure: { [unowned self] (errorMessage) in
print(errorMessage)
MBProgressHUD.hide(for: self.view, animated: true)
})
}
}
// MARK: - UICollectionViewDelegate methods
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.interestsArray.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: SignupInterestsCollectionViewCell.cellIdentifier(), for: indexPath) as! SignupInterestsCollectionViewCell
cell.populateCellWithInterest(name: self.interestsArray[indexPath.item].interest.name!,
imageName: (self.interestsArray[indexPath.item].interest.name!).lowercased(),
checked: self.interestsArray[indexPath.item].checked
)
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let paddingSpace = sectionInsets.left * (itemsPerRow + 1)
let availableWidth = view.frame.width - paddingSpace
let widthPerItem = availableWidth / itemsPerRow
return CGSize(width: widthPerItem, height: heightOfRow)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
return sectionInsets
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return sectionInsets.left
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
self.interestsArray[indexPath.item].checked = !self.interestsArray[indexPath.item].checked
self.collectionView.reloadItems(at: [indexPath])
}
}
| mit | c4f1dbca221390ead309256da34e9b35 | 41.294118 | 180 | 0.654729 | 5.678184 | false | false | false | false |
gobetti/Swift | PagedBasedApp/PagedBasedApp/RootViewController.swift | 1 | 5227 | //
// RootViewController.swift
// PagedBasedApp
//
// Created by Carlos Butron on 07/12/14.
//
// This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public
// License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later
// version.
// This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
// warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
// You should have received a copy of the GNU General Public License along with this program. If not, see
// http:/www.gnu.org/licenses/.
//
import UIKit
class RootViewController: UIViewController, UIPageViewControllerDelegate {
var pageViewController: UIPageViewController?
lazy var modelController = ModelController()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
// Configure the page view controller and add it as a child view controller.
self.pageViewController = UIPageViewController(transitionStyle: .PageCurl, navigationOrientation: .Horizontal, options: nil)
self.pageViewController!.delegate = self
let startingViewController: DataViewController = self.modelController.viewControllerAtIndex(0, storyboard: self.storyboard!)!
let viewControllers = [startingViewController]
self.pageViewController!.setViewControllers(viewControllers, direction: .Forward, animated: false, completion: {done in })
self.pageViewController!.dataSource = self.modelController
self.addChildViewController(self.pageViewController!)
self.view.addSubview(self.pageViewController!.view)
// Set the page view controller's bounds using an inset rect so that self's view is visible around the edges of the pages.
var pageViewRect = self.view.bounds
if UIDevice.currentDevice().userInterfaceIdiom == .Pad {
pageViewRect = CGRectInset(pageViewRect, 40.0, 40.0)
}
self.pageViewController!.view.frame = pageViewRect
self.pageViewController!.didMoveToParentViewController(self)
// Add the page view controller's gesture recognizers to the book view controller's view so that the gestures are started more easily.
self.view.gestureRecognizers = self.pageViewController!.gestureRecognizers
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - UIPageViewController delegate methods
func pageViewController(pageViewController: UIPageViewController, spineLocationForInterfaceOrientation orientation: UIInterfaceOrientation) -> UIPageViewControllerSpineLocation {
if (orientation == .Portrait) || (orientation == .PortraitUpsideDown) || (UIDevice.currentDevice().userInterfaceIdiom == .Phone) {
// In portrait orientation or on iPhone: Set the spine position to "min" and the page view controller's view controllers array to contain just one view controller. Setting the spine position to 'UIPageViewControllerSpineLocationMid' in landscape orientation sets the doubleSided property to true, so set it to false here.
let currentViewController = self.pageViewController!.viewControllers![0]
let viewControllers = [currentViewController]
self.pageViewController!.setViewControllers(viewControllers, direction: .Forward, animated: true, completion: {done in })
self.pageViewController!.doubleSided = false
return .Min
}
// In landscape orientation: Set set the spine location to "mid" and the page view controller's view controllers array to contain two view controllers. If the current page is even, set it to contain the current and next view controllers; if it is odd, set the array to contain the previous and current view controllers.
let currentViewController = self.pageViewController!.viewControllers![0] as! DataViewController
var viewControllers: [UIViewController]
let indexOfCurrentViewController = self.modelController.indexOfViewController(currentViewController)
if (indexOfCurrentViewController == 0) || (indexOfCurrentViewController % 2 == 0) {
let nextViewController = self.modelController.pageViewController(self.pageViewController!, viewControllerAfterViewController: currentViewController)
viewControllers = [currentViewController, nextViewController!]
} else {
let previousViewController = self.modelController.pageViewController(self.pageViewController!, viewControllerBeforeViewController: currentViewController)
viewControllers = [previousViewController!, currentViewController]
}
self.pageViewController!.setViewControllers(viewControllers, direction: .Forward, animated: true, completion: {done in })
return .Mid
}
}
| mit | 0083a1214f05bfd23c2e45b9e19d6d78 | 57.077778 | 333 | 0.727186 | 5.827202 | 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.